oujingyang commited on
Commit
53817ad
·
0 Parent(s):

upload code model

Browse files
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ ---
4
+
5
+ Post-Training Full models on code task based on LLaDA-8B-Instruct for the paper Principled RL for Diffusion LLMs Emerges from a Sequence-Level Perspective
config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_type": "silu",
3
+ "alibi": false,
4
+ "alibi_bias_max": 8.0,
5
+ "architectures": [
6
+ "LLaDAModelLM"
7
+ ],
8
+ "attention_dropout": 0.0,
9
+ "attention_layer_norm": false,
10
+ "attention_layer_norm_with_affine": true,
11
+ "auto_map": {
12
+ "AutoConfig": "configuration_llada.LLaDAConfig",
13
+ "AutoModel": "modeling_llada.LLaDAModelLM",
14
+ "AutoModelForCausalLM": "modeling_llada.LLaDAModelLM"
15
+ },
16
+ "bias_for_layer_norm": false,
17
+ "block_group_size": 1,
18
+ "block_type": "llama",
19
+ "d_model": 4096,
20
+ "embedding_dropout": 0.0,
21
+ "embedding_size": 126464,
22
+ "eos_token_id": 126081,
23
+ "flash_attention": false,
24
+ "include_bias": false,
25
+ "include_qkv_bias": false,
26
+ "init_cutoff_factor": null,
27
+ "init_device": "meta",
28
+ "init_fn": "mitchell",
29
+ "init_std": 0.02,
30
+ "input_emb_norm": false,
31
+ "layer_norm_type": "rms",
32
+ "layer_norm_with_affine": true,
33
+ "mask_token_id": 126336,
34
+ "max_sequence_length": 4096,
35
+ "mlp_hidden_size": 12288,
36
+ "mlp_ratio": 4,
37
+ "model_type": "llada",
38
+ "multi_query_attention": null,
39
+ "n_heads": 32,
40
+ "n_kv_heads": 32,
41
+ "n_layers": 32,
42
+ "pad_token_id": 126081,
43
+ "precision": "amp_bf16",
44
+ "residual_dropout": 0.0,
45
+ "rms_norm_eps": 1e-05,
46
+ "rope": true,
47
+ "rope_full_precision": true,
48
+ "rope_theta": 500000.0,
49
+ "scale_logits": false,
50
+ "torch_dtype": "bfloat16",
51
+ "transformers_version": "4.52.4",
52
+ "use_cache": false,
53
+ "vocab_size": 126464,
54
+ "weight_tying": false
55
+ }
configuration_llada.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LLaDA configuration
3
+ """
4
+ from transformers import AutoConfig, PretrainedConfig
5
+
6
+ from enum import Enum
7
+ from os import PathLike
8
+ from typing import Union
9
+ from dataclasses import asdict, dataclass, field
10
+ from glob import glob
11
+ from pathlib import Path
12
+ from typing import (
13
+ Any,
14
+ Dict,
15
+ Iterable,
16
+ List,
17
+ Optional,
18
+ Tuple,
19
+ Type,
20
+ TypeVar,
21
+ Union,
22
+ cast,
23
+ )
24
+
25
+
26
+ __all__ = [
27
+ "ActivationType",
28
+ "ActivationCheckpointingStrategy",
29
+ "BlockType",
30
+ "LayerNormType",
31
+ "InitFnType",
32
+ "ModelConfig",
33
+ ]
34
+
35
+ PathOrStr = Union[str, PathLike]
36
+
37
+
38
+ class StrEnum(str, Enum):
39
+ """
40
+ This is equivalent to Python's :class:`enum.StrEnum` since version 3.11.
41
+ We include this here for compatibility with older version of Python.
42
+ """
43
+
44
+ def __str__(self) -> str:
45
+ return self.value
46
+
47
+ def __repr__(self) -> str:
48
+ return f"'{str(self)}'"
49
+
50
+
51
+ class LayerNormType(StrEnum):
52
+ default = "default"
53
+ """
54
+ The default LayerNorm implementation, equivalent to PyTorch's built-in version.
55
+ """
56
+
57
+ low_precision = "low_precision"
58
+ """
59
+ A low-precision version of the default LayerNorm.
60
+ """
61
+
62
+ rms = "rms"
63
+ """
64
+ An RMSNorm implementation. When using ``torch.compile`` this is
65
+ probably the fastest implementation.
66
+ """
67
+
68
+ gemma_rms = "gemma_rms"
69
+ """
70
+ An RMSNorm implementation by gemmma. When using ``torch.compile`` this is
71
+ probably the fastest implementation.
72
+ """
73
+
74
+ amd_compatible = "amd_compatible"
75
+ """
76
+ LayerNorm implemented manually to work around an issue with ROCm.
77
+ """
78
+
79
+
80
+ class ActivationType(StrEnum):
81
+ gelu = "gelu"
82
+ relu = "relu"
83
+ silu = "silu"
84
+ swiglu = "swiglu"
85
+
86
+
87
+ class BlockType(StrEnum):
88
+ sequential = "sequential"
89
+ parallel = "parallel"
90
+
91
+ llama = "llama"
92
+ """
93
+ A block similar to the sequential block with slightly different
94
+ implementations of operations like attention to imitate the behavior of Llama.
95
+ """
96
+
97
+
98
+ class InitFnType(StrEnum):
99
+ mitchell = "mitchell"
100
+ """
101
+ The strategy suggested to us by Mitchell Wortsman from UW.
102
+ This uses a truncated normal distribution with an adaptive standard deviation that depends
103
+ on the size of the weights as well as the depth of the layer.
104
+ """
105
+
106
+ normal = "normal"
107
+ """
108
+ All weights are initialized from the same normal distribution.
109
+ """
110
+
111
+ kaiming_normal = "kaiming_normal"
112
+ """
113
+ All weights are initialized with the Kaiming method from a normal distribution.
114
+ Note this currently won't work with FSDP.
115
+ """
116
+
117
+ fan_in = "fan_in"
118
+ """
119
+ "Fan-in variance scaling", i.e. normal with a standard deviation of ``1/sqrt(d_in)`` where ``d_in``
120
+ is the input dimensionality of the kernel.
121
+ """
122
+
123
+ full_megatron = "full_megatron"
124
+ """
125
+ This is what metaseq calls "full megatron init". It is the init used for Llama 2.
126
+ """
127
+
128
+
129
+ @dataclass
130
+ class ModelConfig():
131
+ """
132
+ LLaDA (model) configuration.
133
+ """
134
+
135
+ # Note that the defaults for these attributes are equivalent to the base GPT2 model.
136
+
137
+ d_model: int = 768
138
+ """
139
+ The hidden size of the model.
140
+ """
141
+
142
+ n_heads: int = 12
143
+ """
144
+ The number of self-attention heads.
145
+ """
146
+
147
+ n_kv_heads: Optional[int] = None
148
+ """
149
+ The number of heads to use for keys and values. Defaults to `n_heads`.
150
+ Set this to ``None`` or ``n_heads`` for normal multi-head attention.
151
+ Set this to 1 for multi-query attention.
152
+ Set it to some in-between value for Llama2-style grouped query attention.
153
+ """
154
+
155
+ n_layers: int = 12
156
+ """
157
+ The number of layers/blocks.
158
+ """
159
+
160
+ mlp_ratio: int = 4
161
+ """
162
+ The ratio of the inner MLP dimensionality to ``d_model``.
163
+ This is only used when ``mlp_hidden_size`` is not set.
164
+ """
165
+
166
+ mlp_hidden_size: Optional[int] = None
167
+ """
168
+ Set the exact hidden size for the MLP. Otherwise the inner MLP hidden size will be set to `mlp_ratio * d_model`.
169
+ """
170
+
171
+ activation_type: ActivationType = ActivationType.swiglu
172
+ """
173
+ The activation function to use within the MLP layers.
174
+ """
175
+
176
+ block_type: BlockType = BlockType.sequential
177
+ """
178
+ The transformer block implementation.
179
+ """
180
+
181
+ block_group_size: int = 1
182
+ """
183
+ The number of blocks to group together into a single parent block.
184
+ This has no affect on the number of parameters in the model and is only used to wrap groups
185
+ of blocks together with a single FSDP wrapper during training.
186
+ """
187
+
188
+ alibi: bool = False
189
+ """
190
+ If ``True``, use ALiBi embeddings. Mutually exclusive with ``rope``.
191
+ """
192
+
193
+ alibi_bias_max: float = 8.0
194
+ """
195
+ Maximum absolute value of ALiBi bias.
196
+ """
197
+
198
+ rope: bool = False
199
+ """
200
+ Use rotary positional embeddings (RoPE). Mutually exclusive with ``alibi``.
201
+ """
202
+
203
+ rope_full_precision: bool = True
204
+ """
205
+ If ``True``, apply RoPE embeddings at full precision regardless of the input type. Otherwise,
206
+ apply RoPE at the precision of the input.
207
+ """
208
+
209
+ flash_attention: bool = False
210
+ """
211
+ If ``True``, use ``FlashAttention``.
212
+ """
213
+
214
+ attention_dropout: float = 0.1
215
+ """
216
+ The dropout probability within the attention modules.
217
+ """
218
+
219
+ multi_query_attention: Optional[bool] = None
220
+ """
221
+ Use the Multi-Query formulation of attention used in PaLM. This reduces the number of parameters
222
+ and is more efficient during inference.
223
+ """
224
+
225
+ attention_layer_norm: bool = False
226
+ """
227
+ Apply layer norm to the keys and queries within the attention mechanism.
228
+ This can help stabilize training.
229
+ """
230
+
231
+ residual_dropout: float = 0.1
232
+ """
233
+ The dropout probability for the MLP and attention output within each block.
234
+ """
235
+
236
+ embedding_dropout: float = 0.1
237
+ """
238
+ The dropout probability for embeddings.
239
+ """
240
+
241
+ input_emb_norm: bool = False
242
+ """
243
+ An input hidden_states norm implementation by gemmma.
244
+ """
245
+
246
+ layer_norm_type: LayerNormType = LayerNormType.default
247
+ """
248
+ The layernorm implementation to use.
249
+ """
250
+
251
+ layer_norm_with_affine: bool = True
252
+ """
253
+ Whether to include bias and weight parameters for the layer norms.
254
+ This only affects layer norms that are immediately followed by a linear layer in the forward pass,
255
+ so everything except QK-norms. To turn off affines for QK norms as well, set :attr:`attention_layer_norm_with_affine`
256
+ to ``False``.
257
+ """
258
+
259
+ rms_norm_eps: float = 1e-05
260
+ """
261
+ The rms layernorm eps param.
262
+ """
263
+
264
+ attention_layer_norm_with_affine: bool = True
265
+ """
266
+ Toggle affine transform for the QK norms.
267
+ """
268
+
269
+ max_sequence_length: int = 1024
270
+ """
271
+ The maximum input sequence length supported by the model.
272
+ """
273
+
274
+ rope_theta: float = 10000.0
275
+ """
276
+ The rope base param.
277
+ """
278
+
279
+ include_qkv_bias: Optional[bool] = False
280
+ """
281
+ Whether or not to include bias parameters in qkv linear layers.
282
+ """
283
+
284
+ include_bias: bool = False
285
+ """
286
+ Whether or not to include bias parameters in linear layers.
287
+ In PaLM, they got rid of all bias terms because they found that large
288
+ models tend to have near 0 bias terms anyway.
289
+ """
290
+
291
+ bias_for_layer_norm: Optional[bool] = None
292
+ """
293
+ Whether or not to include bias parameters in layer norm.
294
+ This is separate from the include_bias parameter, because of a ROCm crash when biases are disabled in
295
+ layer norm.
296
+ When this is None (the default), it inherits the setting from include_bias.
297
+ """
298
+
299
+ scale_logits: bool = False
300
+ """
301
+ If ``True``, scale the output logits by ``1 / sqrt(d_model)``.
302
+ """
303
+
304
+ vocab_size: int = 50257
305
+ """
306
+ Vocabulary size of the model.
307
+ """
308
+
309
+ embedding_size: Optional[int] = 50304
310
+ """
311
+ The number of embeddings, i.e. the number of tokens. If set to ``None`` it will default
312
+ to ``vocab_size``. If ``vocab_size`` is not a multiple of 128, setting this to the
313
+ next multiple of 128 that's greater than ``vocab_size`` can improve throughput
314
+ substantially.
315
+ """
316
+
317
+ weight_tying: bool = True
318
+ """
319
+ Whether to tie output linear weights to the input embedding.
320
+ """
321
+
322
+ eos_token_id: int = 50256
323
+ """
324
+ The ID of the end-of-sentence special token.
325
+ """
326
+
327
+ pad_token_id: int = 50256
328
+ """
329
+ The ID of the token to use for padding. Defaults to the ID of the EOS token.
330
+ """
331
+
332
+ mask_token_id: Optional[int] = 50256
333
+ """
334
+ The ID of the token to use for mask token. Defaults to the ID of the EOS token.
335
+ """
336
+
337
+ init_device: Optional[str] = None
338
+ """
339
+ The torch device to use when initializing the model parameters, e.g. "cpu", "cuda:0", "meta".
340
+ """
341
+
342
+ init_fn: InitFnType = InitFnType.normal
343
+ """
344
+ The weight initialization strategy.
345
+ """
346
+
347
+ init_std: float = 0.02
348
+ """
349
+ The standard deviation to use when initializing weights with a "fixed distribution" ``init_fn``, such
350
+ as "normal".
351
+ """
352
+
353
+ init_cutoff_factor: Optional[float] = None
354
+ """
355
+ A positive factor used to scale the cutoff values when initializing weights with a "fixed distribution" ``init_fn``, such
356
+ as "normal". Setting this to None means values are not cutoff.
357
+ """
358
+
359
+ precision: Optional[str] = None
360
+ """
361
+ Precision used to train/evaluate with. You shouldn't set this directly.
362
+ See :data:`TrainConfig.precision` instead.
363
+ """
364
+
365
+ @property
366
+ def effective_n_kv_heads(self) -> int:
367
+ if self.n_kv_heads is None:
368
+ if self.multi_query_attention is True:
369
+ return 1
370
+ else:
371
+ return self.n_heads
372
+ else:
373
+ if self.multi_query_attention is None:
374
+ return self.n_kv_heads
375
+ if self.multi_query_attention:
376
+ n_kv_heads_should_be = 1
377
+ else:
378
+ n_kv_heads_should_be = self.n_heads
379
+ if self.n_kv_heads == n_kv_heads_should_be:
380
+ return n_kv_heads_should_be
381
+ else:
382
+ raise Exception(
383
+ "You can't set `multi_query_attention` and `n_kv_heads` at the same time."
384
+ )
385
+
386
+ class ActivationCheckpointingStrategy(StrEnum):
387
+ whole_layer = "whole_layer"
388
+ """
389
+ Checkpoint every transformer layer.
390
+ """
391
+
392
+ one_in_two = "one_in_two"
393
+ """
394
+ Checkpoint one in two transformer layers.
395
+ """
396
+
397
+ one_in_three = "one_in_three"
398
+ """
399
+ Checkpoint one in three transformer layers.
400
+ """
401
+
402
+ one_in_four = "one_in_four"
403
+ """
404
+ Checkpoint one in four transformer layers.
405
+ """
406
+
407
+ two_in_three = "two_in_three"
408
+ """
409
+ Checkpoint two out of every three transformer layers.
410
+ """
411
+
412
+ three_in_four = "three_in_four"
413
+ """
414
+ Checkpoint three out of four of every transformer layers.
415
+ """
416
+
417
+ four_in_five = "four_in_five"
418
+ """
419
+ Checkpoint four out of five of every transformer layers.
420
+ """
421
+
422
+ nine_in_ten = "nine_in_ten"
423
+ """
424
+ Checkpoint nine out of ten of every transformer layers.
425
+ """
426
+
427
+ fine_grained = "fine_grained"
428
+ """
429
+ Focus checkpointing on where it is cheap to recompute and saves most memory.
430
+ """
431
+
432
+
433
+ class LLaDAConfig(PretrainedConfig):
434
+ model_type = "llada"
435
+ keys_to_ignore_at_inference = ["past_key_values"] # TODO: confirm
436
+
437
+ def __init__(self, use_cache: bool = False, **kwargs):
438
+ model_config = ModelConfig()
439
+ all_kwargs = model_config.__dict__
440
+ all_kwargs.update(kwargs)
441
+ all_kwargs.update({"use_cache": use_cache})
442
+ all_kwargs.update(
443
+ {
444
+ "architectures": all_kwargs.get("architectures", ["LLaDAModelLM"])
445
+ }
446
+ )
447
+ super().__init__(**all_kwargs)
448
+
449
+ @property
450
+ def num_attention_heads(self):
451
+ return self.n_heads
452
+
453
+ @property
454
+ def num_hidden_layers(self):
455
+ return self.n_layers
456
+
457
+ @property
458
+ def hidden_size(self):
459
+ return self.d_model
460
+
461
+
462
+ # Register the config class so that it is available for transformer pipelines, auto-loading etc.
463
+ AutoConfig.register("llada", LLaDAConfig)
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 126080,
4
+ "eos_token_id": 126081,
5
+ "transformers_version": "4.52.4"
6
+ }
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02cfb6407a937165b6cdbd7d07bca4a2f19120cbff1d9f13692db83556cf332c
3
+ size 4995581672
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7b5bffa735d6199981358c6fb3158d89cffb50480f2854cb5b00bb73fc92d0a
3
+ size 4999819552
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8af05b84d02d6a4fcf0a521b94f12c8abf2fc03b89f77dee9d8057060b0aab8a
3
+ size 4999802728
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91475a1e5d06f7e264c1943bdd91a8435067a9df122f25b2859b4c4024c43e41
3
+ size 1035993232
model.safetensors.index.json ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 16031162368
4
+ },
5
+ "weight_map": {
6
+ "model.transformer.blocks.0.attn_norm.weight": "model-00001-of-00004.safetensors",
7
+ "model.transformer.blocks.0.attn_out.weight": "model-00001-of-00004.safetensors",
8
+ "model.transformer.blocks.0.ff_norm.weight": "model-00001-of-00004.safetensors",
9
+ "model.transformer.blocks.0.ff_out.weight": "model-00001-of-00004.safetensors",
10
+ "model.transformer.blocks.0.ff_proj.weight": "model-00001-of-00004.safetensors",
11
+ "model.transformer.blocks.0.k_proj.weight": "model-00001-of-00004.safetensors",
12
+ "model.transformer.blocks.0.q_proj.weight": "model-00001-of-00004.safetensors",
13
+ "model.transformer.blocks.0.up_proj.weight": "model-00001-of-00004.safetensors",
14
+ "model.transformer.blocks.0.v_proj.weight": "model-00001-of-00004.safetensors",
15
+ "model.transformer.blocks.1.attn_norm.weight": "model-00001-of-00004.safetensors",
16
+ "model.transformer.blocks.1.attn_out.weight": "model-00001-of-00004.safetensors",
17
+ "model.transformer.blocks.1.ff_norm.weight": "model-00001-of-00004.safetensors",
18
+ "model.transformer.blocks.1.ff_out.weight": "model-00001-of-00004.safetensors",
19
+ "model.transformer.blocks.1.ff_proj.weight": "model-00001-of-00004.safetensors",
20
+ "model.transformer.blocks.1.k_proj.weight": "model-00001-of-00004.safetensors",
21
+ "model.transformer.blocks.1.q_proj.weight": "model-00001-of-00004.safetensors",
22
+ "model.transformer.blocks.1.up_proj.weight": "model-00001-of-00004.safetensors",
23
+ "model.transformer.blocks.1.v_proj.weight": "model-00001-of-00004.safetensors",
24
+ "model.transformer.blocks.10.attn_norm.weight": "model-00002-of-00004.safetensors",
25
+ "model.transformer.blocks.10.attn_out.weight": "model-00002-of-00004.safetensors",
26
+ "model.transformer.blocks.10.ff_norm.weight": "model-00002-of-00004.safetensors",
27
+ "model.transformer.blocks.10.ff_out.weight": "model-00002-of-00004.safetensors",
28
+ "model.transformer.blocks.10.ff_proj.weight": "model-00002-of-00004.safetensors",
29
+ "model.transformer.blocks.10.k_proj.weight": "model-00002-of-00004.safetensors",
30
+ "model.transformer.blocks.10.q_proj.weight": "model-00002-of-00004.safetensors",
31
+ "model.transformer.blocks.10.up_proj.weight": "model-00002-of-00004.safetensors",
32
+ "model.transformer.blocks.10.v_proj.weight": "model-00002-of-00004.safetensors",
33
+ "model.transformer.blocks.11.attn_norm.weight": "model-00002-of-00004.safetensors",
34
+ "model.transformer.blocks.11.attn_out.weight": "model-00002-of-00004.safetensors",
35
+ "model.transformer.blocks.11.ff_norm.weight": "model-00002-of-00004.safetensors",
36
+ "model.transformer.blocks.11.ff_out.weight": "model-00002-of-00004.safetensors",
37
+ "model.transformer.blocks.11.ff_proj.weight": "model-00002-of-00004.safetensors",
38
+ "model.transformer.blocks.11.k_proj.weight": "model-00002-of-00004.safetensors",
39
+ "model.transformer.blocks.11.q_proj.weight": "model-00002-of-00004.safetensors",
40
+ "model.transformer.blocks.11.up_proj.weight": "model-00002-of-00004.safetensors",
41
+ "model.transformer.blocks.11.v_proj.weight": "model-00002-of-00004.safetensors",
42
+ "model.transformer.blocks.12.attn_norm.weight": "model-00002-of-00004.safetensors",
43
+ "model.transformer.blocks.12.attn_out.weight": "model-00002-of-00004.safetensors",
44
+ "model.transformer.blocks.12.ff_norm.weight": "model-00002-of-00004.safetensors",
45
+ "model.transformer.blocks.12.ff_out.weight": "model-00002-of-00004.safetensors",
46
+ "model.transformer.blocks.12.ff_proj.weight": "model-00002-of-00004.safetensors",
47
+ "model.transformer.blocks.12.k_proj.weight": "model-00002-of-00004.safetensors",
48
+ "model.transformer.blocks.12.q_proj.weight": "model-00002-of-00004.safetensors",
49
+ "model.transformer.blocks.12.up_proj.weight": "model-00002-of-00004.safetensors",
50
+ "model.transformer.blocks.12.v_proj.weight": "model-00002-of-00004.safetensors",
51
+ "model.transformer.blocks.13.attn_norm.weight": "model-00002-of-00004.safetensors",
52
+ "model.transformer.blocks.13.attn_out.weight": "model-00002-of-00004.safetensors",
53
+ "model.transformer.blocks.13.ff_norm.weight": "model-00002-of-00004.safetensors",
54
+ "model.transformer.blocks.13.ff_out.weight": "model-00002-of-00004.safetensors",
55
+ "model.transformer.blocks.13.ff_proj.weight": "model-00002-of-00004.safetensors",
56
+ "model.transformer.blocks.13.k_proj.weight": "model-00002-of-00004.safetensors",
57
+ "model.transformer.blocks.13.q_proj.weight": "model-00002-of-00004.safetensors",
58
+ "model.transformer.blocks.13.up_proj.weight": "model-00002-of-00004.safetensors",
59
+ "model.transformer.blocks.13.v_proj.weight": "model-00002-of-00004.safetensors",
60
+ "model.transformer.blocks.14.attn_norm.weight": "model-00002-of-00004.safetensors",
61
+ "model.transformer.blocks.14.attn_out.weight": "model-00002-of-00004.safetensors",
62
+ "model.transformer.blocks.14.ff_norm.weight": "model-00002-of-00004.safetensors",
63
+ "model.transformer.blocks.14.ff_out.weight": "model-00002-of-00004.safetensors",
64
+ "model.transformer.blocks.14.ff_proj.weight": "model-00002-of-00004.safetensors",
65
+ "model.transformer.blocks.14.k_proj.weight": "model-00002-of-00004.safetensors",
66
+ "model.transformer.blocks.14.q_proj.weight": "model-00002-of-00004.safetensors",
67
+ "model.transformer.blocks.14.up_proj.weight": "model-00002-of-00004.safetensors",
68
+ "model.transformer.blocks.14.v_proj.weight": "model-00002-of-00004.safetensors",
69
+ "model.transformer.blocks.15.attn_norm.weight": "model-00002-of-00004.safetensors",
70
+ "model.transformer.blocks.15.attn_out.weight": "model-00002-of-00004.safetensors",
71
+ "model.transformer.blocks.15.ff_norm.weight": "model-00002-of-00004.safetensors",
72
+ "model.transformer.blocks.15.ff_out.weight": "model-00002-of-00004.safetensors",
73
+ "model.transformer.blocks.15.ff_proj.weight": "model-00002-of-00004.safetensors",
74
+ "model.transformer.blocks.15.k_proj.weight": "model-00002-of-00004.safetensors",
75
+ "model.transformer.blocks.15.q_proj.weight": "model-00002-of-00004.safetensors",
76
+ "model.transformer.blocks.15.up_proj.weight": "model-00002-of-00004.safetensors",
77
+ "model.transformer.blocks.15.v_proj.weight": "model-00002-of-00004.safetensors",
78
+ "model.transformer.blocks.16.attn_norm.weight": "model-00002-of-00004.safetensors",
79
+ "model.transformer.blocks.16.attn_out.weight": "model-00002-of-00004.safetensors",
80
+ "model.transformer.blocks.16.ff_norm.weight": "model-00002-of-00004.safetensors",
81
+ "model.transformer.blocks.16.ff_out.weight": "model-00002-of-00004.safetensors",
82
+ "model.transformer.blocks.16.ff_proj.weight": "model-00002-of-00004.safetensors",
83
+ "model.transformer.blocks.16.k_proj.weight": "model-00002-of-00004.safetensors",
84
+ "model.transformer.blocks.16.q_proj.weight": "model-00002-of-00004.safetensors",
85
+ "model.transformer.blocks.16.up_proj.weight": "model-00002-of-00004.safetensors",
86
+ "model.transformer.blocks.16.v_proj.weight": "model-00002-of-00004.safetensors",
87
+ "model.transformer.blocks.17.attn_norm.weight": "model-00002-of-00004.safetensors",
88
+ "model.transformer.blocks.17.attn_out.weight": "model-00002-of-00004.safetensors",
89
+ "model.transformer.blocks.17.ff_norm.weight": "model-00002-of-00004.safetensors",
90
+ "model.transformer.blocks.17.ff_out.weight": "model-00002-of-00004.safetensors",
91
+ "model.transformer.blocks.17.ff_proj.weight": "model-00002-of-00004.safetensors",
92
+ "model.transformer.blocks.17.k_proj.weight": "model-00002-of-00004.safetensors",
93
+ "model.transformer.blocks.17.q_proj.weight": "model-00002-of-00004.safetensors",
94
+ "model.transformer.blocks.17.up_proj.weight": "model-00002-of-00004.safetensors",
95
+ "model.transformer.blocks.17.v_proj.weight": "model-00002-of-00004.safetensors",
96
+ "model.transformer.blocks.18.attn_norm.weight": "model-00002-of-00004.safetensors",
97
+ "model.transformer.blocks.18.attn_out.weight": "model-00002-of-00004.safetensors",
98
+ "model.transformer.blocks.18.ff_norm.weight": "model-00002-of-00004.safetensors",
99
+ "model.transformer.blocks.18.ff_out.weight": "model-00002-of-00004.safetensors",
100
+ "model.transformer.blocks.18.ff_proj.weight": "model-00002-of-00004.safetensors",
101
+ "model.transformer.blocks.18.k_proj.weight": "model-00002-of-00004.safetensors",
102
+ "model.transformer.blocks.18.q_proj.weight": "model-00002-of-00004.safetensors",
103
+ "model.transformer.blocks.18.up_proj.weight": "model-00002-of-00004.safetensors",
104
+ "model.transformer.blocks.18.v_proj.weight": "model-00002-of-00004.safetensors",
105
+ "model.transformer.blocks.19.attn_norm.weight": "model-00002-of-00004.safetensors",
106
+ "model.transformer.blocks.19.attn_out.weight": "model-00002-of-00004.safetensors",
107
+ "model.transformer.blocks.19.ff_norm.weight": "model-00002-of-00004.safetensors",
108
+ "model.transformer.blocks.19.ff_out.weight": "model-00002-of-00004.safetensors",
109
+ "model.transformer.blocks.19.ff_proj.weight": "model-00002-of-00004.safetensors",
110
+ "model.transformer.blocks.19.k_proj.weight": "model-00002-of-00004.safetensors",
111
+ "model.transformer.blocks.19.q_proj.weight": "model-00002-of-00004.safetensors",
112
+ "model.transformer.blocks.19.up_proj.weight": "model-00002-of-00004.safetensors",
113
+ "model.transformer.blocks.19.v_proj.weight": "model-00002-of-00004.safetensors",
114
+ "model.transformer.blocks.2.attn_norm.weight": "model-00001-of-00004.safetensors",
115
+ "model.transformer.blocks.2.attn_out.weight": "model-00001-of-00004.safetensors",
116
+ "model.transformer.blocks.2.ff_norm.weight": "model-00001-of-00004.safetensors",
117
+ "model.transformer.blocks.2.ff_out.weight": "model-00001-of-00004.safetensors",
118
+ "model.transformer.blocks.2.ff_proj.weight": "model-00001-of-00004.safetensors",
119
+ "model.transformer.blocks.2.k_proj.weight": "model-00001-of-00004.safetensors",
120
+ "model.transformer.blocks.2.q_proj.weight": "model-00001-of-00004.safetensors",
121
+ "model.transformer.blocks.2.up_proj.weight": "model-00001-of-00004.safetensors",
122
+ "model.transformer.blocks.2.v_proj.weight": "model-00001-of-00004.safetensors",
123
+ "model.transformer.blocks.20.attn_norm.weight": "model-00002-of-00004.safetensors",
124
+ "model.transformer.blocks.20.attn_out.weight": "model-00002-of-00004.safetensors",
125
+ "model.transformer.blocks.20.ff_norm.weight": "model-00002-of-00004.safetensors",
126
+ "model.transformer.blocks.20.ff_out.weight": "model-00002-of-00004.safetensors",
127
+ "model.transformer.blocks.20.ff_proj.weight": "model-00003-of-00004.safetensors",
128
+ "model.transformer.blocks.20.k_proj.weight": "model-00002-of-00004.safetensors",
129
+ "model.transformer.blocks.20.q_proj.weight": "model-00002-of-00004.safetensors",
130
+ "model.transformer.blocks.20.up_proj.weight": "model-00003-of-00004.safetensors",
131
+ "model.transformer.blocks.20.v_proj.weight": "model-00002-of-00004.safetensors",
132
+ "model.transformer.blocks.21.attn_norm.weight": "model-00003-of-00004.safetensors",
133
+ "model.transformer.blocks.21.attn_out.weight": "model-00003-of-00004.safetensors",
134
+ "model.transformer.blocks.21.ff_norm.weight": "model-00003-of-00004.safetensors",
135
+ "model.transformer.blocks.21.ff_out.weight": "model-00003-of-00004.safetensors",
136
+ "model.transformer.blocks.21.ff_proj.weight": "model-00003-of-00004.safetensors",
137
+ "model.transformer.blocks.21.k_proj.weight": "model-00003-of-00004.safetensors",
138
+ "model.transformer.blocks.21.q_proj.weight": "model-00003-of-00004.safetensors",
139
+ "model.transformer.blocks.21.up_proj.weight": "model-00003-of-00004.safetensors",
140
+ "model.transformer.blocks.21.v_proj.weight": "model-00003-of-00004.safetensors",
141
+ "model.transformer.blocks.22.attn_norm.weight": "model-00003-of-00004.safetensors",
142
+ "model.transformer.blocks.22.attn_out.weight": "model-00003-of-00004.safetensors",
143
+ "model.transformer.blocks.22.ff_norm.weight": "model-00003-of-00004.safetensors",
144
+ "model.transformer.blocks.22.ff_out.weight": "model-00003-of-00004.safetensors",
145
+ "model.transformer.blocks.22.ff_proj.weight": "model-00003-of-00004.safetensors",
146
+ "model.transformer.blocks.22.k_proj.weight": "model-00003-of-00004.safetensors",
147
+ "model.transformer.blocks.22.q_proj.weight": "model-00003-of-00004.safetensors",
148
+ "model.transformer.blocks.22.up_proj.weight": "model-00003-of-00004.safetensors",
149
+ "model.transformer.blocks.22.v_proj.weight": "model-00003-of-00004.safetensors",
150
+ "model.transformer.blocks.23.attn_norm.weight": "model-00003-of-00004.safetensors",
151
+ "model.transformer.blocks.23.attn_out.weight": "model-00003-of-00004.safetensors",
152
+ "model.transformer.blocks.23.ff_norm.weight": "model-00003-of-00004.safetensors",
153
+ "model.transformer.blocks.23.ff_out.weight": "model-00003-of-00004.safetensors",
154
+ "model.transformer.blocks.23.ff_proj.weight": "model-00003-of-00004.safetensors",
155
+ "model.transformer.blocks.23.k_proj.weight": "model-00003-of-00004.safetensors",
156
+ "model.transformer.blocks.23.q_proj.weight": "model-00003-of-00004.safetensors",
157
+ "model.transformer.blocks.23.up_proj.weight": "model-00003-of-00004.safetensors",
158
+ "model.transformer.blocks.23.v_proj.weight": "model-00003-of-00004.safetensors",
159
+ "model.transformer.blocks.24.attn_norm.weight": "model-00003-of-00004.safetensors",
160
+ "model.transformer.blocks.24.attn_out.weight": "model-00003-of-00004.safetensors",
161
+ "model.transformer.blocks.24.ff_norm.weight": "model-00003-of-00004.safetensors",
162
+ "model.transformer.blocks.24.ff_out.weight": "model-00003-of-00004.safetensors",
163
+ "model.transformer.blocks.24.ff_proj.weight": "model-00003-of-00004.safetensors",
164
+ "model.transformer.blocks.24.k_proj.weight": "model-00003-of-00004.safetensors",
165
+ "model.transformer.blocks.24.q_proj.weight": "model-00003-of-00004.safetensors",
166
+ "model.transformer.blocks.24.up_proj.weight": "model-00003-of-00004.safetensors",
167
+ "model.transformer.blocks.24.v_proj.weight": "model-00003-of-00004.safetensors",
168
+ "model.transformer.blocks.25.attn_norm.weight": "model-00003-of-00004.safetensors",
169
+ "model.transformer.blocks.25.attn_out.weight": "model-00003-of-00004.safetensors",
170
+ "model.transformer.blocks.25.ff_norm.weight": "model-00003-of-00004.safetensors",
171
+ "model.transformer.blocks.25.ff_out.weight": "model-00003-of-00004.safetensors",
172
+ "model.transformer.blocks.25.ff_proj.weight": "model-00003-of-00004.safetensors",
173
+ "model.transformer.blocks.25.k_proj.weight": "model-00003-of-00004.safetensors",
174
+ "model.transformer.blocks.25.q_proj.weight": "model-00003-of-00004.safetensors",
175
+ "model.transformer.blocks.25.up_proj.weight": "model-00003-of-00004.safetensors",
176
+ "model.transformer.blocks.25.v_proj.weight": "model-00003-of-00004.safetensors",
177
+ "model.transformer.blocks.26.attn_norm.weight": "model-00003-of-00004.safetensors",
178
+ "model.transformer.blocks.26.attn_out.weight": "model-00003-of-00004.safetensors",
179
+ "model.transformer.blocks.26.ff_norm.weight": "model-00003-of-00004.safetensors",
180
+ "model.transformer.blocks.26.ff_out.weight": "model-00003-of-00004.safetensors",
181
+ "model.transformer.blocks.26.ff_proj.weight": "model-00003-of-00004.safetensors",
182
+ "model.transformer.blocks.26.k_proj.weight": "model-00003-of-00004.safetensors",
183
+ "model.transformer.blocks.26.q_proj.weight": "model-00003-of-00004.safetensors",
184
+ "model.transformer.blocks.26.up_proj.weight": "model-00003-of-00004.safetensors",
185
+ "model.transformer.blocks.26.v_proj.weight": "model-00003-of-00004.safetensors",
186
+ "model.transformer.blocks.27.attn_norm.weight": "model-00003-of-00004.safetensors",
187
+ "model.transformer.blocks.27.attn_out.weight": "model-00003-of-00004.safetensors",
188
+ "model.transformer.blocks.27.ff_norm.weight": "model-00003-of-00004.safetensors",
189
+ "model.transformer.blocks.27.ff_out.weight": "model-00003-of-00004.safetensors",
190
+ "model.transformer.blocks.27.ff_proj.weight": "model-00003-of-00004.safetensors",
191
+ "model.transformer.blocks.27.k_proj.weight": "model-00003-of-00004.safetensors",
192
+ "model.transformer.blocks.27.q_proj.weight": "model-00003-of-00004.safetensors",
193
+ "model.transformer.blocks.27.up_proj.weight": "model-00003-of-00004.safetensors",
194
+ "model.transformer.blocks.27.v_proj.weight": "model-00003-of-00004.safetensors",
195
+ "model.transformer.blocks.28.attn_norm.weight": "model-00003-of-00004.safetensors",
196
+ "model.transformer.blocks.28.attn_out.weight": "model-00003-of-00004.safetensors",
197
+ "model.transformer.blocks.28.ff_norm.weight": "model-00003-of-00004.safetensors",
198
+ "model.transformer.blocks.28.ff_out.weight": "model-00003-of-00004.safetensors",
199
+ "model.transformer.blocks.28.ff_proj.weight": "model-00003-of-00004.safetensors",
200
+ "model.transformer.blocks.28.k_proj.weight": "model-00003-of-00004.safetensors",
201
+ "model.transformer.blocks.28.q_proj.weight": "model-00003-of-00004.safetensors",
202
+ "model.transformer.blocks.28.up_proj.weight": "model-00003-of-00004.safetensors",
203
+ "model.transformer.blocks.28.v_proj.weight": "model-00003-of-00004.safetensors",
204
+ "model.transformer.blocks.29.attn_norm.weight": "model-00003-of-00004.safetensors",
205
+ "model.transformer.blocks.29.attn_out.weight": "model-00003-of-00004.safetensors",
206
+ "model.transformer.blocks.29.ff_norm.weight": "model-00003-of-00004.safetensors",
207
+ "model.transformer.blocks.29.ff_out.weight": "model-00003-of-00004.safetensors",
208
+ "model.transformer.blocks.29.ff_proj.weight": "model-00003-of-00004.safetensors",
209
+ "model.transformer.blocks.29.k_proj.weight": "model-00003-of-00004.safetensors",
210
+ "model.transformer.blocks.29.q_proj.weight": "model-00003-of-00004.safetensors",
211
+ "model.transformer.blocks.29.up_proj.weight": "model-00003-of-00004.safetensors",
212
+ "model.transformer.blocks.29.v_proj.weight": "model-00003-of-00004.safetensors",
213
+ "model.transformer.blocks.3.attn_norm.weight": "model-00001-of-00004.safetensors",
214
+ "model.transformer.blocks.3.attn_out.weight": "model-00001-of-00004.safetensors",
215
+ "model.transformer.blocks.3.ff_norm.weight": "model-00001-of-00004.safetensors",
216
+ "model.transformer.blocks.3.ff_out.weight": "model-00001-of-00004.safetensors",
217
+ "model.transformer.blocks.3.ff_proj.weight": "model-00001-of-00004.safetensors",
218
+ "model.transformer.blocks.3.k_proj.weight": "model-00001-of-00004.safetensors",
219
+ "model.transformer.blocks.3.q_proj.weight": "model-00001-of-00004.safetensors",
220
+ "model.transformer.blocks.3.up_proj.weight": "model-00001-of-00004.safetensors",
221
+ "model.transformer.blocks.3.v_proj.weight": "model-00001-of-00004.safetensors",
222
+ "model.transformer.blocks.30.attn_norm.weight": "model-00003-of-00004.safetensors",
223
+ "model.transformer.blocks.30.attn_out.weight": "model-00003-of-00004.safetensors",
224
+ "model.transformer.blocks.30.ff_norm.weight": "model-00003-of-00004.safetensors",
225
+ "model.transformer.blocks.30.ff_out.weight": "model-00003-of-00004.safetensors",
226
+ "model.transformer.blocks.30.ff_proj.weight": "model-00003-of-00004.safetensors",
227
+ "model.transformer.blocks.30.k_proj.weight": "model-00003-of-00004.safetensors",
228
+ "model.transformer.blocks.30.q_proj.weight": "model-00003-of-00004.safetensors",
229
+ "model.transformer.blocks.30.up_proj.weight": "model-00003-of-00004.safetensors",
230
+ "model.transformer.blocks.30.v_proj.weight": "model-00003-of-00004.safetensors",
231
+ "model.transformer.blocks.31.attn_norm.weight": "model-00003-of-00004.safetensors",
232
+ "model.transformer.blocks.31.attn_out.weight": "model-00003-of-00004.safetensors",
233
+ "model.transformer.blocks.31.ff_norm.weight": "model-00003-of-00004.safetensors",
234
+ "model.transformer.blocks.31.ff_out.weight": "model-00003-of-00004.safetensors",
235
+ "model.transformer.blocks.31.ff_proj.weight": "model-00003-of-00004.safetensors",
236
+ "model.transformer.blocks.31.k_proj.weight": "model-00003-of-00004.safetensors",
237
+ "model.transformer.blocks.31.q_proj.weight": "model-00003-of-00004.safetensors",
238
+ "model.transformer.blocks.31.up_proj.weight": "model-00003-of-00004.safetensors",
239
+ "model.transformer.blocks.31.v_proj.weight": "model-00003-of-00004.safetensors",
240
+ "model.transformer.blocks.4.attn_norm.weight": "model-00001-of-00004.safetensors",
241
+ "model.transformer.blocks.4.attn_out.weight": "model-00001-of-00004.safetensors",
242
+ "model.transformer.blocks.4.ff_norm.weight": "model-00001-of-00004.safetensors",
243
+ "model.transformer.blocks.4.ff_out.weight": "model-00001-of-00004.safetensors",
244
+ "model.transformer.blocks.4.ff_proj.weight": "model-00001-of-00004.safetensors",
245
+ "model.transformer.blocks.4.k_proj.weight": "model-00001-of-00004.safetensors",
246
+ "model.transformer.blocks.4.q_proj.weight": "model-00001-of-00004.safetensors",
247
+ "model.transformer.blocks.4.up_proj.weight": "model-00001-of-00004.safetensors",
248
+ "model.transformer.blocks.4.v_proj.weight": "model-00001-of-00004.safetensors",
249
+ "model.transformer.blocks.5.attn_norm.weight": "model-00001-of-00004.safetensors",
250
+ "model.transformer.blocks.5.attn_out.weight": "model-00001-of-00004.safetensors",
251
+ "model.transformer.blocks.5.ff_norm.weight": "model-00001-of-00004.safetensors",
252
+ "model.transformer.blocks.5.ff_out.weight": "model-00001-of-00004.safetensors",
253
+ "model.transformer.blocks.5.ff_proj.weight": "model-00001-of-00004.safetensors",
254
+ "model.transformer.blocks.5.k_proj.weight": "model-00001-of-00004.safetensors",
255
+ "model.transformer.blocks.5.q_proj.weight": "model-00001-of-00004.safetensors",
256
+ "model.transformer.blocks.5.up_proj.weight": "model-00001-of-00004.safetensors",
257
+ "model.transformer.blocks.5.v_proj.weight": "model-00001-of-00004.safetensors",
258
+ "model.transformer.blocks.6.attn_norm.weight": "model-00001-of-00004.safetensors",
259
+ "model.transformer.blocks.6.attn_out.weight": "model-00001-of-00004.safetensors",
260
+ "model.transformer.blocks.6.ff_norm.weight": "model-00001-of-00004.safetensors",
261
+ "model.transformer.blocks.6.ff_out.weight": "model-00001-of-00004.safetensors",
262
+ "model.transformer.blocks.6.ff_proj.weight": "model-00001-of-00004.safetensors",
263
+ "model.transformer.blocks.6.k_proj.weight": "model-00001-of-00004.safetensors",
264
+ "model.transformer.blocks.6.q_proj.weight": "model-00001-of-00004.safetensors",
265
+ "model.transformer.blocks.6.up_proj.weight": "model-00001-of-00004.safetensors",
266
+ "model.transformer.blocks.6.v_proj.weight": "model-00001-of-00004.safetensors",
267
+ "model.transformer.blocks.7.attn_norm.weight": "model-00001-of-00004.safetensors",
268
+ "model.transformer.blocks.7.attn_out.weight": "model-00001-of-00004.safetensors",
269
+ "model.transformer.blocks.7.ff_norm.weight": "model-00001-of-00004.safetensors",
270
+ "model.transformer.blocks.7.ff_out.weight": "model-00001-of-00004.safetensors",
271
+ "model.transformer.blocks.7.ff_proj.weight": "model-00001-of-00004.safetensors",
272
+ "model.transformer.blocks.7.k_proj.weight": "model-00001-of-00004.safetensors",
273
+ "model.transformer.blocks.7.q_proj.weight": "model-00001-of-00004.safetensors",
274
+ "model.transformer.blocks.7.up_proj.weight": "model-00001-of-00004.safetensors",
275
+ "model.transformer.blocks.7.v_proj.weight": "model-00001-of-00004.safetensors",
276
+ "model.transformer.blocks.8.attn_norm.weight": "model-00001-of-00004.safetensors",
277
+ "model.transformer.blocks.8.attn_out.weight": "model-00001-of-00004.safetensors",
278
+ "model.transformer.blocks.8.ff_norm.weight": "model-00001-of-00004.safetensors",
279
+ "model.transformer.blocks.8.ff_out.weight": "model-00001-of-00004.safetensors",
280
+ "model.transformer.blocks.8.ff_proj.weight": "model-00001-of-00004.safetensors",
281
+ "model.transformer.blocks.8.k_proj.weight": "model-00001-of-00004.safetensors",
282
+ "model.transformer.blocks.8.q_proj.weight": "model-00001-of-00004.safetensors",
283
+ "model.transformer.blocks.8.up_proj.weight": "model-00001-of-00004.safetensors",
284
+ "model.transformer.blocks.8.v_proj.weight": "model-00001-of-00004.safetensors",
285
+ "model.transformer.blocks.9.attn_norm.weight": "model-00002-of-00004.safetensors",
286
+ "model.transformer.blocks.9.attn_out.weight": "model-00001-of-00004.safetensors",
287
+ "model.transformer.blocks.9.ff_norm.weight": "model-00002-of-00004.safetensors",
288
+ "model.transformer.blocks.9.ff_out.weight": "model-00002-of-00004.safetensors",
289
+ "model.transformer.blocks.9.ff_proj.weight": "model-00002-of-00004.safetensors",
290
+ "model.transformer.blocks.9.k_proj.weight": "model-00002-of-00004.safetensors",
291
+ "model.transformer.blocks.9.q_proj.weight": "model-00002-of-00004.safetensors",
292
+ "model.transformer.blocks.9.up_proj.weight": "model-00002-of-00004.safetensors",
293
+ "model.transformer.blocks.9.v_proj.weight": "model-00002-of-00004.safetensors",
294
+ "model.transformer.ff_out.weight": "model-00004-of-00004.safetensors",
295
+ "model.transformer.ln_f.weight": "model-00001-of-00004.safetensors",
296
+ "model.transformer.wte.weight": "model-00001-of-00004.safetensors"
297
+ }
298
+ }
modeling_llada.py ADDED
@@ -0,0 +1,1506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import math
5
+ import sys
6
+ from abc import abstractmethod
7
+ from collections import defaultdict
8
+ from functools import partial
9
+ from typing import (
10
+ Callable,
11
+ Dict,
12
+ Iterable,
13
+ List,
14
+ NamedTuple,
15
+ Optional,
16
+ Sequence,
17
+ Set,
18
+ Tuple,
19
+ cast,
20
+ )
21
+ from dataclasses import fields
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.backends.cuda
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ from torch import einsum
29
+ from transformers import PreTrainedModel
30
+ from transformers.modeling_outputs import CausalLMOutputWithPast
31
+ from transformers.models.auto import AutoModel
32
+ from transformers.cache_utils import Cache
33
+
34
+ from .configuration_llada import (
35
+ LLaDAConfig,
36
+ StrEnum,
37
+ InitFnType,
38
+ ActivationType,
39
+ BlockType,
40
+ LayerNormType,
41
+ ModelConfig,
42
+ ActivationCheckpointingStrategy,
43
+ )
44
+
45
+ if sys.version_info.minor > 8:
46
+ from collections.abc import MutableMapping
47
+ elif sys.version_info.minor == 8:
48
+ from typing import MutableMapping
49
+ else:
50
+ raise SystemExit("This script supports Python 3.8 or higher")
51
+
52
+ __all__ = [
53
+ "LayerNormBase",
54
+ "LayerNorm",
55
+ "RMSLayerNorm",
56
+ "GemmaRMSLayerNorm",
57
+ "RotaryEmbedding",
58
+ "Activation",
59
+ "GELU",
60
+ "ReLU",
61
+ "SwiGLU",
62
+ "LLaDABlock",
63
+ "LLaDASequentialBlock",
64
+ "LLaDAModel",
65
+ "LLaDAOutput",
66
+ "LLaDAGenerateOutput",
67
+ ]
68
+
69
+
70
+ log = logging.getLogger(__name__)
71
+
72
+
73
+ class ModuleType(StrEnum):
74
+ in_module = "in"
75
+ out_module = "out"
76
+ emb = "emb"
77
+ final_out = "final_out"
78
+
79
+
80
+ def init_weights(
81
+ config: ModelConfig,
82
+ module: Union[nn.Linear, nn.Embedding],
83
+ d: Optional[int] = None,
84
+ layer_id: Optional[int] = None,
85
+ std_factor: float = 1.0,
86
+ type_of_module: Optional[ModuleType] = None,
87
+ ) -> None:
88
+ """
89
+ Initialize weights of a linear or embedding module.
90
+
91
+ :param config: The model config.
92
+ :param module: The linear or embedding submodule to initialize.
93
+ :param d: The effective input dimensionality of the weights. This could be smaller than the actual dimensions
94
+ for fused layers.
95
+ :param layer_id: When set, the standard deviation for the "mitchell" method will be adjusted by
96
+ ``1 / sqrt(2 * (layer_id + 1))``.
97
+ """
98
+ d = d if d is not None else config.d_model
99
+ if config.init_fn == InitFnType.normal:
100
+ std = config.init_std * std_factor
101
+ if config.init_cutoff_factor is not None:
102
+ cutoff_value = config.init_cutoff_factor * std
103
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-cutoff_value, b=cutoff_value)
104
+ else:
105
+ nn.init.normal_(module.weight, mean=0.0, std=std)
106
+ elif config.init_fn == InitFnType.mitchell:
107
+ std = std_factor / math.sqrt(d)
108
+ if layer_id is not None:
109
+ std = std / math.sqrt(2 * (layer_id + 1))
110
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-3 * std, b=3 * std)
111
+ elif config.init_fn == InitFnType.kaiming_normal:
112
+ nn.init.kaiming_normal_(module.weight, nonlinearity="relu")
113
+ elif config.init_fn == InitFnType.fan_in:
114
+ std = std_factor / math.sqrt(d)
115
+ nn.init.normal_(module.weight, mean=0.0, std=std)
116
+ elif config.init_fn == InitFnType.full_megatron:
117
+ if type_of_module is None:
118
+ raise RuntimeError(f"When using the {InitFnType.full_megatron} init, every module must have a type.")
119
+
120
+ cutoff_factor = config.init_cutoff_factor
121
+ if cutoff_factor is None:
122
+ cutoff_factor = 3
123
+
124
+ if type_of_module == ModuleType.in_module:
125
+ # for att_proj (same as QKV), ff_proj
126
+ std = config.init_std
127
+ elif type_of_module == ModuleType.out_module:
128
+ # for attn_out, ff_out
129
+ std = config.init_std / math.sqrt(2.0 * config.n_layers)
130
+ elif type_of_module == ModuleType.emb:
131
+ # positional embeddings (wpe)
132
+ # token embeddings (wte)
133
+ std = config.init_std
134
+ elif type_of_module == ModuleType.final_out:
135
+ # final output (ff_out)
136
+ std = config.d_model**-0.5
137
+ else:
138
+ raise RuntimeError(f"Unknown module type '{type_of_module}'")
139
+ nn.init.trunc_normal_(
140
+ module.weight,
141
+ mean=0.0,
142
+ std=std,
143
+ a=-cutoff_factor * std,
144
+ b=cutoff_factor * std,
145
+ )
146
+ else:
147
+ raise NotImplementedError(config.init_fn)
148
+
149
+ if isinstance(module, nn.Linear):
150
+ if module.bias is not None:
151
+ nn.init.zeros_(module.bias)
152
+
153
+ if config.init_fn == InitFnType.normal and getattr(module, "_is_residual", False):
154
+ with torch.no_grad():
155
+ module.weight.div_(math.sqrt(2 * config.n_layers))
156
+
157
+
158
+ def ensure_finite_(x: torch.Tensor, check_neg_inf: bool = True, check_pos_inf: bool = False):
159
+ """
160
+ Modify ``x`` in place to replace ``float("-inf")`` with the minimum value of the dtype when ``check_neg_inf``
161
+ is ``True`` and to replace ``float("inf")`` with the maximum value of the dtype when ``check_pos_inf`` is ``True``.
162
+ """
163
+ if check_neg_inf:
164
+ x.masked_fill_(x == float("-inf"), torch.finfo(x.dtype).min)
165
+ if check_pos_inf:
166
+ x.masked_fill_(x == float("inf"), torch.finfo(x.dtype).max)
167
+
168
+
169
+ def activation_checkpoint_function(cfg: ModelConfig):
170
+ preserve_rng_state = (
171
+ (cfg.attention_dropout == 0.0) and (cfg.embedding_dropout == 0.0) and (cfg.residual_dropout == 0.0)
172
+ )
173
+ from torch.utils.checkpoint import checkpoint
174
+
175
+ return partial(
176
+ checkpoint,
177
+ preserve_rng_state=preserve_rng_state,
178
+ use_reentrant=False,
179
+ )
180
+
181
+
182
+ class BufferCache(dict, MutableMapping[str, torch.Tensor]):
183
+ """
184
+ Cache for attention biases and other things that would normally be stored as buffers.
185
+ We avoid using buffers because we've run into various issues doing so with FSDP.
186
+ In general it appears the way FSDP handles buffers is not well-defined.
187
+ It doesn't shard them but apparently it does synchronize them across processes, which we want to avoid
188
+ since (A) it isn't necessary, and (B) we sometimes have `-inf` in these biases which might get turned into
189
+ NaNs when they're synchronized due to casting or some other issue.
190
+ """
191
+
192
+
193
+ def _non_meta_init_device(config: ModelConfig) -> torch.device:
194
+ if config.init_device is not None and config.init_device != "meta":
195
+ return torch.device(config.init_device)
196
+ else:
197
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
198
+
199
+
200
+ class Dropout(nn.Dropout):
201
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
202
+ if self.p == 0.0:
203
+ return input
204
+ else:
205
+ return F.dropout(input, self.p, self.training, self.inplace)
206
+
207
+
208
+ class LayerNormBase(nn.Module):
209
+ def __init__(
210
+ self,
211
+ config: ModelConfig,
212
+ *,
213
+ size: Optional[int] = None,
214
+ elementwise_affine: Optional[bool] = True,
215
+ eps: float = 1e-05,
216
+ ):
217
+ super().__init__()
218
+ self.config = config
219
+ self.eps = eps
220
+ self.normalized_shape = (size or config.d_model,)
221
+ if elementwise_affine or (elementwise_affine is None and self.config.layer_norm_with_affine):
222
+ self.weight = nn.Parameter(torch.ones(self.normalized_shape, device=config.init_device))
223
+ use_bias = self.config.bias_for_layer_norm
224
+ if use_bias is None:
225
+ use_bias = self.config.include_bias
226
+ if use_bias:
227
+ self.bias = nn.Parameter(torch.zeros(self.normalized_shape, device=config.init_device))
228
+ else:
229
+ self.register_parameter("bias", None)
230
+ else:
231
+ self.register_parameter("bias", None)
232
+ self.register_parameter("weight", None)
233
+
234
+ @abstractmethod
235
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
236
+ raise NotImplementedError
237
+
238
+ @classmethod
239
+ def build(cls, config: ModelConfig, size: Optional[int] = None, **kwargs) -> LayerNormBase:
240
+ if config.layer_norm_type == LayerNormType.default:
241
+ return LayerNorm(config, size=size, low_precision=False, **kwargs)
242
+ elif config.layer_norm_type == LayerNormType.low_precision:
243
+ return LayerNorm(config, size=size, low_precision=True, **kwargs)
244
+ elif config.layer_norm_type == LayerNormType.rms:
245
+ return RMSLayerNorm(config, size=size, **kwargs)
246
+ elif config.layer_norm_type == LayerNormType.gemma_rms:
247
+ return GemmaRMSLayerNorm(config, size=size, **kwargs)
248
+ else:
249
+ raise NotImplementedError(f"Unknown LayerNorm type: '{config.layer_norm_type}'")
250
+
251
+ def _cast_if_autocast_enabled(self, tensor: torch.Tensor, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
252
+ # NOTE: `is_autocast_enabled()` only checks for CUDA autocast, so we use the separate function
253
+ # `is_autocast_cpu_enabled()` for CPU autocast.
254
+ # See https://github.com/pytorch/pytorch/issues/110966.
255
+ if tensor.device.type == "cuda" and torch.is_autocast_enabled():
256
+ return tensor.to(dtype=dtype if dtype is not None else torch.get_autocast_gpu_dtype())
257
+ elif tensor.device.type == "cpu" and torch.is_autocast_cpu_enabled():
258
+ return tensor.to(dtype=dtype if dtype is not None else torch.get_autocast_cpu_dtype())
259
+ else:
260
+ return tensor
261
+
262
+ def reset_parameters(self):
263
+ if self.weight is not None:
264
+ torch.nn.init.ones_(self.weight) # type: ignore
265
+ if self.bias is not None:
266
+ torch.nn.init.zeros_(self.bias) # type: ignore
267
+
268
+
269
+ class LayerNorm(LayerNormBase):
270
+ """
271
+ The default :class:`LayerNorm` implementation which can optionally run in low precision.
272
+ """
273
+
274
+ def __init__(
275
+ self,
276
+ config: ModelConfig,
277
+ size: Optional[int] = None,
278
+ low_precision: bool = False,
279
+ elementwise_affine: Optional[bool] = None,
280
+ eps: float = 1e-05,
281
+ ):
282
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=eps)
283
+ self.low_precision = low_precision
284
+
285
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
286
+ if self.low_precision:
287
+ module_device = x.device
288
+ downcast_x = self._cast_if_autocast_enabled(x)
289
+ downcast_weight = (
290
+ self._cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
291
+ )
292
+ downcast_bias = self._cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
293
+ with torch.autocast(enabled=False, device_type=module_device.type):
294
+ return F.layer_norm(
295
+ downcast_x, self.normalized_shape, weight=downcast_weight, bias=downcast_bias, eps=self.eps
296
+ )
297
+ else:
298
+ return F.layer_norm(x, self.normalized_shape, weight=self.weight, bias=self.bias, eps=self.eps)
299
+
300
+
301
+ class RMSLayerNorm(LayerNormBase):
302
+ """
303
+ RMS layer norm, a simplified :class:`LayerNorm` implementation
304
+ """
305
+
306
+ def __init__(
307
+ self,
308
+ config: ModelConfig,
309
+ size: Optional[int] = None,
310
+ elementwise_affine: Optional[bool] = None,
311
+ eps: float = 1e-5,
312
+ ):
313
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=config.rms_norm_eps)
314
+
315
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
316
+ with torch.autocast(enabled=False, device_type=x.device.type):
317
+ og_dtype = x.dtype
318
+ x = x.to(torch.float32)
319
+ variance = x.pow(2).mean(-1, keepdim=True)
320
+ x = x * torch.rsqrt(variance + self.eps)
321
+ x = x.to(og_dtype)
322
+
323
+ if self.weight is not None:
324
+ if self.bias is not None:
325
+ return self.weight * x + self.bias
326
+ else:
327
+ return self.weight * x
328
+ else:
329
+ return x
330
+
331
+
332
+ class GemmaRMSLayerNorm(LayerNormBase):
333
+ """
334
+ Gemma RMS layer norm, a simplified :class:`LayerNorm` implementation
335
+ """
336
+
337
+ def __init__(
338
+ self,
339
+ config: ModelConfig,
340
+ size: Optional[int] = None,
341
+ elementwise_affine: Optional[bool] = None,
342
+ eps: float = 1e-5,
343
+ ):
344
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=config.rms_norm_eps)
345
+
346
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
347
+ with torch.autocast(enabled=False, device_type=x.device.type):
348
+ og_dtype = x.dtype
349
+ x = x.to(torch.float32)
350
+ variance = x.pow(2).mean(-1, keepdim=True)
351
+ x = x * torch.rsqrt(variance + self.eps)
352
+ x = x.to(og_dtype)
353
+
354
+ if self.weight is not None:
355
+ if self.bias is not None:
356
+ return x * (1 + self.weight) + self.bias
357
+ else:
358
+ return x * (1 + self.weight)
359
+ else:
360
+ return x
361
+
362
+
363
+ class RotaryEmbedding(nn.Module):
364
+ """
365
+ [Rotary positional embeddings (RoPE)](https://arxiv.org/abs/2104.09864).
366
+ """
367
+
368
+ def __init__(self, config: ModelConfig, cache: BufferCache):
369
+ super().__init__()
370
+ self.config = config
371
+ self.__cache = cache
372
+ # Warm up cache.
373
+ self.rope_theta = config.rope_theta
374
+ self.get_rotary_embedding(config.max_sequence_length, _non_meta_init_device(config))
375
+
376
+ def get_rotary_embedding(self, seq_len: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
377
+ if (
378
+ (pos_sin := self.__cache.get("rope_pos_sin")) is not None
379
+ and (pos_cos := self.__cache.get("rope_pos_cos")) is not None
380
+ and pos_sin.shape[-2] >= seq_len
381
+ and pos_cos.shape[-2] >= seq_len
382
+ ):
383
+ if pos_sin.device != device:
384
+ pos_sin = pos_sin.to(device)
385
+ self.__cache["rope_pos_sin"] = pos_sin
386
+ if pos_cos.device != device:
387
+ pos_cos = pos_cos.to(device)
388
+ self.__cache["rope_pos_cos"] = pos_cos
389
+ return pos_sin[:, :, :seq_len, :], pos_cos[:, :, :seq_len, :]
390
+
391
+ with torch.autocast(device.type, enabled=False):
392
+ dim = self.config.d_model // self.config.n_heads
393
+ inv_freq = 1.0 / (self.rope_theta ** (torch.arange(0, dim, 2, device=device, dtype=torch.float) / dim))
394
+ seq = torch.arange(seq_len, device=device, dtype=torch.float)
395
+ freqs = einsum("i , j -> i j", seq, inv_freq)
396
+ positions = torch.cat((freqs, freqs), dim=-1)
397
+ pos_sin, pos_cos = positions.sin()[None, None, :, :], positions.cos()[None, None, :, :]
398
+ self.__cache["rope_pos_sin"] = pos_sin
399
+ self.__cache["rope_pos_cos"] = pos_cos
400
+ return pos_sin, pos_cos
401
+
402
+ def rotate_half(self, x: torch.Tensor) -> torch.Tensor:
403
+ B, nh, T, hs = x.size()
404
+ x = x.view(B, nh, T, 2, hs // 2)
405
+ x1, x2 = x.unbind(dim=-2)
406
+ return torch.cat((-x2, x1), dim=-1)
407
+
408
+ def apply_rotary_pos_emb(self, pos_sin: torch.Tensor, pos_cos: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
409
+ return ((t * pos_cos) + (self.rotate_half(t) * pos_sin)).to(t.dtype)
410
+
411
+ def forward(self, q: torch.Tensor, k: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
412
+ if self.config.rope_full_precision:
413
+ q_, k_ = q.float(), k.float()
414
+ else:
415
+ q_, k_ = q, k
416
+
417
+ with torch.autocast(q.device.type, enabled=False):
418
+ query_len, key_len = q_.shape[-2], k_.shape[-2] # could be different if layer_past not None
419
+ pos_sin, pos_cos = self.get_rotary_embedding(key_len, q_.device)
420
+ pos_sin = pos_sin.type_as(q_)
421
+ pos_cos = pos_cos.type_as(q_)
422
+ q_ = self.apply_rotary_pos_emb(
423
+ pos_sin[:, :, key_len - query_len : key_len, :],
424
+ pos_cos[:, :, key_len - query_len : key_len, :],
425
+ q_,
426
+ )
427
+ k_ = self.apply_rotary_pos_emb(pos_sin, pos_cos, k_)
428
+ return q_.type_as(q), k_.type_as(k)
429
+
430
+
431
+ class Activation(nn.Module):
432
+ def __init__(self, config: ModelConfig):
433
+ super().__init__()
434
+ self.config = config
435
+
436
+ @abstractmethod
437
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
438
+ raise NotImplementedError
439
+
440
+ @property
441
+ @abstractmethod
442
+ def output_multiplier(self) -> float:
443
+ raise NotImplementedError
444
+
445
+ @classmethod
446
+ def build(cls, config: ModelConfig) -> Activation:
447
+ if config.activation_type == ActivationType.gelu:
448
+ return cast(Activation, GELU(approximate="none"))
449
+ elif config.activation_type == ActivationType.relu:
450
+ return cast(Activation, ReLU(inplace=False))
451
+ elif config.activation_type == ActivationType.silu:
452
+ return cast(Activation, SiLU(inplace=False))
453
+ elif config.activation_type == ActivationType.swiglu:
454
+ return SwiGLU(config)
455
+ else:
456
+ raise NotImplementedError(f"Unknown activation: '{config.activation_type}'")
457
+
458
+
459
+ class GELU(nn.GELU):
460
+ @property
461
+ def output_multiplier(self) -> float:
462
+ return 1.0
463
+
464
+
465
+ class ReLU(nn.ReLU):
466
+ @property
467
+ def output_multiplier(self) -> float:
468
+ return 1.0
469
+
470
+ class SiLU(nn.SiLU):
471
+ @property
472
+ def output_multiplier(self) -> float:
473
+ return 1.0
474
+
475
+ class SwiGLU(Activation):
476
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
477
+ x, gate = x.chunk(2, dim=-1)
478
+ return F.silu(gate) * x
479
+
480
+ @property
481
+ def output_multiplier(self) -> float:
482
+ return 0.5
483
+
484
+
485
+ def causal_attention_bias(seq_len: int, device: torch.device) -> torch.FloatTensor:
486
+ att_bias = torch.triu(
487
+ torch.ones(seq_len, seq_len, device=device, dtype=torch.float),
488
+ diagonal=1,
489
+ )
490
+ att_bias.masked_fill_(att_bias == 1, torch.finfo(att_bias.dtype).min)
491
+ return att_bias.view(1, 1, seq_len, seq_len) # type: ignore
492
+
493
+
494
+ def get_causal_attention_bias(cache: BufferCache, seq_len: int, device: torch.device) -> torch.Tensor:
495
+ if (causal_bias := cache.get("causal_attention_bias")) is not None and causal_bias.shape[-1] >= seq_len:
496
+ if causal_bias.device != device:
497
+ causal_bias = causal_bias.to(device)
498
+ cache["causal_attention_bias"] = causal_bias
499
+ return causal_bias
500
+ with torch.autocast(device.type, enabled=False):
501
+ causal_bias = causal_attention_bias(seq_len, device)
502
+ cache["causal_attention_bias"] = causal_bias
503
+ return causal_bias
504
+
505
+
506
+ def alibi_attention_bias(seq_len: int, config: ModelConfig, device: torch.device) -> torch.FloatTensor:
507
+ alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.float, device=device).view(1, 1, 1, seq_len)
508
+
509
+ # shape: (1, 1, seq_len, seq_len)
510
+ alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.float, device=device).view(1, 1, seq_len, 1)
511
+ alibi_bias.abs_().mul_(-1)
512
+
513
+ # shape: (n_heads,)
514
+ m = torch.arange(1, config.n_heads + 1, dtype=torch.float, device=device)
515
+ m.mul_(config.alibi_bias_max / config.n_heads)
516
+
517
+ # shape: (1, n_heads, seq_len, seq_len)
518
+ return alibi_bias * (1.0 / (2 ** m.view(1, config.n_heads, 1, 1))) # type: ignore
519
+
520
+
521
+ class LLaDABlock(nn.Module):
522
+ """
523
+ A base class for transformer block implementations.
524
+ """
525
+
526
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
527
+ super().__init__()
528
+ self.layer_id = layer_id
529
+ self.config = config
530
+ self.hidden_size = (
531
+ config.mlp_hidden_size if config.mlp_hidden_size is not None else config.mlp_ratio * config.d_model
532
+ )
533
+ self.__cache = cache
534
+ assert config.d_model % config.n_heads == 0
535
+
536
+ self._activation_checkpoint_fn = None
537
+
538
+ # Dropout.
539
+ self.dropout = Dropout(config.residual_dropout)
540
+
541
+ # Layer norms.
542
+ self.k_norm: Optional[LayerNormBase] = None
543
+ self.q_norm: Optional[LayerNormBase] = None
544
+ if config.attention_layer_norm:
545
+ self.k_norm = LayerNormBase.build(
546
+ config,
547
+ size=(config.d_model // config.n_heads) * config.effective_n_kv_heads,
548
+ elementwise_affine=config.attention_layer_norm_with_affine,
549
+ )
550
+ self.q_norm = LayerNormBase.build(config, elementwise_affine=config.attention_layer_norm_with_affine)
551
+
552
+ # Activation function.
553
+ self.act = Activation.build(config)
554
+ assert (self.act.output_multiplier * self.hidden_size) % 1 == 0
555
+
556
+ # Attention output projection.
557
+ self.attn_out = nn.Linear(
558
+ config.d_model, config.d_model, bias=config.include_bias, device=config.init_device
559
+ )
560
+
561
+ # Feed-forward output projection.
562
+ self.ff_out = nn.Linear(
563
+ int(self.act.output_multiplier * self.hidden_size),
564
+ config.d_model,
565
+ bias=config.include_bias,
566
+ device=config.init_device,
567
+ )
568
+ self.ff_out._is_residual = True # type: ignore
569
+
570
+ # Rotary embeddings.
571
+ if self.config.rope:
572
+ self.rotary_emb = RotaryEmbedding(config, self.__cache)
573
+
574
+ self.flash_attn_func = None
575
+ if config.flash_attention:
576
+ try:
577
+ from flash_attn import flash_attn_func # type: ignore
578
+
579
+ self.flash_attn_func = flash_attn_func
580
+ except ModuleNotFoundError:
581
+ pass
582
+
583
+ def reset_parameters(self):
584
+ if self.k_norm is not None:
585
+ self.k_norm.reset_parameters()
586
+ if self.q_norm is not None:
587
+ self.q_norm.reset_parameters()
588
+ init_weights(
589
+ self.config,
590
+ self.attn_out,
591
+ d=self.config.d_model,
592
+ layer_id=self.layer_id,
593
+ type_of_module=ModuleType.out_module,
594
+ )
595
+ init_weights(
596
+ self.config,
597
+ self.ff_out,
598
+ d=self.ff_out.in_features,
599
+ layer_id=self.layer_id,
600
+ type_of_module=ModuleType.out_module,
601
+ )
602
+
603
+ def set_activation_checkpointing(self, strategy: Optional[ActivationCheckpointingStrategy]):
604
+ if strategy == ActivationCheckpointingStrategy.fine_grained:
605
+ self._activation_checkpoint_fn = activation_checkpoint_function(self.config)
606
+ else:
607
+ self._activation_checkpoint_fn = None
608
+
609
+ @classmethod
610
+ def _cast_attn_bias(cls, bias: torch.Tensor, input_dtype: torch.dtype) -> torch.Tensor:
611
+ target_dtype = input_dtype
612
+ # NOTE: `is_autocast_enabled()` only checks for CUDA autocast, so we use the separate function
613
+ # `is_autocast_cpu_enabled()` for CPU autocast.
614
+ # See https://github.com/pytorch/pytorch/issues/110966.
615
+ if bias.device.type == "cuda" and torch.is_autocast_enabled():
616
+ target_dtype = torch.get_autocast_gpu_dtype()
617
+ elif bias.device.type == "cpu" and torch.is_autocast_cpu_enabled():
618
+ target_dtype = torch.get_autocast_cpu_dtype()
619
+ if bias.dtype != target_dtype:
620
+ bias = bias.to(target_dtype)
621
+ ensure_finite_(bias, check_neg_inf=True, check_pos_inf=False)
622
+ return bias
623
+
624
+ def _scaled_dot_product_attention(
625
+ self,
626
+ q: torch.Tensor,
627
+ k: torch.Tensor,
628
+ v: torch.Tensor,
629
+ attn_mask: Optional[torch.Tensor] = None,
630
+ dropout_p: float = 0.0,
631
+ is_causal: bool = False,
632
+ ) -> torch.Tensor:
633
+ """
634
+ Computes scaled dot product attention on query, key and value tensors, using an optional
635
+ attention mask if passed, and applying dropout if a probability greater than 0.0 is specified.
636
+ """
637
+ if self.flash_attn_func is not None and attn_mask is None:
638
+ r = self.flash_attn_func(
639
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), dropout_p=dropout_p, causal=False
640
+ )
641
+ return r.transpose(1, 2)
642
+ else:
643
+ # torch's sdpa doesn't support GQA, so we're doing this
644
+ assert k.size(1) == v.size(1)
645
+ num_kv_heads = k.size(1)
646
+ num_q_heads = q.size(1)
647
+ if num_q_heads != num_kv_heads:
648
+ assert num_q_heads % num_kv_heads == 0
649
+ k = k.repeat_interleave(num_q_heads // num_kv_heads, dim=1, output_size=num_q_heads)
650
+ v = v.repeat_interleave(num_q_heads // num_kv_heads, dim=1, output_size=num_q_heads)
651
+
652
+ # Modify: MDM set causal to False.
653
+ return F.scaled_dot_product_attention(
654
+ q,
655
+ k,
656
+ v,
657
+ attn_mask=attn_mask,
658
+ dropout_p=dropout_p,
659
+ is_causal=False,
660
+ )
661
+
662
+ def attention(
663
+ self,
664
+ q: torch.Tensor,
665
+ k: torch.Tensor,
666
+ v: torch.Tensor,
667
+ attention_bias: Optional[torch.Tensor] = None,
668
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
669
+ use_cache: bool = False,
670
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
671
+ B, T, C = q.size() # batch size, sequence length, d_model
672
+ dtype = k.dtype
673
+
674
+ # Optionally apply layer norm to keys and queries.
675
+ if self.q_norm is not None and self.k_norm is not None:
676
+ q = self.q_norm(q).to(dtype=dtype)
677
+ k = self.k_norm(k).to(dtype=dtype)
678
+
679
+ # Move head forward to be next to the batch dim.
680
+ # shape: (B, nh, T, hs)
681
+ q = q.view(B, T, self.config.n_heads, C // self.config.n_heads).transpose(1, 2)
682
+ # shape: (B, n_kv_h, T, hs)
683
+ k = k.view(B, T, self.config.effective_n_kv_heads, C // self.config.n_heads).transpose(1, 2)
684
+ # shape: (B, n_kv_h, T, hs)
685
+ v = v.view(B, T, self.config.effective_n_kv_heads, C // self.config.n_heads).transpose(1, 2)
686
+
687
+ if layer_past is not None:
688
+ past_key, past_value = layer_past
689
+ k = torch.cat((past_key, k), dim=-2)
690
+ v = torch.cat((past_value, v), dim=-2)
691
+
692
+ present = (k, v) if use_cache else None
693
+ query_len, key_len = q.shape[-2], k.shape[-2] # could be different if layer_past not None
694
+
695
+ if self.config.rope:
696
+ # Apply rotary embeddings.
697
+ q, k = self.rotary_emb(q, k)
698
+
699
+ if attention_bias is not None:
700
+ # Resize and cast attention bias.
701
+ # The current dtype of the attention bias might not match the dtype that the SDP attn function will
702
+ # run in if AMP is enabled, and this can be a problem if some tokens are masked out due to padding
703
+ # as down-casting the attention bias to the autocast precision will result in -infs, which will
704
+ # cause the SDP attn function to produce NaNs.
705
+ attention_bias = self._cast_attn_bias(
706
+ attention_bias[:, :, key_len - query_len : key_len, :key_len], dtype
707
+ )
708
+
709
+ # Get the attention scores.
710
+ # shape: (B, nh, T, hs)
711
+ att = self._scaled_dot_product_attention(
712
+ q,
713
+ k,
714
+ v,
715
+ attn_mask=attention_bias,
716
+ dropout_p=0.0 if not self.training else self.config.attention_dropout,
717
+ is_causal=False,
718
+ )
719
+
720
+ # Re-assemble all head outputs side-by-side.
721
+ att = att.transpose(1, 2).contiguous().view(B, T, C)
722
+
723
+ # Apply output projection.
724
+ return self.attn_out(att), present
725
+
726
+ @abstractmethod
727
+ def forward(
728
+ self,
729
+ x: torch.Tensor,
730
+ attention_bias: Optional[torch.FloatTensor] = None,
731
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
732
+ use_cache: bool = False,
733
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
734
+ raise NotImplementedError
735
+
736
+ @classmethod
737
+ def build(cls, layer_id: int, config: ModelConfig, cache: BufferCache) -> LLaDABlock:
738
+ if config.block_type == BlockType.sequential:
739
+ return LLaDASequentialBlock(layer_id, config, cache)
740
+ elif config.block_type == BlockType.llama:
741
+ return LLaDALlamaBlock(layer_id, config, cache)
742
+ else:
743
+ raise NotImplementedError(f"Unknown block type: '{config.block_type}'")
744
+
745
+
746
+ class LLaDASequentialBlock(LLaDABlock):
747
+ """
748
+ This is a typical transformer block where the output is computed as ``MLP(LN(x + Attention(LN(x))))``
749
+ (plus another skip connection).
750
+ """
751
+
752
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
753
+ super().__init__(layer_id, config, cache)
754
+ # Layer norms.
755
+ self.attn_norm = LayerNorm.build(config)
756
+ self.ff_norm = LayerNorm.build(config)
757
+ # Attention input projection. Projects x -> (q, k, v)
758
+ head_dim = config.d_model // config.n_heads
759
+ self.fused_dims = (
760
+ config.d_model,
761
+ config.effective_n_kv_heads * head_dim,
762
+ config.effective_n_kv_heads * head_dim,
763
+ )
764
+ self.att_proj = nn.Linear(
765
+ config.d_model, sum(self.fused_dims), bias=config.include_bias | config.include_qkv_bias, device=config.init_device
766
+ )
767
+ # Feed-forward input projection.
768
+ self.ff_proj = nn.Linear(
769
+ config.d_model, self.hidden_size, bias=config.include_bias, device=config.init_device
770
+ )
771
+
772
+ def reset_parameters(self):
773
+ super().reset_parameters()
774
+ self.attn_norm.reset_parameters()
775
+ self.ff_norm.reset_parameters()
776
+ # NOTE: the standard deviation for these weights does not depend on the layer.
777
+ init_weights(
778
+ self.config, self.att_proj, d=self.config.d_model, layer_id=None, type_of_module=ModuleType.in_module
779
+ )
780
+ init_weights(
781
+ self.config, self.ff_proj, d=self.config.d_model, layer_id=None, type_of_module=ModuleType.in_module
782
+ )
783
+
784
+ def forward(
785
+ self,
786
+ x: torch.Tensor,
787
+ attention_bias: Optional[torch.Tensor] = None,
788
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
789
+ use_cache: bool = False,
790
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
791
+ # Get query, key, value projections.
792
+ # shape:
793
+ # - for regular attn q, k, v: (batch_size, seq_len, d_model)
794
+ # - for multi-query attn q: (batch_size, seq_len, d_model)
795
+ # k, v: (batch_size, seq_len, d_model // n_heads)
796
+ # - for group query attn q: (batch_size, seq_len, d_model)
797
+ # k, v: (batch_size, seq_len, d_model // n_kv_heads)
798
+ if self._activation_checkpoint_fn is not None:
799
+ q, k, v = self.att_proj(self._activation_checkpoint_fn(self.attn_norm, x)).split(
800
+ self.fused_dims, dim=-1
801
+ )
802
+ else:
803
+ q, k, v = self.att_proj(self.attn_norm(x)).split(self.fused_dims, dim=-1)
804
+
805
+ # Get attention scores.
806
+ if self._activation_checkpoint_fn is not None:
807
+ att, cache = self._activation_checkpoint_fn( # type: ignore
808
+ self.attention, q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache
809
+ )
810
+ else:
811
+ att, cache = self.attention(q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache)
812
+
813
+ # Add attention scores.
814
+ # shape: (B, T, C)
815
+ x = x + self.dropout(att)
816
+
817
+ # Add feed-forward projection.
818
+ # shape: (batch_size, seq_len, d_model)
819
+ og_x = x
820
+ if self._activation_checkpoint_fn is not None:
821
+ x = self._activation_checkpoint_fn(self.ff_norm, x) # type: ignore
822
+ else:
823
+ x = self.ff_norm(x)
824
+ x = self.ff_proj(x)
825
+ if self._activation_checkpoint_fn is not None:
826
+ x = self._activation_checkpoint_fn(self.act, x) # type: ignore
827
+ else:
828
+ x = self.act(x)
829
+ x = self.ff_out(x)
830
+ x = self.dropout(x)
831
+ x = og_x + x
832
+
833
+ return x, cache
834
+
835
+
836
+ class LLaDALlamaBlock(LLaDABlock):
837
+ """
838
+ This is a transformer block where the output is computed as ``MLP(LN(x + Attention(LN(x))))``
839
+ (plus another skip connection). This block is similar to `LLaDASequentialBlock`
840
+ but some operations have slightly different implementations to imitate the
841
+ behavior of Llama.
842
+ """
843
+
844
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
845
+ super().__init__(layer_id, config, cache)
846
+ # Layer norms.
847
+ self.attn_norm = LayerNorm.build(config)
848
+ self.ff_norm = LayerNorm.build(config)
849
+ self.__cache = cache
850
+
851
+ # Attention input projection. Projects x -> (q, k, v)
852
+ head_dim = config.d_model // config.n_heads
853
+ q_proj_out_dim = config.d_model
854
+ k_proj_out_dim = config.effective_n_kv_heads * head_dim
855
+ v_proj_out_dim = config.effective_n_kv_heads * head_dim
856
+ self.q_proj = nn.Linear(
857
+ config.d_model, q_proj_out_dim, bias=config.include_bias | config.include_qkv_bias, device=config.init_device
858
+ )
859
+ self.k_proj = nn.Linear(
860
+ config.d_model, k_proj_out_dim, bias=config.include_bias | config.include_qkv_bias, device=config.init_device
861
+ )
862
+ self.v_proj = nn.Linear(
863
+ config.d_model, v_proj_out_dim, bias=config.include_bias | config.include_qkv_bias, device=config.init_device
864
+ )
865
+
866
+ # Feed-forward input projection.
867
+ self.ff_proj = nn.Linear(
868
+ config.d_model, self.hidden_size, bias=config.include_bias, device=config.init_device
869
+ )
870
+ # new add
871
+ self.up_proj = nn.Linear(
872
+ config.d_model, self.hidden_size, bias=config.include_bias, device=config.init_device
873
+ )
874
+
875
+ def reset_parameters(self):
876
+ super().reset_parameters()
877
+ self.attn_norm.reset_parameters()
878
+ self.ff_norm.reset_parameters()
879
+ # NOTE: the standard deviation for these weights does not depend on the layer.
880
+ init_weights(self.config, self.q_proj, d=self.config.d_model, layer_id=None)
881
+ init_weights(self.config, self.k_proj, d=self.config.d_model, layer_id=None)
882
+ init_weights(self.config, self.v_proj, d=self.config.d_model, layer_id=None)
883
+ init_weights(self.config, self.ff_proj, d=self.config.d_model, layer_id=None)
884
+ init_weights(self.config, self.up_proj, d=self.config.d_model, layer_id=None) # new add
885
+
886
+ def forward(
887
+ self,
888
+ x: torch.Tensor,
889
+ attention_bias: Optional[torch.Tensor] = None,
890
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
891
+ use_cache: bool = False,
892
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
893
+ # Get query, key, value projections.
894
+ # shape:
895
+ # - for regular attn q, k, v: (batch_size, seq_len, d_model)
896
+ # - for multi-query attn q: (batch_size, seq_len, d_model)
897
+ # k, v: (batch_size, seq_len, d_model // n_heads)
898
+ # - for group query attn q: (batch_size, seq_len, d_model)
899
+ # k, v: (batch_size, seq_len, d_model // n_kv_heads)
900
+ x_normed = self.attn_norm(x)
901
+ q = self.q_proj(x_normed)
902
+ k = self.k_proj(x_normed)
903
+ v = self.v_proj(x_normed)
904
+
905
+ # Get attention scores.
906
+ if self._activation_checkpoint_fn is not None:
907
+ att, cache = self._activation_checkpoint_fn( # type: ignore
908
+ self.attention, q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache
909
+ )
910
+ else:
911
+ att, cache = self.attention(q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache)
912
+
913
+ # Add attention scores.
914
+ # shape: (B, T, C)
915
+ x = x + self.dropout(att)
916
+
917
+ # Add feed-forward projection.
918
+ # shape: (batch_size, seq_len, d_model)
919
+ og_x = x
920
+ if self._activation_checkpoint_fn is not None:
921
+ x = self._activation_checkpoint_fn(self.ff_norm, x) # type: ignore
922
+ else:
923
+ x = self.ff_norm(x)
924
+ x, x_up = self.ff_proj(x), self.up_proj(x) # new add
925
+ if self._activation_checkpoint_fn is not None:
926
+ x = self._activation_checkpoint_fn(self.act, x) # type: ignore
927
+ else:
928
+ x = self.act(x)
929
+ x = x * x_up # new add
930
+ x = self.ff_out(x)
931
+ x = self.dropout(x)
932
+ x = og_x + x
933
+
934
+ return x, cache
935
+
936
+
937
+ class LLaDAOutput(NamedTuple):
938
+ logits: torch.FloatTensor
939
+ """
940
+ A tensor of shape `(batch_size, seq_len, vocab_size)` representing the log probabilities
941
+ for the next token *before* normalization via (log) softmax.
942
+ """
943
+
944
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]]
945
+ """
946
+ Attention keys and values from each block.
947
+ """
948
+
949
+ hidden_states: Optional[Tuple[torch.Tensor]]
950
+ """
951
+ Hidden states from each block.
952
+ """
953
+
954
+
955
+ class LLaDAGenerateOutput(NamedTuple):
956
+ token_ids: torch.LongTensor
957
+ """
958
+ The generated token IDs, a tensor of shape `(batch_size, beam_size, max_steps)`.
959
+ These do *not* include the original input IDs.
960
+ """
961
+
962
+ scores: torch.FloatTensor
963
+ """
964
+ The scores of the generated sequences, a tensor of shape `(batch_size, beam_size)`.
965
+ """
966
+
967
+
968
+ class LLaDABlockGroup(nn.ModuleList):
969
+ def __init__(self, config: ModelConfig, layer_offset: int, modules: Optional[Iterable[nn.Module]] = None):
970
+ super().__init__(modules)
971
+ self.config = config
972
+ self.layer_offset = layer_offset
973
+ self.activation_checkpointing_strategy: Optional[ActivationCheckpointingStrategy] = None
974
+ self._activation_checkpoint_fn = activation_checkpoint_function(self.config)
975
+
976
+ def forward(
977
+ self,
978
+ x: torch.Tensor,
979
+ attention_bias: Optional[torch.FloatTensor] = None,
980
+ layers_past: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
981
+ use_cache: bool = False,
982
+ ) -> Tuple[torch.Tensor, Optional[List[Tuple[torch.Tensor, torch.Tensor]]]]:
983
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = [] if use_cache else None
984
+ for block_idx, block in enumerate(self):
985
+ layer_past = None if layers_past is None else layers_past[block_idx]
986
+ block_idx += self.layer_offset
987
+ if (
988
+ (self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.whole_layer)
989
+ or (
990
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_two
991
+ and block_idx % 2 == 0
992
+ )
993
+ or (
994
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_three
995
+ and block_idx % 3 == 0
996
+ )
997
+ or (
998
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_four
999
+ and block_idx % 4 == 0
1000
+ )
1001
+ ):
1002
+ # shape: (batch_size, seq_len, d_model)
1003
+ x, cache = self._activation_checkpoint_fn( # type: ignore
1004
+ block, x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache
1005
+ )
1006
+ else:
1007
+ # shape: (batch_size, seq_len, d_model)
1008
+ x, cache = block(x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache)
1009
+ if attn_key_values is not None:
1010
+ assert cache is not None
1011
+ attn_key_values.append(cache)
1012
+ return x, attn_key_values
1013
+
1014
+ def reset_parameters(self):
1015
+ for block in self:
1016
+ block.reset_parameters()
1017
+
1018
+ def set_activation_checkpointing(self, strategy: Optional[ActivationCheckpointingStrategy]):
1019
+ self.activation_checkpointing_strategy = strategy
1020
+ for block in self:
1021
+ block.set_activation_checkpointing(strategy)
1022
+
1023
+
1024
+ class LLaDAModel(nn.Module):
1025
+ def __init__(self, config: ModelConfig, init_params: bool = True):
1026
+ super().__init__()
1027
+ self.config = config
1028
+ self.__cache = BufferCache()
1029
+
1030
+ # Validate config.
1031
+ if self.config.alibi and self.config.flash_attention:
1032
+ raise Exception("ALiBi is currently not supported with FlashAttention")
1033
+
1034
+ if self.config.alibi and self.config.rope:
1035
+ raise Exception("ALiBi and RoPE are mutually exclusive")
1036
+
1037
+ if self.config.embedding_size is not None and self.config.embedding_size != self.config.vocab_size:
1038
+ if self.config.embedding_size < self.config.vocab_size:
1039
+ raise Exception("embedding size should be at least as big as vocab size")
1040
+ elif self.config.embedding_size % 128 != 0:
1041
+ import warnings
1042
+
1043
+ warnings.warn(
1044
+ "Embedding size is not a multiple of 128! This could hurt throughput performance.", UserWarning
1045
+ )
1046
+
1047
+ self.activation_checkpointing_strategy: Optional[ActivationCheckpointingStrategy] = None
1048
+ self._activation_checkpoint_fn: Callable = activation_checkpoint_function(self.config)
1049
+
1050
+ if not (
1051
+ 0 < self.config.block_group_size <= self.config.n_layers
1052
+ and self.config.n_layers % self.config.block_group_size == 0
1053
+ ):
1054
+ raise Exception("n layers must be divisible by block group size")
1055
+
1056
+ torch.backends.cuda.enable_flash_sdp(True)
1057
+ torch.backends.cuda.enable_mem_efficient_sdp(False) # this is super slow so make sure torch won't use it
1058
+
1059
+ self.transformer = nn.ModuleDict(
1060
+ dict(
1061
+ wte=nn.Embedding(
1062
+ config.embedding_size or config.vocab_size, config.d_model, device=config.init_device
1063
+ ),
1064
+ emb_drop=Dropout(config.embedding_dropout),
1065
+ ln_f=LayerNorm.build(config),
1066
+ )
1067
+ )
1068
+
1069
+ blocks = [LLaDABlock.build(i, config, self.__cache) for i in range(config.n_layers)]
1070
+ if self.config.block_group_size > 1:
1071
+ block_groups = [
1072
+ LLaDABlockGroup(config, i, blocks[i : i + config.block_group_size])
1073
+ for i in range(0, config.n_layers, config.block_group_size)
1074
+ ]
1075
+ self.transformer.update({"block_groups": nn.ModuleList(block_groups)})
1076
+ else:
1077
+ self.transformer.update({"blocks": nn.ModuleList(blocks)})
1078
+
1079
+ if not (self.config.alibi or self.config.rope):
1080
+ self.transformer.update(
1081
+ {"wpe": nn.Embedding(config.max_sequence_length, config.d_model, device=config.init_device)}
1082
+ )
1083
+ if not config.weight_tying:
1084
+ self.transformer.update(
1085
+ {
1086
+ "ff_out": nn.Linear(
1087
+ config.d_model,
1088
+ config.embedding_size or config.vocab_size,
1089
+ bias=config.include_bias,
1090
+ device=config.init_device,
1091
+ )
1092
+ }
1093
+ )
1094
+ # When `init_device="meta"` FSDP will call `reset_parameters()` to initialize weights.
1095
+ if init_params and self.config.init_device != "meta":
1096
+ self.reset_parameters()
1097
+ self.__num_fwd_flops: Optional[int] = None
1098
+
1099
+ # Warm up cache.
1100
+ if self.config.alibi:
1101
+ get_causal_attention_bias(self.__cache, config.max_sequence_length, _non_meta_init_device(config))
1102
+ self.get_alibi_attention_bias(config.max_sequence_length, _non_meta_init_device(config))
1103
+
1104
+ def set_activation_checkpointing(self, strategy: Optional[ActivationCheckpointingStrategy]):
1105
+ self.activation_checkpointing_strategy = strategy
1106
+ if self.config.block_group_size != 1:
1107
+ for block_group in self.transformer.block_groups:
1108
+ block_group.set_activation_checkpointing(strategy)
1109
+ else:
1110
+ for block in self.transformer.blocks:
1111
+ block.set_activation_checkpointing(strategy)
1112
+
1113
+ @property
1114
+ def device(self) -> torch.device:
1115
+ device: torch.device = self.transformer.wte.weight.device # type: ignore
1116
+ if device.type == "meta":
1117
+ return _non_meta_init_device(self.config)
1118
+ else:
1119
+ return device
1120
+
1121
+ def reset_parameters(self):
1122
+ log.info("Initializing model parameters...")
1123
+ # Top-level embeddings / linear layers.
1124
+ init_weights(
1125
+ self.config,
1126
+ self.transformer.wte, # type: ignore
1127
+ std_factor=(0.5 * math.sqrt(self.config.d_model)) if self.config.scale_logits else 1.0,
1128
+ type_of_module=ModuleType.emb,
1129
+ )
1130
+ if hasattr(self.transformer, "wpe"):
1131
+ init_weights(self.config, self.transformer.wpe, type_of_module=ModuleType.emb) # type: ignore
1132
+
1133
+ # Top-level layer norm.
1134
+ self.transformer.ln_f.reset_parameters() # type: ignore
1135
+
1136
+ # Output weights.
1137
+ if hasattr(self.transformer, "ff_out"):
1138
+ init_weights(self.config, self.transformer.ff_out, type_of_module=ModuleType.final_out) # type: ignore
1139
+
1140
+ # Let the blocks handle themselves.
1141
+ if self.config.block_group_size == 1:
1142
+ for block in self.transformer.blocks:
1143
+ block.reset_parameters()
1144
+ else:
1145
+ for block_group in self.transformer.block_groups:
1146
+ block_group.reset_parameters()
1147
+
1148
+ def get_alibi_attention_bias(self, seq_len: int, device: torch.device) -> torch.Tensor:
1149
+ if (alibi_bias := self.__cache.get("alibi_attention_bias")) is not None and alibi_bias.shape[
1150
+ -1
1151
+ ] >= seq_len:
1152
+ if alibi_bias.device != device:
1153
+ alibi_bias = alibi_bias.to(device)
1154
+ self.__cache["alibi_attention_bias"] = alibi_bias
1155
+ return alibi_bias
1156
+ with torch.autocast(device.type, enabled=False):
1157
+ alibi_bias = alibi_attention_bias(seq_len, self.config, device)
1158
+ self.__cache["alibi_attention_bias"] = alibi_bias
1159
+ return alibi_bias
1160
+
1161
+ def get_bidirectional_attention_bias(self, seq_len: int, device: torch.device) -> torch.Tensor:
1162
+ if (bidirectional_bias := self.__cache.get("bidirectional_attention_bias")) is not None and bidirectional_bias.shape[
1163
+ -1
1164
+ ] >= seq_len:
1165
+ if bidirectional_bias.device != device:
1166
+ bidirectional_bias = bidirectional_bias.to(device)
1167
+ self.__cache["bidirectional_attention_bias"] = bidirectional_bias
1168
+ return bidirectional_bias
1169
+ with torch.autocast(device.type, enabled=False):
1170
+ bidirectional_bias = torch.zeros((1, 1, seq_len, seq_len), device=device, dtype=torch.float)
1171
+ self.__cache["bidirectional_attention_bias"] = bidirectional_bias
1172
+ return bidirectional_bias
1173
+
1174
+ def forward(
1175
+ self,
1176
+ input_ids: torch.LongTensor,
1177
+ input_embeddings: Optional[torch.FloatTensor] = None,
1178
+ attention_mask: Optional[torch.Tensor] = None,
1179
+ attention_bias: Optional[torch.Tensor] = None,
1180
+ past_key_values: Optional[Sequence[Tuple[torch.Tensor, torch.Tensor]]] = None,
1181
+ use_cache: bool = False,
1182
+ last_logits_only: bool = False,
1183
+ output_hidden_states: Optional[bool] = None,
1184
+ ) -> LLaDAOutput:
1185
+ """
1186
+ :param input_ids: A tensor of shape `(batch_size, seq_len)`.
1187
+ :param input_embeddings: A tensor of shape `(batch_size, seq_len, d_model)` with input
1188
+ embeddings. When provided, it is treated as the output of the input embedding layer.
1189
+ :param attention_mask: A tensor of shape `(batch_size, seq_len)` that indicates
1190
+ which input IDs are masked. A `1` value in the mask means that
1191
+ the corresponding input ID should *not* be ignored. A `0` means
1192
+ that the corresponding input ID is masked.
1193
+
1194
+ This has the same meaning as the `attention_mask` in HuggingFace's `transformers`
1195
+ library.
1196
+ :param attention_bias: A tensor of shape `(batch_size, 1, seq_len, seq_len)`,
1197
+ `(1, 1, seq_len, seq_len)`, or `(seq_len, seq_len)`. This is used
1198
+ to introduce causal or other biases.
1199
+
1200
+ If the tensor is a bool or byte tensor, a `True` or `1` at `attention_bias[:, :, i, j]`
1201
+ indicates that the i-th element in the sequence is allowed to attend to the j-th
1202
+ element in the sequence.
1203
+
1204
+ If the tensor is a float tensor, it will just be added to the attention
1205
+ scores before the softmax.
1206
+
1207
+ The default is causal, which corresponds to a lower-diagonal byte matrix of ones.
1208
+ :param past_key_values: Pre-computed keys and values for each attention block.
1209
+ Can be used to speed up sequential decoding. The `input_ids` which have
1210
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
1211
+ :param use_cache: If `True`, return key and value tensors for each block.
1212
+ :param last_logits_only: If `True`, only compute the logits for the last token of each sequence.
1213
+ This can speed up decoding when you only care about the next token.
1214
+ """
1215
+ # Add Basic MDM Model config check
1216
+ assert not self.config.alibi, "Alibi length extrapolation is not supported for MDM."
1217
+ assert self.config.rope, "Rope must be used in Llama-Encoder for MDM."
1218
+ assert (past_key_values is None and not use_cache), "The kvcache is not suppotred for MDM."
1219
+
1220
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else False
1221
+
1222
+ if past_key_values:
1223
+ assert len(past_key_values) == self.config.n_layers
1224
+
1225
+ batch_size, seq_len = input_ids.size() if input_embeddings is None else input_embeddings.size()[:2]
1226
+ if past_key_values is None:
1227
+ past_length = 0
1228
+ else:
1229
+ past_length = past_key_values[0][0].size(-2)
1230
+
1231
+ # Get embeddings of input.
1232
+ # shape: (batch_size, seq_len, d_model)
1233
+ x = self.transformer.wte(input_ids) if input_embeddings is None else input_embeddings # type: ignore
1234
+
1235
+ if self.config.input_emb_norm:
1236
+ x = x * (self.config.d_model**0.5)
1237
+
1238
+ if not (self.config.alibi or self.config.rope):
1239
+ # Get positional embeddings.
1240
+ # shape: (1, seq_len)
1241
+ pos = torch.arange(past_length, past_length + seq_len, dtype=torch.long, device=x.device).unsqueeze(0)
1242
+ # shape: (1, seq_len, d_model)
1243
+ pos_emb = self.transformer.wpe(pos) # type: ignore
1244
+ x = pos_emb + x
1245
+
1246
+ # Add input + positional embeddings and apply dropout.
1247
+ # shape: (batch_size, seq_len, d_model)
1248
+ x = self.transformer.emb_drop(x) # type: ignore
1249
+
1250
+ # Transform the attention mask into what the blocks expect.
1251
+ if attention_mask is not None and 0.0 in attention_mask:
1252
+ # shape: (batch_size, 1, 1, seq_len)
1253
+ attention_mask = attention_mask.to(dtype=torch.float).view(batch_size, -1)[:, None, None, :]
1254
+ attention_mask = (1.0 - attention_mask) * torch.finfo(attention_mask.dtype).min
1255
+ else:
1256
+ attention_mask = None
1257
+
1258
+ # Merge attention mask with attention bias.
1259
+ if (
1260
+ attention_bias is not None
1261
+ or attention_mask is not None
1262
+ or self.config.alibi
1263
+ # NOTE (epwalsh): we need to initialize the attn bias in order for attn to work properly
1264
+ # with key+value cache. Otherwise `F.scaled_dot_product_attention()` doesn't seem to compute
1265
+ # scores correctly.
1266
+ or past_key_values is not None
1267
+ ):
1268
+ if attention_bias is None and self.config.alibi:
1269
+ attention_bias = get_causal_attention_bias(
1270
+ self.__cache, past_length + seq_len, x.device
1271
+ ) + self.get_alibi_attention_bias(past_length + seq_len, x.device)
1272
+ elif attention_bias is None:
1273
+ attention_bias = self.get_bidirectional_attention_bias(past_length + seq_len, x.device)
1274
+ elif attention_bias.dtype in (torch.int8, torch.bool):
1275
+ attention_bias = attention_bias.to(dtype=torch.float)
1276
+ attention_bias.masked_fill_(attention_bias == 0.0, torch.finfo(attention_bias.dtype).min)
1277
+
1278
+ # Transform to the right shape and data type.
1279
+ mask_len = seq_len
1280
+ if attention_mask is not None:
1281
+ mask_len = attention_mask.shape[-1]
1282
+ elif past_key_values is not None:
1283
+ mask_len = past_key_values[0][0].shape[-2] + seq_len
1284
+ attention_bias = attention_bias[:, :, :mask_len, :mask_len].to(dtype=torch.float)
1285
+
1286
+ # Add in the masking bias.
1287
+ if attention_mask is not None:
1288
+ attention_bias = attention_bias + attention_mask
1289
+ # Might get -infs after adding attention mask, since dtype.min + dtype.min = -inf.
1290
+ # `F.scaled_dot_product_attention()` doesn't handle -inf like you'd expect, instead
1291
+ # it can produce NaNs.
1292
+ ensure_finite_(attention_bias, check_neg_inf=True, check_pos_inf=False)
1293
+
1294
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = [] if use_cache else None
1295
+
1296
+ # decoder layers
1297
+ all_hidden_states = []
1298
+
1299
+ # Apply blocks one-by-one.
1300
+ if self.config.block_group_size == 1:
1301
+ for block_idx, block in enumerate(self.transformer.blocks):
1302
+ if output_hidden_states:
1303
+ # add hidden states
1304
+ all_hidden_states.append(x)
1305
+
1306
+ layer_past = None if past_key_values is None else past_key_values[block_idx]
1307
+ if (
1308
+ (self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.whole_layer)
1309
+ or (
1310
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_two
1311
+ and block_idx % 2 == 0
1312
+ )
1313
+ or (
1314
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_three
1315
+ and block_idx % 3 == 0
1316
+ )
1317
+ or (
1318
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_four
1319
+ and block_idx % 4 == 0
1320
+ )
1321
+ ):
1322
+ # shape: (batch_size, seq_len, d_model)
1323
+ x, cache = self._activation_checkpoint_fn(
1324
+ block, x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache
1325
+ )
1326
+ else:
1327
+ # shape: (batch_size, seq_len, d_model)
1328
+ x, cache = block(x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache)
1329
+ if attn_key_values is not None:
1330
+ assert cache is not None
1331
+ attn_key_values.append(cache)
1332
+ else:
1333
+ for group_idx, block_group in enumerate(self.transformer.block_groups):
1334
+ if output_hidden_states:
1335
+ # add hidden states
1336
+ all_hidden_states.append(x)
1337
+
1338
+ layers_past = (
1339
+ None
1340
+ if past_key_values is None
1341
+ else past_key_values[
1342
+ group_idx * self.config.block_group_size : (group_idx + 1) * self.config.block_group_size
1343
+ ]
1344
+ )
1345
+ x, cache = block_group(
1346
+ x, attention_bias=attention_bias, layers_past=layers_past, use_cache=use_cache
1347
+ )
1348
+ if attn_key_values is not None:
1349
+ assert cache is not None
1350
+ attn_key_values.extend(cache)
1351
+
1352
+ if last_logits_only:
1353
+ # shape: (batch_size, 1, d_model)
1354
+ x = x[:, -1, :].unsqueeze(1)
1355
+
1356
+ # Apply final layer norm.
1357
+ # shape: (batch_size, seq_len or 1, d_model)
1358
+ x = self.transformer.ln_f(x) # type: ignore
1359
+ if output_hidden_states:
1360
+ # add final hidden state post-final-layernorm, following HuggingFace's convention
1361
+ all_hidden_states.append(x)
1362
+
1363
+ # Get logits.
1364
+ # shape: (batch_size, seq_len or 1, vocab_size)
1365
+ if self.config.weight_tying:
1366
+ logits = F.linear(x, self.transformer.wte.weight, None) # type: ignore
1367
+ else:
1368
+ logits = self.transformer.ff_out(x) # type: ignore
1369
+ if self.config.scale_logits:
1370
+ logits.mul_(1 / math.sqrt(self.config.d_model))
1371
+
1372
+ return LLaDAOutput(logits=logits, attn_key_values=attn_key_values, hidden_states=tuple(all_hidden_states) if output_hidden_states else None) # type: ignore[arg-type]
1373
+
1374
+
1375
+ def create_model_config_from_pretrained_config(config: LLaDAConfig):
1376
+ """
1377
+ Utility function
1378
+ """
1379
+
1380
+ kwargs = {}
1381
+ for field in fields(ModelConfig):
1382
+ kwargs[field.name] = getattr(config, field.name)
1383
+
1384
+ model_config = ModelConfig(**kwargs)
1385
+ return model_config
1386
+
1387
+
1388
+ class LLaDAModelLM(PreTrainedModel):
1389
+ """
1390
+ Extremely barebones HF model wrapper.
1391
+ """
1392
+
1393
+ config_class = LLaDAConfig
1394
+ base_model_prefix = "model"
1395
+ _no_split_modules = ["LLaDABlock", "LLaDASequentialBlock", "LLaDALlamaBlock"]
1396
+
1397
+ def __init__(self, config: LLaDAConfig, model: Optional[LLaDAModel] = None, init_params: bool = False):
1398
+ super().__init__(config)
1399
+
1400
+ if not model:
1401
+ model_config = create_model_config_from_pretrained_config(config)
1402
+ # Initialize model (always on CPU to start with so we don't run out of GPU memory).
1403
+ model_config.init_device = "cpu"
1404
+ self.model = LLaDAModel(model_config, init_params=init_params)
1405
+ else:
1406
+ self.model = model
1407
+
1408
+ def forward(
1409
+ self,
1410
+ input_ids: torch.LongTensor = None,
1411
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1412
+ attention_mask: Optional[torch.Tensor] = None,
1413
+ attention_bias: Optional[torch.Tensor] = None,
1414
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1415
+ labels: Optional[torch.LongTensor] = None,
1416
+ use_cache: Optional[bool] = None,
1417
+ output_attentions: Optional[bool] = None,
1418
+ output_hidden_states: Optional[bool] = None,
1419
+ return_dict: Optional[bool] = None,
1420
+ cache_position: Optional[Cache] = None, # This is a hack mitigation of an issue in transformers `4.39.x`
1421
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1422
+ if use_cache is None:
1423
+ use_cache = self.config.use_cache
1424
+
1425
+ if output_attentions:
1426
+ raise ValueError("output_attentions is not yet supported in LLaDA")
1427
+
1428
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1429
+
1430
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1431
+ outputs = self.model.forward(
1432
+ input_ids=input_ids,
1433
+ input_embeddings=inputs_embeds,
1434
+ attention_mask=attention_mask,
1435
+ attention_bias=attention_bias,
1436
+ past_key_values=past_key_values,
1437
+ use_cache=use_cache,
1438
+ output_hidden_states=output_hidden_states,
1439
+ )
1440
+
1441
+ logits = outputs.logits
1442
+ hidden_states = outputs.hidden_states
1443
+
1444
+ loss = None
1445
+ if labels is not None:
1446
+ import warnings
1447
+ warnings.warn("Note that for LLaDA, you cannot calculate the loss here.", UserWarning)
1448
+ if not return_dict:
1449
+ output = (logits,) + outputs[1:]
1450
+ return (loss,) + output if loss is not None else output
1451
+
1452
+ return CausalLMOutputWithPast(
1453
+ logits=logits,
1454
+ past_key_values=outputs.attn_key_values,
1455
+ hidden_states=hidden_states,
1456
+ )
1457
+
1458
+ def can_generate(self) -> bool:
1459
+ return True
1460
+
1461
+ def prepare_inputs_for_generation(
1462
+ self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple]] = None, **kwargs
1463
+ ):
1464
+ if past_key_values:
1465
+ # This is because we want the model to only process the last generated token.
1466
+ input_ids = input_ids[:, -1:]
1467
+ model_inputs = {"input_ids": input_ids, "past_key_values": past_key_values}
1468
+
1469
+ model_inputs.update(kwargs)
1470
+ model_inputs["use_cache"] = kwargs.pop("use_cache", self.config.use_cache)
1471
+ return model_inputs
1472
+
1473
+ # TODO: these are required to make the implementation complete.
1474
+ # def resize_position_embeddings(self, new_num_position_embeddings: int):
1475
+ # pass
1476
+ #
1477
+ # def get_position_embeddings(self) -> Union[nn.Embedding, Tuple[nn.Embedding]]:
1478
+ # pass
1479
+ #
1480
+ # def _reorder_cache(self, past_key_values, beam_idx):
1481
+ # pass
1482
+
1483
+ def get_input_embeddings(self) -> torch.nn.Module:
1484
+ return self.model.transformer.wte
1485
+
1486
+ def set_input_embeddings(self, value: torch.nn.Module):
1487
+ self.model.transformer.wte = value
1488
+
1489
+ def get_output_embeddings(self):
1490
+ if self.config.weight_tying:
1491
+ return self.model.transformer.wte
1492
+ else:
1493
+ return self.model.transformer.ff_out
1494
+
1495
+ def set_output_embeddings(self, value: torch.nn.Module):
1496
+ if self.config.weight_tying:
1497
+ self.model.transformer.wte = value
1498
+ else:
1499
+ self.model.transformer.ff_out = value
1500
+
1501
+ def tie_weights(self):
1502
+ if self.config.weight_tying:
1503
+ self.model.transformer.ff_out = self.model.transformer.wte
1504
+
1505
+ # Register the model so that it is available for transformer pipelines, auto-loading, etc.
1506
+ AutoModel.register(LLaDAConfig, LLaDAModelLM)