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