davidhd Lolalb commited on
Commit
67eae86
·
0 Parent(s):

Duplicate from Lolalb/AMPLIFY_120M_UR50

Browse files

Co-authored-by: Lola Le Breton <Lolalb@users.noreply.huggingface.co>

Files changed (11) hide show
  1. .gitattributes +35 -0
  2. README.md +199 -0
  3. amplify.py +341 -0
  4. config.json +37 -0
  5. model.safetensors +3 -0
  6. rmsnorm.py +34 -0
  7. rotary.py +59 -0
  8. special_tokens_map.json +7 -0
  9. tokenizer.json +98 -0
  10. tokenizer.py +260 -0
  11. tokenizer_config.json +100 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
amplify.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # From https://stackoverflow.com/a/23689767
2
+ # From https://github.com/pytorch/pytorch/issues/97899
3
+ # From https://github.com/facebookresearch/llama/blob/main/llama/model.py
4
+ import yaml
5
+
6
+ import safetensors
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn.functional import scaled_dot_product_attention
10
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func
11
+ from xformers.ops import SwiGLU
12
+
13
+ from .rmsnorm import RMSNorm
14
+ from .rotary import precompute_freqs_cis, apply_rotary_emb
15
+ from .tokenizer import ProteinTokenizer
16
+
17
+ from transformers import PreTrainedModel, PretrainedConfig
18
+ from transformers.modeling_outputs import MaskedLMOutput
19
+
20
+
21
+ class DotDict(dict):
22
+ """Dictionary that supports the dot notation to access attributes (similarly to HuggingFace)."""
23
+
24
+ __getattr__ = dict.get
25
+ __setattr__ = dict.__setitem__
26
+ __delattr__ = dict.__delitem__
27
+
28
+
29
+ class AMPLIFYConfig(PretrainedConfig):
30
+ model_type = "AMPLIFY"
31
+
32
+ # All config parameters must have a default value.
33
+ def __init__(
34
+ self,
35
+ hidden_size: int = 960,
36
+ num_hidden_layers: int = 32,
37
+ num_attention_heads: int = 15,
38
+ intermediate_size: int = 3840,
39
+ dropout_prob: float = 0,
40
+ embedding_init_range: float = 0.02,
41
+ decoder_init_range: float = 0.02,
42
+ rms_norm: bool = True,
43
+ norm_eps: float = 1e-05,
44
+ hidden_act: str = "SwiGLU",
45
+ layer_norm_after_embedding: bool = False,
46
+ layer_norm_before_last_layer: bool = True,
47
+ vocab_size: int = 27,
48
+ ffn_bias: bool = False,
49
+ att_bias: bool = False,
50
+ pad_token_id: int = 0,
51
+ max_length: int = 2048,
52
+ **kwargs,
53
+ ):
54
+ super().__init__(**kwargs)
55
+
56
+ self.hidden_size = hidden_size
57
+ self.num_hidden_layers = num_hidden_layers
58
+ self.num_attention_heads = num_attention_heads
59
+ self.intermediate_size = intermediate_size
60
+ self.dropout_prob = dropout_prob
61
+ self.embedding_init_range = embedding_init_range
62
+ self.decoder_init_range = decoder_init_range
63
+ self.rms_norm = rms_norm
64
+ self.norm_eps = norm_eps
65
+ self.hidden_act = hidden_act
66
+ self.layer_norm_after_embedding = layer_norm_after_embedding
67
+ self.layer_norm_before_last_layer = layer_norm_before_last_layer
68
+ self.vocab_size = vocab_size
69
+ self.ffn_bias = ffn_bias
70
+ self.att_bias = att_bias
71
+ self.pad_token_id = pad_token_id
72
+ self.max_length = max_length
73
+
74
+
75
+ class EncoderBlock(nn.Module):
76
+ """Transformer encoder block."""
77
+
78
+ def __init__(self, config: AMPLIFYConfig):
79
+ """Initialize a EncoderBlock.
80
+
81
+ Args:
82
+ hidden_size (int): _description_
83
+ num_attention_heads (int): _description_
84
+ intermediate_size (int, optional): _description_. Defaults to 2048.
85
+ dropout_prob (float, optional): _description_. Defaults to 0.1.
86
+ activation (str, optional): _description_. Defaults to "relu".
87
+ rms_norm (bool, optional): _description_. Defaults to True.
88
+ norm_eps (float, optional): _description_. Defaults to 1e-5.
89
+ pad_token_id (int, optional): _description_. Defaults to 0.
90
+ max_length (int, optional): _description_. Defaults to 2048.
91
+ ffn_bias (bool, optional): _description_. Defaults to False.
92
+ att_bias (bool, optional): _description_. Defaults to False.
93
+ """
94
+ super().__init__()
95
+
96
+ self.config = config
97
+ self.d_head = config.hidden_size // config.num_attention_heads
98
+
99
+ # Attention
100
+ self.q = nn.Linear(in_features=config.hidden_size, out_features=config.hidden_size, bias=config.att_bias)
101
+ self.k = nn.Linear(in_features=config.hidden_size, out_features=config.hidden_size, bias=config.att_bias)
102
+ self.v = nn.Linear(in_features=config.hidden_size, out_features=config.hidden_size, bias=config.att_bias)
103
+ self.wo = nn.Linear(in_features=config.hidden_size, out_features=config.hidden_size, bias=config.att_bias)
104
+ self.resid_dropout = nn.Dropout(config.dropout_prob)
105
+
106
+ # Feedforward network
107
+ act = config.hidden_act.lower()
108
+ if act == "swiglu":
109
+ # To keep the number of parameters and the amount of computation constant, we reduce the number of
110
+ # hidden units by a factor of 2/3 (https://arxiv.org/pdf/2002.05202.pdf) and make it a multiple of 8 to
111
+ # avoid RuntimeError due to misaligned operand
112
+ multiple_of = 8
113
+ intermediate_size = int(2 * config.intermediate_size / 3)
114
+ intermediate_size = multiple_of * ((intermediate_size + multiple_of - 1) // multiple_of)
115
+ self.ffn = SwiGLU(config.hidden_size, intermediate_size, config.hidden_size, bias=config.ffn_bias)
116
+ elif act == "relu":
117
+ self.ffn = nn.Sequential(
118
+ nn.Linear(config.hidden_size, config.intermediate_size, bias=config.ffn_bias),
119
+ nn.ReLU(),
120
+ nn.Linear(config.intermediate_size, config.hidden_size, bias=config.ffn_bias),
121
+ )
122
+ elif act == "gelu":
123
+ self.ffn = nn.Sequential(
124
+ nn.Linear(config.hidden_size, config.intermediate_size, bias=config.ffn_bias),
125
+ nn.GELU(),
126
+ nn.Linear(config.intermediate_size, config.hidden_size, bias=config.ffn_bias),
127
+ )
128
+ else:
129
+ raise ValueError(f"Unsupported hidden_act: {config.hidden_act}")
130
+
131
+ self.attention_norm = (
132
+ RMSNorm(config.hidden_size, config.norm_eps) if config.rms_norm else nn.LayerNorm(config.hidden_size, config.norm_eps)
133
+ )
134
+ self.ffn_norm = (
135
+ RMSNorm(config.hidden_size, config.norm_eps) if config.rms_norm else nn.LayerNorm(config.hidden_size, config.norm_eps)
136
+ )
137
+
138
+ self.ffn_dropout = nn.Dropout(config.dropout_prob)
139
+
140
+ def forward(
141
+ self,
142
+ x: torch.Tensor,
143
+ pad_mask: torch.Tensor,
144
+ freqs_cis: torch.Tensor,
145
+ output_attentions: bool,
146
+ max_seqlen: int = None,
147
+ cu_seqlens: torch.Tensor = None,
148
+ ):
149
+ attn, contact = self._att_block(self.attention_norm(x), pad_mask, freqs_cis, output_attentions, max_seqlen, cu_seqlens)
150
+ x = x + attn
151
+ x = x + self._ff_block(self.ffn_norm(x))
152
+ return x, contact
153
+
154
+ def _att_block(
155
+ self,
156
+ x: torch.Tensor,
157
+ pad_mask: torch.Tensor,
158
+ freqs_cis: torch.Tensor,
159
+ output_attentions: bool,
160
+ max_seqlen: int = None,
161
+ cu_seqlens: torch.Tensor = None,
162
+ ):
163
+ batch_size, seq_len, _ = x.shape
164
+ xq, xk, xv = self.q(x), self.k(x), self.v(x)
165
+
166
+ # Reshape for rotary embeddings
167
+ xq = xq.view(batch_size, seq_len, self.config.num_attention_heads, self.d_head)
168
+ xk = xk.view(batch_size, seq_len, self.config.num_attention_heads, self.d_head)
169
+ xv = xv.view(batch_size, seq_len, self.config.num_attention_heads, self.d_head)
170
+ xq, xk = apply_rotary_emb(xq, xk, freqs_cis)
171
+
172
+ # Attn block
173
+ attn_weights = None
174
+
175
+ # Flash attention if the tensors are packed
176
+ if cu_seqlens is not None:
177
+ attn = flash_attn_varlen_func(
178
+ q=xq.squeeze(0),
179
+ k=xk.squeeze(0),
180
+ v=xv.squeeze(0),
181
+ cu_seqlens_q=cu_seqlens,
182
+ cu_seqlens_k=cu_seqlens,
183
+ max_seqlen_q=max_seqlen,
184
+ max_seqlen_k=max_seqlen,
185
+ dropout_p=0.0,
186
+ causal=False,
187
+ )
188
+
189
+ # Eager attention if attention weights are needed in the output
190
+ elif output_attentions:
191
+ attn_weights = xq.permute(0, 2, 1, 3) @ xk.permute(0, 2, 3, 1) / (xq.size(-1) ** 0.5)
192
+ if pad_mask is not None:
193
+ attn_weights = attn_weights + pad_mask.type(attn_weights.dtype)
194
+ attn_weights = attn_weights.softmax(-1)
195
+ attn = attn_weights @ xv.permute(0, 2, 1, 3)
196
+ attn = attn.transpose(1, 2)
197
+
198
+ # SDPA will pick an appropriate backend otherwise
199
+ else:
200
+ attn = scaled_dot_product_attention(
201
+ query=xq.transpose(1, 2),
202
+ key=xk.transpose(1, 2),
203
+ value=xv.transpose(1, 2),
204
+ attn_mask=pad_mask,
205
+ dropout_p=0,
206
+ ).transpose(1, 2)
207
+
208
+ attn_scores = self.wo(attn.reshape(batch_size, seq_len, self.config.num_attention_heads * self.d_head))
209
+ return (self.resid_dropout(attn_scores), attn_weights)
210
+
211
+ def _ff_block(self, x: torch.Tensor):
212
+ return self.ffn_dropout(self.ffn(x))
213
+
214
+
215
+ class AMPLIFYPreTrainedModel(PreTrainedModel):
216
+ config_class = AMPLIFYConfig
217
+
218
+ def _init_weights(self, module):
219
+ if isinstance(module, nn.Linear):
220
+ module.weight.data.uniform_(-self.config.decoder_init_range, self.config.decoder_init_range)
221
+ if module.bias is not None:
222
+ module.bias.data.zero_()
223
+ elif isinstance(module, nn.Embedding):
224
+ module.weight.data.uniform_(-self.config.embedding_init_range, self.config.embedding_init_range)
225
+
226
+
227
+ class AMPLIFY(AMPLIFYPreTrainedModel):
228
+ """The main model class.
229
+
230
+ Args:
231
+ config (amplify.model.amplify.AMPLIFYConfig): model configuration, usually defined from the Hydra configuration.
232
+ """
233
+
234
+ def __init__(self, config: AMPLIFYConfig, **kwargs):
235
+ super().__init__(config)
236
+
237
+ self.config = config
238
+
239
+ self.encoder = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
240
+
241
+ if config.layer_norm_after_embedding:
242
+ self.layer_norm_1 = (
243
+ RMSNorm(config.hidden_size, config.norm_eps) if config.rms_norm else nn.LayerNorm(config.hidden_size, config.norm_eps)
244
+ )
245
+
246
+ self.transformer_encoder = nn.ModuleList()
247
+ for _ in range(config.num_hidden_layers):
248
+ self.transformer_encoder.append(EncoderBlock(config))
249
+
250
+ if config.layer_norm_before_last_layer:
251
+ self.layer_norm_2 = (
252
+ RMSNorm(config.hidden_size, config.norm_eps) if config.rms_norm else nn.LayerNorm(config.hidden_size, config.norm_eps)
253
+ )
254
+
255
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
256
+
257
+ freqs_cis = precompute_freqs_cis(config.hidden_size // config.num_attention_heads, config.max_length)
258
+
259
+ # Ensures freqs_cis is moved to the same devices as the model. Non-persistent buffers are not saved in the state_dict.
260
+ self.register_buffer("freqs_cis", freqs_cis, persistent=False)
261
+
262
+ # Initialize weights and apply final processing
263
+ self.post_init()
264
+
265
+ @classmethod
266
+ def load(cls, checkpoint_path: str, config_path: str):
267
+
268
+ with open(config_path, "r") as file:
269
+ cfg = yaml.safe_load(file)
270
+
271
+ model = AMPLIFY(AMPLIFYConfig(**cfg["model"], **cfg["tokenizer"]))
272
+
273
+ if checkpoint_path.endswith(".safetensors"):
274
+ state_dict = safetensors.torch.load_file(checkpoint_path)
275
+ elif checkpoint_path.endswith(".pt"):
276
+ state_dict = torch.load(checkpoint_path)
277
+ else:
278
+ raise ValueError(f"Expected checkpoint to be a `.pt` or `.safetensors` file.")
279
+
280
+ model.load_state_dict(state_dict)
281
+ return model
282
+
283
+ def forward(
284
+ self,
285
+ src,
286
+ position_ids: torch.Tensor = None,
287
+ max_seqlen: int = None,
288
+ cu_seqlens: torch.Tensor = None,
289
+ pad_mask=None,
290
+ output_hidden_states=False,
291
+ output_attentions=False,
292
+ ):
293
+ # Initialize
294
+ hidden_states, attentions = [], []
295
+
296
+ # We will output all the hidden_states that have an index higher than output_hidden_index
297
+ if type(output_hidden_states) == bool and not output_hidden_states:
298
+ output_hidden_index = self.config.num_hidden_layers + 1
299
+ elif type(output_hidden_states) == int:
300
+ output_hidden_index = output_hidden_states
301
+ else:
302
+ output_hidden_index = 0
303
+
304
+ # Expand and repeat: (Batch, Length) -> (Batch, Heads, Length, Length)
305
+ if pad_mask is not None:
306
+ pad_mask = pad_mask.unsqueeze(1).unsqueeze(1).repeat(1, self.config.num_attention_heads, pad_mask.size(-1), 1)
307
+
308
+ if output_attentions:
309
+ pad_mask = torch.where(pad_mask == 1, float(0.0), float("-inf"))
310
+
311
+ # Checks to be done if inputs are packed sequences
312
+ if cu_seqlens is not None:
313
+ assert not output_attentions, "Output attentions is not supported when sequences are packed."
314
+ assert max_seqlen is not None, "Missing max_seqlen. It must be provided when cu_seqlens are not None."
315
+ assert src.shape[0] == 1, "Cumulative sequence lengths are provided but src are not packed."
316
+ assert src.is_cuda, "Packing uses an implementation of flash-attention and is only supported on GPU."
317
+
318
+ # RoPE
319
+ if position_ids is not None:
320
+ freqs_cis = self.freqs_cis[position_ids]
321
+ else:
322
+ freqs_cis = self.freqs_cis[: src.shape[1]].unsqueeze(0).repeat(src.shape[0], 1, 1)
323
+
324
+ # Embedding
325
+ x = self.encoder(src)
326
+ if self.config.layer_norm_after_embedding:
327
+ x = self.layer_norm_1(x)
328
+
329
+ # Transformer encoder
330
+ for idx, layer in enumerate(self.transformer_encoder):
331
+ x, attn = layer(x, pad_mask, freqs_cis, output_attentions, max_seqlen, cu_seqlens)
332
+ if idx >= output_hidden_index:
333
+ hidden_states.append(x)
334
+ if output_attentions:
335
+ attentions.append(attn)
336
+
337
+ # Classification head with layer norm
338
+ logits = self.decoder(self.layer_norm_2(x) if self.config.layer_norm_before_last_layer else x)
339
+
340
+ # Return logits or the output of the last hidden layer
341
+ return MaskedLMOutput(logits=logits, hidden_states=hidden_states, attentions=attentions)
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_": "PLM",
3
+ "architectures": [
4
+ "AMPLIFY"
5
+ ],
6
+ "att_bias": false,
7
+ "auto_map": {
8
+ "AutoConfig": "amplify.AMPLIFYConfig",
9
+ "AutoModel": "amplify.AMPLIFY"
10
+ },
11
+ "bos_token_id": 3,
12
+ "decoder_init_range": 0.02,
13
+ "dropout_prob": 0,
14
+ "embedding_init_range": 0.02,
15
+ "eos_token_id": 4,
16
+ "ffn_bias": false,
17
+ "hidden_act": "SwiGLU",
18
+ "hidden_size": 640,
19
+ "intermediate_size": 2560,
20
+ "layer_norm_after_embedding": false,
21
+ "layer_norm_before_last_layer": true,
22
+ "mask_token_id": 2,
23
+ "max_length": 2048,
24
+ "model_type": "AMPLIFY",
25
+ "norm_eps": 1e-05,
26
+ "num_attention_heads": 10,
27
+ "num_hidden_layers": 24,
28
+ "other_special_token_ids": null,
29
+ "pad_token_id": 0,
30
+ "pre_activation_layer_norm": true,
31
+ "rms_norm": true,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.46.3",
34
+ "unk_token_id": 1,
35
+ "vocab_path": "/home/mila/q/quentin.fournier/AMPLIFY/conf/tokenizer/amplify_vocab.txt",
36
+ "vocab_size": 27
37
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0692d58352caa6ee902162e62a9f8e68f9b9a7e96c3360b5d0f6b244e57197b9
3
+ size 473126988
rmsnorm.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ class RMSNorm(nn.Module):
6
+ def __init__(self, dim: int, eps: float = 1e-6):
7
+ """
8
+ Initialize the RMSNorm normalization layer.
9
+
10
+ Args:
11
+ dim (int): The dimension of the input tensor.
12
+ eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
13
+
14
+ Attributes:
15
+ eps (float): A small value added to the denominator for numerical stability.
16
+ weight (nn.Parameter): Learnable scaling parameter.
17
+
18
+ """
19
+ super().__init__()
20
+ self.eps = eps
21
+ self.weight = nn.Parameter(torch.ones(dim))
22
+
23
+ def forward(self, x):
24
+ """
25
+ Forward pass through the RMSNorm layer.
26
+
27
+ Args:
28
+ x (torch.Tensor): The input tensor.
29
+
30
+ Returns:
31
+ torch.Tensor: The output tensor after applying RMSNorm.
32
+
33
+ """
34
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
rotary.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Tuple
3
+
4
+
5
+ def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
6
+ """
7
+ Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
8
+
9
+ This function calculates a frequency tensor with complex exponentials using the given dimension 'dim'
10
+ and the end index 'end'. The 'theta' parameter scales the frequencies.
11
+ The returned tensor contains complex values in complex64 data type.
12
+
13
+ Args:
14
+ dim (int): Dimension of the frequency tensor.
15
+ end (int): End index for precomputing frequencies.
16
+ theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
17
+
18
+ Returns:
19
+ torch.Tensor: Precomputed frequency tensor with complex exponentials.
20
+ """
21
+
22
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
23
+ t = torch.arange(end, device=freqs.device) # type: ignore
24
+ freqs = torch.outer(t, freqs).float() # type: ignore
25
+ return torch.polar(torch.ones_like(freqs), freqs) # complex64
26
+
27
+
28
+ def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
29
+ assert freqs_cis.shape == (x.shape[0], x.shape[1], x.shape[-1])
30
+ return freqs_cis.unsqueeze(2)
31
+
32
+
33
+ def apply_rotary_emb(
34
+ xq: torch.Tensor,
35
+ xk: torch.Tensor,
36
+ freqs_cis: torch.Tensor,
37
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
38
+ """
39
+ Apply rotary embeddings to input tensors using the given frequency tensor.
40
+
41
+ This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided
42
+ frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor
43
+ is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are
44
+ returned as real tensors.
45
+
46
+ Args:
47
+ xq (torch.Tensor): Query tensor to apply rotary embeddings.
48
+ xk (torch.Tensor): Key tensor to apply rotary embeddings.
49
+ freqs_cis (torch.Tensor): Precomputed frequency tensor for complex exponentials.
50
+
51
+ Returns:
52
+ Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
53
+ """
54
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
55
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
56
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
57
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
58
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
59
+ return xq_out.type_as(xq), xk_out.type_as(xk)
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<bos>",
3
+ "eos_token": "<eos>",
4
+ "mask_token": "<mask>",
5
+ "pad_token": "<pad>",
6
+ "unk_token": "<unk>"
7
+ }
tokenizer.json ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "1.0",
3
+ "truncation": null,
4
+ "padding": null,
5
+ "added_tokens": [
6
+ {
7
+ "id": 0,
8
+ "content": "<pad>",
9
+ "single_word": false,
10
+ "lstrip": false,
11
+ "rstrip": false,
12
+ "normalized": false,
13
+ "special": true
14
+ },
15
+ {
16
+ "id": 1,
17
+ "content": "<unk>",
18
+ "single_word": false,
19
+ "lstrip": false,
20
+ "rstrip": false,
21
+ "normalized": false,
22
+ "special": true
23
+ },
24
+ {
25
+ "id": 2,
26
+ "content": "<mask>",
27
+ "single_word": false,
28
+ "lstrip": false,
29
+ "rstrip": false,
30
+ "normalized": false,
31
+ "special": true
32
+ },
33
+ {
34
+ "id": 3,
35
+ "content": "<bos>",
36
+ "single_word": false,
37
+ "lstrip": false,
38
+ "rstrip": false,
39
+ "normalized": false,
40
+ "special": true
41
+ },
42
+ {
43
+ "id": 4,
44
+ "content": "<eos>",
45
+ "single_word": false,
46
+ "lstrip": false,
47
+ "rstrip": false,
48
+ "normalized": false,
49
+ "special": true
50
+ }
51
+ ],
52
+ "normalizer": null,
53
+ "pre_tokenizer": {
54
+ "type": "Split",
55
+ "pattern": {
56
+ "String": ""
57
+ },
58
+ "behavior": "Removed",
59
+ "invert": false
60
+ },
61
+ "post_processor": null,
62
+ "decoder": null,
63
+ "model": {
64
+ "type": "WordPiece",
65
+ "unk_token": "<unk>",
66
+ "continuing_subword_prefix": "##",
67
+ "max_input_chars_per_word": 100,
68
+ "vocab": {
69
+ "<pad>": 0,
70
+ "<unk>": 1,
71
+ "<mask>": 2,
72
+ "<bos>": 3,
73
+ "<eos>": 4,
74
+ "|": 5,
75
+ "L": 6,
76
+ "A": 7,
77
+ "G": 8,
78
+ "V": 9,
79
+ "S": 10,
80
+ "E": 11,
81
+ "R": 12,
82
+ "T": 13,
83
+ "I": 14,
84
+ "D": 15,
85
+ "P": 16,
86
+ "K": 17,
87
+ "Q": 18,
88
+ "N": 19,
89
+ "F": 20,
90
+ "Y": 21,
91
+ "M": 22,
92
+ "H": 23,
93
+ "W": 24,
94
+ "C": 25,
95
+ "B": 26
96
+ }
97
+ }
98
+ }
tokenizer.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import List, Optional, Union, Dict
3
+ from torch import Tensor
4
+ import copy
5
+
6
+ from itertools import compress
7
+
8
+ # HuggingFace
9
+ from tokenizers import Tokenizer
10
+ from transformers import PreTrainedTokenizerFast, BatchEncoding
11
+ from tokenizers.models import WordPiece
12
+ from tokenizers.pre_tokenizers import Split
13
+
14
+
15
+ class ProteinTokenizer(PreTrainedTokenizerFast):
16
+
17
+ def __init__(
18
+ self,
19
+ vocab: dict,
20
+ pad_token_id: int,
21
+ mask_token_id: int,
22
+ bos_token_id: int,
23
+ eos_token_id: int,
24
+ unk_token_id: int,
25
+ model_max_length: int,
26
+ other_special_token_ids: Optional[List[int]] = None,
27
+ **kwargs,
28
+ ):
29
+ """Vocabulary comprising the amino acids, and the special tokens <unk>, <bos>, <eos>, <pad> and <mask>.
30
+
31
+ Args:
32
+ vocab_path (str): Path to the vocabulary file to load.
33
+ pad_token_id (int): <PAD> token index.
34
+ mask_token_id (int): <MASK> token index.
35
+ bos_token_id (int): <BOS> token index.
36
+ eos_token_id (int): <EOS> token index.
37
+ unk_token_id (int): <UNK> token index.
38
+ other_special_token_ids (Optional[List[int]]): List of additional special tokens.
39
+ """
40
+ # Create vocabulary with special tokens
41
+ token_to_id = dict()
42
+ id_to_token = dict()
43
+
44
+ for token, token_id in vocab.items():
45
+ token = token.strip()
46
+ token_to_id[token] = token_id
47
+ id_to_token[token_id] = token
48
+
49
+ # Define tokenizer and model
50
+ tokenizer_object = Tokenizer(WordPiece(vocab=token_to_id, unk_token=id_to_token.get(unk_token_id)))
51
+
52
+ # Pretokenize by splitting every character
53
+ tokenizer_object.pre_tokenizer = Split("", behavior="removed")
54
+
55
+ super().__init__(
56
+ vocab=vocab,
57
+ model_max_length=model_max_length,
58
+ padding_side="right",
59
+ truncation_side="right",
60
+ pad_token_id=pad_token_id,
61
+ pad_token=id_to_token.get(pad_token_id),
62
+ mask_token_id=mask_token_id,
63
+ mask_token=id_to_token.get(mask_token_id),
64
+ bos_token_id=bos_token_id,
65
+ bos_token=id_to_token.get(bos_token_id),
66
+ eos_token_id=eos_token_id,
67
+ eos_token=id_to_token.get(eos_token_id),
68
+ unk_token_id=unk_token_id,
69
+ unk_token=id_to_token.get(unk_token_id),
70
+ other_special_token_ids=other_special_token_ids,
71
+ model_input_names=["input_ids", "attention_mask", "special_tokens_mask"],
72
+ tokenizer_object=tokenizer_object,
73
+ )
74
+
75
+ if other_special_token_ids is not None:
76
+ self.add_special_tokens({"additional_special_tokens": list(id_to_token.get(i) for i in other_special_token_ids)})
77
+
78
+ self.key_to_padding = {"input_ids": self.pad_token_id, "attention_mask": 0, "special_tokens_mask": 1, "position_ids": 0}
79
+ self.key_to_dtype = {
80
+ "input_ids": torch.long,
81
+ "attention_mask": torch.bool,
82
+ "special_tokens_mask": torch.bool,
83
+ "position_ids": torch.int,
84
+ }
85
+
86
+ def truncate(
87
+ self,
88
+ encoded_inputs: Dict[str, List[int]],
89
+ max_length: Optional[int] = None,
90
+ random_truncate: bool = True,
91
+ ) -> Dict[str, List[List[int]]]:
92
+ """
93
+ Randomly truncate sequences in encoded inputs to the specified maximum length.
94
+
95
+ Args:
96
+ encoded_inputs (BatchEncoding): Tokenized inputs with keys like 'input_ids' as tensors.
97
+ max_length (Optional[int]): Maximum length for truncation. Defaults to model's max length if None.
98
+ random_truncate (bool): Whether to randomly truncate sequences.
99
+
100
+ Returns:
101
+ Dict[str, List[List[int]]]: Randomly truncated tokenized inputs.
102
+ """
103
+
104
+ for i, sequence in enumerate(encoded_inputs["input_ids"]):
105
+ if len(sequence) > max_length:
106
+ if random_truncate:
107
+ offset = torch.randint(0, len(sequence) - max_length + 1, (1,)).item()
108
+ else:
109
+ offset = 0
110
+ for key in encoded_inputs:
111
+ encoded_inputs[key][i] = encoded_inputs[key][i][offset : offset + max_length]
112
+
113
+ # add option for different random truncate
114
+
115
+ return encoded_inputs
116
+
117
+ def remove_ambiguous(self, encoded_inputs: Dict[str, List[int]]) -> Dict[str, List[List[int]]]:
118
+ """
119
+ Remove ambiguous amino acids from the input sequences.
120
+
121
+ Args:
122
+ encoded_inputs (BatchEncoding): Tokenized inputs with keys like 'input_ids' as tensors.
123
+
124
+ Returns:
125
+ Dict[str, List[List[int]]]: Tokenized inputs without ambiguous amino acids.
126
+ """
127
+
128
+ for i, sequence in enumerate(encoded_inputs["input_ids"]):
129
+ mask = [token_id != self.unk_token_id for token_id in sequence]
130
+ for key in encoded_inputs:
131
+ encoded_inputs[key][i] = list(compress(encoded_inputs[key][i], mask))
132
+ return encoded_inputs
133
+
134
+ def _pad(
135
+ self,
136
+ encoded_inputs: Dict[str, List[List[int]]],
137
+ padding: Union[bool, str] = True,
138
+ max_length: Optional[int] = None,
139
+ pad_to_multiple_of: int = 8,
140
+ **kwargs,
141
+ ) -> Dict[str, List[List[int]]]:
142
+
143
+ if isinstance(encoded_inputs, list):
144
+ tmp = dict()
145
+ for key in encoded_inputs[0]:
146
+ tmp[key] = [encoded_inputs[i][key] for i in range(len(encoded_inputs))]
147
+ encoded_inputs = tmp
148
+
149
+ if max_length is None:
150
+ max_length = self.model_max_length
151
+
152
+ sequence_lengths = [len(sequence) for sequence in encoded_inputs["input_ids"]]
153
+ if padding == "longest" or padding == True:
154
+ max_length = min(max_length, max(sequence_lengths))
155
+
156
+ if pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
157
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
158
+
159
+ for i, seq_len in enumerate(sequence_lengths):
160
+ if seq_len < max_length:
161
+ for key in encoded_inputs:
162
+ encoded_inputs[key][i] = encoded_inputs[key][i] + [self.key_to_padding[key]] * (max_length - seq_len)
163
+
164
+ return encoded_inputs
165
+
166
+ def pad(
167
+ self,
168
+ encoded_inputs: Dict[str, List[List[int]]],
169
+ padding: Union[bool, str] = True,
170
+ max_length: Optional[int] = None,
171
+ pad_to_multiple_of: int = 8,
172
+ return_tensors: str = "pt",
173
+ **kwargs,
174
+ ) -> Dict[str, List[List[int]]]:
175
+
176
+ encoded_inputs = self._pad(
177
+ encoded_inputs,
178
+ padding,
179
+ max_length,
180
+ pad_to_multiple_of,
181
+ **kwargs,
182
+ )
183
+
184
+ if return_tensors is not None:
185
+ return BatchEncoding(encoded_inputs, tensor_type=return_tensors)
186
+
187
+ return encoded_inputs
188
+
189
+ def __call__(
190
+ self,
191
+ text: str | List[str],
192
+ max_length: Optional[int] = None,
193
+ padding: Union[bool, str] = False,
194
+ truncation: bool = False,
195
+ random_truncate: bool = False,
196
+ remove_ambiguous: bool = False,
197
+ return_special_tokens_mask: bool = True,
198
+ return_tensors: str = None,
199
+ add_special_tokens: bool = True,
200
+ **kwargs,
201
+ ) -> Dict[str, Tensor]:
202
+
203
+ if isinstance(text, str):
204
+ encoded_inputs = self.__call__(
205
+ [text],
206
+ max_length,
207
+ padding,
208
+ truncation,
209
+ random_truncate,
210
+ remove_ambiguous,
211
+ return_special_tokens_mask,
212
+ return_tensors,
213
+ )
214
+ for key in encoded_inputs:
215
+ encoded_inputs[key] = encoded_inputs[key][0]
216
+ return encoded_inputs
217
+
218
+ # Tokenize without truncation or padding
219
+ encoded_inputs = super().__call__(
220
+ text,
221
+ padding=False,
222
+ truncation=False,
223
+ verbose=False,
224
+ return_special_tokens_mask=return_special_tokens_mask,
225
+ **kwargs,
226
+ )
227
+
228
+ if max_length is None:
229
+ max_length = self.model_max_length
230
+
231
+ # Add special tokens
232
+ if add_special_tokens:
233
+ encoded_inputs["input_ids"] = [[self.bos_token_id] + seq + [self.eos_token_id] for seq in encoded_inputs["input_ids"]]
234
+ encoded_inputs["attention_mask"] = [[1, 1] + seq for seq in encoded_inputs["attention_mask"]]
235
+ encoded_inputs["special_tokens_mask"] = [[1] + seq + [1] for seq in encoded_inputs["special_tokens_mask"]]
236
+
237
+ # Truncate
238
+ if truncation:
239
+ encoded_inputs = self.truncate(
240
+ encoded_inputs,
241
+ max_length=max_length, # Need to account for the BOS and EOS tokens
242
+ random_truncate=random_truncate,
243
+ )
244
+
245
+ ## NOTE: Moved this to after truncation to avoid the offset when random truncation is used
246
+ # Track original position indexes
247
+ encoded_inputs["position_ids"] = [list(range(len(seq))) for seq in encoded_inputs["input_ids"]]
248
+
249
+ # Remove ambiguous amino acids
250
+ if remove_ambiguous:
251
+ encoded_inputs = self.remove_ambiguous(encoded_inputs)
252
+
253
+ # Add padding
254
+ if padding:
255
+ encoded_inputs = self._pad(encoded_inputs, max_length=max_length, return_tensors=return_tensors)
256
+
257
+ if return_tensors is not None:
258
+ return BatchEncoding(encoded_inputs, tensor_type=return_tensors)
259
+
260
+ return encoded_inputs
tokenizer_config.json ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<pad>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<unk>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<mask>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<bos>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "<eos>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "auto_map": {
45
+ "AutoTokenizer": [
46
+ "tokenizer.ProteinTokenizer",
47
+ null
48
+ ]
49
+ },
50
+ "bos_token": "<bos>",
51
+ "bos_token_id": 3,
52
+ "clean_up_tokenization_spaces": false,
53
+ "eos_token": "<eos>",
54
+ "eos_token_id": 4,
55
+ "mask_token": "<mask>",
56
+ "mask_token_id": 2,
57
+ "model_input_names": [
58
+ "input_ids",
59
+ "attention_mask",
60
+ "special_tokens_mask"
61
+ ],
62
+ "model_max_length": 2048,
63
+ "other_special_token_ids": null,
64
+ "pad_token": "<pad>",
65
+ "pad_token_id": 0,
66
+ "padding_side": "right",
67
+ "tokenizer_class": "ProteinTokenizer",
68
+ "truncation_side": "right",
69
+ "unk_token": "<unk>",
70
+ "unk_token_id": 1,
71
+ "vocab": {
72
+ "<bos>": 3,
73
+ "<eos>": 4,
74
+ "<mask>": 2,
75
+ "<pad>": 0,
76
+ "<unk>": 1,
77
+ "A": 7,
78
+ "B": 26,
79
+ "C": 25,
80
+ "D": 15,
81
+ "E": 11,
82
+ "F": 20,
83
+ "G": 8,
84
+ "H": 23,
85
+ "I": 14,
86
+ "K": 17,
87
+ "L": 6,
88
+ "M": 22,
89
+ "N": 19,
90
+ "P": 16,
91
+ "Q": 18,
92
+ "R": 12,
93
+ "S": 10,
94
+ "T": 13,
95
+ "V": 9,
96
+ "W": 24,
97
+ "Y": 21,
98
+ "|": 5
99
+ }
100
+ }