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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from transformers import PreTrainedModel
|
| 10 |
+
|
| 11 |
+
from .configuration_nanogpt import NanoGPTConfig
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _rms_norm(x: torch.Tensor) -> torch.Tensor:
|
| 15 |
+
return F.rms_norm(x, (x.size(-1),))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _apply_rotary_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 19 |
+
assert x.ndim == 4
|
| 20 |
+
d = x.shape[3] // 2
|
| 21 |
+
x1, x2 = x[..., :d], x[..., d:]
|
| 22 |
+
y1 = x1 * cos + x2 * sin
|
| 23 |
+
y2 = x1 * (-sin) + x2 * cos
|
| 24 |
+
out = torch.cat([y1, y2], 3)
|
| 25 |
+
return out.to(x.dtype)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 29 |
+
if n_rep == 1:
|
| 30 |
+
return x
|
| 31 |
+
bs, n_kv_heads, slen, head_dim = x.shape
|
| 32 |
+
return (
|
| 33 |
+
x[:, :, None, :, :]
|
| 34 |
+
.expand(bs, n_kv_heads, n_rep, slen, head_dim)
|
| 35 |
+
.reshape(bs, n_kv_heads * n_rep, slen, head_dim)
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class CausalSelfAttention(nn.Module):
|
| 40 |
+
def __init__(self, config: NanoGPTConfig, layer_idx: int):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.layer_idx = layer_idx
|
| 43 |
+
self.n_head = config.n_head
|
| 44 |
+
self.n_kv_head = config.n_kv_head
|
| 45 |
+
self.n_embd = config.n_embd
|
| 46 |
+
self.head_dim = self.n_embd // self.n_head
|
| 47 |
+
assert self.n_embd % self.n_head == 0
|
| 48 |
+
assert self.n_kv_head <= self.n_head and self.n_head % self.n_kv_head == 0
|
| 49 |
+
self.c_q = nn.Linear(self.n_embd, self.n_head * self.head_dim, bias=False)
|
| 50 |
+
self.c_k = nn.Linear(self.n_embd, self.n_kv_head * self.head_dim, bias=False)
|
| 51 |
+
self.c_v = nn.Linear(self.n_embd, self.n_kv_head * self.head_dim, bias=False)
|
| 52 |
+
self.c_proj = nn.Linear(self.n_embd, self.n_embd, bias=False)
|
| 53 |
+
|
| 54 |
+
def forward(self, x: torch.Tensor, cos_sin, kv_cache=None) -> torch.Tensor:
|
| 55 |
+
B, T, C = x.size()
|
| 56 |
+
q = self.c_q(x).view(B, T, self.n_head, self.head_dim)
|
| 57 |
+
k = self.c_k(x).view(B, T, self.n_kv_head, self.head_dim)
|
| 58 |
+
v = self.c_v(x).view(B, T, self.n_kv_head, self.head_dim)
|
| 59 |
+
cos, sin = cos_sin
|
| 60 |
+
q, k = _apply_rotary_emb(q, cos, sin), _apply_rotary_emb(k, cos, sin)
|
| 61 |
+
q, k = _rms_norm(q), _rms_norm(k)
|
| 62 |
+
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
| 63 |
+
Tq = q.size(2)
|
| 64 |
+
Tk = k.size(2)
|
| 65 |
+
nrep = self.n_head // self.n_kv_head
|
| 66 |
+
k, v = _repeat_kv(k, nrep), _repeat_kv(v, nrep)
|
| 67 |
+
if Tq == Tk:
|
| 68 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 69 |
+
elif Tq == 1:
|
| 70 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=False)
|
| 71 |
+
else:
|
| 72 |
+
attn_mask = torch.zeros((Tq, Tk), dtype=torch.bool, device=q.device)
|
| 73 |
+
prefix_len = Tk - Tq
|
| 74 |
+
if prefix_len > 0:
|
| 75 |
+
attn_mask[:, :prefix_len] = True
|
| 76 |
+
attn_mask[:, prefix_len:] = torch.tril(torch.ones((Tq, Tq), dtype=torch.bool, device=q.device))
|
| 77 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
|
| 78 |
+
y = y.transpose(1, 2).contiguous().view(B, T, -1)
|
| 79 |
+
y = self.c_proj(y)
|
| 80 |
+
return y
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class MLP(nn.Module):
|
| 84 |
+
def __init__(self, config: NanoGPTConfig):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=False)
|
| 87 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=False)
|
| 88 |
+
|
| 89 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 90 |
+
x = self.c_fc(x)
|
| 91 |
+
x = F.relu(x).square()
|
| 92 |
+
x = self.c_proj(x)
|
| 93 |
+
return x
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class Block(nn.Module):
|
| 97 |
+
def __init__(self, config: NanoGPTConfig, layer_idx: int):
|
| 98 |
+
super().__init__()
|
| 99 |
+
self.attn = CausalSelfAttention(config, layer_idx)
|
| 100 |
+
self.mlp = MLP(config)
|
| 101 |
+
|
| 102 |
+
def forward(self, x: torch.Tensor, cos_sin, kv_cache=None) -> torch.Tensor:
|
| 103 |
+
x = x + self.attn(_rms_norm(x), cos_sin, kv_cache)
|
| 104 |
+
x = x + self.mlp(_rms_norm(x))
|
| 105 |
+
return x
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class NanoGPTModel(PreTrainedModel):
|
| 109 |
+
config_class = NanoGPTConfig
|
| 110 |
+
|
| 111 |
+
def __init__(self, config: NanoGPTConfig):
|
| 112 |
+
super().__init__(config)
|
| 113 |
+
self.transformer = nn.ModuleDict({
|
| 114 |
+
"wte": nn.Embedding(config.vocab_size, config.n_embd),
|
| 115 |
+
"h": nn.ModuleList([Block(config, layer_idx) for layer_idx in range(config.n_layer)]),
|
| 116 |
+
})
|
| 117 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 118 |
+
self.rotary_seq_len = config.sequence_len * 10
|
| 119 |
+
head_dim = config.n_embd // config.n_head
|
| 120 |
+
cos, sin = self._precompute_rotary_embeddings(self.rotary_seq_len, head_dim)
|
| 121 |
+
self.register_buffer("cos", cos, persistent=False)
|
| 122 |
+
self.register_buffer("sin", sin, persistent=False)
|
| 123 |
+
# ensure fp32 activations
|
| 124 |
+
self.transformer.wte.to(dtype=torch.bfloat16)
|
| 125 |
+
|
| 126 |
+
# following HF API expectations
|
| 127 |
+
self.post_init()
|
| 128 |
+
|
| 129 |
+
def _init_weights(self, module: nn.Module):
|
| 130 |
+
if isinstance(module, nn.Linear):
|
| 131 |
+
fan_out = module.weight.size(0)
|
| 132 |
+
fan_in = module.weight.size(1)
|
| 133 |
+
std = 1.0 / math.sqrt(fan_in) * min(1.0, math.sqrt(fan_out / fan_in))
|
| 134 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
| 135 |
+
if module.bias is not None:
|
| 136 |
+
torch.nn.init.zeros_(module.bias)
|
| 137 |
+
elif isinstance(module, nn.Embedding):
|
| 138 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=1.0)
|
| 139 |
+
|
| 140 |
+
def _precompute_rotary_embeddings(self, seq_len: int, head_dim: int, base: int = 10000, device=None):
|
| 141 |
+
if device is None:
|
| 142 |
+
device = self.transformer.wte.weight.device
|
| 143 |
+
# Handle meta device case - use CPU as fallback
|
| 144 |
+
if device.type == 'meta':
|
| 145 |
+
device = torch.device('cpu')
|
| 146 |
+
channel_range = torch.arange(0, head_dim, 2, dtype=torch.float32, device=device)
|
| 147 |
+
inv_freq = 1.0 / (base ** (channel_range / head_dim))
|
| 148 |
+
t = torch.arange(seq_len, dtype=torch.float32, device=device)
|
| 149 |
+
freqs = torch.outer(t, inv_freq)
|
| 150 |
+
cos, sin = freqs.cos(), freqs.sin()
|
| 151 |
+
cos, sin = cos.bfloat16(), sin.bfloat16()
|
| 152 |
+
cos, sin = cos[None, :, None, :], sin[None, :, None, :]
|
| 153 |
+
return cos, sin
|
| 154 |
+
|
| 155 |
+
def forward(self, input_ids: torch.Tensor, labels=None, **kwargs):
|
| 156 |
+
idx = input_ids
|
| 157 |
+
B, T = idx.size()
|
| 158 |
+
T0 = 0
|
| 159 |
+
cos_sin = self.cos[:, T0:T0+T], self.sin[:, T0:T0+T]
|
| 160 |
+
x = self.transformer.wte(idx)
|
| 161 |
+
x = x.float()
|
| 162 |
+
x = _rms_norm(x)
|
| 163 |
+
for block in self.transformer.h:
|
| 164 |
+
x = block(x, cos_sin, None)
|
| 165 |
+
x = _rms_norm(x)
|
| 166 |
+
|
| 167 |
+
softcap = 15
|
| 168 |
+
logits = self.lm_head(x)
|
| 169 |
+
logits = softcap * torch.tanh(logits / softcap)
|
| 170 |
+
loss = None
|
| 171 |
+
if labels is not None:
|
| 172 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=-1, reduction='mean')
|
| 173 |
+
return {"loss": loss, "logits": logits}
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 177 |
+
config = kwargs.pop("config", None)
|
| 178 |
+
subfolder = kwargs.pop("subfolder", None)
|
| 179 |
+
device_map = kwargs.get("device_map")
|
| 180 |
+
if device_map is not None:
|
| 181 |
+
# Delegate complex dispatch (like accelerate) to the base implementation.
|
| 182 |
+
if subfolder is not None:
|
| 183 |
+
kwargs["subfolder"] = subfolder
|
| 184 |
+
if config is not None:
|
| 185 |
+
kwargs["config"] = config
|
| 186 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 187 |
+
|
| 188 |
+
base_path = Path(pretrained_model_name_or_path)
|
| 189 |
+
if subfolder:
|
| 190 |
+
base_path = base_path / subfolder
|
| 191 |
+
|
| 192 |
+
weight_path = None
|
| 193 |
+
if base_path.is_dir():
|
| 194 |
+
candidate_files = [
|
| 195 |
+
base_path / "pytorch_model.bin",
|
| 196 |
+
base_path / "model.bin",
|
| 197 |
+
]
|
| 198 |
+
candidate_files.extend(sorted(base_path.glob("model_*.pt"), reverse=True))
|
| 199 |
+
candidate_files.extend(sorted(base_path.glob("*.bin"), reverse=True))
|
| 200 |
+
for cand in candidate_files:
|
| 201 |
+
if cand.is_file():
|
| 202 |
+
weight_path = cand
|
| 203 |
+
break
|
| 204 |
+
|
| 205 |
+
if weight_path is None:
|
| 206 |
+
# Fall back to the default behaviour (e.g. remote repo or standard filenames)
|
| 207 |
+
if subfolder is not None:
|
| 208 |
+
kwargs["subfolder"] = subfolder
|
| 209 |
+
if config is not None:
|
| 210 |
+
kwargs["config"] = config
|
| 211 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 212 |
+
|
| 213 |
+
if config is None:
|
| 214 |
+
config = NanoGPTConfig.from_pretrained(pretrained_model_name_or_path, subfolder=subfolder)
|
| 215 |
+
|
| 216 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
| 217 |
+
strict = kwargs.pop("strict", True)
|
| 218 |
+
|
| 219 |
+
state_dict = torch.load(str(weight_path), map_location="cpu")
|
| 220 |
+
if isinstance(state_dict, dict) and "state_dict" in state_dict:
|
| 221 |
+
state_dict = state_dict["state_dict"]
|
| 222 |
+
state_dict = {k.lstrip("_orig_mod."): v for k, v in state_dict.items()}
|
| 223 |
+
|
| 224 |
+
model = cls(config, *model_args)
|
| 225 |
+
model.load_state_dict(state_dict, strict=strict)
|
| 226 |
+
if torch_dtype is not None:
|
| 227 |
+
model = model.to(dtype=torch_dtype)
|
| 228 |
+
model.eval()
|
| 229 |
+
return model
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
|