Upload Seq2SeqCrossFormer
Browse files- README.md +199 -0
- config.json +10 -10
- generation_config.json +7 -0
- hf_transformer.py +372 -0
- model.safetensors +2 -2
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]
|
config.json
CHANGED
@@ -2,24 +2,24 @@
|
|
2 |
"architectures": [
|
3 |
"Seq2SeqCrossFormer"
|
4 |
],
|
5 |
-
"
|
|
|
|
|
6 |
"bos_token_id": 1,
|
7 |
-
"d_ff":
|
8 |
-
"d_model":
|
9 |
-
"dropout": 0.
|
10 |
"eos_token_id": 2,
|
11 |
-
"model_size": 105627906,
|
12 |
"model_type": "custom_code",
|
13 |
-
"n_heads":
|
14 |
-
"n_layers":
|
15 |
-
"num_train_epochs": 20,
|
16 |
"pad_token_id": 0,
|
17 |
"router_dim": 10,
|
18 |
-
"sequence_length":
|
19 |
"source_sequence_dimension": 70,
|
20 |
"target_sequence_dimension": 306,
|
21 |
"torch_dtype": "float32",
|
22 |
-
"transformers_version": "4.
|
23 |
"vocab_size_src": 258,
|
24 |
"vocab_size_tgt": 258
|
25 |
}
|
|
|
2 |
"architectures": [
|
3 |
"Seq2SeqCrossFormer"
|
4 |
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoModel": "hf_transformer.Seq2SeqCrossFormer"
|
7 |
+
},
|
8 |
"bos_token_id": 1,
|
9 |
+
"d_ff": 2048,
|
10 |
+
"d_model": 512,
|
11 |
+
"dropout": 0.1,
|
12 |
"eos_token_id": 2,
|
|
|
13 |
"model_type": "custom_code",
|
14 |
+
"n_heads": 8,
|
15 |
+
"n_layers": 6,
|
|
|
16 |
"pad_token_id": 0,
|
17 |
"router_dim": 10,
|
18 |
+
"sequence_length": 8192,
|
19 |
"source_sequence_dimension": 70,
|
20 |
"target_sequence_dimension": 306,
|
21 |
"torch_dtype": "float32",
|
22 |
+
"transformers_version": "4.49.0.dev0",
|
23 |
"vocab_size_src": 258,
|
24 |
"vocab_size_tgt": 258
|
25 |
}
|
generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"pad_token_id": 0,
|
6 |
+
"transformers_version": "4.49.0.dev0"
|
7 |
+
}
|
hf_transformer.py
ADDED
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import matplotlib.pyplot as plt
|
2 |
+
import seaborn as sns
|
3 |
+
from tqdm import tqdm
|
4 |
+
|
5 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
6 |
+
from typing import Optional, Tuple, Union
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
from model.architectures.transformer import EncoderDecoderTransformer
|
10 |
+
from model.architectures.crossformer import EncoderDecoderCrossFormer
|
11 |
+
from model.hf_configs import Seq2SeqConfig, Seq2SeqCrossConfig
|
12 |
+
from einops import rearrange
|
13 |
+
|
14 |
+
class Seq2SeqTransformer(PreTrainedModel):
|
15 |
+
"""
|
16 |
+
Custom Transformer for Sequence to Sequence tasks.
|
17 |
+
"""
|
18 |
+
config_class = Seq2SeqConfig
|
19 |
+
base_model_prefix = "transformer"
|
20 |
+
|
21 |
+
def __init__(self, config: PretrainedConfig, device: Optional[str]=None):
|
22 |
+
super().__init__(config)
|
23 |
+
self.softmax = nn.Softmax(dim=-1)
|
24 |
+
|
25 |
+
self.transformer = EncoderDecoderTransformer(
|
26 |
+
src_vocab_size=config.vocab_size_src,
|
27 |
+
tgt_vocab_size=config.vocab_size_tgt,
|
28 |
+
embed_dim=config.d_model,
|
29 |
+
num_heads=config.n_heads,
|
30 |
+
ff_dim=config.d_ff,
|
31 |
+
num_encoder_layers=config.n_layers,
|
32 |
+
num_decoder_layers=config.n_layers,
|
33 |
+
max_seq_length=config.sequence_length
|
34 |
+
)
|
35 |
+
|
36 |
+
def _init_weights(self, module: nn.Module):
|
37 |
+
if isinstance(module, nn.Linear):
|
38 |
+
nn.init.xavier_uniform_(module.weight)
|
39 |
+
if module.bias is not None:
|
40 |
+
nn.init.constant_(module.bias, 0)
|
41 |
+
|
42 |
+
def _create_padding_mask(self, ids: torch.LongTensor) -> torch.DoubleTensor:
|
43 |
+
"""Creates a mask to avoid padded tokens to be interfering with attention"""
|
44 |
+
# First create boolean mask where True = padding token
|
45 |
+
is_padding = ids.eq(self.config.pad_token_id)
|
46 |
+
|
47 |
+
# Convert to float and replace padding positions with -inf, others with 1.0
|
48 |
+
mask = is_padding.float()
|
49 |
+
mask = mask.masked_fill(is_padding, float('-inf'))
|
50 |
+
mask = mask.masked_fill(~is_padding, 1.0)
|
51 |
+
return mask
|
52 |
+
|
53 |
+
def _shift_right(self, x: torch.LongTensor) -> torch.LongTensor:
|
54 |
+
"""Helper method to prepare decoder inputs (teacher forcing) by shifting right label tokens"""
|
55 |
+
shifted = torch.full(
|
56 |
+
(*x.shape[:-1], 1),
|
57 |
+
self.config.bos_token_id,
|
58 |
+
dtype=x.dtype,
|
59 |
+
device=x.device
|
60 |
+
)
|
61 |
+
shifted = torch.cat([shifted, x[:, :-1]], dim=-1)
|
62 |
+
return shifted
|
63 |
+
|
64 |
+
def _add_beginning_of_stream(self, x: torch.LongTensor) -> torch.LongTensor:
|
65 |
+
"""
|
66 |
+
Helper method to add BOS token to the beginning of input sequences
|
67 |
+
"""
|
68 |
+
bos = torch.full(
|
69 |
+
(*x.shape[:-1], 1),
|
70 |
+
self.config.bos_token_id,
|
71 |
+
dtype=x.dtype,
|
72 |
+
device=x.device
|
73 |
+
)
|
74 |
+
|
75 |
+
return torch.cat([bos, x], dim=-1)
|
76 |
+
|
77 |
+
def _add_end_of_stream(self, x: torch.LongTensor) -> torch.LongTensor:
|
78 |
+
"""Helper method to add EOS token to the end of label sequences"""
|
79 |
+
eos = torch.full(
|
80 |
+
(*x.shape[:-1], 1),
|
81 |
+
self.config.eos_token_id,
|
82 |
+
dtype=x.dtype,
|
83 |
+
device=x.device
|
84 |
+
)
|
85 |
+
return torch.cat([x, eos], dim=-1)
|
86 |
+
|
87 |
+
def forward(
|
88 |
+
self,
|
89 |
+
input_ids: torch.LongTensor,
|
90 |
+
labels: Optional[torch.LongTensor] = None,
|
91 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
92 |
+
attention_mask: Optional[torch.Tensor] = None,
|
93 |
+
decoder_attention_mask: Optional[torch.BoolTensor] = None,
|
94 |
+
**kwargs
|
95 |
+
) -> Union[Tuple, dict]:
|
96 |
+
# TODO: add/end of streaming and right shift should take place outside of the model in tokenizer
|
97 |
+
|
98 |
+
# adding beginning of stream tokens to input too
|
99 |
+
input_ids = self._add_beginning_of_stream(input_ids)
|
100 |
+
|
101 |
+
# adding end of stream tokens to labels
|
102 |
+
labels = self._add_end_of_stream(labels)
|
103 |
+
# Prepare input for the decoder
|
104 |
+
if decoder_input_ids is None and labels is not None:
|
105 |
+
decoder_input_ids = self._shift_right(labels)
|
106 |
+
|
107 |
+
src_key_padding_mask = self._create_padding_mask(input_ids)
|
108 |
+
tgt_key_padding_mask = self._create_padding_mask(decoder_input_ids)
|
109 |
+
|
110 |
+
# Forward pass through your model
|
111 |
+
outputs = self.transformer(
|
112 |
+
src=input_ids,
|
113 |
+
tgt=decoder_input_ids,
|
114 |
+
src_mask=attention_mask,
|
115 |
+
tgt_mask=decoder_attention_mask,
|
116 |
+
src_key_padding_mask=src_key_padding_mask,
|
117 |
+
tgt_key_padding_mask=tgt_key_padding_mask
|
118 |
+
)
|
119 |
+
|
120 |
+
loss = None
|
121 |
+
if labels is not None:
|
122 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
|
123 |
+
loss = loss_fct(outputs.view(-1, self.config.vocab_size_tgt), labels.view(-1))
|
124 |
+
|
125 |
+
return dict(
|
126 |
+
loss=loss,
|
127 |
+
logits=outputs,
|
128 |
+
)
|
129 |
+
|
130 |
+
def generate(
|
131 |
+
self,
|
132 |
+
input_ids: torch.LongTensor,
|
133 |
+
attention_mask: Optional[torch.Tensor] = None,
|
134 |
+
max_length: Optional[int] = None,
|
135 |
+
temperature: float = 1.0,
|
136 |
+
do_sample: bool = False,
|
137 |
+
**kwargs
|
138 |
+
) -> torch.LongTensor:
|
139 |
+
|
140 |
+
batch_size = input_ids.shape[0]
|
141 |
+
max_length = max_length or self.config.max_length or 128
|
142 |
+
|
143 |
+
decoder_input_ids = torch.full(
|
144 |
+
(batch_size, 1),
|
145 |
+
self.config.bos_token_id,
|
146 |
+
dtype=torch.long,
|
147 |
+
device=input_ids.device
|
148 |
+
)
|
149 |
+
|
150 |
+
for _ in range(max_length - 1):
|
151 |
+
outputs = self.forward(
|
152 |
+
input_ids=input_ids,
|
153 |
+
decoder_input_ids=decoder_input_ids,
|
154 |
+
attention_mask=attention_mask,
|
155 |
+
)
|
156 |
+
|
157 |
+
next_token_logits = outputs["logits"][:, -1, :]
|
158 |
+
|
159 |
+
if do_sample:
|
160 |
+
# Apply temperature scaling
|
161 |
+
scaled_logits = next_token_logits / temperature
|
162 |
+
# Convert to probabilities
|
163 |
+
next_token_probs = self.softmax(scaled_logits)
|
164 |
+
# Sample from the probability distribution
|
165 |
+
next_token = torch.multinomial(
|
166 |
+
next_token_probs, num_samples=1
|
167 |
+
).squeeze(-1)
|
168 |
+
else:
|
169 |
+
# Greedy decoding
|
170 |
+
next_token = next_token_logits.argmax(dim=-1)
|
171 |
+
|
172 |
+
decoder_input_ids = torch.cat(
|
173 |
+
[decoder_input_ids, next_token.unsqueeze(-1)],
|
174 |
+
dim=-1
|
175 |
+
)
|
176 |
+
|
177 |
+
# Stop if all sequences have generated EOS token
|
178 |
+
if (decoder_input_ids == self.config.eos_token_id).any(dim=-1).all():
|
179 |
+
break
|
180 |
+
|
181 |
+
return decoder_input_ids
|
182 |
+
|
183 |
+
|
184 |
+
class Seq2SeqCrossFormer(Seq2SeqTransformer):
|
185 |
+
"""CrossFormer wrapper predicting over a discrete vocabulatory."""
|
186 |
+
config_class = Seq2SeqCrossConfig
|
187 |
+
|
188 |
+
def __init__(self, config: PretrainedConfig):
|
189 |
+
super().__init__(config)
|
190 |
+
self.softmax = nn.Softmax(dim=-1)
|
191 |
+
|
192 |
+
self.transformer = EncoderDecoderCrossFormer(
|
193 |
+
source_sequence_dimension=config.source_sequence_dimension,
|
194 |
+
target_sequence_dimension=config.target_sequence_dimension,
|
195 |
+
router_dim=config.router_dim,
|
196 |
+
src_vocab_size=config.vocab_size_src,
|
197 |
+
tgt_vocab_size=config.vocab_size_tgt,
|
198 |
+
embed_dim=config.d_model,
|
199 |
+
num_heads=config.n_heads,
|
200 |
+
ff_dim=config.d_ff,
|
201 |
+
num_encoder_layers=config.n_layers,
|
202 |
+
num_decoder_layers=config.n_layers,
|
203 |
+
max_seq_length=config.sequence_length
|
204 |
+
)
|
205 |
+
|
206 |
+
def _shift_right(self, x: torch.LongTensor) -> torch.LongTensor:
|
207 |
+
"""
|
208 |
+
Helper method to prepare decoder inputs (teacher forcing) by shifting right label tokens.
|
209 |
+
Handles 3D (B, S, C) tensors
|
210 |
+
"""
|
211 |
+
# Create shape that matches x's dimensions except for seq_len which will be 1
|
212 |
+
shape = list(x.shape)
|
213 |
+
shape[-2] = 1 # Set sequence dimension to 1
|
214 |
+
|
215 |
+
shifted = torch.full(
|
216 |
+
shape,
|
217 |
+
self.config.bos_token_id,
|
218 |
+
dtype=x.dtype,
|
219 |
+
device=x.device
|
220 |
+
)
|
221 |
+
shifted = torch.cat([shifted, x[..., :-1, :]], dim=-2)
|
222 |
+
return shifted
|
223 |
+
|
224 |
+
def _add_beginning_of_stream(self, x: torch.LongTensor) -> torch.LongTensor:
|
225 |
+
"""
|
226 |
+
Helper method to add BOS token to the beginning of input sequences.
|
227 |
+
Handles 3D (B, S, C) tensors
|
228 |
+
"""
|
229 |
+
shape = list(x.shape)
|
230 |
+
shape[-2] = 1 # Set sequence dimension to 1
|
231 |
+
sos = torch.full(
|
232 |
+
shape,
|
233 |
+
self.config.bos_token_id,
|
234 |
+
dtype=x.dtype,
|
235 |
+
device=x.device
|
236 |
+
)
|
237 |
+
|
238 |
+
return torch.cat([sos, x], dim=-2)
|
239 |
+
|
240 |
+
def _add_end_of_stream(self, x: torch.LongTensor) -> torch.LongTensor:
|
241 |
+
"""
|
242 |
+
Helper method to add EOS token to the end of label sequences.
|
243 |
+
Handles 3D (B, S, C) tensors
|
244 |
+
"""
|
245 |
+
# Create shape that matches x's dimensions except for seq_len which will be 1
|
246 |
+
shape = list(x.shape)
|
247 |
+
shape[-2] = 1 # Set sequence dimension to 1
|
248 |
+
|
249 |
+
eos = torch.full(
|
250 |
+
shape,
|
251 |
+
self.config.eos_token_id,
|
252 |
+
dtype=x.dtype,
|
253 |
+
device=x.device
|
254 |
+
)
|
255 |
+
return torch.cat([x, eos], dim=-2)
|
256 |
+
|
257 |
+
def forward(
|
258 |
+
self,
|
259 |
+
input_ids: torch.LongTensor,
|
260 |
+
labels: Optional[torch.LongTensor] = None,
|
261 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
262 |
+
**kwargs
|
263 |
+
):
|
264 |
+
# FIXME: add/end of streaming and right shift should take place outside of the model in tokenizer
|
265 |
+
|
266 |
+
# (in tokenizer) adding beginning of stream tokens to input too
|
267 |
+
input_ids = self._add_beginning_of_stream(input_ids)
|
268 |
+
|
269 |
+
# (in tokenizer) adding end of stream tokens to labels
|
270 |
+
if labels is not None:
|
271 |
+
labels = self._add_end_of_stream(labels)
|
272 |
+
|
273 |
+
# Prepare input for the decoder
|
274 |
+
if decoder_input_ids is None and labels is not None:
|
275 |
+
decoder_input_ids = self._shift_right(labels)
|
276 |
+
|
277 |
+
src_src_key_padding_time_mask = rearrange(
|
278 |
+
self._create_padding_mask(
|
279 |
+
input_ids
|
280 |
+
),
|
281 |
+
'b s c -> (b c) s'
|
282 |
+
)
|
283 |
+
|
284 |
+
tgt_tgt_key_padding_time_mask = rearrange(
|
285 |
+
self._create_padding_mask(
|
286 |
+
decoder_input_ids
|
287 |
+
),
|
288 |
+
'b s c -> (b c) s'
|
289 |
+
)
|
290 |
+
|
291 |
+
# Forward pass through your model
|
292 |
+
outputs = self.transformer(
|
293 |
+
src=input_ids,
|
294 |
+
tgt=decoder_input_ids,
|
295 |
+
src_src_time_mask=kwargs.get("src_src_time_mask"),
|
296 |
+
src_src_dimension_mask=kwargs.get("src_src_dimension_mask"),
|
297 |
+
src_src_key_padding_time_mask=src_src_key_padding_time_mask,
|
298 |
+
tgt_tgt_time_mask=kwargs.get("tgt_tgt_time_mask"),
|
299 |
+
tgt_tgt_dimension_mask=kwargs.get("tgt_tgt_dimension_mask"),
|
300 |
+
tgt_tgt_key_padding_time_mask=tgt_tgt_key_padding_time_mask,
|
301 |
+
tgt_src_dimension_mask=kwargs.get("tgt_src_dimension_mask")
|
302 |
+
)
|
303 |
+
|
304 |
+
loss = None
|
305 |
+
if labels is not None:
|
306 |
+
loss_fct = nn.CrossEntropyLoss(
|
307 |
+
ignore_index=self.config.pad_token_id
|
308 |
+
)
|
309 |
+
loss = loss_fct(
|
310 |
+
outputs.view(-1, self.config.vocab_size_tgt), labels.view(-1)
|
311 |
+
)
|
312 |
+
|
313 |
+
return dict(
|
314 |
+
loss=loss,
|
315 |
+
logits=outputs,
|
316 |
+
)
|
317 |
+
|
318 |
+
def generate(
|
319 |
+
self,
|
320 |
+
input_ids: torch.LongTensor,
|
321 |
+
attention_mask: Optional[torch.Tensor]=None,
|
322 |
+
max_length: Optional[int]=None,
|
323 |
+
temperature: float=1.0,
|
324 |
+
do_sample: bool=False,
|
325 |
+
**kwargs
|
326 |
+
) -> torch.LongTensor:
|
327 |
+
|
328 |
+
batch_size, timesteps, channels = input_ids.shape
|
329 |
+
|
330 |
+
src_key_padding_mask = self._create_padding_mask(input_ids)
|
331 |
+
max_length = max_length or self.config.max_length or 128
|
332 |
+
|
333 |
+
decoder_input_ids = torch.full(
|
334 |
+
(batch_size, timesteps + 1, 306), # decoder model generates MEG data
|
335 |
+
self.config.pad_token_id,
|
336 |
+
dtype=torch.long,
|
337 |
+
device=input_ids.device
|
338 |
+
)
|
339 |
+
|
340 |
+
# Set BOS token at the start
|
341 |
+
decoder_input_ids[:, 0, :] = self.config.bos_token_id
|
342 |
+
|
343 |
+
for t in tqdm(range(timesteps + max_length)):
|
344 |
+
outputs = self.forward(
|
345 |
+
input_ids=input_ids,
|
346 |
+
decoder_input_ids=decoder_input_ids,
|
347 |
+
attention_mask=attention_mask
|
348 |
+
)
|
349 |
+
|
350 |
+
# Get predictions for this timestep
|
351 |
+
next_token_logits = outputs["logits"][:, t, :]
|
352 |
+
|
353 |
+
if do_sample:
|
354 |
+
scaled_logits = next_token_logits / temperature
|
355 |
+
next_token_probs = self.softmax(scaled_logits)
|
356 |
+
next_token = torch.multinomial(
|
357 |
+
next_token_probs, num_samples=1
|
358 |
+
).squeeze(-1)
|
359 |
+
else:
|
360 |
+
next_token = next_token_logits.argmax(dim=-1)
|
361 |
+
|
362 |
+
# Place the predicted token at position t
|
363 |
+
decoder_input_ids[:, t, :] = next_token
|
364 |
+
|
365 |
+
# Check if all sequences have generated EOS token
|
366 |
+
if (next_token == self.config.eos_token_id).all():
|
367 |
+
break
|
368 |
+
|
369 |
+
decoder_input_ids = decoder_input_ids[:, -(timesteps+1):, :]
|
370 |
+
|
371 |
+
return decoder_input_ids
|
372 |
+
|
model.safetensors
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:af9bfed22b64ce72f8741b5d4f11b9a61060158c816627143ec6c00430165ef5
|
3 |
+
size 2393519960
|