JakeOh commited on
Commit
18d9e1b
·
verified ·
1 Parent(s): f6b5ce6

Upload modeling_llada.py with huggingface_hub

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