Upload AMPLIFY
Browse files- README.md +199 -0
- amplify.py +347 -0
- config.json +37 -0
- model.safetensors +3 -0
- rmsnorm.py +34 -0
- rotary.py +80 -0
- tokenizer.py +133 -0
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,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
cfg["tokenizer"]["vocab_path"] = "/home/mila/l/lola.lebreton/AMPLIFY/conf/tokenizer/amplify_vocab.txt"
|
282 |
+
tokenizer = ProteinTokenizer(**cfg["tokenizer"])
|
283 |
+
return model, tokenizer
|
284 |
+
|
285 |
+
def forward(
|
286 |
+
self,
|
287 |
+
src,
|
288 |
+
position_ids: torch.Tensor = None,
|
289 |
+
max_seqlen: int = None,
|
290 |
+
cu_seqlens: torch.Tensor = None,
|
291 |
+
pad_mask=None,
|
292 |
+
output_hidden_states=False,
|
293 |
+
output_attentions=False,
|
294 |
+
):
|
295 |
+
# Initialize
|
296 |
+
hidden_states, attentions = [], []
|
297 |
+
|
298 |
+
# We will output all the hidden_states that have an index higher than output_hidden_index
|
299 |
+
if type(output_hidden_states) == bool and not output_hidden_states:
|
300 |
+
output_hidden_index = self.config.num_hidden_layers + 1
|
301 |
+
elif type(output_hidden_states) == int:
|
302 |
+
output_hidden_index = output_hidden_states
|
303 |
+
else:
|
304 |
+
output_hidden_index = 0
|
305 |
+
|
306 |
+
# Expand and repeat: (Batch, Length) -> (Batch, Heads, Length, Length)
|
307 |
+
if pad_mask is not None:
|
308 |
+
pad_mask = pad_mask.unsqueeze(1).unsqueeze(1).repeat(1, self.config.num_attention_heads, pad_mask.size(-1), 1)
|
309 |
+
|
310 |
+
if output_attentions:
|
311 |
+
pad_mask = torch.where(pad_mask == 1, float(0.0), float("-inf"))
|
312 |
+
|
313 |
+
# Checks to be done if inputs are packed sequences
|
314 |
+
if cu_seqlens is not None:
|
315 |
+
assert not output_attentions, "Output attentions is not supported when sequences are packed."
|
316 |
+
assert max_seqlen is not None, "Missing max_seqlen. It must be provided when cu_seqlens are not None."
|
317 |
+
assert src.shape[0] == 1, "Cumulative sequence lengths are provided but src are not packed."
|
318 |
+
assert src.is_cuda, "Packing uses an implementation of flash-attention and is only supported on GPU."
|
319 |
+
|
320 |
+
# Create position_ids if not provided
|
321 |
+
if position_ids is None:
|
322 |
+
position_ids = torch.stack([torch.arange(0, seqlen, device=src.device) for seqlen in cu_seqlens], dim=0)
|
323 |
+
|
324 |
+
# RoPE
|
325 |
+
if position_ids is not None:
|
326 |
+
freqs_cis = self.freqs_cis[position_ids]
|
327 |
+
else:
|
328 |
+
freqs_cis = self.freqs_cis[: src.shape[1]]
|
329 |
+
|
330 |
+
# Embedding
|
331 |
+
x = self.encoder(src)
|
332 |
+
if self.config.layer_norm_after_embedding:
|
333 |
+
x = self.layer_norm_1(x)
|
334 |
+
|
335 |
+
# Transformer encoder
|
336 |
+
for idx, layer in enumerate(self.transformer_encoder):
|
337 |
+
x, attn = layer(x, pad_mask, freqs_cis, output_attentions, max_seqlen, cu_seqlens)
|
338 |
+
if idx >= output_hidden_index:
|
339 |
+
hidden_states.append(x)
|
340 |
+
if output_attentions:
|
341 |
+
attentions.append(attn)
|
342 |
+
|
343 |
+
# Classification head with layer norm
|
344 |
+
logits = self.decoder(self.layer_norm_2(x) if self.config.layer_norm_before_last_layer else x)
|
345 |
+
|
346 |
+
# Return logits or the output of the last hidden layer
|
347 |
+
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": "conf/tokenizer/plm_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:a2375f1f54cbe00bdbe27eedcd039c92d12f165720c0349bc582a6eb42c099ce
|
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,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""
|
30 |
+
Reshape frequency tensor for broadcasting it with another tensor.
|
31 |
+
|
32 |
+
This function reshapes the frequency tensor to have the same shape as the target tensor 'x'
|
33 |
+
for the purpose of broadcasting the frequency tensor during element-wise operations.
|
34 |
+
|
35 |
+
Args:
|
36 |
+
freqs_cis (torch.Tensor): Frequency tensor to be reshaped.
|
37 |
+
x (torch.Tensor): Target tensor for broadcasting compatibility.
|
38 |
+
|
39 |
+
Returns:
|
40 |
+
torch.Tensor: Reshaped frequency tensor.
|
41 |
+
|
42 |
+
Raises:
|
43 |
+
AssertionError: If the frequency tensor doesn't match the expected shape.
|
44 |
+
AssertionError: If the target tensor 'x' doesn't have the expected number of dimensions.
|
45 |
+
"""
|
46 |
+
|
47 |
+
ndim = x.ndim
|
48 |
+
assert 0 <= 1 < ndim
|
49 |
+
assert freqs_cis.shape == (x.shape[1], x.shape[-1])
|
50 |
+
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
|
51 |
+
return freqs_cis.view(*shape)
|
52 |
+
|
53 |
+
|
54 |
+
def apply_rotary_emb(
|
55 |
+
xq: torch.Tensor,
|
56 |
+
xk: torch.Tensor,
|
57 |
+
freqs_cis: torch.Tensor,
|
58 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
59 |
+
"""
|
60 |
+
Apply rotary embeddings to input tensors using the given frequency tensor.
|
61 |
+
|
62 |
+
This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided
|
63 |
+
frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor
|
64 |
+
is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are
|
65 |
+
returned as real tensors.
|
66 |
+
|
67 |
+
Args:
|
68 |
+
xq (torch.Tensor): Query tensor to apply rotary embeddings.
|
69 |
+
xk (torch.Tensor): Key tensor to apply rotary embeddings.
|
70 |
+
freqs_cis (torch.Tensor): Precomputed frequency tensor for complex exponentials.
|
71 |
+
|
72 |
+
Returns:
|
73 |
+
Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
|
74 |
+
"""
|
75 |
+
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
|
76 |
+
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
|
77 |
+
freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
|
78 |
+
xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
|
79 |
+
xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
|
80 |
+
return xq_out.type_as(xq), xk_out.type_as(xk)
|
tokenizer.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from typing import List, Optional, Union
|
3 |
+
from torch import Tensor
|
4 |
+
|
5 |
+
|
6 |
+
class ProteinTokenizer(object):
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
vocab_path: str,
|
10 |
+
pad_token_id: int,
|
11 |
+
mask_token_id: int,
|
12 |
+
bos_token_id: int,
|
13 |
+
eos_token_id: int,
|
14 |
+
unk_token_id: int,
|
15 |
+
other_special_token_ids: Optional[List[int]],
|
16 |
+
**kwargs,
|
17 |
+
):
|
18 |
+
"""Vocabulary comprising the amino acids, and the special tokens <unk>, <bos>, <eos>, <pad> and <mask>.
|
19 |
+
|
20 |
+
Args:
|
21 |
+
vocab_path (str): Path to the vocabulary file to load.
|
22 |
+
pad_token_id (int): <PAD> token index.
|
23 |
+
mask_token_id (int): <MASK> token index.
|
24 |
+
bos_token_id (int): <BOS> token index.
|
25 |
+
eos_token_id (int): <EOS> token index.
|
26 |
+
unk_token_id (int): <UNK> token index.
|
27 |
+
other_special_token_ids (Optional[List[int]]): List of additional special tokens.
|
28 |
+
"""
|
29 |
+
self._token_to_id = dict()
|
30 |
+
self._id_to_token = dict()
|
31 |
+
|
32 |
+
with open(vocab_path, "r") as vocab_file:
|
33 |
+
for i, token in enumerate(vocab_file):
|
34 |
+
token = token.strip()
|
35 |
+
self._token_to_id[token] = i
|
36 |
+
self._id_to_token[i] = token
|
37 |
+
|
38 |
+
# Padding token
|
39 |
+
self.pad_token_id = pad_token_id
|
40 |
+
self.pad_token = self._token_to_id.get(pad_token_id)
|
41 |
+
|
42 |
+
# Beginning and end of sequence
|
43 |
+
self.bos_token_id = bos_token_id
|
44 |
+
self.eos_token_id = eos_token_id
|
45 |
+
self.bos_token = self._token_to_id.get(bos_token_id)
|
46 |
+
self.eos_token = self._token_to_id.get(eos_token_id)
|
47 |
+
|
48 |
+
# Mask token
|
49 |
+
self.mask_token_id = mask_token_id
|
50 |
+
self.mask_token = self._token_to_id.get(mask_token_id)
|
51 |
+
|
52 |
+
# Unknown token
|
53 |
+
self.unk_token_id = unk_token_id
|
54 |
+
self.unk_token = self._id_to_token.get(unk_token_id)
|
55 |
+
|
56 |
+
# Set of all special token indices
|
57 |
+
self.special_token_ids = set()
|
58 |
+
self.special_token_ids.add(pad_token_id)
|
59 |
+
self.special_token_ids.add(mask_token_id)
|
60 |
+
self.special_token_ids.add(bos_token_id)
|
61 |
+
self.special_token_ids.add(eos_token_id)
|
62 |
+
self.special_token_ids.add(unk_token_id)
|
63 |
+
if other_special_token_ids is not None:
|
64 |
+
self.special_token_ids.update(other_special_token_ids)
|
65 |
+
|
66 |
+
def __len__(self) -> int:
|
67 |
+
return len(self._token_to_id)
|
68 |
+
|
69 |
+
def token_to_id(self, token: str) -> int:
|
70 |
+
return self._token_to_id.get(token, self.unk_token_id)
|
71 |
+
|
72 |
+
def id_to_token(self, index: int) -> str:
|
73 |
+
return self._id_to_token.get(index, self.unk_token)
|
74 |
+
|
75 |
+
def encode(
|
76 |
+
self,
|
77 |
+
tokens: List[str],
|
78 |
+
max_length: Optional[int] = None,
|
79 |
+
add_special_tokens: bool = True,
|
80 |
+
random_truncate: bool = True,
|
81 |
+
**kwargs,
|
82 |
+
) -> Union[List[int], Tensor]:
|
83 |
+
"""Encodes a list of tokens into a list or tensor of token indices.
|
84 |
+
|
85 |
+
Args:
|
86 |
+
tokens (List[str]): Sequence of tokens to encode.
|
87 |
+
max_length (Optional[int], optional): Truncate the sequence to the specified length. Defaults to None.
|
88 |
+
add_special_tokens (bool, optional): Add special tokens <bos> and <eos> at the start and end.. Defaults to True.
|
89 |
+
random_truncate (bool, optional): Truncate the sequence to a random subsequence of if longer than truncate.
|
90 |
+
Defaults to True.
|
91 |
+
|
92 |
+
Returns:
|
93 |
+
Union[List[int], Tensor]: Token indices.
|
94 |
+
"""
|
95 |
+
token_ids = list(map(self.token_to_id, tokens))
|
96 |
+
if add_special_tokens:
|
97 |
+
token_ids = [self.bos_token_id] + token_ids + [self.eos_token_id]
|
98 |
+
if max_length is not None and max_length < len(token_ids):
|
99 |
+
if random_truncate:
|
100 |
+
offset = int(torch.randint(0, len(token_ids) - max_length, (1,)).item())
|
101 |
+
else:
|
102 |
+
offset = 0
|
103 |
+
token_ids = token_ids[offset : offset + max_length]
|
104 |
+
return torch.as_tensor(token_ids, dtype=torch.long)
|
105 |
+
|
106 |
+
def decode(
|
107 |
+
self,
|
108 |
+
token_ids: List[int],
|
109 |
+
skip_special_tokens: bool = True,
|
110 |
+
**kwargs,
|
111 |
+
) -> Union[List[str], str]:
|
112 |
+
"""Decodes a list or tensor of token ids into a list or string of tokens.
|
113 |
+
|
114 |
+
Args:
|
115 |
+
token_ids (List[int]): Token indices to decode.
|
116 |
+
skip_special_tokens (bool, optional): Skip the special tokens <bos> and <eos> at the start and end.
|
117 |
+
Defaults to True.
|
118 |
+
|
119 |
+
Returns:
|
120 |
+
Union[List[str], str]: Protein.
|
121 |
+
"""
|
122 |
+
if torch.is_tensor(token_ids):
|
123 |
+
token_ids = token_ids.tolist()
|
124 |
+
|
125 |
+
if skip_special_tokens:
|
126 |
+
if len(token_ids) > 0 and token_ids[0] in self.special_token_ids:
|
127 |
+
token_ids = token_ids[1:]
|
128 |
+
if len(token_ids) > 0 and token_ids[-1] in self.special_token_ids:
|
129 |
+
token_ids = token_ids[:-1]
|
130 |
+
|
131 |
+
tokens = " ".join(map(self.id_to_token, token_ids))
|
132 |
+
|
133 |
+
return tokens
|