WorldModelForMaze / model /transformer.py
Kalso42's picture
Upload folder using huggingface_hub
34e468d verified
Raw
History Blame Contribute Delete
54.2 kB
"""
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
# @torch.jit.script # good to enable when not using torch.compile, disable when using (our default)
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
# key, query, value projections for all heads, but in a batch
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
# output projection
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
# regularization
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
# flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
# Check both config setting and PyTorch support
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")
# causal mask to ensure that attention is only applied to the left in the input sequence
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() # batch size, sequence length, embedding dimensionality (n_embd)
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
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) # (B, nh, T, hs)
q = q.view(B, T, nh, hs).transpose(1, 2) # (B, nh, T, hs)
v = v.view(B, T, nh, hs).transpose(1, 2) # (B, nh, T, hs)
if kv_cache is None:
# ---- standard path: full causal self-attention ----
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:
# ---- incremental path: append k,v to preallocated buffer, attend over full prefix ----
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] # (B, nh, new_end, hs)
v_full = kv_cache['v_buf'][:, :, :new_end]
if T == 1:
# Single new query attends to all prior keys; no causal mask needed.
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:
# Multiple new queries (e.g. initial prompt). Build rectangular causal mask.
# Query i (absolute pos cur_len + i) may attend to keys [0, cur_len + i].
device = q.device
q_abs = torch.arange(cur_len, new_end, device=device).unsqueeze(1) # (T, 1)
k_abs = torch.arange(0, new_end, device=device).unsqueeze(0) # (1, new_end)
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) # re-assemble all head outputs side by side
# output projection
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)])
# Zero-init the last linear so the scan starts as a no-op (residual = 0).
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)
# ---- Path 1: no cache (training, or eval without incremental) ----
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
# ---- Path 2a: dict cache (fast, preallocated) ----
if isinstance(cache, dict):
return self._forward_cached_dict(x, cache)
# ---- Path 2b: list cache (legacy, growing torch.cat) ----
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:
# x already contains only the new tokens.
new_start = L_cached
L = L_cached + T_in
else:
# x is the full sequence [0..L).
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)
# Stale (cache longer than expected) or empty: full rebuild over [0, L).
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]
# ---- Incremental extension from L_cached to L ----
if not incremental:
# Legacy path: extract new tail from full x.
new_tokens = x[:, new_start:]
else:
new_tokens = x
# Append new tokens to level 0.
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:
# Level (k+1) didn't exist before; build from scratch over [0, L).
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:
# Incremental: only fill positions [new_start, L).
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 only the new positions [new_start, L).
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
# Fallback to a fresh full scan if cache is empty, stale, or longer than x.
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]
# Incremental extension from L_cached to L.
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 # 2 ** layer_idx
# value projection only; output projection mirrors CausalSelfAttention.
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:
# Full sequence path. shifted[t] = v[t-stride] for t >= stride,
# else v[t] (boundary uses self, so the average degenerates to v_t).
if stride < T:
shifted = torch.cat([v[:, :stride], v[:, :-stride]], dim=1)
y = 0.5 * (v + shifted)
else:
y = v
else:
# Incremental path: append new v's into a buffer and gather
# v[t-stride] for the new query positions.
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] # (B, T, D)
cur_v = v_buf[:, cur_len:new_end] # (B, T, D)
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)
# DyadicAttn baseline: replace standard self-attention with a fixed
# 0.5/0.5 dyadic-pattern aggregator that mirrors what the NLS scan does.
# ``dyadic_attn_override`` (when not None) takes precedence over the
# global config flag, allowing a hybrid stack that mixes normal and
# dyadic blocks (used by --DyadicHybrid).
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)
# Per-block GRU sublayer (TransformerPostGRU style).
# When config.post_gru is True, each block ends with its own GRU
# sublayer (Attn -> MLP -> GRU), giving sequential cross-time
# recurrence and breaking TC^0.
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,
)
# Small init so post-GRU residual is near-identity at start.
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)
# Optional per-block Non-Linear prefix Scan sublayer (TransformerNLS).
# Depth O(log L) non-linear cross-time aggregation; breaks TC^0.
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:
# GRU fused CUDA kernel requires float32 under autocast.
# NOTE: this layer does not have an incremental cache; in
# incremental decoding mode it processes only new tokens, so the
# recurrent state across steps is broken. PostGRU is currently not
# supported for fast incremental inference.
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 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
n_layer: int = 12
n_head: int = 12
n_embd: int = 768
dropout: float = 0.0
bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
use_flash: bool = True # Enable flash attention (disable for local GPUs that don't support it)
post_gru: bool = False # TransformerPostGRU: each block ends with its own GRU sublayer (Attn -> MLP -> GRU)
per_block_nls: bool = False # TransformerNLS: each block ends with a Non-Linear prefix Scan sublayer (depth O(log L))
dyadic_attn: bool = False # DyadicTransformer baseline: replace self-attention with fixed 0.5/0.5 dyadic-pattern attention
dyadic_hybrid: bool = False # DyadicHybrid ablation: each n_layer normal Transformer block is followed by ceil(log2(block_size)) DyadicAttn blocks
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) # (B, 2D)
x = self.ln(x)
x = F.gelu(self.fc1(x))
x = F.gelu(self.fc2(x))
x = self.fc3(x)
return x + h_t # residual connection
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
# Build the per-block list. Two modes:
# - dyadic_hybrid=True: each of the n_layer "outer" units consists of
# 1 normal Transformer block followed by ceil(log2(block_size))
# DyadicAttn blocks (strides 1, 2, 4, ..., 2^(L-1)). Total physical
# blocks = n_layer * (1 + L_levels).
# - otherwise: standard n_layer blocks (each may itself be DyadicAttn
# when config.dyadic_attn is True; otherwise standard).
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):
# Normal Transformer block (layer_idx unused by standard attn).
blocks.append(Block(config, layer_idx=0, dyadic_attn_override=False))
# ceil(log2 L) DyadicAttn blocks with stride 2^k.
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)
# with weight tying when using torch.compile() some warnings get generated:
# "UserWarning: functional_call was passed multiple values for tied weights.
# This behavior is deprecated and will be an error in future versions"
# not 100% sure what this is, so far seems to be harmless. TODO investigate
self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
# init all weights
self.apply(self._init_weights)
# apply special scaled init to the residual projections, per GPT-2 paper
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)))
# report number of parameters
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()
# Determine position offset for incremental decoding.
# If kv_caches[0] already has a length, idx contains only the NEW
# tokens that should be appended after that prefix.
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)
# forward the GPT model itself
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (1, t, n_embd)
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:
# if we are given some desired targets also calculate the loss
logits = self.lm_head(x)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=0)
else:
# inference-time mini-optimization: only forward the lm_head on the very last position
logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
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)
# Forward the transformer to get hidden states
tok_emb = self.transformer.wte(idx) # (B, T, D)
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) # (B, T, D)
# Standard next-token prediction loss
logits = self.lm_head(hidden_states)
loss_next_token = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=0)
# NextLat auxiliary losses
# We need token embeddings for the target tokens (teacher-forced next tokens)
# targets[:, i] = x_{i+1}, which is the next token at position i
target_tok_emb = self.transformer.wte(targets) # (B, T, D)
# Compute next-h loss (SmoothL1) and KL loss over the sequence
# For each starting position t, unroll latent dynamics for `horizon` steps
# Use positions 0..T-1-horizon as starting points
max_start = t - horizon
if max_start <= 0:
# Sequence too short for the given horizon; fall back to horizon=1
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
# Detach hidden state targets (stop-gradient)
hidden_targets = hidden_states.detach() # (B, T, D)
for d in range(1, horizon + 1):
if d == 1:
# First step: predict from actual hidden states
# h_t for positions 0..max_start-1, predict h_{t+1}
h_current = hidden_states[:, :max_start, :] # (B, max_start, D)
tok_emb_next = target_tok_emb[:, :max_start, :] # (B, max_start, D)
# Reshape for latent model: (B*max_start, D)
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) # (B, max_start, D)
else:
# Multi-step: unroll from previous predicted states
# h_pred is from positions d-1..max_start+d-2, predict d..max_start+d-1
tok_emb_next = target_tok_emb[:, d-1:max_start+d-1, :] # (B, max_start, D)
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)
# SmoothL1 loss: compare predicted h with actual h (stop-gradient on target)
h_target = hidden_targets[:, d:max_start+d, :] # (B, max_start, D)
# --- FIX STARTS HERE ---
# 1. Create valid mask to ignore padding tokens (index 0)
valid_mask = (targets[:, d:max_start+d] != 0) # (B, max_start)
valid_tokens_count = valid_mask.sum()
if valid_tokens_count > 0:
# 2. Masked SmoothL1 Loss
h_loss_unreduced = F.smooth_l1_loss(h_pred, h_target, reduction='none') # (B, max_start, D)
h_loss_unreduced = h_loss_unreduced.mean(dim=-1) # (B, max_start)
loss_next_h = loss_next_h + (h_loss_unreduced * valid_mask).sum() / valid_tokens_count
# 3. Masked KL Loss
with torch.no_grad():
logits_target = self.lm_head(h_target) # (B, max_start, V)
log_probs_target = F.log_softmax(logits_target, dim=-1)
# Use detached lm_head weights
logits_pred = F.linear(h_pred, self.lm_head.weight.detach()) # (B, max_start, V)
log_probs_pred = F.log_softmax(logits_pred, dim=-1)
# KL(p_target || p_pred)
# Using log_target=True avoids .exp() numerical issues and is more stable
kl_unreduced = F.kl_div(log_probs_pred, log_probs_target, reduction='none', log_target=True) # (B, max_start, V)
kl_unreduced = kl_unreduced.sum(dim=-1) # sum over vocabulary dimension -> (B, max_start)
loss_kl = loss_kl + (kl_unreduced * valid_mask).sum() / valid_tokens_count
count += 1
# --- FIX ENDS HERE ---
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):
# model surgery to decrease the block size if necessary
# e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
# but want to use a smaller block size for some smaller, simpler model
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 {} # default to empty dict
# only dropout can be overridden see more notes below
assert all(k == 'dropout' for k in override_args)
from transformers import GPT2LMHeadModel
print("loading weights from pretrained gpt: %s" % model_type)
# n_layer, n_head and n_embd are determined from model_type
config_args = {
'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
}[model_type]
print("forcing vocab_size=50257, block_size=1024, bias=True")
config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
config_args['bias'] = True # always True for GPT model checkpoints
# we can override the dropout rate, if desired
if 'dropout' in override_args:
print(f"overriding dropout rate to {override_args['dropout']}")
config_args['dropout'] = override_args['dropout']
# create a from-scratch initialized minGPT model
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')] # discard this mask / buffer, not a param
# init a huggingface/transformers model
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
sd_hf = model_hf.state_dict()
# copy while ensuring all of the parameters are aligned and match in names and shapes
sd_keys_hf = sd_hf.keys()
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
# basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
# this means that we have to transpose these weights when we import them
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):
# special treatment for the Conv1D weights we need to transpose
assert sd_hf[k].shape[::-1] == sd[k].shape
with torch.no_grad():
sd[k].copy_(sd_hf[k].t())
else:
# vanilla copy over the other parameters
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.
"""
# separate out all parameters to those that will and won't experience regularizing weight decay
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 # full param name
# random note: because named_modules and named_parameters are recursive
# we will see the same tensors p many many times. but doing it this way
# allows us to know which parent module any tensor p belongs to...
if pn.endswith('bias') or pn.endswith('bias_ih') or pn.endswith('bias_hh'):
# all biases will not be decayed
no_decay.add(fpn)
elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
# weights of whitelist modules will be weight decayed
decay.add(fpn)
elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
# weights of blacklist modules will NOT be weight decayed
no_decay.add(fpn)
elif pn.endswith('weight_ih') or pn.endswith('weight_hh'):
# GRU weight matrices will be weight decayed
decay.add(fpn)
# subtle: 'transformer.wte.weight' and 'lm_head.weight' are tied, so they
# will appear in the no_decay and decay sets respectively after the above.
# In addition, because named_parameters() doesn't return duplicates, it
# will only return the first occurence, key'd by 'transformer.wte.weight', below.
# so let's manually remove 'lm_head.weight' from decay set. This will include
# this tensor into optimization via transformer.wte.weight only, and not decayed.
decay.remove('lm_head.weight')
# validate that we considered every parameter
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), )
# create the pytorch optimizer object
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},
]
# new PyTorch nightly has a new 'fused' option for AdamW that is much faster
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 """
# first estimate the number of flops we do per iteration.
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
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
# express our flops throughput as ratio of A100 bfloat16 peak flops
flops_achieved = flops_per_iter * (1.0/dt) # per second
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
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)
# Fast path: KV-cached + NLS-cached incremental decoding.
# Disabled for PostGRU (no recurrent state cache implemented for
# the per-block GRU), and during training (use_incremental requires
# eval-mode shape-1 forwards).
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:
# Greedy decoding (argmax); probs are the raw softmax for confidence reporting.
probs = F.softmax(logits_last, dim=-1)
idx_next = probs.argmax(dim=-1, keepdim=True) # (B, 1)
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) # (B, 1)
if return_confidence:
sampled_probs = probs.gather(1, idx_next).squeeze(-1) # (B,)
confidences.append(sampled_probs.cpu().tolist())
top3_prob_vals, top3_token_ids = torch.topk(probs, 3, dim=-1) # (B, 3)
top3_tokens.append(top3_token_ids.cpu().tolist())
top3_probs.append(top3_prob_vals.cpu().tolist())
return idx_next
# Initial forward over the full prompt (cropped if needed).
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:
# Caches are full; slide the window: reset and re-encode
# the most recent `block_size - 1` tokens so the new token
# can be appended in a single incremental step next time.
_reset_caches()
idx_cond = idx[:, -(block_size - 1):]
logits, _ = self(idx_cond, nls_caches=nls_caches, kv_caches=kv_caches)
else:
# Incremental: feed only the most recently sampled token.
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
# ---- Legacy path: full re-forward each step (used when PostGRU active) ----
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):
# if the sequence context is growing too long we must crop it at block_size
idx_cond = idx if idx.size(1) <= block_size else idx[:, -block_size:]
# If the prefix was cropped (sliding window), the cached level-0
# corresponds to absolute positions and is no longer valid; reset.
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:
# Greedy decoding (argmax); probs are the raw softmax for confidence reporting.
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())
# append sampled index to the running sequence and continue
idx = torch.cat((idx, idx_next), dim=1)
if return_confidence:
conf, t3t, t3p = _format_conf_outputs()
return idx, conf, t3t, t3p
return idx