fracapuano commited on
Commit
45c3d78
·
verified ·
1 Parent(s): 80aeadd

Upload Seq2SeqCrossFormer

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