File size: 17,491 Bytes
fa69329 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | """Checkpoint-compatible model and tokenizer extracted from the training implementation."""
import re, json, hashlib, math
from pathlib import Path
from dataclasses import dataclass
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint
EOS, VOCAB, FORMAT_VERSION = 50256, 50257, 10
BG_TOKENIZER_REPO = 'ldilov/llama2-bg-tokenizer'
BG_TOKENIZER_REVISION = '76b7208d3d64bd9a09eca8ac5d2ca680d0f1c80b'
BULGARIAN_LETTER = re.compile(r'[А-Яа-яѝЍ]')
ASCII_DIGITS = re.compile(r'[0-9]+')
class BulgarianExtensionTokenizer:
"""Exact greedy BG surfaces; GPT-2 IDs unchanged; ASCII digits split singly."""
def __init__(self, added_tokens, base_tokenizer=None):
if base_tokenizer is None:
import tiktoken
base_tokenizer = tiktoken.get_encoding('gpt2')
self.base, self.digit_ids = base_tokenizer, {}
for digit in '0123456789':
ids = self.base.encode(digit, disallowed_special=())
if len(ids) != 1:
raise ValueError(f'Digit {digit!r} is not one token: {ids}')
self.digit_ids[digit] = ids[0]
self.added_tokens = list(added_tokens)
if len(set(self.added_tokens)) != len(self.added_tokens):
raise ValueError('Duplicate Bulgarian subwords')
self.vocab_size, self.root = VOCAB + len(self.added_tokens), {}
for i, piece in enumerate(self.added_tokens):
node = self.root
for char in piece:
node = node.setdefault(char, {})
node[None] = VOCAB + i
canonical = json.dumps(self.added_tokens, ensure_ascii=False, separators=(',', ':'))
self.fingerprint = hashlib.sha256(canonical.encode()).hexdigest()
@classmethod
def from_file(cls, path, max_tokens=8192):
raw = Path(path).read_bytes()
model = json.loads(raw).get('model', {})
if model.get('type') != 'BPE' or not isinstance(model.get('vocab'), dict):
raise ValueError('Expected BPE tokenizer.json with model.vocab')
pieces, used = [], set()
for source, _ in sorted(model['vocab'].items(), key=lambda item: item[1]):
if not BULGARIAN_LETTER.search(source):
continue
piece = source.replace('▁', ' ')
if not piece or piece in used or any(not c.isprintable() for c in piece):
continue
pieces.append(piece)
used.add(piece)
if max_tokens > 0 and len(pieces) >= max_tokens:
break
if not pieces:
raise ValueError('No Bulgarian subwords found')
tok = cls(pieces)
tok.source_sha256 = hashlib.sha256(raw).hexdigest()
return tok
@classmethod
def from_metadata(cls, metadata, base_tokenizer=None):
if not metadata:
return cls([], base_tokenizer)
if metadata.get('kind') != 'gpt2_plus_bulgarian_subwords_v1' or metadata.get('base_vocab') != VOCAB:
raise ValueError('Unknown tokenizer metadata')
tok = cls(metadata['added_tokens'], base_tokenizer)
if tok.fingerprint != metadata.get('fingerprint'):
raise ValueError('Tokenizer fingerprint mismatch')
tok.source_sha256 = metadata.get('source_sha256')
return tok
def metadata(self):
return dict(kind='gpt2_plus_bulgarian_subwords_v1', base_vocab=VOCAB,
added_tokens=self.added_tokens, fingerprint=self.fingerprint,
source_repo=BG_TOKENIZER_REPO, source_sha256=getattr(self, 'source_sha256', None))
def _encode_non_numeric(self, text, disallowed_special=()):
if not self.added_tokens or not BULGARIAN_LETTER.search(text):
return self.base.encode(text, disallowed_special=disallowed_special)
out, fallback, i = [], [], 0
def flush():
if fallback:
out.extend(self.base.encode(''.join(fallback), disallowed_special=disallowed_special))
fallback.clear()
while i < len(text):
node, j, match_id, match_end = self.root, i, None, i
while j < len(text) and text[j] in node:
node = node[text[j]]
j += 1
if None in node:
match_id, match_end = node[None], j
if match_id is None:
fallback.append(text[i])
i += 1
else:
flush()
out.append(match_id)
i = match_end
flush()
return out
def encode(self, text, disallowed_special=()):
out, last = [], 0
for match in ASCII_DIGITS.finditer(text):
out.extend(self._encode_non_numeric(text[last:match.start()], disallowed_special))
out.extend(self.digit_ids[d] for d in match.group())
last = match.end()
out.extend(self._encode_non_numeric(text[last:], disallowed_special))
return out
def decode(self, ids):
parts, run = [], []
for token in ids:
token = int(token)
if 0 <= token < VOCAB:
run.append(token)
elif VOCAB <= token < self.vocab_size:
if run:
parts.append(self.base.decode(run))
run.clear()
parts.append(self.added_tokens[token - VOCAB])
else:
raise ValueError(f'Invalid token ID {token}')
if run:
parts.append(self.base.decode(run))
return ''.join(parts)
@dataclass
class Config:
dim: int = 1536
heads: int = 24
ff: int = 4096
layers: int = 22
rope_theta: float = 10000.
sliding_window: int = 0 # 0 = legacy full attention; training defaults to 2048
activation_checkpointing: bool = True
checkpoint_every: int = 2
repetition_dropout: float = 0
gated_middle: bool = True
repetition_ngram: int = 2
class RMSNorm(nn.Module):
def __init__(self, dim):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
xf = x.float()
return (xf * torch.rsqrt(xf.square().mean(-1, keepdim=True) + 1e-6) * self.weight.float()).to(x.dtype)
def repetition_groups(input_ids, n):
if input_ids.device.type != 'cpu':
raise ValueError('Compute repetition_groups on the original CPU batch')
result = []
for row in input_ids.tolist():
occurrences, segment_start = {}, 0
for end, token in enumerate(row):
if token == EOS:
segment_start = end + 1
continue
start = end - n + 1
if start >= segment_start:
occurrences.setdefault((segment_start, tuple(row[start:end + 1])), []).append(start)
positions, groups, count = [], [], 0
for starts in occurrences.values():
if len(starts) > 1:
for start in starts:
positions.extend(range(start, start + n))
groups.extend([count] * n)
count += 1
result.append((torch.tensor(positions, dtype=torch.long), torch.tensor(groups, dtype=torch.long), count))
return result
def sample_blocked(groups, length, probability, device):
rows = []
for positions, group_ids, count in groups:
hits = torch.zeros(length, dtype=torch.int32, device=device)
if count:
chosen = torch.rand(count, device=device) < probability
hits.scatter_add_(0, positions, chosen[group_ids].to(torch.int32))
rows.append(hits > 0)
return torch.stack(rows)
_ATTENTION_MASK_CACHE, _FLEX_CAUSAL_CACHE, _FLEX = {}, {}, None
def attention_constants(length, device, window=0):
key = (length, device, window)
if key not in _ATTENTION_MASK_CACHE:
pos = torch.arange(length, device=device)
distance = pos[:, None] - pos[None, :]
causal = distance >= 0
if window:
causal = causal & (distance < window)
_ATTENTION_MASK_CACHE[key] = (causal[None, None], (distance == 0)[None, None])
return _ATTENTION_MASK_CACHE[key]
def empty_local_prefix(blocked, window=0):
# A row can lose every visible key to repetition dropout. Restore its
# self edge in that case, including after the sliding window has moved.
prefix = F.pad((~blocked).to(torch.int32).cumsum(-1), (1, 0))
counts = prefix[:, 1:]
if window:
starts = (torch.arange(blocked.shape[1], device=blocked.device) + 1 - window).clamp_min(0)
counts = counts - prefix.index_select(1, starts)
return counts == 0
def dense_repetition_mask(blocked, constants, window=0):
causal, diagonal = constants
empty_prefix = empty_local_prefix(blocked, window)
return (causal & ~blocked[:, None, None, :]) | (empty_prefix[:, None, :, None] & diagonal)
def flex_causal_mask(length, device, window=0):
key = (length, device, window)
if key not in _FLEX_CAUSAL_CACHE:
from torch.nn.attention.flex_attention import create_block_mask
def causal(batch, head, query, key):
return (query >= key) & ((query - key < window) if window else True)
_FLEX_CAUSAL_CACHE[key] = create_block_mask(causal, B=None, H=None, Q_LEN=length, KV_LEN=length, device=str(device))
return _FLEX_CAUSAL_CACHE[key]
class RotaryAttention(nn.Module):
def __init__(self, dim, heads, theta, repetition_dropout=0.):
super().__init__()
self.heads, self.head_dim = heads, dim // heads
self.repetition_dropout = repetition_dropout
self.qkv, self.out = nn.Linear(dim, 3 * dim, bias=False), nn.Linear(dim, dim, bias=False)
self.register_buffer('inv_freq', theta ** (-torch.arange(0, self.head_dim, 2).float() / self.head_dim), persistent=False)
self._rope_cache, self.attention_backend = {}, 'sdpa'
self.sliding_window = 0
def rope(self, length, device, dtype):
key = (length, device, dtype)
if key not in self._rope_cache:
with torch.autocast(device_type=device.type, enabled=False):
phases = torch.outer(torch.arange(length, device=device, dtype=torch.float32), self.inv_freq.float())
self._rope_cache[key] = (phases.cos().to(dtype)[None, None], phases.sin().to(dtype)[None, None])
return self._rope_cache[key]
def rotate(self, x, cos, sin):
even, odd = x[..., 0::2], x[..., 1::2]
return torch.stack((even * cos - odd * sin, even * sin + odd * cos), -1).flatten(-2)
def forward(self, x, blocked=None, rope=None, constants=None):
b, t, d = x.shape
q, k, v = self.qkv(x).view(b, t, 3, self.heads, self.head_dim).unbind(2)
q, k, v = (z.transpose(1, 2) for z in (q, k, v))
cos, sin = rope if rope is not None else self.rope(t, x.device, q.dtype)
q, k = self.rotate(q, cos, sin), self.rotate(k, cos, sin)
window = self.sliding_window
if self.attention_backend == 'flex' and x.is_cuda and (self.training or t % 128 == 0):
if constants is None:
constants = flex_causal_mask(t, x.device, window)
if blocked is None:
def score_mod(score, batch, head, query, key):
return torch.where((query >= key) & ((query - key < window) if window else True), score, -float('inf'))
else:
empty_prefix = empty_local_prefix(blocked, window)
def score_mod(score, batch, head, query, key):
safe_key = key.clamp(max=blocked.shape[1] - 1)
safe_query = query.clamp(max=blocked.shape[1] - 1)
allowed = (query >= key) & ((query - key < window) if window else True) & (~blocked[batch, safe_key] | ((query == key) & empty_prefix[batch, safe_query]))
return torch.where(allowed, score, -float('inf'))
y = _FLEX(q, k, v, score_mod=score_mod, block_mask=constants)
else:
if blocked is not None or (window and t > window):
if constants is None:
constants = attention_constants(t, x.device, window)
mask = constants[0] if blocked is None else dense_repetition_mask(blocked, constants, window)
else:
mask = None
y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0., is_causal=mask is None)
return self.out(y.transpose(1, 2).contiguous().view(b, t, d))
class Block(nn.Module):
def __init__(self, dim, heads, ff, theta, repetition_dropout=0.):
super().__init__()
self.norm1, self.norm2 = RMSNorm(dim), RMSNorm(dim)
self.attn = RotaryAttention(dim, heads, theta, repetition_dropout)
self.gate, self.up, self.down = nn.Linear(dim, ff, bias=False), nn.Linear(dim, ff, bias=False), nn.Linear(ff, dim, bias=False)
def forward(self, x, blocked=None, rope=None, constants=None):
x = x + self.attn(self.norm1(x), blocked, rope, constants)
h = self.norm2(x)
return x + self.down(F.silu(self.gate(h)) * self.up(h))
class Network(nn.Module):
def __init__(self, dim, heads, ff, layers, cfg):
super().__init__()
self.blocks = nn.ModuleList([Block(dim, heads, ff, cfg.rope_theta, cfg.repetition_dropout) for _ in range(layers)])
for block in self.blocks:
block.attn.sliding_window = cfg.sliding_window
self.norm = RMSNorm(dim)
self.checkpointing, self.checkpoint_every = cfg.activation_checkpointing, cfg.checkpoint_every
middle_count = max(1, round(layers * .40))
self.middle_start = (layers - middle_count + 1) // 2
self.middle_end = self.middle_start + middle_count
self.gates = nn.ModuleList(
nn.Linear(dim, 1) for _ in range(4 if cfg.gated_middle else 0)
)
def run_block(self, index, x, rep_groups=None):
block, blocked = self.blocks[index], None
if self.training and block.attn.repetition_dropout > 0 and rep_groups is not None:
blocked = sample_blocked(rep_groups, x.shape[1], block.attn.repetition_dropout, x.device)
dtype = torch.get_autocast_dtype(x.device.type) if torch.is_autocast_enabled(x.device.type) else x.dtype
rope = block.attn.rope(x.shape[1], x.device, dtype)
constants = None
window = block.attn.sliding_window
if block.attn.attention_backend == 'flex' and x.is_cuda and (self.training or x.shape[1] % 128 == 0):
constants = flex_causal_mask(x.shape[1], x.device, window)
elif blocked is not None or (window and x.shape[1] > window):
constants = attention_constants(x.shape[1], x.device, window)
if self.checkpointing and self.checkpoint_every > 0 and index % self.checkpoint_every == 0 and self.training and torch.is_grad_enabled():
return checkpoint(block, x, blocked, rope, constants, use_reentrant=False, preserve_rng_state=True)
return block(x, blocked, rope, constants)
def forward(self, x, middle_loops=0, rep_groups=None):
if not 0 <= middle_loops <= 3:
raise ValueError('middle_loops must be 0..3')
for i in range(self.middle_start):
x = self.run_block(i, x, rep_groups)
for iteration in range(middle_loops + 1):
previous = x
for i in range(self.middle_start, self.middle_end):
x = self.run_block(i, x, rep_groups)
if middle_loops and len(self.gates):
gate = self.gates[iteration](previous).sigmoid().to(previous.dtype)
x = torch.lerp(previous, x.to(previous.dtype), gate)
for i in range(self.middle_end, len(self.blocks)):
x = self.run_block(i, x, rep_groups)
return self.norm(x)
class GPT(nn.Module):
def __init__(self, cfg, vocab_size=VOCAB):
super().__init__()
self.cfg, self.vocab_size = cfg, vocab_size
self.loss_chunk_size, self.loss_backend, self.sft_loss_backend = 512, 'chunked', 'chunked'
self.fused_ce, self.compact_sft = None, True
self.embedding = nn.Embedding(vocab_size, cfg.dim)
self.network = Network(cfg.dim, cfg.heads, cfg.ff, cfg.layers, cfg)
for module in self.modules():
if isinstance(module, (nn.Linear, nn.Embedding)):
nn.init.normal_(module.weight, std=.02)
for block in self.network.blocks:
nn.init.normal_(block.attn.out.weight, std=.02 / math.sqrt(2 * cfg.layers))
nn.init.normal_(block.down.weight, std=.02 / math.sqrt(2 * cfg.layers))
# Start a converted model close to its original single middle pass.
for iteration, gate in enumerate(self.network.gates):
nn.init.zeros_(gate.weight)
nn.init.constant_(gate.bias, 4.0 if iteration == 0 else -4.0)
def forward(self, x, middle_loops=0, rep_groups=None):
if self.training and self.cfg.repetition_dropout > 0 and rep_groups is None:
if x.device.type != "cpu":
raise ValueError("Pass CPU-prepared rep_groups for CUDA training")
rep_groups = repetition_groups(x, self.cfg.repetition_ngram)
hidden = self.embedding(x)
if hidden.is_cuda and torch.is_autocast_enabled("cuda"):
hidden = hidden.to(torch.get_autocast_dtype("cuda"))
return self.network(hidden, middle_loops, rep_groups)
|