fm4bio-ning commited on
Commit
c0b5787
·
verified ·
1 Parent(s): b3382f6

upload tokenizer and model config

Browse files
config.json CHANGED
@@ -1,32 +1,91 @@
1
  {
2
- "add_linear_bias": true,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  "architectures": [
4
  "FM4BioForMaskedLM"
5
  ],
6
- "attention_probs_dropout_prob": 0.0,
7
- "experts_per_token": 2,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  "hidden_act": "swiglu",
 
9
  "hidden_dropout_prob": 0.0,
10
- "hidden_size": 2304,
 
 
11
  "initializer_range": 0.02,
12
- "intermediate_size": 7680,
13
  "layer_norm_eps": 1e-05,
14
- "max_position_embeddings": 2048,
15
- "model_type": "fm4bio",
16
- "moe": true,
17
- "normalization_type": "RMSNorm",
18
- "num_attention_heads": 36,
19
- "num_experts": 8,
20
- "num_hidden_layers": 36,
21
- "pad_token_id": 0,
22
  "position_embedding_type": "rope",
 
 
 
23
  "rotary_percent": 1.0,
24
  "seq_len_interpolation_factor": null,
25
- "tie_word_embeddings": false,
26
- "torch_dtype": "float32",
27
- "transformers_version": "4.38.0.dev0",
28
- "type_vocab_size": 2,
29
- "use_cache": true,
30
  "use_lm_head": false,
31
- "vocab_size": 128
32
- }
 
 
 
