"""Blueberry model architecture adapted from nanochat/gpt.py for inference.""" from dataclasses import dataclass from math import isfinite import torch import torch.nn as nn import torch.nn.functional as F from .attention import flash_attn @dataclass class GPTConfig: sequence_len: int = 2048 vocab_size: int = 32768 n_layer: int = 12 n_head: int = 6 # number of query heads n_kv_head: int = 6 # number of key/value heads (GQA) n_embd: int = 768 ffn: str = "relu2" intermediate_size: int | None = None # Sliding window attention pattern string, tiled across layers. Final layer always L. # Characters: L=long (full context), S=short (quarter context) # Examples: "L"=all full context, "SL"=alternating, "SSL"=two short then one long window_pattern: str = "SSSL" local_window: int | None = None # By default, repeat the middle half. Set all three sizes for an explicit split. loop_repeats: int = 3 loop_gate: bool = False # learn how much of the previous pass to carry forward n_prelude: int | None = None n_recurrent: int | None = None n_coda: int | None = None input_injection: float | None = None # initial scale of the learned prelude injection message_rank: int | None = None # enable pass resets and cross-pass messages def validate(self): if self.n_layer < 1: raise ValueError("--depth must be at least 1") if self.n_head < 1 or self.n_embd < 1 or self.n_embd % (2 * self.n_head): raise ValueError("Model width must give a positive, even dimension per query head") if self.n_kv_head < 1 or self.n_head % self.n_kv_head: raise ValueError("The number of KV heads must divide the number of query heads") if self.ffn not in ("relu2", "swiglu") or (self.intermediate_size is not None and self.intermediate_size < 1): raise ValueError("Choose relu2 or swiglu with a positive FFN width") if not self.window_pattern or any(c not in "SL" for c in self.window_pattern.upper()): raise ValueError("--window-pattern must contain only S and L") if self.local_window is not None and self.local_window < 1: raise ValueError("--local-window must be at least 1") if self.loop_repeats < 1: raise ValueError("--loops must be at least 1") split = (self.n_prelude, self.n_recurrent, self.n_coda) if any(size is not None for size in split): no_core = self.loop_repeats == 1 and split == (self.n_layer, 0, 0) if not no_core and (any(size is None or size < 0 for size in split) or self.n_recurrent == 0): raise ValueError("Set all three block counts with at least one recurrent block") if sum(split) != self.n_layer: raise ValueError("Prelude, recurrent, and coda block counts must add up to --depth") elif self.loop_repeats > 1 and (self.n_layer < 4 or self.n_layer % 2): raise ValueError("--depth must be even and at least 4 when --loops is greater than 1") if self.loop_gate and self.loop_repeats == 1: raise ValueError("--loop-gate requires at least two passes") if self.input_injection is not None and (self.loop_repeats == 1 or not isfinite(self.input_injection)): raise ValueError("--input-injection requires a finite scale and at least two passes") if self.message_rank is not None: if self.message_rank < 1 or self.loop_repeats < 2 or self.block_split()[1] < 2: raise ValueError("--message-rank requires a positive rank, at least two passes and two recurrent blocks") if self.loop_gate or self.input_injection is not None: raise ValueError("Use cross-pass messages without --loop-gate or --input-injection") def block_split(self): if self.n_prelude is not None: return self.n_prelude, self.n_recurrent, self.n_coda if self.loop_repeats == 1: return self.n_layer, 0, 0 # For fractional quarters, the coda gets the extra block. prelude, recurrent = self.n_layer // 4, self.n_layer // 2 return prelude, recurrent, self.n_layer - prelude - recurrent def ffn_width(self): if self.intermediate_size is not None: return self.intermediate_size # Match the ReLU² parameter budget approximately and align the gated projections. return 4 * self.n_embd if self.ffn == "relu2" else max(8, 8 * round(self.n_embd / 3)) def local_window_size(self): if self.local_window is not None: return self.local_window return -(-self.sequence_len // 512) * 128 # quarter context, rounded up to an FA3 tile @classmethod def from_dict(cls, config): """Load a resolved config or a checkpoint that saved unresolved defaults.""" options = dict(config) for name in ("input_injection", "message_rank"): if options.get(name) == "disabled": options[name] = None return cls(**options) def norm(x): return F.rms_norm(x, (x.size(-1),)) # note that this will run in bf16, seems ok class Linear(nn.Linear): """nn.Linear that casts weights to match input dtype in forward. Replaces autocast: master weights stay fp32 for optimizer precision, but matmuls run in the activation dtype (typically bf16 from embeddings).""" def forward(self, x): return F.linear(x, self.weight.to(dtype=x.dtype)) def has_ve(layer_idx, n_layer): """Returns True if GPT layer should have Value Embedding (alternating, last layer always included).""" return layer_idx % 2 == (n_layer - 1) % 2 def apply_rotary_emb(x, cos, sin): # note: this rotates by -theta, the transpose of the textbook convention. Functionally # equivalent (only the relative q/k rotation matters), kept for checkpoint compatibility. assert x.ndim == 4 # multihead attention d = x.shape[3] // 2 x1, x2 = x[..., :d], x[..., d:] # split up last dim into two halves y1 = x1 * cos + x2 * sin # rotate pairs of dims y2 = x1 * (-sin) + x2 * cos return torch.cat([y1, y2], 3) class CausalSelfAttention(nn.Module): def __init__(self, config, layer_idx): super().__init__() self.n_head = config.n_head self.n_kv_head = config.n_kv_head self.n_embd = config.n_embd self.head_dim = self.n_embd // self.n_head assert self.n_embd % self.n_head == 0 assert self.n_kv_head <= self.n_head and self.n_head % self.n_kv_head == 0 self.c_q = Linear(self.n_embd, self.n_head * self.head_dim, bias=False) self.c_k = Linear(self.n_embd, self.n_kv_head * self.head_dim, bias=False) self.c_v = Linear(self.n_embd, self.n_kv_head * self.head_dim, bias=False) self.c_proj = Linear(self.n_embd, self.n_embd, bias=False) self.ve_gate_channels = 12 self.ve_gate = Linear(self.ve_gate_channels, self.n_kv_head, bias=False) if has_ve(layer_idx, config.n_layer) else None def forward(self, x, ve, cos_sin, window_size, kv_cache, cache_layer_idx, qkv_inputs=None): B, T, C = x.size() # Project the input to get queries, keys, and values # Shape: (B, T, H, D) - FA3's native layout, no transpose needed! q_input, k_input, v_input = (x, x, x) if qkv_inputs is None else qkv_inputs q = self.c_q(q_input).view(B, T, self.n_head, self.head_dim) k = self.c_k(k_input).view(B, T, self.n_kv_head, self.head_dim) v = self.c_v(v_input).view(B, T, self.n_kv_head, self.head_dim) # Value residual (ResFormer): mix in value embedding with input-dependent gate per head if ve is not None: ve = ve.view(B, T, self.n_kv_head, self.head_dim) gate = 3 * torch.sigmoid(self.ve_gate(x[..., :self.ve_gate_channels])) # (B, T, n_kv_head), range (0, 3) v = v + gate.unsqueeze(-1) * ve # Apply Rotary Embeddings to queries and keys to get relative positional encoding cos, sin = cos_sin q, k = apply_rotary_emb(q, cos, sin), apply_rotary_emb(k, cos, sin) q, k = norm(q), norm(k) # QK norm q = q * 1.2 # sharper attention (split scale between Q and K), TODO think through better k = k * 1.2 # Flash Attention or SDPA fallback # window_size is (left, right) tuple: (N, 0) for causal, (-1, 0) for full context if kv_cache is None: # Training: causal attention with optional sliding window y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=window_size) else: # Inference: use flash_attn_with_kvcache which handles cache management k_cache, v_cache = kv_cache.get_layer_cache(cache_layer_idx) y = flash_attn.flash_attn_with_kvcache( q, k_cache, v_cache, k=k, v=v, cache_seqlens=kv_cache.cache_seqlens, causal=True, window_size=window_size, ) # Re-assemble the heads and project back to residual stream y = y.contiguous().view(B, T, -1) y = self.c_proj(y) return y class MLP(nn.Module): def __init__(self, config): super().__init__() width = config.ffn_width() self.c_fc = Linear(config.n_embd, width, bias=False) self.c_gate = Linear(config.n_embd, width, bias=False) if config.ffn == "swiglu" else None self.c_proj = Linear(width, config.n_embd, bias=False) def forward(self, x): up = self.c_fc(x) hidden = F.relu(up).square() if self.c_gate is None else F.silu(self.c_gate(x)) * up return self.c_proj(hidden) class CrossPassMessages(nn.Module): """Read previous-pass states at the same token position with distinct Q, K, V and FFN queries.""" def __init__(self, width, rank): super().__init__() self.read_queries = Linear(width, 4, bias=False) self.gate_down = Linear(width, rank, bias=False) self.attention_gate = Linear(rank, 3 * width, bias=False) self.ffn_gate = Linear(rank, width, bias=False) def retrieve(self, summaries, summary_keys): # Softmax over two logits is an interpolation with sigmoid(logit1 - logit0). scores = self.read_queries(summary_keys) weight = torch.sigmoid(scores[1].float() - scores[0].float()).to(summaries.dtype) weight = weight.movedim(-1, 0).unsqueeze(-1) return norm(torch.lerp(summaries[0], summaries[1], weight)) def mix_attention(self, x, messages): gates = self.attention_gate(F.silu(self.gate_down(x))) gates = gates.unflatten(-1, (3, x.size(-1))).movedim(-2, 0) return torch.lerp(x, messages, torch.sigmoid(gates - 4.0)).unbind(0) def mix_ffn(self, x, message): gate = torch.sigmoid(self.ffn_gate(F.silu(self.gate_down(x))) - 4.0) return torch.lerp(x, message, gate) class Block(nn.Module): def __init__(self, config, layer_idx, message_rank=None): super().__init__() self.attn = CausalSelfAttention(config, layer_idx) self.mlp = MLP(config) self.messages = CrossPassMessages(config.n_embd, message_rank) if message_rank is not None else None def forward(self, x, ve, cos_sin, window_size, kv_cache, cache_layer_idx, previous_pass=None): attn_input = norm(x) messages = self.messages.retrieve(*previous_pass) if self.messages is not None and previous_pass is not None else None qkv_inputs = self.messages.mix_attention(attn_input, messages[:3]) if messages is not None else None x = x + self.attn(attn_input, ve, cos_sin, window_size, kv_cache, cache_layer_idx, qkv_inputs) ffn_input = norm(x) if messages is not None: ffn_input = self.messages.mix_ffn(ffn_input, messages[3]) x = x + self.mlp(ffn_input) return x class GPT(nn.Module): def __init__(self, config, compute_dtype, pad_vocab_size_to=64): super().__init__() config.validate() self.config = config self.compute_dtype = compute_dtype n_prelude, n_recurrent, _ = config.block_split() indices = tuple(range(config.n_layer)) core_end = n_prelude + n_recurrent # Keep one registered block stack so all visits share weights and checkpoint keys. self.prelude_indices = indices[:n_prelude] self.recurrent_indices = indices[n_prelude:core_end] self.coda_indices = indices[core_end:] self.message_midpoint = (self.recurrent_indices[(n_recurrent - 1) // 2] if config.message_rank is not None else None) self.layer_indices, self.loop_pass_starts = self._execution_schedule(config.loop_repeats) # A block uses the same attention window on each visit. self.block_windows = self._compute_window_sizes(config) # Pad vocab for efficiency (DDP, tensor cores). This is just an optimization - outputs are cropped in forward(). # https://huggingface.co/docs/transformers/main_classes/model#transformers.PreTrainedModel.resize_token_embeddings padded_vocab_size = ((config.vocab_size + pad_vocab_size_to - 1) // pad_vocab_size_to) * pad_vocab_size_to self.transformer = nn.ModuleDict({ "wte": nn.Embedding(padded_vocab_size, config.n_embd), "h": nn.ModuleList([ Block(config, i, config.message_rank if i in self.recurrent_indices else None) for i in indices ]), }) self.lm_head = Linear(config.n_embd, padded_vocab_size, bias=False) # Per-layer learnable scalars (inspired by modded-nanogpt) # resid_lambdas: scales the residual stream at each layer (init 1.0 = neutral) # x0_lambdas: blends initial embedding back in at each layer (init 0.0 = disabled) # Separate parameters so they can have different optimizer treatment self.resid_lambdas = nn.Parameter(torch.ones(config.n_layer)) self.x0_lambdas = nn.Parameter(torch.zeros(config.n_layer)) # Smear: mix previous token's embedding into current token (cheap bigram-like info) self.smear_gate = Linear(24, 1, bias=False) self.smear_lambda = nn.Parameter(torch.zeros(1)) # Backout: subtract cached mid-layer residual before final norm to remove low-level features self.backout_lambda = nn.Parameter(0.2 * torch.ones(1)) # Value embeddings (ResFormer-style): alternating layers, last layer always included head_dim = config.n_embd // config.n_head kv_dim = config.n_kv_head * head_dim self.value_embeds = nn.ModuleDict({str(i): nn.Embedding(padded_vocab_size, kv_dim) for i in range(config.n_layer) if has_ve(i, config.n_layer)}) # The loader materializes these nonpersistent buffers after assigning checkpoint weights. self.rotary_seq_len = config.sequence_len head_dim = config.n_embd // config.n_head cos, sin = self._precompute_rotary_embeddings(self.rotary_seq_len, head_dim) self.register_buffer("cos", cos, persistent=False) # persistent=False means it's not saved to the checkpoint self.register_buffer("sin", sin, persistent=False) self.loop_gate = Linear(2 * config.n_embd, 1, bias=False) if config.loop_gate else None self.loop_gate_bias = nn.Parameter(torch.zeros(1)) if config.loop_gate else None self.input_injection = (nn.Parameter(torch.full((1,), config.input_injection)) if config.input_injection is not None else None) def _precompute_rotary_embeddings(self, seq_len, head_dim, base=100000, device=None): # TODO: bump base theta more? e.g. 100K is more common more recently # autodetect the device from model embeddings if device is None: device = self.transformer.wte.weight.device # stride the channels channel_range = torch.arange(0, head_dim, 2, dtype=torch.float32, device=device) inv_freq = 1.0 / (base ** (channel_range / head_dim)) # stride the time steps t = torch.arange(seq_len, dtype=torch.float32, device=device) # calculate the rotation frequencies at each (time, channel) pair freqs = torch.outer(t, inv_freq) cos, sin = freqs.cos(), freqs.sin() cos, sin = cos.to(self.compute_dtype), sin.to(self.compute_dtype) cos, sin = cos[None, :, None, :], sin[None, :, None, :] # add batch and head dims for later broadcasting return cos, sin def _compute_window_sizes(self, config): """ Compute per-layer window sizes for sliding window attention. Returns list of (left, right) tuples for FA3's window_size parameter: - left: how many tokens before current position to attend to (-1 = unlimited) - right: how many tokens after current position to attend to (0 for causal) Pattern string is tiled across layers. Final layer always gets L (full context). Characters: L=long (full context), S=short (quarter context) """ pattern = config.window_pattern.upper() # Map characters to window sizes long_window = config.sequence_len short_window = config.local_window_size() char_to_window = { "L": (long_window, 0), "S": (short_window, 0), } # Tile pattern across layers window_sizes = [] for layer_idx in range(config.n_layer): char = pattern[layer_idx % len(pattern)] window_sizes.append(char_to_window[char]) # Final layer always gets full context window_sizes[-1] = (long_window, 0) return window_sizes def get_device(self): return self.transformer.wte.weight.device def _execution_schedule(self, loop_iterations): if loop_iterations < 1: raise ValueError("loop_iterations must be at least 1") if loop_iterations > 1 and not self.recurrent_indices: raise ValueError("Multiple passes require a recurrent core") if loop_iterations == 1 and (self.config.loop_gate or self.config.message_rank is not None): raise ValueError("The loop gate and cross-pass messages require at least two passes") core_size = len(self.recurrent_indices) indices = self.prelude_indices + self.recurrent_indices * loop_iterations + self.coda_indices pass_starts = tuple(len(self.prelude_indices) + i * core_size for i in range(loop_iterations)) if core_size else () return indices, pass_starts @property def n_layer_executions(self): return len(self.layer_indices) def forward(self, idx, kv_cache=None): _, T = idx.size() layer_indices, pass_starts = self.layer_indices, self.loop_pass_starts # Grab the rotary embeddings for the current sequence length (they are of shape (1, seq_len, 1, head_dim/2)) assert idx.device == self.cos.device, f"Rotary embeddings and idx are on different devices: {idx.device} != {self.cos.device}" assert self.cos.dtype == self.compute_dtype, f"Rotary embeddings must be in {self.compute_dtype}, got {self.cos.dtype}" if kv_cache is not None and kv_cache.n_layers != len(layer_indices): raise ValueError(f"Expected {len(layer_indices)} KV cache slots, got {kv_cache.n_layers}") # if kv cache exists, we need to offset the rotary embeddings to the current position in the cache T0 = 0 if kv_cache is None else kv_cache.get_pos() if T0 + T > self.cos.size(1): raise ValueError("The conversation exceeds this model's context window.") cos_sin = self.cos[:, T0:T0+T], self.sin[:, T0:T0+T] # truncate cache to current sequence length # Embed the tokens x = self.transformer.wte(idx) # embed current token x = x.to(self.compute_dtype) # ensure activations are in compute dtype (no-op usually, but active for fp16 code path) x = norm(x) # Smear: mix previous token's embedding into current position (cheap bigram info) if kv_cache is None: gate = self.smear_lambda.to(x.dtype) * torch.sigmoid(self.smear_gate(x[:, 1:, :24])) x = torch.cat([x[:, :1], x[:, 1:] + gate * x[:, :-1]], dim=1) else: # KV cache inference: save the unsmeared embedding for the next step next_prev_embedding = x[:, -1:, :] x_pre_smear = kv_cache.prev_embedding if T > 1: # Prefill: apply smear to positions 1+, same as training gate = self.smear_lambda.to(x.dtype) * torch.sigmoid(self.smear_gate(x[:, 1:, :24])) x = torch.cat([x[:, :1], x[:, 1:] + gate * x[:, :-1]], dim=1) elif x_pre_smear is not None: # Decode: single token, use cached prev embedding gate = self.smear_lambda.to(x.dtype) * torch.sigmoid(self.smear_gate(x[:, :, :24])) x = x + gate * x_pre_smear # Forward the trunk of the Transformer x0 = x # save initial normalized embedding for x0 residual backout_layer = len(layer_indices) // 2 # cache at halfway point x_backout = None prelude = None midpoint = None previous_pass = None for execution_idx, layer_idx in enumerate(layer_indices): if self.message_midpoint is not None and execution_idx in pass_starts: if prelude is None: prelude = x else: summaries = torch.stack((midpoint, x)) previous_pass = (summaries, norm(summaries)) x = prelude elif (self.loop_gate is not None or self.input_injection is not None) and execution_idx in pass_starts: if prelude is None: prelude = x elif self.loop_gate is not None: gate_input = torch.cat((norm(prelude), norm(x)), dim=-1) gate = torch.sigmoid(self.loop_gate(gate_input) + self.loop_gate_bias.to(x.dtype)) x = torch.lerp(prelude, x, gate) if self.input_injection is not None: x = x + self.input_injection.to(x.dtype) * prelude x = self.resid_lambdas[layer_idx] * x + self.x0_lambdas[layer_idx] * x0 ve = self.value_embeds[str(layer_idx)](idx).to(x.dtype) if str(layer_idx) in self.value_embeds else None block = self.transformer.h[layer_idx] x = block(x, ve, cos_sin, self.block_windows[layer_idx], kv_cache, execution_idx, previous_pass) if layer_idx == self.message_midpoint: midpoint = x if execution_idx == backout_layer: x_backout = x # Subtract mid-layer residual to remove low-level features before logit projection if x_backout is not None: x = x - self.backout_lambda.to(x.dtype) * x_backout x = norm(x) # Forward the lm_head (compute logits) softcap = 15 # smoothly cap the logits to the range [-softcap, softcap] logits = self.lm_head(x[:, -1:]) # only the next-token logits are needed logits = logits[..., :self.config.vocab_size] # slice to remove padding logits = logits.float() # switch to fp32 for logit softcap and loss computation logits = softcap * torch.tanh(logits / softcap) # squash the logits if kv_cache is not None: kv_cache.prev_embedding = next_prev_embedding kv_cache.advance(T) return logits[:, -1, :]