| """
|
| Full definition of a GPT Language Model, all of it in this single file.
|
| References:
|
| 1) the official GPT-2 TensorFlow implementation released by OpenAI:
|
| https://github.com/openai/gpt-2/blob/master/src/model.py
|
| 2) huggingface/transformers PyTorch implementation:
|
| https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
|
| """
|
|
|
| import math
|
| import inspect
|
| from dataclasses import dataclass, field
|
|
|
| import os
|
|
|
| import torch
|
| import torch.nn as nn
|
| from torch.nn import functional as F
|
| import pickle
|
|
|
|
|
| def new_gelu(x):
|
| """
|
| Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT).
|
| Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415
|
| """
|
| return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
|
|
|
| class LayerNorm(nn.Module):
|
| """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """
|
|
|
| def __init__(self, ndim, bias):
|
| super().__init__()
|
| self.weight = nn.Parameter(torch.ones(ndim))
|
| self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
|
|
|
| def forward(self, input):
|
| return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
|
|
|
| class CausalSelfAttention(nn.Module):
|
|
|
| def __init__(self, config):
|
| super().__init__()
|
| assert config.n_embd % config.n_head == 0
|
|
|
| self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
|
|
|
| self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
|
|
| self.attn_dropout = nn.Dropout(config.dropout)
|
| self.resid_dropout = nn.Dropout(config.dropout)
|
| self.n_head = config.n_head
|
| self.n_embd = config.n_embd
|
| self.dropout = config.dropout
|
|
|
|
|
| self.flash = config.use_flash and hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
| if not self.flash:
|
| if not config.use_flash:
|
| print("INFO: Flash attention disabled via --local flag (for local GPU compatibility)")
|
| else:
|
| print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
|
|
|
| self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
|
| .view(1, 1, config.block_size, config.block_size))
|
|
|
| def forward(self, x, kv_cache=None):
|
| B, T, C = x.size()
|
|
|
|
|
| q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
| nh = self.n_head; hs = C // nh
|
| k = k.view(B, T, nh, hs).transpose(1, 2)
|
| q = q.view(B, T, nh, hs).transpose(1, 2)
|
| v = v.view(B, T, nh, hs).transpose(1, 2)
|
|
|
| if kv_cache is None:
|
|
|
| if self.flash:
|
| y = torch.nn.functional.scaled_dot_product_attention(
|
| q, k, v, attn_mask=None,
|
| dropout_p=self.dropout if self.training else 0,
|
| is_causal=True)
|
| else:
|
| att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
| att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
|
| att = F.softmax(att, dim=-1)
|
| att = self.attn_dropout(att)
|
| y = att @ v
|
| else:
|
|
|
| cur_len = kv_cache.get('len', 0)
|
| max_L = kv_cache['max_L']
|
| if 'k_buf' not in kv_cache:
|
| kv_cache['k_buf'] = torch.empty(B, nh, max_L, hs, dtype=k.dtype, device=k.device)
|
| kv_cache['v_buf'] = torch.empty(B, nh, max_L, hs, dtype=v.dtype, device=v.device)
|
| new_end = cur_len + T
|
| assert new_end <= max_L, f"KV cache overflow: {new_end} > {max_L}"
|
| kv_cache['k_buf'][:, :, cur_len:new_end].copy_(k)
|
| kv_cache['v_buf'][:, :, cur_len:new_end].copy_(v)
|
| kv_cache['len'] = new_end
|
|
|
| k_full = kv_cache['k_buf'][:, :, :new_end]
|
| v_full = kv_cache['v_buf'][:, :, :new_end]
|
|
|
| if T == 1:
|
|
|
| if self.flash:
|
| y = torch.nn.functional.scaled_dot_product_attention(
|
| q, k_full, v_full, attn_mask=None, dropout_p=0, is_causal=False)
|
| else:
|
| att = (q @ k_full.transpose(-2, -1)) * (1.0 / math.sqrt(hs))
|
| att = F.softmax(att, dim=-1)
|
| y = att @ v_full
|
| else:
|
|
|
|
|
| device = q.device
|
| q_abs = torch.arange(cur_len, new_end, device=device).unsqueeze(1)
|
| k_abs = torch.arange(0, new_end, device=device).unsqueeze(0)
|
| mask = (k_abs <= q_abs).view(1, 1, T, new_end)
|
| if self.flash:
|
| y = torch.nn.functional.scaled_dot_product_attention(
|
| q, k_full, v_full, attn_mask=mask, dropout_p=0, is_causal=False)
|
| else:
|
| att = (q @ k_full.transpose(-2, -1)) * (1.0 / math.sqrt(hs))
|
| att = att.masked_fill(~mask, float('-inf'))
|
| att = F.softmax(att, dim=-1)
|
| y = att @ v_full
|
|
|
| y = y.transpose(1, 2).contiguous().view(B, T, C)
|
|
|
|
|
| y = self.resid_dropout(self.c_proj(y))
|
| return y
|
|
|
| class MLP(nn.Module):
|
|
|
| def __init__(self, config):
|
| super().__init__()
|
| self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
|
| self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
|
| self.dropout = nn.Dropout(config.dropout)
|
|
|
| def forward(self, x):
|
| x = self.c_fc(x)
|
| x = new_gelu(x)
|
| x = self.c_proj(x)
|
| x = self.dropout(x)
|
| return x
|
|
|
| class NonLinearPrefixScan(nn.Module):
|
| """Causal non-linear prefix scan via dyadic doubling (depth O(log L)).
|
|
|
| Each "merge" step is a small MLP applied to (u_{t-stride}, u_t),
|
| with stride doubling each level. Strictly causal: position t only
|
| aggregates positions [1..t]. Used as a per-block sublayer to break
|
| Transformer's TC^0 ceiling on state-tracking tasks.
|
| """
|
|
|
| def __init__(self, n_embd, hidden_mult=2, share=True, n_levels_max=16,
|
| dropout=0.0):
|
| super().__init__()
|
| self.share = share
|
| self.n_levels_max = n_levels_max
|
| h = hidden_mult * n_embd
|
|
|
| def make_mlp():
|
| return nn.Sequential(
|
| nn.LayerNorm(2 * n_embd),
|
| nn.Linear(2 * n_embd, h),
|
| nn.GELU(),
|
| nn.Linear(h, n_embd),
|
| nn.Dropout(dropout),
|
| )
|
|
|
| n = 1 if share else n_levels_max
|
| self.mlps = nn.ModuleList([make_mlp() for _ in range(n)])
|
|
|
|
|
| for mlp in self.mlps:
|
| nn.init.zeros_(mlp[-2].weight)
|
| nn.init.zeros_(mlp[-2].bias)
|
|
|
| def forward(self, x, cache=None):
|
| """
|
| Args:
|
| x: (B, L, D)
|
| cache: optional, used for incremental inference. Two formats supported:
|
| - dict (preferred, fast): {'bufs': list[Tensor (B, max_L, D)],
|
| 'lens': list[int],
|
| 'max_L': int}
|
| Pre-allocates per-level buffers once and writes into them in
|
| place. O(log L) work per token; no growing torch.cat. Use this
|
| format when generating long sequences.
|
| - list[Tensor] (legacy, slow): cache[k] is u^{(k)} for the
|
| positions seen so far. Each incremental call grows the cached
|
| tensors via torch.cat (O(L) memory copy per level per step).
|
| Kept for backward compatibility with existing callers.
|
| Pass an empty container ({} or []) on the first call.
|
| Returns: u (B, L, D) -- the final-level prefix scan output for the full x.
|
| """
|
| L = x.size(1)
|
|
|
|
|
| if cache is None:
|
| u = x
|
| k, stride = 0, 1
|
| while stride < L:
|
| mlp = self.mlps[0 if self.share else min(k, len(self.mlps) - 1)]
|
| left = u[:, :-stride]
|
| right = u[:, stride:]
|
| merged = mlp(torch.cat([left, right], dim=-1))
|
| u = torch.cat([u[:, :stride], merged + right], dim=1)
|
| stride *= 2
|
| k += 1
|
| return u
|
|
|
|
|
| if isinstance(cache, dict):
|
| return self._forward_cached_dict(x, cache)
|
|
|
|
|
| return self._forward_cached_list(x, cache)
|
|
|
| def _mlp_for_level(self, k):
|
| return self.mlps[0 if self.share else min(k, len(self.mlps) - 1)]
|
|
|
| def _forward_cached_dict(self, x, cache):
|
| """Incremental scan using pre-allocated per-level buffers.
|
|
|
| Contract: ``x`` may be either
|
| (a) the FULL sequence (B, L, D) — older callers; legacy convention.
|
| In this case L_cached <= L and we use x[:, L_cached:] as the new
|
| tokens to append.
|
| (b) ONLY the new tokens (B, n_new, D) — preferred for incremental
|
| decoding. Detected when ``cache.get('incremental', False)`` is True.
|
|
|
| Returns the final-level prefix scan output for the FULL sequence
|
| [0, L_total) when (a), or for the NEW tokens only when (b).
|
| """
|
| B, T_in, D = x.size()
|
| bufs = cache.setdefault('bufs', [])
|
| lens = cache.setdefault('lens', [])
|
| incremental = cache.get('incremental', False)
|
| L_cached = lens[0] if bufs else 0
|
|
|
| if incremental:
|
|
|
| new_start = L_cached
|
| L = L_cached + T_in
|
| else:
|
|
|
| L = T_in
|
| new_start = L_cached
|
|
|
| max_L = cache.get('max_L', L)
|
| if max_L < L:
|
| max_L = L
|
| cache['max_L'] = max_L
|
|
|
| def ensure_buf(level):
|
| while len(bufs) <= level:
|
| bufs.append(torch.empty(B, max_L, D, dtype=x.dtype, device=x.device))
|
| lens.append(0)
|
|
|
|
|
| if (not incremental) and (L_cached == 0 or L_cached > L):
|
| bufs.clear()
|
| lens.clear()
|
| ensure_buf(0)
|
| bufs[0][:, :L].copy_(x)
|
| lens[0] = L
|
| k, stride = 0, 1
|
| while stride < L:
|
| mlp = self._mlp_for_level(k)
|
| u_k = bufs[k][:, :L]
|
| left = u_k[:, :-stride]
|
| right = u_k[:, stride:]
|
| merged = mlp(torch.cat([left, right], dim=-1))
|
| ensure_buf(k + 1)
|
| bufs[k + 1][:, :stride].copy_(u_k[:, :stride])
|
| bufs[k + 1][:, stride:L].copy_(merged + right)
|
| lens[k + 1] = L
|
| stride *= 2
|
| k += 1
|
| return bufs[-1][:, :L]
|
|
|
| if (not incremental) and L_cached == L:
|
| return bufs[-1][:, :L]
|
|
|
|
|
| if not incremental:
|
|
|
| new_tokens = x[:, new_start:]
|
| else:
|
| new_tokens = x
|
|
|
|
|
| ensure_buf(0)
|
| bufs[0][:, new_start:L].copy_(new_tokens)
|
| lens[0] = L
|
|
|
| k, stride = 0, 1
|
| while stride < L:
|
| mlp = self._mlp_for_level(k)
|
| u_k = bufs[k][:, :L]
|
| ensure_buf(k + 1)
|
| buf_next = bufs[k + 1]
|
| prev_len_next = lens[k + 1]
|
|
|
| if prev_len_next == 0:
|
|
|
| buf_next[:, :stride].copy_(u_k[:, :stride])
|
| if stride < L:
|
| left = u_k[:, :-stride]
|
| right_full = u_k[:, stride:]
|
| merged_full = mlp(torch.cat([left, right_full], dim=-1))
|
| buf_next[:, stride:L].copy_(merged_full + right_full)
|
| else:
|
|
|
| keep_end = min(stride, L)
|
| merge_start = max(stride, new_start)
|
| if new_start < keep_end:
|
| buf_next[:, new_start:keep_end].copy_(u_k[:, new_start:keep_end])
|
| if merge_start < L:
|
| left = u_k[:, merge_start - stride: L - stride]
|
| right = u_k[:, merge_start: L]
|
| merged = mlp(torch.cat([left, right], dim=-1))
|
| buf_next[:, merge_start:L].copy_(merged + right)
|
|
|
| lens[k + 1] = L
|
| stride *= 2
|
| k += 1
|
|
|
| if incremental:
|
|
|
| return bufs[-1][:, new_start:L]
|
| return bufs[-1][:, :L]
|
|
|
| def _forward_cached_list(self, x, cache):
|
| """Legacy list-based incremental cache (uses torch.cat; slower)."""
|
| L = x.size(1)
|
| L_cached = cache[0].size(1) if len(cache) > 0 else 0
|
|
|
|
|
| if L_cached == 0 or L_cached > L:
|
| cache.clear()
|
| u = x
|
| cache.append(u)
|
| k, stride = 0, 1
|
| while stride < L:
|
| mlp = self._mlp_for_level(k)
|
| left = u[:, :-stride]
|
| right = u[:, stride:]
|
| merged = mlp(torch.cat([left, right], dim=-1))
|
| u = torch.cat([u[:, :stride], merged + right], dim=1)
|
| cache.append(u)
|
| stride *= 2
|
| k += 1
|
| return cache[-1]
|
|
|
| if L_cached == L:
|
| return cache[-1]
|
|
|
|
|
| cache[0] = torch.cat([cache[0], x[:, L_cached:]], dim=1)
|
| k, stride = 0, 1
|
| while stride < L:
|
| mlp = self._mlp_for_level(k)
|
| u_k = cache[k]
|
| new_start = L_cached
|
| keep_end = min(stride, L)
|
| merge_start = max(stride, new_start)
|
|
|
| pieces = []
|
| if new_start < keep_end:
|
| pieces.append(u_k[:, new_start:keep_end])
|
| if merge_start < L:
|
| left = u_k[:, merge_start - stride: L - stride]
|
| right = u_k[:, merge_start: L]
|
| merged = mlp(torch.cat([left, right], dim=-1))
|
| pieces.append(merged + right)
|
| new_tail = pieces[0] if len(pieces) == 1 else torch.cat(pieces, dim=1)
|
|
|
| if k + 1 < len(cache):
|
| cache[k + 1] = torch.cat([cache[k + 1], new_tail], dim=1)
|
| else:
|
| left = u_k[:, :-stride]
|
| right_full = u_k[:, stride:]
|
| merged_full = mlp(torch.cat([left, right_full], dim=-1))
|
| cache.append(torch.cat([u_k[:, :stride], merged_full + right_full], dim=1))
|
| stride *= 2
|
| k += 1
|
| return cache[-1]
|
|
|
|
|
| class DyadicFixedAttention(nn.Module):
|
| """Fixed-pattern attention used by the DyadicTransformer baseline.
|
|
|
| For block at layer index k, this layer computes
|
| y_t = 0.5 * v_t + 0.5 * v_{t - stride}, stride = 2 ** k
|
| y_t = v_t for t < stride (boundary)
|
| where v = c_v(x). There are NO Q / K projections: the attention pattern
|
| is hard-coded to two positions with weights (0.5, 0.5), exactly mirroring
|
| the dyadic-doubling reduction used by NonLinearPrefixScan. The point of
|
| this baseline is to test the co-author's claim that the NLS scan model
|
| is equivalent to a Transformer whose attention is restricted to that
|
| same fixed dyadic pattern.
|
|
|
| Note that for fair comparison the model should be configured with
|
| n_layer = ceil(log2(block_size)) so that the deepest block can reach
|
| distance block_size, matching the scan's O(log L) depth.
|
| """
|
|
|
| def __init__(self, config, layer_idx):
|
| super().__init__()
|
| self.layer_idx = layer_idx
|
| self.stride = 1 << layer_idx
|
|
|
| self.c_v = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
| self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
| self.resid_dropout = nn.Dropout(config.dropout)
|
|
|
| def forward(self, x, kv_cache=None):
|
| B, T, D = x.size()
|
| v = self.c_v(x)
|
| stride = self.stride
|
|
|
| if kv_cache is None:
|
|
|
|
|
| if stride < T:
|
| shifted = torch.cat([v[:, :stride], v[:, :-stride]], dim=1)
|
| y = 0.5 * (v + shifted)
|
| else:
|
| y = v
|
| else:
|
|
|
|
|
| cur_len = kv_cache.get('len', 0)
|
| max_L = kv_cache['max_L']
|
| if 'v_buf_da' not in kv_cache:
|
| kv_cache['v_buf_da'] = torch.empty(B, max_L, D, dtype=v.dtype, device=v.device)
|
| new_end = cur_len + T
|
| assert new_end <= max_L, f"DyadicAttn v-cache overflow: {new_end} > {max_L}"
|
| kv_cache['v_buf_da'][:, cur_len:new_end].copy_(v)
|
| kv_cache['len'] = new_end
|
|
|
| v_buf = kv_cache['v_buf_da']
|
| t_idx = torch.arange(cur_len, new_end, device=v.device)
|
| src_idx = (t_idx - stride).clamp(min=0)
|
| src = v_buf[:, src_idx]
|
| cur_v = v_buf[:, cur_len:new_end]
|
| mask = (t_idx >= stride).view(1, T, 1).to(v.dtype)
|
| y = mask * 0.5 * (cur_v + src) + (1 - mask) * cur_v
|
|
|
| y = self.resid_dropout(self.c_proj(y))
|
| return y
|
|
|
|
|
| class Block(nn.Module):
|
|
|
| def __init__(self, config, layer_idx=0, dyadic_attn_override=None):
|
| super().__init__()
|
| self.layer_idx = layer_idx
|
| self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
|
|
|
|
|
|
|
|
|
|
|
| if dyadic_attn_override is None:
|
| use_dyadic = bool(getattr(config, 'dyadic_attn', False))
|
| else:
|
| use_dyadic = bool(dyadic_attn_override)
|
| self.is_dyadic_attn = use_dyadic
|
| if use_dyadic:
|
| self.attn = DyadicFixedAttention(config, layer_idx)
|
| else:
|
| self.attn = CausalSelfAttention(config)
|
| self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
|
| self.mlp = MLP(config)
|
|
|
|
|
|
|
|
|
|
|
| self.per_block_gru = None
|
| self.ln_gru = None
|
| if getattr(config, 'post_gru', False):
|
| self.ln_gru = LayerNorm(config.n_embd, bias=config.bias)
|
| self.per_block_gru = nn.GRU(
|
| config.n_embd, config.n_embd, num_layers=1, batch_first=True,
|
| )
|
|
|
| for name, p in self.per_block_gru.named_parameters():
|
| if 'weight_hh' in name or 'weight_ih' in name:
|
| nn.init.xavier_uniform_(p, gain=0.1)
|
| elif 'bias' in name:
|
| nn.init.zeros_(p)
|
|
|
|
|
|
|
| self.per_block_nls = None
|
| self.ln_nls = None
|
| if getattr(config, 'per_block_nls', False):
|
| self.ln_nls = LayerNorm(config.n_embd, bias=config.bias)
|
| self.per_block_nls = NonLinearPrefixScan(
|
| config.n_embd, dropout=config.dropout,
|
| )
|
|
|
| def forward(self, x, nls_cache=None, kv_cache=None):
|
| x = x + self.attn(self.ln_1(x), kv_cache=kv_cache)
|
| x = x + self.mlp(self.ln_2(x))
|
| if self.per_block_gru is not None:
|
|
|
|
|
|
|
|
|
|
|
| orig_dtype = x.dtype
|
| with torch.amp.autocast(device_type='cuda', enabled=False):
|
| g, _ = self.per_block_gru(self.ln_gru(x).float())
|
| x = x + g.to(orig_dtype)
|
| if self.per_block_nls is not None:
|
| x = x + self.per_block_nls(self.ln_nls(x), cache=nls_cache)
|
| return x
|
|
|
| @dataclass
|
| class GPTConfig:
|
| block_size: int = 1024
|
| vocab_size: int = 50304
|
| n_layer: int = 12
|
| n_head: int = 12
|
| n_embd: int = 768
|
| dropout: float = 0.0
|
| bias: bool = True
|
| use_flash: bool = True
|
| post_gru: bool = False
|
| per_block_nls: bool = False
|
| dyadic_attn: bool = False
|
| dyadic_hybrid: bool = False
|
|
|
| class LatentDynamicsModel(nn.Module):
|
| """
|
| NextLat latent dynamics model p_ψ (arXiv:2511.05963).
|
| A 3-layer MLP that predicts the next hidden state from the current hidden state
|
| and the next token embedding, using a residual connection:
|
| h_hat_{t+1} = f_ψ(h_t, emb(x_{t+1})) + h_t
|
| """
|
|
|
| def __init__(self, n_embd, mlp_hidden_dim=None):
|
| super().__init__()
|
| if mlp_hidden_dim is None:
|
| mlp_hidden_dim = 2 * n_embd
|
| self.ln = LayerNorm(2 * n_embd, bias=True)
|
| self.fc1 = nn.Linear(2 * n_embd, mlp_hidden_dim)
|
| self.fc2 = nn.Linear(mlp_hidden_dim, mlp_hidden_dim)
|
| self.fc3 = nn.Linear(mlp_hidden_dim, n_embd)
|
|
|
| def forward(self, h_t, tok_emb_next):
|
| """
|
| Args:
|
| h_t: (B, D) current hidden state
|
| tok_emb_next: (B, D) token embedding of the next token
|
| Returns:
|
| h_hat_next: (B, D) predicted next hidden state
|
| """
|
| x = torch.cat([h_t, tok_emb_next], dim=-1)
|
| x = self.ln(x)
|
| x = F.gelu(self.fc1(x))
|
| x = F.gelu(self.fc2(x))
|
| x = self.fc3(x)
|
| return x + h_t
|
|
|
| class GPT(nn.Module):
|
|
|
| def __init__(self, config):
|
| super().__init__()
|
| assert config.vocab_size is not None
|
| assert config.block_size is not None
|
| self.config = config
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| if getattr(config, 'dyadic_hybrid', False):
|
| L_levels = max(1, math.ceil(math.log2(config.block_size))) if config.block_size > 1 else 1
|
| blocks = []
|
| for unit in range(config.n_layer):
|
|
|
| blocks.append(Block(config, layer_idx=0, dyadic_attn_override=False))
|
|
|
| for k in range(L_levels):
|
| blocks.append(Block(config, layer_idx=k, dyadic_attn_override=True))
|
| block_list = nn.ModuleList(blocks)
|
| else:
|
| block_list = nn.ModuleList([Block(config, layer_idx=i) for i in range(config.n_layer)])
|
|
|
| self.transformer = nn.ModuleDict(dict(
|
| wte = nn.Embedding(config.vocab_size, config.n_embd),
|
| wpe = nn.Embedding(config.block_size, config.n_embd),
|
| drop = nn.Dropout(config.dropout),
|
| h = block_list,
|
| ln_f = LayerNorm(config.n_embd, bias=config.bias),
|
| ))
|
| self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
|
|
|
|
|
|
|
|
| self.transformer.wte.weight = self.lm_head.weight
|
|
|
|
|
| self.apply(self._init_weights)
|
|
|
| for pn, p in self.named_parameters():
|
| if pn.endswith('c_proj.weight'):
|
| torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * len(self.transformer.h)))
|
|
|
|
|
| print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
|
|
|
| def get_num_params(self, non_embedding=True):
|
| """
|
| Return the number of parameters in the model.
|
| For non-embedding count (default), the position embeddings get subtracted.
|
| The token embeddings would too, except due to the parameter sharing these
|
| params are actually used as weights in the final layer, so we include them.
|
| """
|
| n_params = sum(p.numel() for p in self.parameters())
|
| if non_embedding:
|
| n_params -= self.transformer.wpe.weight.numel()
|
| return n_params
|
|
|
| def _init_weights(self, module):
|
| if isinstance(module, nn.Linear):
|
| torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| if module.bias is not None:
|
| torch.nn.init.zeros_(module.bias)
|
| elif isinstance(module, nn.Embedding):
|
| torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
|
|
| def forward(self, idx, targets=None, nls_caches=None, kv_caches=None):
|
| device = idx.device
|
| b, t = idx.size()
|
|
|
|
|
|
|
|
|
| if kv_caches is not None and len(kv_caches) > 0 and kv_caches[0].get('len', 0) > 0:
|
| pos_offset = kv_caches[0]['len']
|
| else:
|
| pos_offset = 0
|
|
|
| assert pos_offset + t <= self.config.block_size, (
|
| f"Cannot forward sequence of length {pos_offset + t}, block size is only {self.config.block_size}")
|
| pos = torch.arange(pos_offset, pos_offset + t, dtype=torch.long, device=device).unsqueeze(0)
|
|
|
|
|
| tok_emb = self.transformer.wte(idx)
|
| pos_emb = self.transformer.wpe(pos)
|
| x = self.transformer.drop(tok_emb + pos_emb)
|
| for i, block in enumerate(self.transformer.h):
|
| blk_nls_cache = nls_caches[i] if nls_caches is not None else None
|
| blk_kv_cache = kv_caches[i] if kv_caches is not None else None
|
| x = block(x, nls_cache=blk_nls_cache, kv_cache=blk_kv_cache)
|
| x = self.transformer.ln_f(x)
|
|
|
| if targets is not None:
|
|
|
| logits = self.lm_head(x)
|
| loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=0)
|
| else:
|
|
|
| logits = self.lm_head(x[:, [-1], :])
|
| loss = None
|
|
|
| return logits, loss
|
|
|
| def forward_nextlat(self, idx, targets, latent_model, horizon=1, lambda_h=1.0, lambda_kl=1.0):
|
| """
|
| NextLat forward pass (arXiv:2511.05963).
|
| Computes standard next-token loss plus auxiliary latent dynamics losses.
|
|
|
| Args:
|
| idx: (B, T) input token indices
|
| targets: (B, T) target token indices
|
| latent_model: LatentDynamicsModel instance
|
| horizon: number of steps to unroll the latent dynamics model
|
| lambda_h: weight for the next-hidden-state regression loss
|
| lambda_kl: weight for the KL divergence loss
|
| Returns:
|
| total_loss, loss_next_token, loss_next_h, loss_kl
|
| """
|
| device = idx.device
|
| b, t = idx.size()
|
| assert t <= self.config.block_size
|
| pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0)
|
|
|
|
|
| tok_emb = self.transformer.wte(idx)
|
| pos_emb = self.transformer.wpe(pos)
|
| x = self.transformer.drop(tok_emb + pos_emb)
|
| for block in self.transformer.h:
|
| x = block(x)
|
| hidden_states = self.transformer.ln_f(x)
|
|
|
|
|
| logits = self.lm_head(hidden_states)
|
| loss_next_token = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=0)
|
|
|
|
|
|
|
|
|
| target_tok_emb = self.transformer.wte(targets)
|
|
|
|
|
|
|
|
|
| max_start = t - horizon
|
| if max_start <= 0:
|
|
|
| horizon = max(1, t - 1)
|
| max_start = t - horizon
|
|
|
| loss_next_h = torch.tensor(0.0, device=device)
|
| loss_kl = torch.tensor(0.0, device=device)
|
| count = 0
|
|
|
|
|
| hidden_targets = hidden_states.detach()
|
|
|
| for d in range(1, horizon + 1):
|
| if d == 1:
|
|
|
|
|
| h_current = hidden_states[:, :max_start, :]
|
| tok_emb_next = target_tok_emb[:, :max_start, :]
|
|
|
| B_T = b * max_start
|
| h_pred = latent_model(
|
| h_current.reshape(B_T, -1),
|
| tok_emb_next.reshape(B_T, -1)
|
| ).reshape(b, max_start, -1)
|
| else:
|
|
|
|
|
| tok_emb_next = target_tok_emb[:, d-1:max_start+d-1, :]
|
| B_T = b * max_start
|
| h_pred = latent_model(
|
| h_pred.reshape(B_T, -1),
|
| tok_emb_next.reshape(B_T, -1)
|
| ).reshape(b, max_start, -1)
|
|
|
|
|
| h_target = hidden_targets[:, d:max_start+d, :]
|
|
|
|
|
|
|
| valid_mask = (targets[:, d:max_start+d] != 0)
|
| valid_tokens_count = valid_mask.sum()
|
|
|
| if valid_tokens_count > 0:
|
|
|
| h_loss_unreduced = F.smooth_l1_loss(h_pred, h_target, reduction='none')
|
| h_loss_unreduced = h_loss_unreduced.mean(dim=-1)
|
| loss_next_h = loss_next_h + (h_loss_unreduced * valid_mask).sum() / valid_tokens_count
|
|
|
|
|
| with torch.no_grad():
|
| logits_target = self.lm_head(h_target)
|
| log_probs_target = F.log_softmax(logits_target, dim=-1)
|
|
|
|
|
| logits_pred = F.linear(h_pred, self.lm_head.weight.detach())
|
| log_probs_pred = F.log_softmax(logits_pred, dim=-1)
|
|
|
|
|
|
|
| kl_unreduced = F.kl_div(log_probs_pred, log_probs_target, reduction='none', log_target=True)
|
| kl_unreduced = kl_unreduced.sum(dim=-1)
|
| loss_kl = loss_kl + (kl_unreduced * valid_mask).sum() / valid_tokens_count
|
|
|
| count += 1
|
|
|
|
|
| if count > 0:
|
| loss_next_h = loss_next_h / count
|
| loss_kl = loss_kl / count
|
|
|
| total_loss = loss_next_token + lambda_h * loss_next_h + lambda_kl * loss_kl
|
| return total_loss, loss_next_token, loss_next_h, loss_kl
|
|
|
| def crop_block_size(self, block_size):
|
|
|
|
|
|
|
| assert block_size <= self.config.block_size
|
| self.config.block_size = block_size
|
| self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
|
| for block in self.transformer.h:
|
| if hasattr(block.attn, 'bias'):
|
| block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
|
|
|
| @classmethod
|
| def from_pretrained(cls, model_type, override_args=None):
|
| assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
|
| override_args = override_args or {}
|
|
|
| assert all(k == 'dropout' for k in override_args)
|
| from transformers import GPT2LMHeadModel
|
| print("loading weights from pretrained gpt: %s" % model_type)
|
|
|
|
|
| config_args = {
|
| 'gpt2': dict(n_layer=12, n_head=12, n_embd=768),
|
| 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024),
|
| 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280),
|
| 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600),
|
| }[model_type]
|
| print("forcing vocab_size=50257, block_size=1024, bias=True")
|
| config_args['vocab_size'] = 50257
|
| config_args['block_size'] = 1024
|
| config_args['bias'] = True
|
|
|
| if 'dropout' in override_args:
|
| print(f"overriding dropout rate to {override_args['dropout']}")
|
| config_args['dropout'] = override_args['dropout']
|
|
|
| config = GPTConfig(**config_args)
|
| model = GPT(config)
|
| sd = model.state_dict()
|
| sd_keys = sd.keys()
|
| sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')]
|
|
|
|
|
| model_hf = GPT2LMHeadModel.from_pretrained(model_type)
|
| sd_hf = model_hf.state_dict()
|
|
|
|
|
| sd_keys_hf = sd_hf.keys()
|
| sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')]
|
| sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')]
|
| transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
|
|
|
|
|
| assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
|
| for k in sd_keys_hf:
|
| if any(k.endswith(w) for w in transposed):
|
|
|
| assert sd_hf[k].shape[::-1] == sd[k].shape
|
| with torch.no_grad():
|
| sd[k].copy_(sd_hf[k].t())
|
| else:
|
|
|
| assert sd_hf[k].shape == sd[k].shape
|
| with torch.no_grad():
|
| sd[k].copy_(sd_hf[k])
|
|
|
| return model
|
|
|
| def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
|
| """
|
| This long function is unfortunately doing something very simple and is being very defensive:
|
| We are separating out all parameters of the model into two buckets: those that will experience
|
| weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
|
| We are then returning the PyTorch optimizer object.
|
| """
|
|
|
|
|
| decay = set()
|
| no_decay = set()
|
| whitelist_weight_modules = (torch.nn.Linear, )
|
| blacklist_weight_modules = (torch.nn.LayerNorm, LayerNorm, torch.nn.Embedding)
|
| for mn, m in self.named_modules():
|
| for pn, p in m.named_parameters():
|
| fpn = '%s.%s' % (mn, pn) if mn else pn
|
|
|
|
|
|
|
| if pn.endswith('bias') or pn.endswith('bias_ih') or pn.endswith('bias_hh'):
|
|
|
| no_decay.add(fpn)
|
| elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
|
|
|
| decay.add(fpn)
|
| elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
|
|
|
| no_decay.add(fpn)
|
| elif pn.endswith('weight_ih') or pn.endswith('weight_hh'):
|
|
|
| decay.add(fpn)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| decay.remove('lm_head.weight')
|
|
|
|
|
| param_dict = {pn: p for pn, p in self.named_parameters()}
|
| inter_params = decay & no_decay
|
| union_params = decay | no_decay
|
| assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
|
| assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
|
| % (str(param_dict.keys() - union_params), )
|
|
|
|
|
| optim_groups = [
|
| {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": weight_decay},
|
| {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
|
| ]
|
|
|
| use_fused = (device_type == 'cuda') and ('fused' in inspect.signature(torch.optim.AdamW).parameters)
|
| print(f"using fused AdamW: {use_fused}")
|
| extra_args = dict(fused=True) if use_fused else dict()
|
| optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
|
|
|
| return optimizer
|
|
|
| def estimate_mfu(self, fwdbwd_per_iter, dt):
|
| """ estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
|
|
|
|
|
| N = self.get_num_params()
|
| cfg = self.config
|
| L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
|
| flops_per_token = 6*N + 12*L*H*Q*T
|
| flops_per_fwdbwd = flops_per_token * T
|
| flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
|
|
|
| flops_achieved = flops_per_iter * (1.0/dt)
|
| flops_promised = 312e12
|
| mfu = flops_achieved / flops_promised
|
| return mfu
|
|
|
| @torch.no_grad()
|
| def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, return_confidence=False):
|
| """
|
| Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
|
| the sequence max_new_tokens times, feeding the predictions back into the model each time.
|
| Most likely you'll want to make sure to be in model.eval() mode of operation for this.
|
|
|
| Args:
|
| idx: Input token indices of shape (b, t)
|
| max_new_tokens: Number of tokens to generate
|
| temperature: Sampling temperature
|
| top_k: If set, only sample from top k tokens
|
| return_confidence: If True, also return confidence scores and top-3 alternatives
|
|
|
| Returns:
|
| If return_confidence=False: idx (generated sequence)
|
| If return_confidence=True: (idx, confidences, top3_tokens, top3_probs)
|
| - confidences: list of probabilities for each generated token
|
| - top3_tokens: list of top-3 token indices at each step
|
| - top3_probs: list of top-3 probabilities at each step
|
| """
|
| confidences = [] if return_confidence else None
|
| top3_tokens = [] if return_confidence else None
|
| top3_probs = [] if return_confidence else None
|
| B = idx.size(0)
|
|
|
| block_size = self.config.block_size
|
| any_nls = any(getattr(b, 'per_block_nls', None) is not None for b in self.transformer.h)
|
| any_postgru = any(getattr(b, 'per_block_gru', None) is not None for b in self.transformer.h)
|
|
|
|
|
|
|
|
|
|
|
| use_incremental = (not self.training) and (not any_postgru)
|
|
|
| def _format_conf_outputs():
|
| """Reshape collected per-step (B, ...) lists into the documented format.
|
|
|
| For B == 1 (legacy callers): flat lists indexed by time step.
|
| confidences: List[float] of length T
|
| top3_tokens: List[List[int]] of length T (each inner list len 3)
|
| top3_probs: List[List[float]] of length T
|
| For B > 1: per-sample lists indexed by sample then time step.
|
| confidences: List[List[float]] of shape (B, T)
|
| top3_tokens: List[List[List[int]]] of shape (B, T, 3)
|
| top3_probs: List[List[List[float]]] of shape (B, T, 3)
|
| """
|
| if B == 1:
|
| return ([c[0] for c in confidences],
|
| [t[0] for t in top3_tokens],
|
| [p[0] for p in top3_probs])
|
| T = len(confidences)
|
| conf_bs = [[confidences[t][b] for t in range(T)] for b in range(B)]
|
| tok_bs = [[top3_tokens[t][b] for t in range(T)] for b in range(B)]
|
| prob_bs = [[top3_probs[t][b] for t in range(T)] for b in range(B)]
|
| return conf_bs, tok_bs, prob_bs
|
|
|
| if use_incremental:
|
| kv_caches = [{'max_L': block_size} for _ in self.transformer.h]
|
| nls_caches = ([{'max_L': block_size, 'incremental': True}
|
| for _ in self.transformer.h] if any_nls else None)
|
|
|
| def _reset_caches():
|
| for c in kv_caches:
|
| c.pop('k_buf', None)
|
| c.pop('v_buf', None)
|
| c['len'] = 0
|
| if nls_caches is not None:
|
| for c in nls_caches:
|
| c['bufs'] = []
|
| c['lens'] = []
|
|
|
| def _sample_from(logits_last):
|
| if temperature <= 0:
|
|
|
| probs = F.softmax(logits_last, dim=-1)
|
| idx_next = probs.argmax(dim=-1, keepdim=True)
|
| else:
|
| logits_last = logits_last / temperature
|
| if top_k is not None:
|
| v, _ = torch.topk(logits_last, min(top_k, logits_last.size(-1)))
|
| logits_last = torch.where(logits_last < v[:, [-1]],
|
| torch.full_like(logits_last, -float('Inf')),
|
| logits_last)
|
| probs = F.softmax(logits_last, dim=-1)
|
| idx_next = torch.multinomial(probs, num_samples=1)
|
| if return_confidence:
|
| sampled_probs = probs.gather(1, idx_next).squeeze(-1)
|
| confidences.append(sampled_probs.cpu().tolist())
|
| top3_prob_vals, top3_token_ids = torch.topk(probs, 3, dim=-1)
|
| top3_tokens.append(top3_token_ids.cpu().tolist())
|
| top3_probs.append(top3_prob_vals.cpu().tolist())
|
| return idx_next
|
|
|
|
|
| idx_cond = idx if idx.size(1) <= block_size else idx[:, -block_size:]
|
| logits, _ = self(idx_cond, nls_caches=nls_caches, kv_caches=kv_caches)
|
| idx_next = _sample_from(logits[:, -1, :])
|
| idx = torch.cat((idx, idx_next), dim=1)
|
|
|
| for _ in range(max_new_tokens - 1):
|
| cur_len = kv_caches[0]['len']
|
| if cur_len + 1 > block_size:
|
|
|
|
|
|
|
| _reset_caches()
|
| idx_cond = idx[:, -(block_size - 1):]
|
| logits, _ = self(idx_cond, nls_caches=nls_caches, kv_caches=kv_caches)
|
| else:
|
|
|
| logits, _ = self(idx_next, nls_caches=nls_caches, kv_caches=kv_caches)
|
| idx_next = _sample_from(logits[:, -1, :])
|
| idx = torch.cat((idx, idx_next), dim=1)
|
|
|
| if return_confidence:
|
| conf, t3t, t3p = _format_conf_outputs()
|
| return idx, conf, t3t, t3p
|
| return idx
|
|
|
|
|
| nls_caches = ([{'max_L': block_size} for _ in self.transformer.h]
|
| if any_nls else None)
|
| prev_cond_len = 0
|
|
|
| for _ in range(max_new_tokens):
|
|
|
| idx_cond = idx if idx.size(1) <= block_size else idx[:, -block_size:]
|
|
|
|
|
| if nls_caches is not None and (
|
| idx_cond.size(1) < prev_cond_len
|
| or (idx_cond.size(1) == block_size and prev_cond_len == block_size)
|
| ):
|
| for c in nls_caches:
|
| if isinstance(c, dict):
|
| c['bufs'] = []
|
| c['lens'] = []
|
| else:
|
| c.clear()
|
| prev_cond_len = idx_cond.size(1)
|
| logits, _ = self(idx_cond, nls_caches=nls_caches)
|
| if temperature <= 0:
|
|
|
| probs = F.softmax(logits[:, -1, :], dim=-1)
|
| idx_next = probs.argmax(dim=-1, keepdim=True)
|
| else:
|
| logits = logits[:, -1, :] / temperature
|
| if top_k is not None:
|
| v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| logits[logits < v[:, [-1]]] = -float('Inf')
|
| probs = F.softmax(logits, dim=-1)
|
| idx_next = torch.multinomial(probs, num_samples=1)
|
|
|
| if return_confidence:
|
| sampled_probs = probs.gather(1, idx_next).squeeze(-1)
|
| confidences.append(sampled_probs.cpu().tolist())
|
| top3_prob_vals, top3_token_ids = torch.topk(probs, 3, dim=-1)
|
| top3_tokens.append(top3_token_ids.cpu().tolist())
|
| top3_probs.append(top3_prob_vals.cpu().tolist())
|
|
|
|
|
| idx = torch.cat((idx, idx_next), dim=1)
|
|
|
| if return_confidence:
|
| conf, t3t, t3p = _format_conf_outputs()
|
| return idx, conf, t3t, t3p
|
| return idx |