1
  {
2
+ "return_dict": true,
3
+ "output_hidden_states": false,
4
+ "output_attentions": false,
5
+ "torchscript": false,
6
+ "torch_dtype": "float32",
7
+ "use_bfloat16": false,
8
+ "tf_legacy_loss": false,
9
+ "pruned_heads": {},
10
+ "tie_word_embeddings": false,
11
+ "chunk_size_feed_forward": 0,
12
+ "is_encoder_decoder": false,
13
+ "is_decoder": false,
14
+ "cross_attention_hidden_size": null,
15
+ "add_cross_attention": false,
16
+ "tie_encoder_decoder": false,
17
+ "max_length": 20,
18
+ "min_length": 0,
19
+ "do_sample": false,
20
+ "early_stopping": false,
21
+ "num_beams": 1,
22
+ "num_beam_groups": 1,
23
+ "diversity_penalty": 0.0,
24
+ "temperature": 1.0,
25
+ "top_k": 50,
26
+ "top_p": 1.0,
27
+ "typical_p": 1.0,
28
+ "repetition_penalty": 1.0,
29
+ "length_penalty": 1.0,
30
+ "no_repeat_ngram_size": 0,
31
+ "encoder_no_repeat_ngram_size": 0,
32
+ "bad_words_ids": null,
33
+ "num_return_sequences": 1,
34
+ "output_scores": false,
35
+ "return_dict_in_generate": false,
36
+ "forced_bos_token_id": null,
37
+ "forced_eos_token_id": null,
38
+ "remove_invalid_values": false,
39
+ "exponential_decay_length_penalty": null,
40
+ "suppress_tokens": null,
41
+ "begin_suppress_tokens": null,
42
  "architectures": [
43
  "FM4BioForMaskedLM"
44
  ],
45
+ "finetuning_task": null,
46
+ "id2label": {
47
+ "0": "LABEL_0",
48
+ "1": "LABEL_1"
49
+ },
50
+ "label2id": {
51
+ "LABEL_0": 0,
52
+ "LABEL_1": 1
53
+ },
54
+ "tokenizer_class": null,
55
+ "prefix": null,
56
+ "bos_token_id": null,
57
+ "pad_token_id": 0,
58
+ "eos_token_id": null,
59
+ "sep_token_id": null,
60
+ "decoder_start_token_id": null,
61
+ "task_specific_params": null,
62
+ "problem_type": null,
63
+ "_name_or_path": "genbio-ai/AIDO.Protein-16B",
64
+ "transformers_version": "4.38.0",
65
+ "model_type": "fm4bio",
66
+ "vocab_size": 128,
67
+ "hidden_size": 2304,
68
+ "num_hidden_layers": 36,
69
+ "num_attention_heads": 36,
70
  "hidden_act": "swiglu",
71
+ "intermediate_size": 7680,
72
  "hidden_dropout_prob": 0.0,
73
+ "attention_probs_dropout_prob": 0.0,
74
+ "max_position_embeddings": 2048,
75
+ "type_vocab_size": 2,
76
  "initializer_range": 0.02,
 
77
  "layer_norm_eps": 1e-05,
 
 
 
 
 
 
 
 
78
  "position_embedding_type": "rope",
79
+ "use_cache": true,
80
+ "add_linear_bias": true,
81
+ "normalization_type": "RMSNorm",
82
  "rotary_percent": 1.0,
83
  "seq_len_interpolation_factor": null,
84
+ "moe": true,
85
+ "num_experts": 8,
86
+ "experts_per_token": 2,
 
 
87
  "use_lm_head": false,
88
+ "output_vocab_size": null,
89
+ "gradient_checkpointing": false,
90
+ "str_embedding_in": null
91
+ }
configuration_fm4bio.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ class FM4BioConfig(PretrainedConfig):
3
+ model_type = "fm4bio"
4
+
5
+ def __init__(
6
+ self,
7
+ vocab_size=128,
8
+ hidden_size=1024,
9
+ num_hidden_layers=24,
10
+ num_attention_heads=16,
11
+ intermediate_size=4096,
12
+ hidden_act="swiglu",
13
+ hidden_dropout_prob=0.0,
14
+ attention_probs_dropout_prob=0.0,
15
+ max_position_embeddings=2048,
16
+ type_vocab_size=2,
17
+ initializer_range=0.02,
18
+ layer_norm_eps=1e-05,
19
+ pad_token_id=0,
20
+ add_linear_bias=True,
21
+ position_embedding_type="rope",
22
+ normalization_type="RMSNorm",
23
+ use_cache=True,
24
+ rotary_percent=1.0,
25
+ seq_len_interpolation_factor=None,
26
+ moe=False,
27
+ num_experts=0,
28
+ experts_per_token=0,
29
+ use_lm_head=True,
30
+ tie_word_embeddings=True,
31
+ output_vocab_size: int = None, # when set, the output vocab size is different from the input vocab size
32
+ gradient_checkpointing=False, # << Pan: Gradient checkpoint for memory saving
33
+ **kwargs,
34
+ ):
35
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
36
+
37
+ self.vocab_size = vocab_size
38
+ self.hidden_size = hidden_size
39
+ self.num_hidden_layers = num_hidden_layers
40
+ self.num_attention_heads = num_attention_heads
41
+ self.hidden_act = hidden_act
42
+ self.intermediate_size = intermediate_size
43
+ self.hidden_dropout_prob = hidden_dropout_prob
44
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
45
+ self.max_position_embeddings = max_position_embeddings
46
+ self.type_vocab_size = type_vocab_size
47
+ self.initializer_range = initializer_range
48
+ self.layer_norm_eps = layer_norm_eps
49
+ self.position_embedding_type = position_embedding_type
50
+ self.use_cache = use_cache
51
+ self.add_linear_bias = add_linear_bias
52
+ assert normalization_type in [
53
+ "RMSNorm",
54
+ "LayerNorm",
55
+ ], "normalization_type must be 'RMSNorm' or 'LayerNorm'"
56
+ self.normalization_type = normalization_type
57
+ self.rotary_percent = rotary_percent
58
+ self.seq_len_interpolation_factor = seq_len_interpolation_factor
59
+ self.moe = moe
60
+ self.num_experts = num_experts
61
+ self.experts_per_token = experts_per_token
62
+ self.use_lm_head = use_lm_head
63
+ self.tie_word_embeddings = tie_word_embeddings
64
+ self.output_vocab_size = output_vocab_size
65
+ self.gradient_checkpointing = gradient_checkpointing # << Pan: Gradient checkpoint for memory saving
modeling_fm4bio.py ADDED
@@ -0,0 +1,2148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch MegatronBERT model."""
17
+
18
+
19
+ import math
20
+ import os
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple, Union
24
+ import sys
25
+ from functools import partial
26
+
27
+ import torch
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss, HuberLoss
31
+ import torch.nn.functional as F
32
+
33
+ from transformers.activations import ACT2FN
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPastAndCrossAttentions,
36
+ BaseModelOutputWithPoolingAndCrossAttentions,
37
+ MaskedLMOutput,
38
+ SequenceClassifierOutput,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import (
43
+ apply_chunking_to_forward,
44
+ find_pruneable_heads_and_indices,
45
+ prune_linear_layer,
46
+ )
47
+ from transformers.utils import (
48
+ ModelOutput,
49
+ add_code_sample_docstrings,
50
+ add_start_docstrings,
51
+ add_start_docstrings_to_model_forward,
52
+ logging,
53
+ replace_return_docstrings,
54
+ )
55
+ from .configuration_fm4bio import FM4BioConfig
56
+ from collections import namedtuple
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ _CONFIG_FOR_DOC = "FM4BioConfig"
62
+ _CHECKPOINT_FOR_DOC = ""
63
+
64
+ FM4BIO_PRETRAINED_MODEL_ARCHIVE_LIST = [
65
+ "",
66
+ # See all FM4Bio models at https://huggingface.co/models?filter=fm4bio
67
+ ]
68
+
69
+ if sys.platform != "darwin":
70
+ torch._C._jit_set_profiling_mode(False)
71
+ torch._C._jit_set_profiling_executor(False)
72
+ torch._C._jit_override_can_fuse_on_cpu(True)
73
+ torch._C._jit_override_can_fuse_on_gpu(True)
74
+
75
+ logger = logging.get_logger(__name__)
76
+ DeepNormCoefficients = namedtuple("DeepNormCoefficients", ["alpha", "beta"])
77
+
78
+ # << Pan: checkpoint function
79
+ def get_checkpoint_fn():
80
+ # import deepspeed
81
+ #if deepspeed.checkpointing.is_configured():
82
+ # checkpoint = deepspeed.checkpointing.checkpoint
83
+ #else:
84
+ checkpoint = partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
85
+ return checkpoint
86
+
87
+ class FM4BioEmbeddings(nn.Module):
88
+ """Construct the embeddings from word, position and token_type embeddings."""
89
+
90
+ def __init__(self, config):
91
+ super().__init__()
92
+ self.word_embeddings = nn.Embedding(
93
+ config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
94
+ )
95
+ if config.position_embedding_type not in ("rope", "rope_2d"): # << Pan: add rope_2d
96
+ self.position_embeddings = nn.Embedding(
97
+ config.max_position_embeddings, config.hidden_size
98
+ )
99
+ # self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
100
+
101
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
102
+ # any TensorFlow checkpoint file
103
+
104
+ # << Pan: Structure embedding input dimension
105
+ if isinstance(config.str_embedding_in, str):
106
+ if config.str_embedding_in.isdigit():
107
+ self.str_embedding_in = int(config.str_embedding_in)
108
+ else:
109
+ self.str_embedding_in = None
110
+ else:
111
+ self.str_embedding_in = config.str_embedding_in
112
+
113
+ if self.str_embedding_in is not None and self.str_embedding_in > 0:
114
+ self.str_embeddings = nn.Linear(self.str_embedding_in, config.hidden_size, bias=False)
115
+
116
+ # In Megatron, layer-norm is applied after the 1st dropout.
117
+ # self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
118
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
119
+
120
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
121
+ self.register_buffer(
122
+ "position_ids",
123
+ torch.arange(config.max_position_embeddings).expand((1, -1)),
124
+ persistent=False,
125
+ )
126
+ self.position_embedding_type = getattr(
127
+ config, "position_embedding_type", "rope"
128
+ )
129
+
130
+ def forward(
131
+ self,
132
+ input_ids: Optional[torch.LongTensor] = None,
133
+ token_type_ids: Optional[torch.LongTensor] = None,
134
+ position_ids: Optional[torch.LongTensor] = None,
135
+ inputs_embeds: Optional[torch.LongTensor] = None,
136
+ inputs_str_embeds: Optional[torch.LongTensor] = None, # << Pan: add structure embedding input
137
+ past_key_values_length: int = 0,
138
+ ) -> torch.Tensor:
139
+ if input_ids is not None:
140
+ input_shape = input_ids.size()
141
+ else:
142
+ input_shape = inputs_embeds.size()[:-1]
143
+
144
+ seq_length = input_shape[1]
145
+
146
+ if position_ids is None:
147
+ position_ids = self.position_ids[
148
+ :, past_key_values_length : seq_length + past_key_values_length
149
+ ]
150
+
151
+ if token_type_ids is None:
152
+ token_type_ids = torch.zeros(
153
+ input_shape, dtype=torch.long, device=self.position_ids.device
154
+ )
155
+
156
+ if inputs_embeds is None:
157
+ inputs_embeds = self.word_embeddings(input_ids)
158
+ # token_type_embeddings = self.token_type_embeddings(token_type_ids)
159
+
160
+ # << Pan: add structure embedding
161
+ if self.str_embedding_in is not None and self.str_embedding_in > 0:
162
+ if inputs_str_embeds is None:
163
+ print(f"Warning: str_embedding_in={self.str_embedding_in}, but inputs_str_embeds is None")
164
+ else:
165
+ # inputs_str_embeds: [B, L, D1]
166
+ # inputs_embeds: [B, L, D]
167
+ shape = f"inputs_str_embeds.shape={inputs_str_embeds.shape}, inputs_embeds.shape={inputs_embeds.shape}"
168
+ assert inputs_str_embeds.ndim == 3, shape
169
+ assert inputs_str_embeds.shape[0] == inputs_embeds.shape[0], shape
170
+ assert inputs_str_embeds.shape[1] == inputs_embeds.shape[1], shape
171
+ inputs_embeds = inputs_embeds + self.str_embeddings(inputs_str_embeds)
172
+
173
+ if os.environ.get("DEBUG", "FALSE") == "TRUE":
174
+ if torch.distributed.get_rank() == 0:
175
+ breakpoint()
176
+ torch.distributed.barrier()
177
+
178
+ # embeddings = inputs_embeds + token_type_embeddings
179
+ embeddings = inputs_embeds
180
+ if self.position_embedding_type == "absolute":
181
+ position_embeddings = self.position_embeddings(position_ids)
182
+ embeddings += position_embeddings
183
+
184
+ # Megatron BERT moves that layer norm after the drop-out (and to each layer).
185
+ # embeddings = self.LayerNorm(embeddings)
186
+ embeddings = self.dropout(embeddings)
187
+ return embeddings
188
+
189
+
190
+ # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->FM4Bio
191
+ class FM4BioSelfAttention(nn.Module):
192
+ def __init__(self, config, position_embedding_type=None):
193
+ super().__init__()
194
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
195
+ config, "embedding_size"
196
+ ):
197
+ raise ValueError(
198
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
199
+ f"heads ({config.num_attention_heads})"
200
+ )
201
+
202
+ self.num_attention_heads = config.num_attention_heads
203
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
204
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
205
+
206
+ self.query = nn.Linear(
207
+ config.hidden_size, self.all_head_size, bias=config.add_linear_bias
208
+ )
209
+ self.key = nn.Linear(
210
+ config.hidden_size, self.all_head_size, bias=config.add_linear_bias
211
+ )
212
+ self.value = nn.Linear(
213
+ config.hidden_size, self.all_head_size, bias=config.add_linear_bias
214
+ )
215
+
216
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
217
+ self.position_embedding_type = position_embedding_type or getattr(
218
+ config, "position_embedding_type", "absolute"
219
+ )
220
+ if (
221
+ self.position_embedding_type == "relative_key"
222
+ or self.position_embedding_type == "relative_key_query"
223
+ ):
224
+ self.max_position_embeddings = config.max_position_embeddings
225
+ self.distance_embedding = nn.Embedding(
226
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
227
+ )
228
+
229
+ self.is_decoder = config.is_decoder
230
+
231
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
232
+ new_x_shape = x.size()[:-1] + (
233
+ self.num_attention_heads,
234
+ self.attention_head_size,
235
+ )
236
+ x = x.view(new_x_shape)
237
+ return x.permute(0, 2, 1, 3)
238
+
239
+ def forward(
240
+ self,
241
+ hidden_states: torch.Tensor,
242
+ attention_mask: Optional[torch.FloatTensor] = None,
243
+ head_mask: Optional[torch.FloatTensor] = None,
244
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
245
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
246
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
247
+ output_attentions: Optional[bool] = False,
248
+ rotary_pos_emb=None,
249
+ ) -> Tuple[torch.Tensor]:
250
+ mixed_query_layer = self.query(hidden_states)
251
+
252
+ # If this is instantiated as a cross-attention module, the keys
253
+ # and values come from an encoder; the attention mask needs to be
254
+ # such that the encoder's padding tokens are not attended to.
255
+ is_cross_attention = encoder_hidden_states is not None
256
+
257
+ if is_cross_attention and past_key_value is not None:
258
+ # reuse k,v, cross_attentions
259
+ key_layer = past_key_value[0]
260
+ value_layer = past_key_value[1]
261
+ attention_mask = encoder_attention_mask
262
+ elif is_cross_attention:
263
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
264
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
265
+ attention_mask = encoder_attention_mask
266
+ elif past_key_value is not None:
267
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
268
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
269
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
270
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
271
+ else:
272
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
273
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
274
+
275
+ # [b, hn, sq, c]
276
+ query_layer = self.transpose_for_scores(mixed_query_layer)
277
+
278
+ if rotary_pos_emb is not None:
279
+ if isinstance(rotary_pos_emb, tuple):
280
+ rotary_pos_emb = rotary_pos_emb
281
+ else:
282
+ rotary_pos_emb = (rotary_pos_emb,) * 2
283
+ q_pos_emb, k_pos_emb = rotary_pos_emb
284
+
285
+ # [b, hn, sq, c] --> [sq, b, hn, c]
286
+ query_layer = query_layer.permute(2, 0, 1, 3).contiguous()
287
+ key_layer = key_layer.permute(2, 0, 1, 3).contiguous()
288
+
289
+ # debug_tensor = query_layer[:3, 0]
290
+ # query_layer = apply_rotary_pos_emb(
291
+ # query_layer, q_pos_emb
292
+ # ) # debug query_layer[:,0]
293
+ # key_layer = apply_rotary_pos_emb(key_layer, k_pos_emb)
294
+
295
+ # << Pan: add 2d rope
296
+ if q_pos_emb.ndim == 5: ## 2d rope
297
+ dim = query_layer.shape[-1]
298
+ query_layer1 = apply_rotary_pos_emb(query_layer[..., :dim//2], q_pos_emb[0])
299
+ query_layer2 = apply_rotary_pos_emb(query_layer[..., dim//2:], q_pos_emb[1])
300
+ query_layer = torch.cat([query_layer1, query_layer2], axis=-1)
301
+
302
+ dim = key_layer.shape[-1]
303
+ key_layer1 = apply_rotary_pos_emb(key_layer[..., :dim//2], k_pos_emb[0])
304
+ key_layer2 = apply_rotary_pos_emb(key_layer[..., dim//2:], k_pos_emb[1])
305
+ key_layer = torch.cat([key_layer1, key_layer2], axis=-1)
306
+ else: ## 1d rope
307
+ query_layer = apply_rotary_pos_emb(query_layer, q_pos_emb)
308
+ key_layer = apply_rotary_pos_emb(key_layer, k_pos_emb)
309
+
310
+ # [sq, b, hn, c] --> [b, hn, sq, c]
311
+ query_layer = query_layer.permute(1, 2, 0, 3).contiguous()
312
+ key_layer = key_layer.permute(1, 2, 0, 3).contiguous()
313
+
314
+ use_cache = past_key_value is not None
315
+ if self.is_decoder:
316
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
317
+ # Further calls to cross_attention layer can then reuse all cross-attention
318
+ # key/value_states (first "if" case)
319
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
320
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
321
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
322
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
323
+ past_key_value = (key_layer, value_layer)
324
+
325
+ ######### << Pan: FlashAttention implementation
326
+ if output_attentions or head_mask is not None:
327
+ # Don't use FA
328
+
329
+ # Take the dot product between "query" and "key" to get the raw attention scores.
330
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
331
+
332
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
333
+ if attention_mask is not None:
334
+ # Apply the attention mask is (precomputed for all layers in FM4BioModel forward() function)
335
+ attention_scores = attention_scores + attention_mask.to(attention_scores.dtype)
336
+
337
+ # Normalize the attention scores to probabilities.
338
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
339
+
340
+ no_prob_mask = attention_mask < -1e-5
341
+ attention_probs = attention_probs.masked_fill(no_prob_mask, 0.0)
342
+ # This is actually dropping out entire tokens to attend to, which might
343
+ # seem a bit unusual, but is taken from the original Transformer paper.
344
+ attention_probs = self.dropout(attention_probs)
345
+
346
+ # Mask heads if we want to
347
+ if head_mask is not None:
348
+ attention_probs = attention_probs * head_mask
349
+
350
+ context_layer = torch.matmul(attention_probs, value_layer)
351
+
352
+ else:
353
+
354
+ if attention_mask is not None:
355
+ if attention_mask.shape[0] == 1: # Batch size = 1
356
+ attention_mask = None
357
+ else:
358
+ attention_mask = attention_mask.clone()
359
+ if torch.is_floating_point(attention_mask):
360
+ attention_mask[attention_mask < -1e-5] = torch.finfo(attention_mask.dtype).min
361
+ if torch.allclose(attention_mask, torch.zeros_like(attention_mask)):
362
+ attention_mask = None
363
+
364
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer, attn_mask=attention_mask, dropout_p=self.dropout.p, is_causal=False, scale=None, enable_gqa=False)
365
+
366
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
367
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
368
+ context_layer = context_layer.view(new_context_layer_shape)
369
+
370
+ outputs = (
371
+ (context_layer, attention_probs) if output_attentions else (context_layer,)
372
+ )
373
+
374
+ if self.is_decoder:
375
+ outputs = outputs + (past_key_value,)
376
+ return outputs
377
+
378
+
379
+ # Based transformers.models.bert.modeling_bert.BertSelfOutput. Moved LayerNorm to FM4BioAttention below.
380
+ class FM4BioSelfOutput(nn.Module):
381
+ def __init__(self, config):
382
+ super().__init__()
383
+ self.dense = nn.Linear(
384
+ config.hidden_size, config.hidden_size, bias=config.add_linear_bias
385
+ )
386
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
387
+
388
+ def forward(
389
+ self, hidden_states: torch.Tensor, residual: torch.Tensor
390
+ ) -> torch.Tensor:
391
+ hidden_states = self.dense(hidden_states)
392
+ hidden_states = self.dropout(hidden_states)
393
+ return residual + hidden_states
394
+
395
+
396
+ # Based transformers.models.bert.modeling_bert.BertAttention. Added LayerNorm.
397
+ class FM4BioAttention(nn.Module):
398
+ def __init__(self, config):
399
+ super().__init__()
400
+ self.ln = config.norm_cls(config.hidden_size, eps=config.layer_norm_eps)
401
+
402
+ self.self = FM4BioSelfAttention(config)
403
+ self.output = FM4BioSelfOutput(config)
404
+ self.pruned_heads = set()
405
+
406
+ def prune_heads(self, heads):
407
+ if len(heads) == 0:
408
+ return
409
+ heads, index = find_pruneable_heads_and_indices(
410
+ heads,
411
+ self.self.num_attention_heads,
412
+ self.self.attention_head_size,
413
+ self.pruned_heads,
414
+ )
415
+
416
+ # Prune linear layers
417
+ self.self.query = prune_linear_layer(self.self.query, index)
418
+ self.self.key = prune_linear_layer(self.self.key, index)
419
+ self.self.value = prune_linear_layer(self.self.value, index)
420
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
421
+
422
+ # Update hyper params and store pruned heads
423
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
424
+ self.self.all_head_size = (
425
+ self.self.attention_head_size * self.self.num_attention_heads
426
+ )
427
+ self.pruned_heads = self.pruned_heads.union(heads)
428
+
429
+ def forward(
430
+ self,
431
+ hidden_states: torch.Tensor,
432
+ attention_mask: Optional[torch.FloatTensor] = None,
433
+ head_mask: Optional[torch.FloatTensor] = None,
434
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
435
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
436
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
437
+ output_attentions: Optional[bool] = False,
438
+ rotary_pos_emb=None,
439
+ ) -> Tuple[torch.Tensor]:
440
+ # debug_point1 = hidden_states[0]
441
+ ln_outputs = self.ln(hidden_states)
442
+ self_outputs = self.self(
443
+ ln_outputs,
444
+ attention_mask,
445
+ head_mask,
446
+ encoder_hidden_states,
447
+ encoder_attention_mask,
448
+ past_key_value,
449
+ output_attentions,
450
+ rotary_pos_emb,
451
+ )
452
+ attention_output = self.output(self_outputs[0], hidden_states)
453
+ outputs = (attention_output,) + self_outputs[
454
+ 1:
455
+ ] # add attentions if we output them
456
+ return outputs
457
+
458
+
459
+ def _config_to_kwargs(args):
460
+ # << Pan: support string input for torch_dtype
461
+ if isinstance(args.torch_dtype, str):
462
+ torch_dtype = eval(args.torch_dtype)
463
+ else:
464
+ torch_dtype = args.torch_dtype
465
+ common_kwargs = {
466
+ "dtype": torch_dtype,
467
+ }
468
+ return common_kwargs
469
+
470
+
471
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->FM4Bio
472
+ class FM4BioMLP(nn.Module):
473
+ # def __init__(self, config: FM4BioConfig):
474
+ # super().__init__()
475
+ # assert config.hidden_act == "swiglu", "Only swiglu is supported."
476
+ # self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.add_linear_bias)
477
+ # self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.add_linear_bias)
478
+ # self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.add_linear_bias)
479
+ # self.intermediate_act_fn = ACT2FN['silu'] # swiglu use silu as part of its activation function
480
+
481
+ # def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
482
+ # down_proj = self.down_proj(self.intermediate_act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
483
+ # return down_proj
484
+
485
+ def __init__(self, config: FM4BioConfig, device=None):
486
+ super(FM4BioMLP, self).__init__()
487
+
488
+ self.add_bias = config.add_linear_bias
489
+ self.moe = config.moe
490
+ self.num_experts = config.num_experts
491
+ self.experts_per_token = config.experts_per_token # 2
492
+
493
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
494
+ self.dense_h_to_4h = nn.Linear(
495
+ config.hidden_size,
496
+ config.intermediate_size * 2,
497
+ bias=self.add_bias,
498
+ device=device,
499
+ **_config_to_kwargs(config),
500
+ )
501
+
502
+ def swiglu(x):
503
+ x = torch.chunk(x, 2, dim=-1)
504
+ return x[0] * F.silu(x[1])
505
+
506
+ def geglu(x):
507
+ x = torch.chunk(x, 2, dim=-1)
508
+ return x[0] * F.gelu(x[1])
509
+
510
+ if config.hidden_act == "geglu":
511
+ self.activation_func = geglu
512
+ elif config.hidden_act == "swiglu":
513
+ self.activation_func = swiglu
514
+ else:
515
+ assert RuntimeError(f"Unsupported glu_activation: {config.hidden_act}")
516
+
517
+ # Project back to h.
518
+ self.dense_4h_to_h = nn.Linear(
519
+ config.intermediate_size,
520
+ config.hidden_size,
521
+ bias=self.add_bias,
522
+ device=device,
523
+ **_config_to_kwargs(config),
524
+ )
525
+
526
+ if self.moe:
527
+ assert self.num_experts > 1
528
+ del self.dense_h_to_4h
529
+ del self.dense_4h_to_h
530
+ self.router = nn.Linear(
531
+ config.hidden_size,
532
+ config.num_experts,
533
+ bias=False,
534
+ device=device,
535
+ dtype=torch.float32,
536
+ )
537
+ for i in range(0, self.num_experts):
538
+ self.register_module(
539
+ f"dense_h_to_4h_{i}",
540
+ nn.Linear(
541
+ config.hidden_size,
542
+ config.intermediate_size * 2,
543
+ bias=self.add_bias,
544
+ device=device,
545
+ **_config_to_kwargs(config),
546
+ ),
547
+ )
548
+ self.register_module(
549
+ f"dense_4h_to_h_{i}",
550
+ nn.Linear(
551
+ config.intermediate_size,
552
+ config.hidden_size,
553
+ bias=self.add_bias,
554
+ device=device,
555
+ **_config_to_kwargs(config),
556
+ ),
557
+ )
558
+
559
+ def moe_forward(self, hidden_states, expert_idx):
560
+ intermediate_parallel = getattr(self, f"dense_h_to_4h_{expert_idx}")(
561
+ hidden_states
562
+ )
563
+ intermediate_parallel = self.activation_func(intermediate_parallel)
564
+ output = getattr(self, f"dense_4h_to_h_{expert_idx}")(intermediate_parallel)
565
+ return output
566
+
567
+ def forward(self, hidden_states):
568
+ if self.moe:
569
+ # import pdb; pdb.set_trace();
570
+ s, b, n = hidden_states.shape
571
+ dtype = hidden_states.dtype
572
+ hidden_states = hidden_states.view(-1, hidden_states.size(2)) # [s*b h]
573
+ ## <<< Pan: router model dtype must be float32
574
+ self.router = self.router.float()
575
+ route = self.router(hidden_states.float()).to(dtype)
576
+
577
+ weights, selected_experts = torch.topk(route, self.experts_per_token)
578
+ weights = F.softmax(weights, dim=1, dtype=torch.float).to(
579
+ hidden_states.dtype
580
+ )
581
+ ## << Ning: trace moe weight and assignment
582
+ if getattr(self, "trace_moe", False):
583
+ # 保存本层最后一次前向的权重与索引(按需放CPU,避免显存占用)
584
+ self.last_moe_weights = weights.detach() # 形状: [N, K] 或 [B, T, K]
585
+ self.last_moe_indices = selected_experts.detach() # 形状: 同上
586
+
587
+ output = torch.zeros_like(
588
+ hidden_states, dtype=hidden_states.dtype, device=hidden_states.device
589
+ )
590
+ for expert_idx in range(self.num_experts):
591
+ batch_idx, nth_expert = torch.where(selected_experts == expert_idx)
592
+ if nth_expert.shape[0] == 0:
593
+ continue
594
+ cur_out = self.moe_forward(hidden_states[batch_idx], expert_idx)
595
+ output[batch_idx] += weights[batch_idx, nth_expert, None] * cur_out
596
+ output = output.reshape(s, b, n)
597
+ else:
598
+ # [s, b, 4hp]
599
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
600
+ intermediate_parallel = self.activation_func(intermediate_parallel)
601
+ # [s, b, h]
602
+ output = self.dense_4h_to_h(intermediate_parallel)
603
+ return output
604
+
605
+
606
+ # Based on transformers.models.bert.modeling_bert.BertOutput. Moved LayerNorm to FM4BioLayer below.
607
+ class FM4BioOutput(nn.Module):
608
+ def __init__(self, config):
609
+ super().__init__()
610
+ # self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
611
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
612
+
613
+ def forward(
614
+ self, hidden_states: torch.Tensor, input_tensor: torch.Tensor
615
+ ) -> torch.Tensor:
616
+ # hidden_states = self.dense(hidden_states)
617
+ hidden_states = self.dropout(hidden_states)
618
+ return input_tensor + hidden_states
619
+
620
+
621
+ # Based on transformers.models.bert.modeling_bert.BertLayer. Added LayerNorm.
622
+ class FM4BioLayer(nn.Module):
623
+ def __init__(self, config):
624
+ super().__init__()
625
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
626
+ self.seq_len_dim = 1
627
+ self.attention = FM4BioAttention(config)
628
+ self.is_decoder = config.is_decoder
629
+ self.add_cross_attention = config.add_cross_attention
630
+ if self.add_cross_attention:
631
+ if not self.is_decoder:
632
+ raise TypeError(
633
+ f"{self} should be used as a decoder model if cross attention is added"
634
+ )
635
+ self.crossattention = FM4BioAttention(config)
636
+ self.ln = config.norm_cls(config.hidden_size, eps=config.layer_norm_eps)
637
+ self.mlp = FM4BioMLP(config)
638
+ self.output = FM4BioOutput(config)
639
+
640
+ def forward(
641
+ self,
642
+ hidden_states: torch.Tensor,
643
+ attention_mask: Optional[torch.FloatTensor] = None,
644
+ head_mask: Optional[torch.FloatTensor] = None,
645
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
646
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
647
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
648
+ output_attentions: Optional[bool] = False,
649
+ rotary_pos_emb=None,
650
+ ) -> Tuple[torch.Tensor]:
651
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
652
+ self_attn_past_key_value = (
653
+ past_key_value[:2] if past_key_value is not None else None
654
+ )
655
+ self_attention_outputs = self.attention(
656
+ hidden_states,
657
+ attention_mask,
658
+ head_mask,
659
+ output_attentions=output_attentions,
660
+ past_key_value=self_attn_past_key_value,
661
+ rotary_pos_emb=rotary_pos_emb,
662
+ )
663
+ attention_output = self_attention_outputs[0]
664
+
665
+ # if decoder, the last output is tuple of self-attn cache
666
+ if self.is_decoder:
667
+ outputs = self_attention_outputs[1:-1]
668
+ present_key_value = self_attention_outputs[-1]
669
+ else:
670
+ outputs = self_attention_outputs[
671
+ 1:
672
+ ] # add self attentions if we output attention weights
673
+
674
+ cross_attn_present_key_value = None
675
+ if self.is_decoder and encoder_hidden_states is not None:
676
+ if not hasattr(self, "crossattention"):
677
+ raise AttributeError(
678
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
679
+ " by setting `config.add_cross_attention=True`"
680
+ )
681
+
682
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
683
+ cross_attn_past_key_value = (
684
+ past_key_value[-2:] if past_key_value is not None else None
685
+ )
686
+ cross_attention_outputs = self.crossattention(
687
+ attention_output,
688
+ attention_mask,
689
+ head_mask,
690
+ encoder_hidden_states,
691
+ encoder_attention_mask,
692
+ cross_attn_past_key_value,
693
+ output_attentions,
694
+ )
695
+ attention_output = cross_attention_outputs[0]
696
+ outputs = (
697
+ outputs + cross_attention_outputs[1:-1]
698
+ ) # add cross attentions if we output attention weights
699
+
700
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
701
+ cross_attn_present_key_value = cross_attention_outputs[-1]
702
+ present_key_value = present_key_value + cross_attn_present_key_value
703
+
704
+ layer_output = apply_chunking_to_forward(
705
+ self.feed_forward_chunk,
706
+ self.chunk_size_feed_forward,
707
+ self.seq_len_dim,
708
+ attention_output,
709
+ )
710
+ outputs = (layer_output,) + outputs
711
+
712
+ # if decoder, return the attn key/values as the last output
713
+ if self.is_decoder:
714
+ outputs = outputs + (present_key_value,)
715
+
716
+ return outputs
717
+
718
+ def feed_forward_chunk(self, attention_output):
719
+ # debug: attention_output[0]
720
+ ln_output = self.ln(attention_output)
721
+ mlp_output = self.mlp(ln_output)
722
+ layer_output = self.output(mlp_output, attention_output)
723
+ return layer_output
724
+
725
+
726
+ class RnaRMSNorm(nn.Module):
727
+ def __init__(self, hidden_size, eps=1e-6):
728
+ """
729
+ same as LlamaRMSNorm
730
+ """
731
+ super().__init__()
732
+ self.weight = nn.Parameter(torch.ones(hidden_size))
733
+ self.variance_epsilon = eps
734
+
735
+ def forward(self, hidden_states):
736
+ input_dtype = hidden_states.dtype
737
+ hidden_states = hidden_states.to(torch.float32)
738
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
739
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
740
+ return self.weight * hidden_states.to(input_dtype)
741
+
742
+
743
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
744
+
745
+ ALL_LAYERNORM_LAYERS.append(RnaRMSNorm)
746
+
747
+
748
+ class FM4BioEncoder(nn.Module):
749
+ def __init__(self, config):
750
+ super().__init__()
751
+ self.config = config
752
+ self.layer = nn.ModuleList(
753
+ [FM4BioLayer(config) for _ in range(config.num_hidden_layers)]
754
+ )
755
+
756
+ # The final layer norm. We removed the 1st LN, moved LN to each hidden layer and this one
757
+ # is simply the final LN (Transformer's BERT has it attached to each hidden layer).
758
+ self.ln = config.norm_cls(config.hidden_size, eps=config.layer_norm_eps)
759
+ self.gradient_checkpointing = False
760
+
761
+ def forward(
762
+ self,
763
+ hidden_states: torch.Tensor,
764
+ attention_mask: Optional[torch.FloatTensor] = None,
765
+ head_mask: Optional[torch.FloatTensor] = None,
766
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
767
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
768
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
769
+ use_cache: Optional[bool] = None,
770
+ output_attentions: Optional[bool] = False,
771
+ output_hidden_states: Optional[bool] = False,
772
+ return_dict: Optional[bool] = True,
773
+ rotary_pos_emb: Optional[torch.FloatTensor] = None,
774
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
775
+ if self.gradient_checkpointing and self.training:
776
+ if use_cache:
777
+ logger.warning_once(
778
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
779
+ )
780
+ use_cache = False
781
+ all_hidden_states = () if output_hidden_states else None
782
+ all_self_attentions = () if output_attentions else None
783
+ all_cross_attentions = (
784
+ () if output_attentions and self.config.add_cross_attention else None
785
+ )
786
+
787
+ next_decoder_cache = () if use_cache else None
788
+ for i, layer_module in enumerate(self.layer):
789
+ if output_hidden_states:
790
+ all_hidden_states = all_hidden_states + (hidden_states,)
791
+
792
+ layer_head_mask = head_mask[i] if head_mask is not None else None
793
+ past_key_value = past_key_values[i] if past_key_values is not None else None
794
+
795
+ if self.gradient_checkpointing and self.training:
796
+ # layer_outputs = self._gradient_checkpointing_func(
797
+ # layer_module.__call__,
798
+ # hidden_states,
799
+ # attention_mask,
800
+ # layer_head_mask,
801
+ # encoder_hidden_states,
802
+ # encoder_attention_mask,
803
+ # past_key_value,
804
+ # output_attentions,
805
+ # rotary_pos_emb,
806
+ # )
807
+ # <<< Pan: use gradient checkpoint
808
+ # If use the self._gradient_checkpointing_func version. program will abord with parameters used twice error for fold prediction task
809
+ layer_outputs = get_checkpoint_fn()(
810
+ layer_module,
811
+ hidden_states,
812
+ attention_mask,
813
+ layer_head_mask,
814
+ encoder_hidden_states,
815
+ encoder_attention_mask,
816
+ past_key_value,
817
+ output_attentions,
818
+ rotary_pos_emb,
819
+ )
820
+ else:
821
+ layer_outputs = layer_module(
822
+ hidden_states,
823
+ attention_mask,
824
+ layer_head_mask,
825
+ encoder_hidden_states,
826
+ encoder_attention_mask,
827
+ past_key_value,
828
+ output_attentions,
829
+ rotary_pos_emb,
830
+ )
831
+
832
+ # Because we moved the layer-norm at the end of the hidden layer, we have non-normali-
833
+ # zed data here. If that's really needed, we must apply LN to match Transformer's BERT.
834
+
835
+ hidden_states = layer_outputs[0]
836
+ if use_cache:
837
+ next_decoder_cache += (layer_outputs[-1],)
838
+ if output_attentions:
839
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
840
+ if self.config.add_cross_attention:
841
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
842
+
843
+ # Finalize the hidden states.
844
+ hidden_states = self.ln(hidden_states)
845
+
846
+ if output_hidden_states:
847
+ all_hidden_states = all_hidden_states + (hidden_states,)
848
+
849
+ if not return_dict:
850
+ return tuple(
851
+ v
852
+ for v in [
853
+ hidden_states,
854
+ next_decoder_cache,
855
+ all_hidden_states,
856
+ all_self_attentions,
857
+ all_cross_attentions,
858
+ ]
859
+ if v is not None
860
+ )
861
+ return BaseModelOutputWithPastAndCrossAttentions(
862
+ last_hidden_state=hidden_states,
863
+ past_key_values=next_decoder_cache,
864
+ hidden_states=all_hidden_states,
865
+ attentions=all_self_attentions,
866
+ cross_attentions=all_cross_attentions,
867
+ )
868
+
869
+
870
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->FM4Bio
871
+ class FM4BioPooler(nn.Module):
872
+ def __init__(self, config):
873
+ super().__init__()
874
+ self.dense = nn.Linear(
875
+ config.hidden_size, config.hidden_size, bias=config.add_linear_bias
876
+ )
877
+ self.activation = nn.Tanh()
878
+
879
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
880
+ # We "pool" the model by simply taking the hidden state corresponding
881
+ # to the first token.
882
+ first_token_tensor = hidden_states[:, 0]
883
+ pooled_output = self.dense(first_token_tensor)
884
+ pooled_output = self.activation(pooled_output)
885
+ return pooled_output
886
+
887
+
888
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->FM4Bio
889
+ class FM4BioPredictionHeadTransform(nn.Module):
890
+ def __init__(self, config):
891
+ super().__init__()
892
+ self.dense = nn.Linear(
893
+ config.hidden_size, config.hidden_size
894
+ ) # in megatron, this will always have bias
895
+
896
+ self.transform_act_fn = ACT2FN["gelu"]
897
+
898
+ if config.normalization_type == "RMSNorm":
899
+ self.LayerNorm = RnaRMSNorm(config.hidden_size, eps=config.layer_norm_eps)
900
+ else:
901
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
902
+
903
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
904
+ hidden_states = self.dense(hidden_states)
905
+ hidden_states = self.transform_act_fn(hidden_states)
906
+ hidden_states = self.LayerNorm(hidden_states)
907
+ return hidden_states
908
+
909
+
910
+ # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->FM4Bio
911
+ class FM4BioLMPredictionHead(nn.Module):
912
+ def __init__(self, config):
913
+ super().__init__()
914
+ self.transform = FM4BioPredictionHeadTransform(config)
915
+
916
+ # The output weights are the same as the input embeddings, but there is
917
+ # an output-only bias for each token.
918
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
919
+
920
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
921
+
922
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
923
+ self.decoder.bias = self.bias
924
+
925
+ def forward(self, hidden_states):
926
+ hidden_states = self.transform(hidden_states)
927
+ hidden_states = self.decoder(hidden_states)
928
+ return hidden_states
929
+
930
+
931
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->FM4Bio
932
+ class FM4BioOnlyMLMHead(nn.Module):
933
+ def __init__(self, config):
934
+ super().__init__()
935
+ self.predictions = FM4BioLMPredictionHead(config)
936
+
937
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
938
+ prediction_scores = self.predictions(sequence_output)
939
+ return prediction_scores
940
+
941
+
942
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->FM4Bio
943
+ class FM4BioPreTrainingHeads(nn.Module):
944
+ def __init__(self, config):
945
+ super().__init__()
946
+ self.predictions = FM4BioLMPredictionHead(config)
947
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
948
+
949
+ def forward(self, sequence_output, pooled_output):
950
+ prediction_scores = self.predictions(sequence_output)
951
+ seq_relationship_score = self.seq_relationship(pooled_output)
952
+ return prediction_scores, seq_relationship_score
953
+
954
+
955
+ class FM4BioPreTrainedModel(PreTrainedModel):
956
+ """
957
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
958
+ models.
959
+ """
960
+
961
+ config_class = FM4BioConfig
962
+ # load_tf_weights = load_tf_weights_in_fm4bio
963
+ base_model_prefix = "bert"
964
+ supports_gradient_checkpointing = True
965
+ _no_split_modules = [
966
+ "FM4BioLayer",
967
+ "FM4BioEmbeddings",
968
+ "FM4BioMLP",
969
+ ] # should not be on different machines
970
+
971
+ def _init_weights(self, module):
972
+ """Initialize the weights"""
973
+ if isinstance(module, (nn.Linear, nn.Embedding)):
974
+ # Slightly different from the TF version which uses truncated_normal for initialization
975
+ # cf https://github.com/pytorch/pytorch/pull/5617
976
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
977
+ elif isinstance(module, nn.LayerNorm):
978
+ module.bias.data.zero_()
979
+ module.weight.data.fill_(1.0)
980
+ elif isinstance(module, RnaRMSNorm):
981
+ module.weight.data.fill_(1.0)
982
+ # no bias
983
+ if isinstance(module, nn.Linear) and module.bias is not None:
984
+ module.bias.data.zero_()
985
+
986
+
987
+ @dataclass
988
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTrainingOutput with Bert->FM4Bio
989
+ class FM4BioForPreTrainingOutput(ModelOutput):
990
+ """
991
+ Output type of [`FM4BioForPreTraining`].
992
+
993
+ Args:
994
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
995
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
996
+ (classification) loss.
997
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
998
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
999
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
1000
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
1001
+ before SoftMax).
1002
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1003
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
1004
+ shape `(batch_size, sequence_length, hidden_size)`.
1005
+
1006
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
1007
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1008
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1009
+ sequence_length)`.
1010
+
1011
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
1012
+ heads.
1013
+ """
1014
+
1015
+ loss: Optional[torch.FloatTensor] = None
1016
+ prediction_logits: torch.FloatTensor = None
1017
+ seq_relationship_logits: torch.FloatTensor = None
1018
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1019
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1020
+
1021
+
1022
+ FM4BIO_START_DOCSTRING = r"""
1023
+
1024
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1025
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1026
+ etc.)
1027
+
1028
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1029
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1030
+ and behavior.
1031
+
1032
+ Parameters:
1033
+ config ([`FM4BioConfig`]): Model configuration class with all the parameters of the model.
1034
+ Initializing with a config file does not load the weights associated with the model, only the
1035
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1036
+ """
1037
+
1038
+ FM4BIO_INPUTS_DOCSTRING = r"""
1039
+ Args:
1040
+ input_ids (`torch.LongTensor` of shape `({0})`):
1041
+ Indices of input sequence tokens in the vocabulary.
1042
+
1043
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1044
+ [`PreTrainedTokenizer.__call__`] for details.
1045
+
1046
+ [What are input IDs?](../glossary#input-ids)
1047
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
1048
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1049
+
1050
+ - 1 for tokens that are **not masked**,
1051
+ - 0 for tokens that are **masked**.
1052
+
1053
+ [What are attention masks?](../glossary#attention-mask)
1054
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
1055
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1056
+ 1]`:
1057
+
1058
+ - 0 corresponds to a *sentence A* token,
1059
+ - 1 corresponds to a *sentence B* token.
1060
+
1061
+ [What are token type IDs?](../glossary#token-type-ids)
1062
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
1063
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1064
+ config.max_position_embeddings - 1]`.
1065
+
1066
+ [What are position IDs?](../glossary#position-ids)
1067
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1068
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1069
+
1070
+ - 1 indicates the head is **not masked**,
1071
+ - 0 indicates the head is **masked**.
1072
+
1073
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
1074
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1075
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1076
+ model's internal embedding lookup matrix.
1077
+ output_attentions (`bool`, *optional*):
1078
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1079
+ tensors for more detail.
1080
+ output_hidden_states (`bool`, *optional*):
1081
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1082
+ more detail.
1083
+ return_dict (`bool`, *optional*):
1084
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1085
+ """
1086
+
1087
+
1088
+ @add_start_docstrings(
1089
+ "The bare FM4Bio Model transformer outputting raw hidden-states without any specific head on top.",
1090
+ FM4BIO_START_DOCSTRING,
1091
+ )
1092
+ class FM4BioModel(FM4BioPreTrainedModel):
1093
+ """
1094
+
1095
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
1096
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
1097
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
1098
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
1099
+
1100
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
1101
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
1102
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
1103
+ """
1104
+
1105
+ def __init__(self, config, add_pooling_layer=False):
1106
+ super().__init__(config)
1107
+ self.config = config
1108
+ if config.normalization_type == "RMSNorm":
1109
+ self.config.norm_cls = RnaRMSNorm
1110
+ else:
1111
+ assert config.normalization_type == "LayerNorm"
1112
+ self.config.norm_cls = nn.LayerNorm
1113
+ self.embeddings = FM4BioEmbeddings(config)
1114
+ self.encoder = FM4BioEncoder(config)
1115
+
1116
+ self.pooler = FM4BioPooler(config) if add_pooling_layer else None
1117
+
1118
+ # rotary position embeddings
1119
+ if config.position_embedding_type == "rope":
1120
+ rotary_dim = config.hidden_size // config.num_attention_heads
1121
+
1122
+ # partial rotary embeddings, which is better than full rotary
1123
+ # Wang and Komatsuzaki et al
1124
+ # https://github.com/kingoflolz/mesh-transformer-jax/
1125
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim, config.rotary_percent)
1126
+
1127
+ # << Pan: add 2D rope
1128
+ elif config.position_embedding_type == "rope_2d":
1129
+ rotary_dim = config.hidden_size // config.num_attention_heads // 2
1130
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim, config.rotary_percent)
1131
+
1132
+ # delete this from config so the config can be successfully saved
1133
+ del self.config.norm_cls
1134
+
1135
+ # Initialize weights and apply final processing
1136
+ self.post_init()
1137
+
1138
+ def get_input_embeddings(self):
1139
+ return self.embeddings.word_embeddings
1140
+
1141
+ def set_input_embeddings(self, value):
1142
+ self.embeddings.word_embeddings = value
1143
+
1144
+ def _prune_heads(self, heads_to_prune):
1145
+ """
1146
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1147
+ class PreTrainedModel
1148
+ """
1149
+ for layer, heads in heads_to_prune.items():
1150
+ self.encoder.layer[layer].attention.prune_heads(heads)
1151
+
1152
+ @add_start_docstrings_to_model_forward(
1153
+ FM4BIO_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1154
+ )
1155
+ @add_code_sample_docstrings(
1156
+ checkpoint=_CHECKPOINT_FOR_DOC,
1157
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
1158
+ config_class=_CONFIG_FOR_DOC,
1159
+ )
1160
+ def forward(
1161
+ self,
1162
+ input_ids: Optional[torch.LongTensor] = None,
1163
+ attention_mask: Optional[torch.FloatTensor] = None,
1164
+ token_type_ids: Optional[torch.LongTensor] = None,
1165
+ position_ids: Optional[torch.LongTensor] = None,
1166
+ head_mask: Optional[torch.FloatTensor] = None,
1167
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1168
+ inputs_str_embeds: Optional[torch.FloatTensor] = None, # << Pan: input structure embedding
1169
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1170
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1171
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1172
+ use_cache: Optional[bool] = None,
1173
+ output_attentions: Optional[bool] = None,
1174
+ output_hidden_states: Optional[bool] = None,
1175
+ return_dict: Optional[bool] = None,
1176
+ ) -> Union[Tuple, BaseModelOutputWithPoolingAndCrossAttentions]:
1177
+ r"""
1178
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1179
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1180
+ the model is configured as a decoder.
1181
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1182
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1183
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1184
+
1185
+ - 1 for tokens that are **not masked**,
1186
+ - 0 for tokens that are **masked**.
1187
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1188
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1189
+
1190
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1191
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1192
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1193
+ use_cache (`bool`, *optional*):
1194
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1195
+ `past_key_values`).
1196
+ """
1197
+ output_attentions = (
1198
+ output_attentions
1199
+ if output_attentions is not None
1200
+ else self.config.output_attentions
1201
+ )
1202
+ output_hidden_states = (
1203
+ output_hidden_states
1204
+ if output_hidden_states is not None
1205
+ else self.config.output_hidden_states
1206
+ )
1207
+ return_dict = (
1208
+ return_dict if return_dict is not None else self.config.use_return_dict
1209
+ )
1210
+
1211
+ if self.config.is_decoder:
1212
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1213
+ else:
1214
+ use_cache = False
1215
+
1216
+ if input_ids is not None and inputs_embeds is not None:
1217
+ raise ValueError(
1218
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1219
+ )
1220
+ elif input_ids is not None:
1221
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1222
+ input_shape = input_ids.size()
1223
+ elif inputs_embeds is not None:
1224
+ input_shape = inputs_embeds.size()[:-1]
1225
+ else:
1226
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1227
+
1228
+ batch_size, seq_length = input_shape
1229
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1230
+
1231
+ # past_key_values_length
1232
+ past_key_values_length = (
1233
+ past_key_values[0][0].shape[2] if past_key_values is not None else 0
1234
+ )
1235
+
1236
+ if attention_mask is None:
1237
+ attention_mask = torch.ones(
1238
+ ((batch_size, seq_length + past_key_values_length)), device=device
1239
+ )
1240
+ if token_type_ids is None:
1241
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
1242
+
1243
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
1244
+ # ourselves in which case we just need to make it broadcastable to all heads.
1245
+ # extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
1246
+ extended_attention_mask = bert_extended_attention_mask(
1247
+ attention_mask
1248
+ ) # True for pad, false for non-pad
1249
+ extended_attention_mask = extended_attention_mask * torch.finfo(torch.float).min
1250
+
1251
+ # If a 2D or 3D attention mask is provided for the cross-attention
1252
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1253
+ if self.config.is_decoder and encoder_hidden_states is not None:
1254
+ encoder_batch_size, encoder_sequence_length, _ = (
1255
+ encoder_hidden_states.size()
1256
+ )
1257
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1258
+ if encoder_attention_mask is None:
1259
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
1260
+ encoder_extended_attention_mask = self.invert_attention_mask(
1261
+ encoder_attention_mask
1262
+ )
1263
+ else:
1264
+ encoder_extended_attention_mask = None
1265
+
1266
+ # Prepare head mask if needed
1267
+ # 1.0 in head_mask indicate we keep the head
1268
+ # attention_probs has shape bsz x n_heads x N x N
1269
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1270
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1271
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1272
+
1273
+ if os.environ.get("DEBUG", "FALSE") == "TRUE":
1274
+ if torch.distributed.get_rank() == 0:
1275
+ breakpoint()
1276
+ torch.distributed.barrier()
1277
+
1278
+ # Rotary positional embeddings
1279
+ rotary_pos_emb = None
1280
+ if self.config.position_embedding_type == "rope":
1281
+ rotary_pos_emb = self.rotary_pos_emb(input_ids.size(1))
1282
+ # << Pan: rope_2d
1283
+ elif self.config.position_embedding_type == 'rope_2d':
1284
+ # input_ids: [1, 12800]
1285
+ # position_ids: [B, 2, 12800]
1286
+ # breakpoint()
1287
+ rotary_pos_emb = self.rotary_pos_emb(input_ids.size(1)).squeeze(1) # [12800, 1, 1, D//H] -> [12800, 1, D//H//2]
1288
+ rotary_pos_emb = rotary_pos_emb[ position_ids ] # [12800, 1, D//H] -> [B, 2, 12800, 1, D//H//2]
1289
+ rotary_pos_emb = rotary_pos_emb.permute([1,2,0,3,4]) # [2, 12800, B, 1, D//H//2]
1290
+
1291
+ if os.environ.get("DEBUG", "FALSE") == "TRUE":
1292
+ if torch.distributed.get_rank() == 0:
1293
+ breakpoint()
1294
+ torch.distributed.barrier()
1295
+
1296
+ embedding_output = self.embeddings(
1297
+ input_ids=input_ids,
1298
+ position_ids=position_ids,
1299
+ token_type_ids=token_type_ids,
1300
+ inputs_embeds=inputs_embeds,
1301
+ inputs_str_embeds=inputs_str_embeds, # << Pan: input structure embedding
1302
+ past_key_values_length=past_key_values_length,
1303
+ )
1304
+
1305
+ if os.environ.get("DEBUG", "FALSE") == "TRUE":
1306
+ if torch.distributed.get_rank() == 0:
1307
+ breakpoint()
1308
+ torch.distributed.barrier()
1309
+
1310
+ encoder_outputs = self.encoder(
1311
+ embedding_output,
1312
+ attention_mask=extended_attention_mask,
1313
+ head_mask=head_mask,
1314
+ encoder_hidden_states=encoder_hidden_states,
1315
+ encoder_attention_mask=encoder_extended_attention_mask,
1316
+ past_key_values=past_key_values,
1317
+ use_cache=use_cache,
1318
+ output_attentions=output_attentions,
1319
+ output_hidden_states=output_hidden_states,
1320
+ return_dict=return_dict,
1321
+ rotary_pos_emb=rotary_pos_emb,
1322
+ )
1323
+
1324
+ if os.environ.get("DEBUG", "FALSE") == "TRUE":
1325
+ if torch.distributed.get_rank() == 0:
1326
+ breakpoint()
1327
+ torch.distributed.barrier()
1328
+
1329
+ sequence_output = encoder_outputs[0]
1330
+ pooled_output = (
1331
+ self.pooler(sequence_output) if self.pooler is not None else None
1332
+ )
1333
+
1334
+ if not return_dict:
1335
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1336
+
1337
+ if os.environ.get("DEBUG", "FALSE") == "TRUE":
1338
+ if torch.distributed.get_rank() == 0:
1339
+ breakpoint()
1340
+ torch.distributed.barrier()
1341
+
1342
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1343
+ last_hidden_state=sequence_output,
1344
+ pooler_output=pooled_output,
1345
+ past_key_values=encoder_outputs.past_key_values,
1346
+ hidden_states=encoder_outputs.hidden_states,
1347
+ attentions=encoder_outputs.attentions,
1348
+ cross_attentions=encoder_outputs.cross_attentions,
1349
+ )
1350
+
1351
+
1352
+ @add_start_docstrings(
1353
+ """
1354
+ FM4Bio Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
1355
+ `next sentence prediction (classification)` head.
1356
+ """,
1357
+ FM4BIO_START_DOCSTRING,
1358
+ )
1359
+ class FM4BioForPreTraining(FM4BioPreTrainedModel):
1360
+ # _tied_weights_keys = ["cls.predictions.decoder"]
1361
+
1362
+ def __init__(self, config, add_binary_head=True):
1363
+ super().__init__(config)
1364
+
1365
+ self.bert = FM4BioModel(config)
1366
+ self.cls = FM4BioPreTrainingHeads(config)
1367
+
1368
+ # Initialize weights and apply final processing
1369
+ self.post_init()
1370
+
1371
+ def get_output_embeddings(self):
1372
+ return self.cls.predictions.decoder
1373
+
1374
+ def set_output_embeddings(self, new_embeddings):
1375
+ self.cls.predictions.decoder = new_embeddings
1376
+
1377
+ @add_start_docstrings_to_model_forward(
1378
+ FM4BIO_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1379
+ )
1380
+ @replace_return_docstrings(
1381
+ output_type=FM4BioForPreTrainingOutput, config_class=_CONFIG_FOR_DOC
1382
+ )
1383
+ def forward(
1384
+ self,
1385
+ input_ids: Optional[torch.LongTensor] = None,
1386
+ attention_mask: Optional[torch.FloatTensor] = None,
1387
+ token_type_ids: Optional[torch.LongTensor] = None,
1388
+ position_ids: Optional[torch.LongTensor] = None,
1389
+ head_mask: Optional[torch.FloatTensor] = None,
1390
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1391
+ inputs_str_embeds: Optional[torch.FloatTensor] = None, # << Pan: input structure embedding
1392
+ labels: Optional[torch.LongTensor] = None,
1393
+ next_sentence_label: Optional[torch.LongTensor] = None,
1394
+ output_attentions: Optional[bool] = None,
1395
+ output_hidden_states: Optional[bool] = None,
1396
+ return_dict: Optional[bool] = None,
1397
+ ) -> Union[Tuple, FM4BioForPreTrainingOutput]:
1398
+ r"""
1399
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1400
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1401
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1402
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1403
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1404
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1405
+ (see `input_ids` docstring) Indices should be in `[0, 1]`:
1406
+
1407
+ - 0 indicates sequence B is a continuation of sequence A,
1408
+ - 1 indicates sequence B is a random sequence.
1409
+ kwargs (`Dict[str, any]`, optional, defaults to *{}*):
1410
+ Used to hide legacy arguments that have been deprecated.
1411
+
1412
+ Returns:
1413
+
1414
+ Example:
1415
+
1416
+ ```python
1417
+ >>> from transformers import AutoTokenizer, FM4BioForPreTraining
1418
+ >>> import torch
1419
+
1420
+ >>> tokenizer = AutoTokenizer.from_pretrained("")
1421
+ >>> model = FM4BioForPreTraining.from_pretrained("")
1422
+
1423
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1424
+ >>> outputs = model(**inputs)
1425
+
1426
+ >>> prediction_logits = outputs.prediction_logits
1427
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1428
+ ```"""
1429
+ return_dict = (
1430
+ return_dict if return_dict is not None else self.config.use_return_dict
1431
+ )
1432
+
1433
+ outputs = self.bert(
1434
+ input_ids,
1435
+ attention_mask=attention_mask,
1436
+ token_type_ids=token_type_ids,
1437
+ position_ids=position_ids,
1438
+ head_mask=head_mask,
1439
+ inputs_embeds=inputs_embeds,
1440
+ inputs_str_embeds=inputs_str_embeds, # << Pan: input structure embedding
1441
+ output_attentions=output_attentions,
1442
+ output_hidden_states=output_hidden_states,
1443
+ return_dict=return_dict,
1444
+ )
1445
+
1446
+ sequence_output, pooled_output = outputs[:2]
1447
+ prediction_scores, seq_relationship_score = self.cls(
1448
+ sequence_output, pooled_output
1449
+ )
1450
+
1451
+ total_loss = None
1452
+ if labels is not None and next_sentence_label is not None:
1453
+ loss_fct = CrossEntropyLoss()
1454
+ masked_lm_loss = loss_fct(
1455
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
1456
+ )
1457
+ next_sentence_loss = loss_fct(
1458
+ seq_relationship_score.view(-1, 2), next_sentence_label.view(-1)
1459
+ )
1460
+ total_loss = masked_lm_loss + next_sentence_loss
1461
+
1462
+ if not return_dict:
1463
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1464
+ return ((total_loss,) + output) if total_loss is not None else output
1465
+
1466
+ return FM4BioForPreTrainingOutput(
1467
+ loss=total_loss,
1468
+ prediction_logits=prediction_scores,
1469
+ seq_relationship_logits=seq_relationship_score,
1470
+ hidden_states=outputs.hidden_states,
1471
+ attentions=outputs.attentions,
1472
+ )
1473
+
1474
+
1475
+ @add_start_docstrings(
1476
+ """FM4Bio Model with a `language modeling` head on top.""", FM4BIO_START_DOCSTRING
1477
+ )
1478
+ class FM4BioForMaskedLM(FM4BioPreTrainedModel):
1479
+ # _tied_weights_keys = ["cls.predictions.decoder"]
1480
+
1481
+ def __init__(self, config):
1482
+ super().__init__(config)
1483
+
1484
+ if config.is_decoder:
1485
+ logger.warning(
1486
+ "If you want to use `FM4BioForMaskedLM` make sure `config.is_decoder=False` for "
1487
+ "bi-directional self-attention."
1488
+ )
1489
+
1490
+ self.bert = FM4BioModel(config, add_pooling_layer=False)
1491
+ self.use_lm_head = config.use_lm_head
1492
+ if config.use_lm_head:
1493
+ self.cls = FM4BioOnlyMLMHead(config)
1494
+ else:
1495
+ if getattr(config, "output_vocab_size", None) is not None:
1496
+ # used when the output uses a different vocab
1497
+ # e.g., input vocab is amino acids, output vocab is structure tokens
1498
+ self.output_embed = nn.Linear(
1499
+ config.hidden_size, config.output_vocab_size, bias=False
1500
+ )
1501
+ else:
1502
+ self.output_embed = nn.Linear(
1503
+ config.hidden_size, config.vocab_size, bias=False
1504
+ )
1505
+
1506
+ # Initialize weights and apply final processing
1507
+ self.post_init()
1508
+
1509
+ def get_output_embeddings(self):
1510
+ if self.use_lm_head:
1511
+ return self.cls.predictions.decoder
1512
+ else:
1513
+ return self.output_embed
1514
+
1515
+ def set_output_embeddings(self, new_embeddings):
1516
+ if self.use_lm_head:
1517
+ self.cls.predictions.decoder = new_embeddings
1518
+ else:
1519
+ raise NotImplementedError
1520
+
1521
+ @add_start_docstrings_to_model_forward(
1522
+ FM4BIO_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1523
+ )
1524
+ @add_code_sample_docstrings(
1525
+ checkpoint=_CHECKPOINT_FOR_DOC,
1526
+ output_type=MaskedLMOutput,
1527
+ config_class=_CONFIG_FOR_DOC,
1528
+ )
1529
+ def forward(
1530
+ self,
1531
+ input_ids: Optional[torch.LongTensor] = None,
1532
+ attention_mask: Optional[torch.FloatTensor] = None,
1533
+ token_type_ids: Optional[torch.LongTensor] = None,
1534
+ position_ids: Optional[torch.LongTensor] = None,
1535
+ head_mask: Optional[torch.FloatTensor] = None,
1536
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1537
+ inputs_str_embeds: Optional[torch.FloatTensor] = None, # << Pan: input structure embedding
1538
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1539
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1540
+ labels: Optional[torch.LongTensor] = None,
1541
+ output_attentions: Optional[bool] = None,
1542
+ output_hidden_states: Optional[bool] = None,
1543
+ return_dict: Optional[bool] = None,
1544
+ ) -> Union[Tuple, MaskedLMOutput]:
1545
+ r"""
1546
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1547
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1548
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1549
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1550
+ """
1551
+
1552
+ return_dict = (
1553
+ return_dict if return_dict is not None else self.config.use_return_dict
1554
+ )
1555
+
1556
+ outputs = self.bert(
1557
+ input_ids,
1558
+ attention_mask=attention_mask,
1559
+ token_type_ids=token_type_ids,
1560
+ position_ids=position_ids,
1561
+ head_mask=head_mask,
1562
+ inputs_embeds=inputs_embeds,
1563
+ inputs_str_embeds=inputs_str_embeds, # << Pan: input structure embedding
1564
+ encoder_hidden_states=encoder_hidden_states,
1565
+ encoder_attention_mask=encoder_attention_mask,
1566
+ output_attentions=output_attentions,
1567
+ output_hidden_states=output_hidden_states,
1568
+ return_dict=return_dict,
1569
+ )
1570
+
1571
+ sequence_output = outputs[0]
1572
+ if self.use_lm_head:
1573
+ prediction_scores = self.cls(sequence_output)
1574
+ else:
1575
+ prediction_scores = self.output_embed(sequence_output)
1576
+
1577
+ masked_lm_loss = None
1578
+ if labels is not None:
1579
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1580
+ masked_lm_loss = loss_fct(
1581
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
1582
+ )
1583
+
1584
+ if not return_dict:
1585
+ output = (prediction_scores,) + outputs[2:]
1586
+ return (
1587
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1588
+ )
1589
+
1590
+ return MaskedLMOutput(
1591
+ loss=masked_lm_loss,
1592
+ logits=prediction_scores,
1593
+ hidden_states=outputs.hidden_states,
1594
+ attentions=outputs.attentions,
1595
+ )
1596
+
1597
+ def prepare_inputs_for_generation(
1598
+ self, input_ids, attention_mask=None, **model_kwargs
1599
+ ):
1600
+ input_shape = input_ids.shape
1601
+ effective_batch_size = input_shape[0]
1602
+
1603
+ # add a dummy token
1604
+ if self.config.pad_token_id is None:
1605
+ raise ValueError("The PAD token should be defined for generation")
1606
+ attention_mask = torch.cat(
1607
+ [attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))],
1608
+ dim=-1,
1609
+ )
1610
+ dummy_token = torch.full(
1611
+ (effective_batch_size, 1),
1612
+ self.config.pad_token_id,
1613
+ dtype=torch.long,
1614
+ device=input_ids.device,
1615
+ )
1616
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1617
+
1618
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1619
+
1620
+
1621
+ from torch import Tensor, nn
1622
+
1623
+
1624
+ class RotaryEmbedding(nn.Module):
1625
+ """Rotary Embedding for language model.
1626
+
1627
+ Args:
1628
+ kv_channels (int): Projection weights dimension in multi-head attention. Obtained from transformer config
1629
+ rotary_percent (float): Percent of rotary dimension to use for rotary position embeddings.
1630
+ seq_len_interpolation_factor (float, optional): scale of linearly interpolating RoPE for longer sequences. The value must be a float larger than 1.0. Defaults to None
1631
+ rotary_base (int, optional): Base period for rotary position embeddings. Defaults to 10000.
1632
+ """
1633
+
1634
+ def __init__(
1635
+ self,
1636
+ kv_channels: int,
1637
+ rotary_percent: float,
1638
+ seq_len_interpolation_factor: float = None,
1639
+ rotary_base: int = 10000,
1640
+ ) -> None:
1641
+ super().__init__()
1642
+
1643
+ dim = kv_channels
1644
+ if rotary_percent < 1.0:
1645
+ dim = int(dim * rotary_percent)
1646
+
1647
+ self.seq_len_interpolation_factor = seq_len_interpolation_factor
1648
+ device = (
1649
+ torch.cuda.current_device()
1650
+ if torch.cuda.is_available()
1651
+ else torch.device("cpu")
1652
+ )
1653
+ self.inv_freq = 1.0 / (
1654
+ rotary_base
1655
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
1656
+ )
1657
+
1658
+ def forward(self, max_seq_len: int, offset: int = 0) -> Tensor:
1659
+ """Forward pass of RoPE embedding.
1660
+
1661
+ Args:
1662
+ max_seq_len (int): Maximum size of sequence
1663
+ offset (int, optional): _description_. Defaults to 0.
1664
+
1665
+ Returns:
1666
+ Tensor: Embeddings after applying RoPE.
1667
+ """
1668
+ seq = (
1669
+ torch.arange(
1670
+ max_seq_len, device=self.inv_freq.device, dtype=self.inv_freq.dtype
1671
+ )
1672
+ + offset
1673
+ )
1674
+
1675
+ if self.seq_len_interpolation_factor is not None:
1676
+ seq *= 1 / self.seq_len_interpolation_factor
1677
+
1678
+ freqs = torch.outer(seq, self.inv_freq)
1679
+ # first part even vector components, second part odd vector components,
1680
+ # 2 * dim in dimension size
1681
+ emb = torch.cat((freqs, freqs), dim=-1)
1682
+ # emb [seq_length, .., dim]
1683
+ emb = emb[:, None, None, :]
1684
+
1685
+ return emb
1686
+
1687
+ def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs):
1688
+ state_dict.pop(f"{prefix}inv_freq", None)
1689
+ return super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)
1690
+
1691
+
1692
+ def _rotate_half(x: Tensor) -> Tensor:
1693
+ """Change sign so the last dimension becomes [-odd, +even]
1694
+
1695
+ Args:
1696
+ x (Tensor): Input tensor
1697
+
1698
+ Returns:
1699
+ Tensor: Tensor rotated half
1700
+ """
1701
+
1702
+ x1, x2 = torch.chunk(x, 2, dim=-1)
1703
+ return torch.cat((-x2, x1), dim=-1)
1704
+
1705
+
1706
+ def apply_rotary_pos_emb(t: Tensor, freqs: Tensor) -> Tensor:
1707
+ """Apply rotary positional embedding to input tensor T.
1708
+
1709
+ check https://kexue.fm/archives/8265 for detailed formulas
1710
+
1711
+ Args:
1712
+ t (Tensor): Input tensor T is of shape [seq_length, ... , dim]
1713
+ freqs (Tensor): Rotary Positional embedding tensor freq is of shape [seq_length, ..., dim]
1714
+
1715
+ Returns:
1716
+ Tensor: The input tensor after applying RoPE
1717
+ """
1718
+ rot_dim = freqs.shape[-1]
1719
+
1720
+ # ideally t_pass is empty so rotary pos embedding is applied to all tensor t
1721
+ t, t_pass = t[..., :rot_dim], t[..., rot_dim:]
1722
+
1723
+ # first part is cosine component
1724
+ # second part is sine component, need to change signs with _rotate_half method
1725
+ cos_ = torch.cos(freqs).to(t.dtype).to(t.device)
1726
+ sin_ = torch.sin(freqs).to(t.dtype).to(t.device)
1727
+
1728
+ t = (t * cos_) + (_rotate_half(t) * sin_)
1729
+ return torch.cat((t, t_pass), dim=-1)
1730
+
1731
+
1732
+ def bert_extended_attention_mask(attention_mask):
1733
+ # We create a 3D attention mask from a 2D tensor mask.
1734
+ # [b, 1, s]
1735
+ attention_mask_b1s = attention_mask.unsqueeze(1)
1736
+ # [b, s, 1]
1737
+ attention_mask_bs1 = attention_mask.unsqueeze(2)
1738
+ # [b, s, s]
1739
+ attention_mask_bss = attention_mask_b1s * attention_mask_bs1
1740
+ # [b, 1, s, s]
1741
+ extended_attention_mask = attention_mask_bss.unsqueeze(1)
1742
+
1743
+ # Convert attention mask to binary:
1744
+ extended_attention_mask = extended_attention_mask < 0.5
1745
+
1746
+ return extended_attention_mask
1747
+
1748
+
1749
+ class FM4BioForSequenceClassification(FM4BioPreTrainedModel):
1750
+ def __init__(
1751
+ self,
1752
+ config,
1753
+ arch="MLP",
1754
+ pooling="mean_pooling",
1755
+ conv_kernel_size=9,
1756
+ dropout_prob=None,
1757
+ augment_with_zeroshot=False,
1758
+ inter_hidden_size=None,
1759
+ activation_func="tanh",
1760
+ ):
1761
+ super().__init__(config)
1762
+ self.num_labels = config.num_labels
1763
+ self.config = config
1764
+ self.pooling = pooling
1765
+ self.augment_with_zeroshot = augment_with_zeroshot
1766
+ self.inter_hidden_size = inter_hidden_size
1767
+
1768
+ self.bert = FM4BioModel(config, add_pooling_layer=False)
1769
+ self.classifier = FM4BioClassificationHead(
1770
+ config,
1771
+ arch,
1772
+ pooling,
1773
+ conv_kernel_size,
1774
+ dropout_prob,
1775
+ inter_hidden_size,
1776
+ augment_with_zeroshot,
1777
+ activation_func,
1778
+ )
1779
+
1780
+ self.init_weights()
1781
+
1782
+ @add_start_docstrings_to_model_forward(
1783
+ FM4BIO_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1784
+ )
1785
+ @add_code_sample_docstrings(
1786
+ checkpoint=_CHECKPOINT_FOR_DOC,
1787
+ output_type=SequenceClassifierOutput,
1788
+ config_class=_CONFIG_FOR_DOC,
1789
+ )
1790
+ def forward(
1791
+ self,
1792
+ input_ids: Optional[torch.LongTensor] = None,
1793
+ attention_mask: Optional[torch.Tensor] = None, # (bs, seq_len), 0 means masking
1794
+ zero_shot_fitness_predictions: Optional[torch.Tensor] = None,
1795
+ position_ids: Optional[torch.LongTensor] = None,
1796
+ head_mask: Optional[torch.Tensor] = None,
1797
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1798
+ inputs_str_embeds: Optional[torch.FloatTensor] = None, # << Pan: input string embeddings
1799
+ labels: Optional[torch.LongTensor] = None,
1800
+ output_attentions: Optional[bool] = None,
1801
+ output_hidden_states: Optional[bool] = None,
1802
+ return_dict: Optional[bool] = None,
1803
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1804
+ r"""
1805
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1806
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1807
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1808
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1809
+ """
1810
+ return_dict = (
1811
+ return_dict if return_dict is not None else self.config.use_return_dict
1812
+ )
1813
+
1814
+ outputs = self.bert(
1815
+ input_ids,
1816
+ attention_mask=attention_mask,
1817
+ position_ids=position_ids,
1818
+ head_mask=head_mask,
1819
+ inputs_embeds=inputs_embeds,
1820
+ inputs_str_embeds=inputs_str_embeds, # << Pan: input string embeddings
1821
+ output_attentions=output_attentions,
1822
+ output_hidden_states=output_hidden_states,
1823
+ return_dict=return_dict,
1824
+ )
1825
+
1826
+ sequence_output = outputs[0] # (bs, seq_len, hidden_size)
1827
+ logits = self.classifier(
1828
+ sequence_output, attention_mask, zero_shot_fitness_predictions
1829
+ )
1830
+
1831
+ loss = None
1832
+ if labels is not None:
1833
+ labels = labels.to(logits.device)
1834
+
1835
+ if self.config.problem_type is None:
1836
+ if self.num_labels == 1:
1837
+ self.config.problem_type = "regression"
1838
+ elif self.num_labels > 1 and (
1839
+ labels.dtype == torch.long or labels.dtype == torch.int
1840
+ ):
1841
+ self.config.problem_type = "single_label_classification"
1842
+ else:
1843
+ self.config.problem_type = "multi_label_classification"
1844
+
1845
+ if self.config.problem_type == "regression":
1846
+ loss_fct = MSELoss()
1847
+ if self.num_labels == 1:
1848
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1849
+ else:
1850
+ loss = loss_fct(logits, labels)
1851
+ elif self.config.problem_type == "single_label_classification":
1852
+ loss_fct = CrossEntropyLoss()
1853
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1854
+ elif self.config.problem_type == "multi_label_classification":
1855
+ loss_fct = BCEWithLogitsLoss()
1856
+ loss = loss_fct(logits, labels)
1857
+
1858
+ if not return_dict:
1859
+ output = (logits,) + outputs[2:]
1860
+ return ((loss,) + output) if loss is not None else output
1861
+
1862
+ return SequenceClassifierOutput(
1863
+ loss=loss,
1864
+ logits=logits,
1865
+ hidden_states=outputs.hidden_states,
1866
+ attentions=outputs.attentions,
1867
+ )
1868
+
1869
+
1870
+ class FM4BioForTokenClassification(FM4BioPreTrainedModel):
1871
+ def __init__(
1872
+ self,
1873
+ config,
1874
+ arch="MLP",
1875
+ conv_kernel_size=9,
1876
+ dropout_prob=None,
1877
+ pairwise=False,
1878
+ inter_hidden_size=128,
1879
+ ):
1880
+ super().__init__(config)
1881
+ self.num_labels = config.num_labels
1882
+ self.pairwise = pairwise
1883
+
1884
+ self.bert = FM4BioModel(config, add_pooling_layer=False)
1885
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1886
+
1887
+ if self.pairwise:
1888
+ self.inter_hidden_size = [inter_hidden_size, self.num_labels]
1889
+ self.classifier = FM4BioContactHead(config, self.inter_hidden_size)
1890
+ else:
1891
+ self.classifier = FM4BioClassificationHead(
1892
+ config,
1893
+ arch=arch,
1894
+ pooling=None,
1895
+ conv_kernel_size=conv_kernel_size,
1896
+ dropout_prob=dropout_prob,
1897
+ inter_hidden_size=inter_hidden_size,
1898
+ )
1899
+
1900
+ self.init_weights()
1901
+
1902
+ @add_start_docstrings_to_model_forward(
1903
+ FM4BIO_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1904
+ )
1905
+ @add_code_sample_docstrings(
1906
+ checkpoint=_CHECKPOINT_FOR_DOC,
1907
+ output_type=TokenClassifierOutput,
1908
+ config_class=_CONFIG_FOR_DOC,
1909
+ )
1910
+ def forward(
1911
+ self,
1912
+ input_ids: Optional[torch.LongTensor] = None,
1913
+ attention_mask: Optional[torch.Tensor] = None,
1914
+ position_ids: Optional[torch.LongTensor] = None,
1915
+ head_mask: Optional[torch.Tensor] = None,
1916
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1917
+ inputs_str_embeds: Optional[torch.FloatTensor] = None, # << Pan: input structure embedding
1918
+ labels: Optional[torch.LongTensor] = None,
1919
+ output_attentions: Optional[bool] = None,
1920
+ output_hidden_states: Optional[bool] = None,
1921
+ return_dict: Optional[bool] = None,
1922
+ ) -> Union[Tuple, TokenClassifierOutput]:
1923
+ r"""
1924
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1925
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1926
+ """
1927
+ return_dict = (
1928
+ return_dict if return_dict is not None else self.config.use_return_dict
1929
+ )
1930
+
1931
+ outputs = self.bert(
1932
+ input_ids,
1933
+ attention_mask=attention_mask,
1934
+ position_ids=position_ids,
1935
+ head_mask=head_mask,
1936
+ inputs_embeds=inputs_embeds,
1937
+ inputs_str_embeds=inputs_str_embeds, # << Pan: input structure embedding
1938
+ output_attentions=output_attentions,
1939
+ output_hidden_states=output_hidden_states,
1940
+ return_dict=return_dict,
1941
+ )
1942
+
1943
+ sequence_output = outputs[0] # (bs, seq_len, hidden_size)
1944
+
1945
+ # remove padding and [eos]
1946
+ mbs = input_ids.shape[0]
1947
+ seq_len = attention_mask.sum(1) # (bs,)
1948
+ seq_len = seq_len - 1 # (bs,)
1949
+ assert mbs == 1, "currently only support mbs=1"
1950
+ sequence_output = sequence_output[:, : seq_len[0]]
1951
+
1952
+ sequence_output = self.dropout(sequence_output)
1953
+ logits = self.classifier(sequence_output)
1954
+
1955
+ loss = None
1956
+ if labels is not None:
1957
+ if self.config.problem_type == "regression":
1958
+ loss_fct = MSELoss()
1959
+ else:
1960
+ loss_fct = CrossEntropyLoss()
1961
+
1962
+ labels = labels.to(logits.device)
1963
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1964
+
1965
+ if not return_dict:
1966
+ output = (logits,) + outputs[2:]
1967
+ return ((loss,) + output) if loss is not None else output
1968
+
1969
+ return TokenClassifierOutput(
1970
+ loss=loss,
1971
+ logits=logits,
1972
+ hidden_states=outputs.hidden_states,
1973
+ attentions=outputs.attentions,
1974
+ )
1975
+
1976
+
1977
+ class FM4BioClassificationHead(nn.Module):
1978
+ """Head for classification tasks and regression tasks."""
1979
+
1980
+ def __init__(
1981
+ self,
1982
+ config,
1983
+ arch="MLP",
1984
+ pooling="mean_pooling",
1985
+ conv_kernel_size=9,
1986
+ dropout_prob=None,
1987
+ inter_hidden_size=None,
1988
+ augment_with_zeroshot=False,
1989
+ activation_func="tanh",
1990
+ ):
1991
+ super().__init__()
1992
+ self.arch = arch
1993
+ self.pooling = pooling
1994
+ self.conv_kernal_size = conv_kernel_size
1995
+ self.augment_with_zeroshot = augment_with_zeroshot
1996
+
1997
+ if dropout_prob is not None:
1998
+ self.dropout_prob = dropout_prob
1999
+ else:
2000
+ self.dropout_prob = config.hidden_dropout_prob
2001
+
2002
+ if self.arch == "MLP" and inter_hidden_size is None:
2003
+ self.inter_hidden_size = config.hidden_size // 2
2004
+ else:
2005
+ self.inter_hidden_size = inter_hidden_size
2006
+
2007
+ if activation_func == "tanh":
2008
+ self.activation_func = nn.Tanh()
2009
+ else:
2010
+ self.activation_func = nn.ReLU()
2011
+
2012
+ if self.augment_with_zeroshot:
2013
+ input_hidden_size = config.hidden_size + 1
2014
+ else:
2015
+ input_hidden_size = config.hidden_size
2016
+
2017
+ assert self.pooling in ["mean_pooling", None]
2018
+ if self.arch == "CNN":
2019
+ self.conv = nn.Conv1d(
2020
+ in_channels=config.hidden_size,
2021
+ out_channels=config.hidden_size,
2022
+ kernel_size=conv_kernel_size,
2023
+ padding="same",
2024
+ )
2025
+ self.dropout = nn.Dropout(self.dropout_prob)
2026
+ self.out_proj = nn.Linear(input_hidden_size, config.num_labels)
2027
+ elif self.arch == "MLP":
2028
+ self.ffn = nn.Linear(input_hidden_size, self.inter_hidden_size)
2029
+ self.dropout = nn.Dropout(self.dropout_prob)
2030
+ self.out_proj = nn.Linear(self.inter_hidden_size, config.num_labels)
2031
+ else:
2032
+ raise NotImplementedError
2033
+
2034
+ def forward(
2035
+ self, hidden_states, attention_mask=None, zero_shot_fitness_predictions=None
2036
+ ):
2037
+ """
2038
+ Args:
2039
+ hidden_states: (bs, seq_len, hidden_size)
2040
+ attention_mask: (bs, seq_len), 0 means masking
2041
+ """
2042
+ x = hidden_states
2043
+ if self.arch == "CNN":
2044
+ # Refer to ProteinNPT
2045
+ x = self.dropout(x)
2046
+ x = x.permute(0, 2, 1) # (bs, hidden_size, seq_len)
2047
+ x = self.conv(x) # (bs, hidden_size, seq_len1)
2048
+ x = self.dropout(x)
2049
+ x = self.activation_func(x)
2050
+ x = x.permute(0, 2, 1) # (bs, seq_len, hidden_size)
2051
+ # mean pooling
2052
+ if self.pooling == "mean_pooling":
2053
+ x = x.mean(dim=-2) # (bs, hidden_size)
2054
+ if self.augment_with_zeroshot:
2055
+ x = self._get_zero_shot_aug_feats(
2056
+ x, zero_shot_fitness_predictions
2057
+ ) # (bs, hidden_size+1)
2058
+ x = self.out_proj(x)
2059
+
2060
+ elif self.arch == "MLP":
2061
+ if self.pooling == "mean_pooling":
2062
+ input_mask_expanded = (
2063
+ attention_mask.unsqueeze(-1).expand(x.size()).float()
2064
+ )
2065
+ x = torch.sum(x * input_mask_expanded, 1) / torch.clamp(
2066
+ input_mask_expanded.sum(1), min=1e-9
2067
+ )
2068
+ if self.augment_with_zeroshot:
2069
+ x = self._get_zero_shot_aug_feats(
2070
+ x, zero_shot_fitness_predictions
2071
+ ) # (bs, hidden_size+1)
2072
+ x = self.dropout(x)
2073
+ x = self.ffn(x)
2074
+ x = self.activation_func(x)
2075
+ x = self.dropout(x)
2076
+ x = self.out_proj(x)
2077
+ return x
2078
+
2079
+ def _get_zero_shot_aug_feats(self, x, zero_shot_fitness_predictions):
2080
+ """
2081
+ Add zero_shot_prediction to the beginning of x as the first feats
2082
+ x: torch.tensor, of shape (bs, hidden_size)
2083
+ zero_shot_fitness_predictions: torch.tensor, of shape (bs,) or (bs, 1)
2084
+ """
2085
+ assert zero_shot_fitness_predictions is not None
2086
+ if len(zero_shot_fitness_predictions.shape) == 1:
2087
+ zero_shot_fitness_predictions = zero_shot_fitness_predictions.unsqueeze(
2088
+ -1
2089
+ ).to(x.dtype)
2090
+ x = torch.cat((zero_shot_fitness_predictions, x), 1) # (bs, hidden_size+1)
2091
+ return x
2092
+
2093
+
2094
+ class FM4BioContactHead(nn.Module):
2095
+ """Head for contact prediction."""
2096
+
2097
+ def __init__(self, config, inter_hidden_size=[128, 2]):
2098
+ super().__init__()
2099
+ self.ffn_0 = nn.Linear(config.hidden_size * 2, inter_hidden_size[0])
2100
+ self.ffn_1 = nn.Linear(inter_hidden_size[0], inter_hidden_size[1])
2101
+
2102
+ def outer_concat(self, x):
2103
+ batch_size, seq_len, features = x.shape
2104
+
2105
+ # Permute to [batch_size, features, seq_len]
2106
+ x = x.permute(0, 2, 1)
2107
+
2108
+ # Introduce new dimensions for broadcasting
2109
+ x_1 = x[:, None, :, :, None] # [batch_size, 1, features, seq_len, 1]
2110
+ x_2 = x[:, None, :, None, :] # [batch_size, 1, features, 1, seq_len]
2111
+
2112
+ # Repeat along new dimensions
2113
+ x_1 = x_1.repeat(
2114
+ 1, 1, 1, 1, seq_len
2115
+ ) # [batch_size, 1, features, seq_len, seq_len]
2116
+ x_2 = x_2.repeat(
2117
+ 1, 1, 1, seq_len, 1
2118
+ ) # [batch_size, 1, features, seq_len, seq_len]
2119
+
2120
+ # Concatenate along the second dimension
2121
+ x = torch.cat((x_1, x_2), dim=1) # [batch_size, 2, features, seq_len, seq_len]
2122
+
2123
+ # Get lower triangular indices
2124
+ I, J = torch.tril_indices(seq_len, seq_len, -1)
2125
+
2126
+ # Symmetrize
2127
+ x[:, :, :, I, J] = x[:, :, :, J, I]
2128
+
2129
+ # Permute to desired shape and make contiguous
2130
+ x = x.permute(
2131
+ 0, 3, 4, 2, 1
2132
+ ).contiguous() # [batch_size, seq_len, seq_len, features, 2]
2133
+
2134
+ # Reshape to combine the last two dimensions
2135
+ x = x.view(
2136
+ batch_size, seq_len, seq_len, features * 2
2137
+ ) # [batch_size, seq_len, seq_len, features * 2]
2138
+
2139
+ return x
2140
+
2141
+ def forward(self, hidden_states):
2142
+ # remove [sep] token at the end
2143
+ # x = hidden_states[:, :-1] #(bs, seq_len, hidden_size)
2144
+ x = self.outer_concat(hidden_states)
2145
+ x = self.ffn_0(x)
2146
+ x = nn.ReLU()(x)
2147
+ x = self.ffn_1(x)
2148
+ return x
tokenization_fm4bio.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for FM4Bio
2
+ Currently supports only protein
3
+ """
4
+
5
+ import os
6
+ from typing import List, Optional
7
+
8
+ from transformers.tokenization_utils import PreTrainedTokenizer
9
+ from transformers.utils import logging
10
+
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab_protein.txt"}
15
+
16
+ PRETRAINED_VOCAB_FILES_MAP = {
17
+ "vocab_file": {
18
+ "fm4bio/proteinmoe": "https://huggingface.co/fm4bio/proteinmoe/resolve/main/vocab.txt",
19
+ },
20
+ }
21
+
22
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"proteinmoe": 2048, "rnabert": 1024}
23
+
24
+
25
+ def load_vocab_file(vocab_file):
26
+ with open(vocab_file, "r") as f:
27
+ lines = f.read().splitlines()
28
+ return [l.strip() for l in lines]
29
+
30
+
31
+ class FM4BioTokenizer(PreTrainedTokenizer):
32
+ """
33
+ Constructs an FM4Bio tokenizer.
34
+ """
35
+
36
+ vocab_files_names = VOCAB_FILES_NAMES
37
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
38
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
39
+ model_input_names = ["input_ids", "attention_mask"]
40
+
41
+ def __init__(
42
+ self,
43
+ vocab_file,
44
+ biotype="protein",
45
+ unk_token="-",
46
+ pad_token="[PAD]",
47
+ mask_token="[MASK]",
48
+ sep_token="[SEP]",
49
+ cls_token=None,
50
+ bos_token=None,
51
+ eos_token=None,
52
+ **kwargs,
53
+ ):
54
+ """
55
+ Args:
56
+ biotype: str, could be protein/rna/dna
57
+ the input is like ...[SEP]
58
+ """
59
+ self.biotype = biotype
60
+ if self.biotype != "protein":
61
+ raise NotImplementedError
62
+
63
+ self.all_tokens = load_vocab_file(vocab_file)
64
+ self._id_to_token = dict(enumerate(self.all_tokens))
65
+ self._token_to_id = {tok: ind for ind, tok in enumerate(self.all_tokens)}
66
+
67
+ super().__init__(
68
+ unk_token=unk_token,
69
+ cls_token=cls_token,
70
+ pad_token=pad_token,
71
+ mask_token=mask_token,
72
+ sep_token=sep_token,
73
+ bos_token=bos_token,
74
+ eos_token=eos_token,
75
+ **kwargs,
76
+ )
77
+
78
+ # TODO, all the tokens are added? But they are also part of the vocab... bit strange.
79
+ # none of them are special, but they all need special splitting.
80
+
81
+ self.unique_no_split_tokens = self.all_tokens
82
+ self._update_trie(self.unique_no_split_tokens)
83
+
84
+ def _convert_id_to_token(self, index: int) -> str:
85
+ return self._id_to_token.get(index, self.unk_token)
86
+
87
+ def _convert_token_to_id(self, token: str) -> int:
88
+ return self._token_to_id.get(token, self._token_to_id.get(self.unk_token))
89
+
90
+ def _tokenize(self, text, **kwargs):
91
+ """
92
+ Hack for multiple chains (seperated by |)
93
+ Args:
94
+ text: str, eg. CALVSGGNYKPTF|CASSWGGAPLF|ELAGIGILTV
95
+ """
96
+ return text.replace("|", self.sep_token).split()
97
+
98
+ def get_vocab(self):
99
+ base_vocab = self._token_to_id.copy()
100
+ base_vocab.update(self.added_tokens_encoder)
101
+ return base_vocab
102
+
103
+ def token_to_id(self, token: str) -> int:
104
+ return self._token_to_id.get(token, self._token_to_id.get(self.unk_token))
105
+
106
+ def id_to_token(self, index: int) -> str:
107
+ return self._id_to_token.get(index, self.unk_token)
108
+
109
+ def build_inputs_with_special_tokens(
110
+ self,
111
+ token_ids_0: List[int],
112
+ token_ids_1: Optional[List[int]] = None,
113
+ ) -> List[int]:
114
+ if self.biotype == "protein":
115
+ sep = [self.sep_token_id]
116
+ if token_ids_1 is None:
117
+ return token_ids_0 + sep
118
+ else:
119
+ return token_ids_0 + sep + token_ids_1 + sep
120
+ else:
121
+ raise NotImplementedError
122
+
123
+ def get_special_tokens_mask(
124
+ self,
125
+ token_ids_0: List,
126
+ token_ids_1: Optional[List] = None,
127
+ already_has_special_tokens: bool = False,
128
+ ) -> List[int]:
129
+ """
130
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
131
+ special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
132
+
133
+ Args:
134
+ token_ids_0 (`List[int]`):
135
+ List of ids of the first sequence.
136
+ token_ids_1 (`List[int]`, *optional*):
137
+ List of ids of the second sequence.
138
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
139
+ Whether or not the token list is already formatted with special tokens for the model.
140
+
141
+ Returns:
142
+ A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
143
+ """
144
+ if already_has_special_tokens:
145
+ if token_ids_1 is not None:
146
+ raise ValueError(
147
+ "You should not supply a second sequence if the provided sequence of "
148
+ "ids is already formatted with special tokens for the model."
149
+ )
150
+
151
+ return [1 if token in self.all_special_ids else 0 for token in token_ids_0]
152
+ mask = ([0] * len(token_ids_0)) + [1]
153
+ if token_ids_1 is not None:
154
+ mask += [0] * len(token_ids_1) + [1]
155
+ return mask
156
+
157
+ def save_vocabulary(self, save_directory, filename_prefix):
158
+ vocab_file = os.path.join(
159
+ save_directory,
160
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.txt",
161
+ )
162
+ with open(vocab_file, "w") as f:
163
+ f.write("\n".join(self.all_tokens))
164
+ return (vocab_file,)
165
+
166
+ @property
167
+ def vocab_size(self) -> int:
168
+ return len(self.all_tokens)
vocab_protein.txt ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [PAD]
2
+ L
3
+ A
4
+ G
5
+ V
6
+ S
7
+ E
8
+ R
9
+ T
10
+ I
11
+ D
12
+ P
13
+ K
14
+ Q
15
+ N
16
+ F
17
+ Y
18
+ M
19
+ H
20
+ W
21
+ C
22
+ X
23
+ B
24
+ U
25
+ Z
26
+ O
27
+ .
28
+ -
29
+ [MASK]
30
+ [gMASK]
31
+ [sMASK]
32
+ [eod]
33
+ [sop]
34
+ [eop]
35
+ [SEP]
36
+ [HC]
37
+ [LC]
38
+ [HUMAN]
39
+ <cdr1>
40
+ </cdr1>
41
+ <cdr2>
42
+ </cdr2>
43
+ <cdr3>
44
+ </cdr3>