"""Tiny decoder-only transformer with pluggable embedding strategies. The experiment this file exists to run: on an ESP32-S3, weights touched on every token must live in ~512KB of internal SRAM, while flash is huge but only good for sparse random reads. That is the same memory-tier shape Gemma's Per-Layer Embeddings were designed for, three orders of magnitude down. So we hold the *core* (dense, every-token) parameter count fixed and vary how extra *table* (sparse, per-token-lookup) parameters are spent. Arms: baseline -- no table params at all. What a tiny LM looks like today. ple -- faithful Gemma-4 PLE: per-layer inputs are (RMSNorm(proj(embed)) + table) / sqrt(2), gated into each layer's residual. ple_notable -- the same per-layer adapters and projection, but *no* lookup table. Isolates whether flash-resident table params buy anything, or whether the per-layer plumbing alone explains any gain. Costs core params, buys no table params. fatembed -- same table budget as `ple`, but a wide input embedding factorised down to d_model once at the bottom. Decides whether the *per-layer* part earns its keep or whether any sparse embedding capacity would do. bigcore -- spend the table budget on a wider core instead. Reference for how much a thin core is actually costing us. """ import math from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F @dataclass class Config: arm: str = "baseline" # "tinylm" preserves every historical checkpoint. "glimmer" swaps only # the text backbone; PLE remains selected independently by arm so it can be # measured as an addition rather than smuggled into the comparison. architecture: str = "tinylm" vocab_size: int = 4096 d_model: int = 128 n_layers: int = 6 n_heads: int = 4 ffn_hidden: int = 256 seq_len: int = 512 ple_dim: int = 64 # Weight-shared depth: the block stack is applied this many times per # token, re-injecting the token stream at the start of every extra # pass. Depth without parameters: flash bytes are unchanged, compute per # token multiplies. 1 is the plain model. loops: int = 1 # What the extra passes are fed. "none": the token stream is re-added. # "shift": the Recurrent Looped Transformer merge (Zhang 2026, eqs # 2.9-2.11) with the recurrence truncated to one step, so training stays # parallel: pass k's input at position t is pass k-1's output at t plus a # gated projection of pass k-1's output at t-1 (a learned start state at # t=0). Causal, and on a device one extra d-vector of state per token. feedback: str = "none" rope_theta: float = 10000.0 # Comma-separated layer indices whose sequence mixer is a Mamba (S6) scan # instead of attention ("" = pure transformer). ONLY the mixer swaps: norms, # SwiGLU, and the PLE injection stay identical, so an ablation against the # same-config transformer isolates the mixer choice. mamba_layers: str = "" # Attention with Bounded-memory Control (ABC) replaces selected attention # mixers while preserving their qkv/proj parameter names. ``mlp`` learns a # content-dependent write weight and has context-independent parameters; # ``linformer`` learns one write vector per absolute position. abc_layers: str = "" abc_rank: int = 16 abc_control: str = "mlp" # Sliding-window width for the attention layers (0 = full causal). In the # hybrid, capping the ONE remaining attention layer at W makes the whole # architecture O(1) memory in context length: exact recall within W, the # scans carry the gist beyond it. The callback eval referees whether that # trade holds. attn_window: int = 0 # Muse Glimmer text invariants. At this scale 8:1 is the strongest useful # Q:KV ratio for the default d_model=96/n_heads=8; the released model is # 16:1. Local layers repeat [local, local, local, global]. n_kv_heads: int = 1 glimmer_window: int = 64 # Landmark Attention can turn Glimmer's one-in-four global layer into a # block retriever. Input preprocessing replaces a nearby newline with the # existing EOT token every ``landmark_stride`` positions, so model shapes # and the flash budget do not change. During training a grouped softmax # makes each landmark gate its preceding block; deployment can score the # compact landmark index and fetch only the top-k exact KV blocks. landmark_attention: bool = False landmark_stride: int = 64 landmark_token_id: int = 0 landmark_topk: int = 2 glimmer_rope_theta: float = 500_000.0 qk_scale_factor: float = 3.87 output_multiplier: float = 0.19611613513818404 final_logit_softcapping: float = 20.0 rms_norm_eps: float = 1e-5 post_norm_eps: float = 1e-8 # Evaluation/deployment experiment matching the ExecuTorch backend's # opt-in OP_BMM_DYN_I8 path. Training keeps this false. dynamic_qk: bool = False @property def mamba_set(self): return {int(s) for s in self.mamba_layers.split(",") if s.strip() != ""} @property def abc_set(self): return {int(s) for s in self.abc_layers.split(",") if s.strip() != ""} @property def head_dim(self): return self.d_model // self.n_heads @property def kv_heads(self): return self.n_heads if self.architecture == "tinylm" else self.n_kv_heads @property def uses_per_layer(self): return self.arm in ("ple", "ple_notable") @property def table_width(self): """Width of the wide input embedding in the fatembed arm. Chosen so its table has exactly the same parameter count as the PLE arm's table: vocab x (n_layers * ple_dim). """ return self.n_layers * self.ple_dim class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x): return self.weight * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) class WeightlessRMSNorm(nn.Module): """Glimmer's embedding and Q/K normalization.""" def __init__(self, eps=1e-6): super().__init__() self.eps = eps def forward(self, x): xf = x.float() return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype) class CenteredRMSNorm(nn.Module): """Glimmer scale parameterization: effective weight is 1 + weight.""" def __init__(self, dim, eps=1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.zeros(dim)) def forward(self, x): xf = x.float() y = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps) return (y * (1.0 + self.weight.float())).to(x.dtype) def build_rope(seq_len, head_dim, theta, device): inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim)) t = torch.arange(seq_len, device=device).float() freqs = torch.outer(t, inv) return torch.cos(freqs), torch.sin(freqs) def apply_rope(x, cos, sin): # x: (B, H, T, Dh) x1, x2 = x.chunk(2, dim=-1) cos = cos[None, None, : x.shape[2], :] sin = sin[None, None, : x.shape[2], :] return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1) class Attention(nn.Module): def __init__(self, cfg: Config): super().__init__() self.cfg = cfg self.qkv = nn.Linear(cfg.d_model, 3 * cfg.d_model, bias=False) self.proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False) def forward(self, x, cos, sin): B, T, C = x.shape H, Dh = self.cfg.n_heads, self.cfg.head_dim q, k, v = self.qkv(x).split(C, dim=2) q = q.view(B, T, H, Dh).transpose(1, 2) k = k.view(B, T, H, Dh).transpose(1, 2) v = v.view(B, T, H, Dh).transpose(1, 2) q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) W = self.cfg.attn_window if W > 0: # Banded causal mask: attend to positions (t-W, t]. Additive -inf # mask rather than is_causal so the band composes with causality. i = torch.arange(T, device=x.device) keep = (i[None, :] <= i[:, None]) & (i[:, None] - i[None, :] < W) mask = torch.zeros(T, T, device=x.device, dtype=q.dtype) mask.masked_fill_(~keep, float("-inf")) o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) else: o = F.scaled_dot_product_attention(q, k, v, is_causal=True) return self.proj(o.transpose(1, 2).contiguous().view(B, T, C)) class ABCAttention(nn.Module): """Causal attention with a fixed number of learned memory slots. The full-sequence path vectorizes the recurrent outer-product updates with cumsum for training. ``step`` spells the constant-state autoregressive graph that deployment exports. Both controls reuse an ordinary attention layer's qkv/proj names, allowing a trained qwide checkpoint to initialize everything except the new memory controller. """ def __init__(self, cfg: Config): super().__init__() if cfg.abc_rank < 1: raise ValueError("abc_rank must be positive") if cfg.abc_control not in ("mlp", "linformer"): raise ValueError("abc_control must be 'mlp' or 'linformer'") self.cfg = cfg self.qkv = nn.Linear(cfg.d_model, 3 * cfg.d_model, bias=False) self.proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False) if cfg.abc_control == "mlp": self.control = nn.Linear(cfg.d_model, cfg.abc_rank, bias=False) else: # Decode reads one position row; prefill streams the prefix. Treat # this like a sparse table rather than dense every-token core state. self.position_control = nn.Embedding(cfg.seq_len, cfg.abc_rank) def _project(self, x, cos, sin): B, T, C = x.shape H, Dh = self.cfg.n_heads, self.cfg.head_dim q, k, v = self.qkv(x).split(C, dim=2) q = q.view(B, T, H, Dh).transpose(1, 2) k = k.view(B, T, H, Dh).transpose(1, 2) v = v.view(B, T, H, Dh).transpose(1, 2) return apply_rope(q, cos, sin), apply_rope(k, cos, sin), v def _read(self, q, kmem, vmem): # q: [B,H,T,D], memories: [B,T,R,H,D] qt = q.transpose(1, 2) scores = torch.einsum("bthd,btrhd->bthr", qt, kmem) probs = F.softmax(scores * (self.cfg.head_dim ** -0.5), dim=-1) out = torch.einsum("bthr,btrhd->bthd", probs, vmem) B, T, H, D = out.shape return self.proj(out.contiguous().view(B, T, H * D)) def forward(self, x, cos, sin): B, T, _ = x.shape q, k, v = self._project(x, cos, sin) kt = k.transpose(1, 2) # [B,T,H,D] vt = v.transpose(1, 2) if self.cfg.abc_control == "mlp": scores = self.control(x) # One per-slot numerical scale shared over time cancels from both # numerator and denominator at every causal prefix. Detaching that # scale avoids a spurious future-dependent gradient path; the exact # normalized function is invariant to the common scale. anchor = scores.amax(dim=1, keepdim=True).detach() alpha = torch.exp((scores - anchor).clamp(min=-30.0)) weights = alpha.unsqueeze(-1).unsqueeze(-1) ksum = torch.cumsum(weights * kt.unsqueeze(2), dim=1) vsum = torch.cumsum(weights * vt.unsqueeze(2), dim=1) z = torch.cumsum(alpha, dim=1).unsqueeze(-1).unsqueeze(-1) kmem, vmem = ksum / z, vsum / z else: phi = self.position_control.weight[:T].view( 1, T, self.cfg.abc_rank, 1, 1) kmem = torch.cumsum(phi * kt.unsqueeze(2), dim=1) vmem = torch.cumsum(phi * vt.unsqueeze(2), dim=1) return self._read(q, kmem, vmem) def step(self, x, cos, sin, position, state=None): """One-token recurrent graph; return ``(output, next_state)``. State is ``(Ksum, Vsum, Z, max_score)``. Linformer does not need the last two tensors but keeps empty placeholders so export signatures stay stable across the two controls. """ if x.shape[1] != 1: raise ValueError("ABC recurrent step expects exactly one token") # Decode exporters may pass the one required RoPE row directly. This # prevents a nominal 16K context from embedding two full 16K tables in # every one-token method. Full model buffers remain accepted for eager # parity and the position-based Linformer controller still uses position. rope_cos = cos if cos.shape[0] == 1 else cos[position:position + 1] rope_sin = sin if sin.shape[0] == 1 else sin[position:position + 1] q, k, v = self._project(x, rope_cos, rope_sin) kt = k[:, :, 0] # [B,H,D] vt = v[:, :, 0] rank = self.cfg.abc_rank if self.cfg.abc_control == "mlp": score = self.control(x[:, 0]) if state is None: ksum = kt.unsqueeze(1).expand(-1, rank, -1, -1) vsum = vt.unsqueeze(1).expand(-1, rank, -1, -1) z = torch.ones_like(score) maximum = score else: old_k, old_v, old_z, old_max = state maximum = torch.maximum(old_max, score) old_scale = torch.exp((old_max - maximum).clamp(min=-30.0)) new_scale = torch.exp((score - maximum).clamp(min=-30.0)) ksum = (old_k * old_scale.unsqueeze(-1).unsqueeze(-1) + kt.unsqueeze(1) * new_scale.unsqueeze(-1).unsqueeze(-1)) vsum = (old_v * old_scale.unsqueeze(-1).unsqueeze(-1) + vt.unsqueeze(1) * new_scale.unsqueeze(-1).unsqueeze(-1)) z = old_z * old_scale + new_scale denom = z.unsqueeze(-1).unsqueeze(-1) kmem, vmem = ksum / denom, vsum / denom next_state = (ksum, vsum, z, maximum) else: if torch.is_tensor(position): # A runtime int64 position keeps this as aten.embedding, which # the ESP32 backend can pack and delegate. Directly indexing # ``weight`` would strand a max-context-sized fp32 table in the # PTE. Decode supplies the matching one-row RoPE values. phi = self.position_control(position.reshape(-1)).view( 1, rank, 1, 1) else: phi = self.position_control.weight[position].view( 1, rank, 1, 1) update_k = phi * kt.unsqueeze(1) update_v = phi * vt.unsqueeze(1) if state is None: ksum, vsum = update_k, update_v else: ksum, vsum = state[0] + update_k, state[1] + update_v empty = x.new_empty(x.shape[0], 0) kmem, vmem = ksum, vsum next_state = (ksum, vsum, empty, empty) # Add the singleton time dimension expected by _read. out = self._read(q, kmem.unsqueeze(1), vmem.unsqueeze(1)) return out, next_state def recurrent_state_bytes(self, scalar_bytes=4): scalars = 2 * self.cfg.abc_rank * self.cfg.d_model if self.cfg.abc_control == "mlp": scalars += 2 * self.cfg.abc_rank return scalars * scalar_bytes class MambaMixer(nn.Module): """Minimal Mamba-1 (S6) drop-in for the attention mixer. Sequential scan, deliberately: at d_inner 192 x d_state 16 x seq 256 the naive loop trains fine and stays auditable; a parallel scan buys nothing an ablation needs. Quantisation split (matches train.py's QAT and quantize.py's PTQ): the four projections are ordinary Linears and ride the int4 shipped format like every other matrix; the scan internals (A_log, conv, D, dt bias -- ~4K params) stay fp32 like norms. The decay's resolution near 1.0 IS the memory horizon, so it is the one tensor family int4 would visibly damage. """ def __init__(self, cfg: Config): super().__init__() d = cfg.d_model self.d_inner = 2 * d self.d_state = 16 self.dt_rank = max(1, d // 16) self.in_proj = nn.Linear(d, 2 * self.d_inner, bias=False) self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, 4, groups=self.d_inner, padding=3, bias=True) self.x_proj = nn.Linear(self.d_inner, self.dt_rank + 2 * self.d_state, bias=False) self.dt_proj = nn.Linear(self.dt_rank, self.d_inner, bias=True) self.out_proj = nn.Linear(self.d_inner, d, bias=False) A = torch.arange(1, self.d_state + 1).float().repeat(self.d_inner, 1) self.A_log = nn.Parameter(torch.log(A)) self.D = nn.Parameter(torch.ones(self.d_inner)) # Standard Mamba dt init: softplus(dt_proj bias) lands in [1e-3, 0.1]. dt = torch.exp(torch.rand(self.d_inner) * (math.log(0.1) - math.log(1e-3)) + math.log(1e-3)).clamp(min=1e-4) with torch.no_grad(): self.dt_proj.bias.copy_(dt + torch.log(-torch.expm1(-dt))) def forward(self, x): # (B, T, C) -> (B, T, C), causal B, T, _ = x.shape xi, z = self.in_proj(x).chunk(2, dim=-1) xi = self.conv1d(xi.transpose(1, 2))[:, :, :T].transpose(1, 2) xi = F.silu(xi) dt, Bs, Cs = torch.split( self.x_proj(xi), [self.dt_rank, self.d_state, self.d_state], dim=-1) dt = F.softplus(self.dt_proj(dt)) # (B,T,d_inner) A = -torch.exp(self.A_log) # (d_inner,d_state) # Exponent clamp: a decay below e^-30 is already a total state reset, # but letting it underflow to an exact 0.0 pushes cumprod's backward # onto its lossy zero-handling path (measured: 2% gradient error at # those entries). Strictly-positive decays keep it on the exact path. dA = torch.exp((dt.unsqueeze(-1) * A).clamp(min=-30.0)) dBx = (dt * xi).unsqueeze(-1) * Bs.unsqueeze(2) y = self._scan(dA, dBx, Cs) + self.D * xi return self.out_proj(y * F.silu(z)) def _scan(self, dA, dBx, Cs): """y[t] = C[t]·h[t] with h[t] = dA[t]*h[t-1] + dBx[t], h[-1] = 0. A recursive blocked affine scan keeps both loop depth and retained workspace small. Each eight-token group is scanned in parallel over all groups, then the group transforms are scanned by the same routine. At T=1024 this spells 8+8+8+2 dependent iterations rather than the old 16+64. Nothing divides and all decay products remain in (0, 1], so underflow is a benign state reset. This is the same recurrence up to floating-point reassociation, not an approximation. """ hidden = self._affine_prefix(dA, dBx) return (hidden * Cs.unsqueeze(2)).sum(-1) def _affine_prefix(self, decay, update, block=8): """Inclusive prefix scan of elementwise affine state transforms.""" B, T, d, s = decay.shape if T <= block or T % block: h = decay.new_zeros(B, d, s) states = [] for t in range(T): h = decay[:, t] * h + update[:, t] states.append(h) return torch.stack(states, dim=1) groups = T // block a = decay.view(B, groups, block, d, s) b = update.view(B, groups, block, d, s) local_state = a.new_zeros(B, groups, d, s) local_decay = torch.ones_like(local_state) states, decays = [], [] for t in range(block): local_state = a[:, :, t] * local_state + b[:, :, t] local_decay = a[:, :, t] * local_decay states.append(local_state) decays.append(local_decay) states = torch.stack(states, dim=2) decays = torch.stack(decays, dim=2) # Each group is itself the affine transform # h_out = group_decay * h_in + group_update. Recursing over those # transforms yields the state after every complete preceding group. group_ends = self._affine_prefix( decays[:, :, -1], states[:, :, -1], block) zero = torch.zeros_like(group_ends[:, :1]) entries = torch.cat((zero, group_ends[:, :-1]), dim=1) hidden = states + decays * entries.unsqueeze(2) return hidden.reshape(B, T, d, s) class SwiGLU(nn.Module): def __init__(self, cfg: Config): super().__init__() self.gate = nn.Linear(cfg.d_model, cfg.ffn_hidden, bias=False) self.up = nn.Linear(cfg.d_model, cfg.ffn_hidden, bias=False) self.down = nn.Linear(cfg.ffn_hidden, cfg.d_model, bias=False) def forward(self, x): return self.down(F.silu(self.gate(x)) * self.up(x)) class Block(nn.Module): def __init__(self, cfg: Config, idx: int = -1): super().__init__() self.cfg = cfg self.is_mamba = idx in cfg.mamba_set self.is_abc = idx in cfg.abc_set if self.is_mamba and self.is_abc: raise ValueError(f"layer {idx} cannot be both Mamba and ABC") self.attn_norm = RMSNorm(cfg.d_model) # Kept under the name `attn` either way, so checkpoints and the export # path see one stable naming scheme for "the mixer". self.attn = (MambaMixer(cfg) if self.is_mamba else ABCAttention(cfg) if self.is_abc else Attention(cfg)) self.ffn_norm = RMSNorm(cfg.d_model) self.ffn = SwiGLU(cfg) if cfg.uses_per_layer: # Gemma 4's Gemma4TextDecoderLayer, minus AltUp: squeeze the hidden # state to ple_dim, gate it elementwise *by* the per-layer input, # project back, norm, add to the residual. The multiply is what makes # this conditioning rather than a per-token bias -- either factor can # suppress the other. self.ple_gate = nn.Linear(cfg.d_model, cfg.ple_dim, bias=False) self.ple_proj = nn.Linear(cfg.ple_dim, cfg.d_model, bias=False) self.ple_norm = RMSNorm(cfg.d_model) def forward(self, x, cos, sin, ple=None): if self.is_mamba: x = x + self.attn(self.attn_norm(x)) else: x = x + self.attn(self.attn_norm(x), cos, sin) x = x + self.ffn(self.ffn_norm(x)) if ple is not None: g = F.gelu(self.ple_gate(x)) x = x + self.ple_norm(self.ple_proj(g * ple)) return x def repeat_kv(x, repeats): """[B, KVH, T, Dh] -> [B, QH, T, Dh] without learned parameters.""" if repeats == 1: return x B, H, T, D = x.shape return x[:, :, None, :, :].expand(B, H, repeats, T, D).reshape(B, H * repeats, T, D) def dynamic_i8_qk(q, k): """Backend-exact dynamic int8 Q@K. Each vector gets an absmax/127 scale and round-half-away codes. Float32 matmul sums the integer products exactly at Glimmer head widths, then the two scales are applied in the device's `(acc * sq) * sk` order. """ def codes(x): scale = x.abs().amax(dim=-1, keepdim=True) / 127.0 inv = torch.where(scale > 0, scale.reciprocal(), torch.zeros_like(scale)) z = x * inv qx = torch.sign(z) * torch.floor(torch.abs(z) + 0.5) return qx.clamp(-127, 127), scale qq, sq = codes(q) kk, sk = codes(k) acc = torch.matmul(qq, kk.transpose(-1, -2)) return (acc * sq) * sk.transpose(-1, -2) def sliding_window_attention(q, k, v, window, *, dynamic_qk=False): """Exact causal local attention with O(T*window), rather than O(T*T), state. Left-padding turns every query's causal history into one fixed-width view: query ``t`` sees ``[t-window+1, ..., t]``. ``unfold`` itself is a view; the only context-sized intermediate is the B*H*T*window score/probability slab. The early rows mask padded positions so they are identical in meaning to the dense additive mask used by the short-sequence/export path. """ if q.ndim != 4 or k.shape != q.shape or v.shape != q.shape: raise ValueError("sliding_window_attention expects matching [B,H,T,D] tensors") T, Dh = q.shape[-2:] window = min(int(window), T) if window < 1: raise ValueError("attention window must be positive") # unfold(2) appends the window axis after D: [B,H,T,D,W]. kpad = F.pad(k, (0, 0, window - 1, 0)) vpad = F.pad(v, (0, 0, window - 1, 0)) kw = kpad.unfold(2, window, 1).permute(0, 1, 2, 4, 3) vw = vpad.unfold(2, window, 1).permute(0, 1, 2, 4, 3) if dynamic_qk: scores = dynamic_i8_qk(q.unsqueeze(-2), kw).squeeze(-2) else: scores = torch.einsum("bhtd,bhtwd->bhtw", q, kw) scores = scores * (Dh ** -0.5) row = torch.arange(T, device=q.device)[:, None] slot = torch.arange(window, device=q.device)[None, :] valid = slot >= (window - 1 - row) scores = scores.masked_fill(~valid.view(1, 1, T, window), float("-inf")) probs = F.softmax(scores, dim=-1, dtype=torch.float32).to(q.dtype) return torch.einsum("bhtw,bhtwd->bhtd", probs, vw) def chunked_causal_attention(q, k, v, chunk_size=512, *, dynamic_qk=False): """Exact global causal attention with O(T*chunk_size) forward workspace. MPS's causal SDPA currently materializes context-quadratic driver memory even without an explicit mask (27.2 GiB at T=16K for nano-Glimmer). Query blocking preserves the same independent softmax rows while bounding each call's score slab. During training, non-reentrant checkpointing prevents autograd from retaining every block's SDPA intermediates; backward recomputes them one block at a time. """ if q.ndim != 4 or k.shape != q.shape or v.shape != q.shape: raise ValueError("chunked_causal_attention expects matching [B,H,T,D] tensors") T, Dh = q.shape[-2:] if chunk_size < 1: raise ValueError("attention chunk_size must be positive") def attend(qb, kb, vb, mask): if dynamic_qk: scores = dynamic_i8_qk(qb, kb) * (Dh ** -0.5) scores = scores.masked_fill(~mask, float("-inf")) return torch.matmul(torch.softmax(scores, dim=-1), vb) return F.scaled_dot_product_attention(qb, kb, vb, attn_mask=mask) use_checkpoint = (torch.is_grad_enabled() and (q.requires_grad or k.requires_grad or v.requires_grad)) outputs = [] key_pos = torch.arange(T, device=q.device) for start in range(0, T, chunk_size): end = min(start + chunk_size, T) query_pos = torch.arange(start, end, device=q.device)[:, None] # A fixed K length makes every full query block request the same score # allocation. MPS otherwise caches one successively larger slab per # prefix (12.6 GiB of driver memory at 16K despite a 512-row peak). # Masking future columns is exact; the deliberate cost is about 2x the # global layer's arithmetic versus triangular prefix calls. mask = (key_pos[None, :] <= query_pos)[None, None, :, :] args = (q[:, :, start:end], k, v, mask) if use_checkpoint: from torch.utils.checkpoint import checkpoint out = checkpoint(attend, *args, use_reentrant=False) else: out = attend(*args) outputs.append(out) return torch.cat(outputs, dim=-2) def landmark_grouped_attention(q, k, v, landmarks, max_groups, *, dynamic_qk=False, return_weights=False): """Causal Landmark Attention training rule from Mohtashami/Jaggi. Tokens inside every completed block receive a conditional softmax. The corresponding landmark's ordinary attention probability gates that entire block. Tokens since the latest landmark compete directly with all earlier landmark gates. Landmark values themselves are never read. This dense spelling is for training and equivalence tests; recurrent inference first scores the small landmark index, then reads only selected exact KV blocks. """ if q.ndim != 4 or k.shape != q.shape or v.shape != q.shape: raise ValueError("landmark attention expects matching [B,H,T,D] tensors") B, H, T, Dh = q.shape if landmarks.shape != (B, T) or landmarks.dtype != torch.bool: raise ValueError("landmarks must be a boolean [B,T] tensor") if max_groups < 2: raise ValueError("max_groups must leave one group for landmark gates") if dynamic_qk: scores = dynamic_i8_qk(q, k) else: scores = torch.matmul(q, k.transpose(-1, -2)) scores = scores * (Dh ** -0.5) row = torch.arange(T, device=q.device)[:, None] col = torch.arange(T, device=q.device)[None, :] causal_mask = (col > row).view(1, 1, T, T) is_landmark_base = landmarks[:, None, None, :] # Group IDs are structural and deliberately outside autograd. A landmark # belongs to the block immediately before it. For every query, the latest # (unfinished) block is detected from the largest causally visible ID. with torch.no_grad(): landmark_int = landmarks.to(torch.int64) key_groups = torch.cumsum(landmark_int, dim=-1) - landmark_int group_ids_base = key_groups[:, None, None, :].expand(B, 1, T, T) query_groups = key_groups[:, None, :, None] current_base = (group_ids_base == query_groups) & ~causal_mask mask_base = causal_mask | (is_landmark_base & current_base) current_base = current_base & ~mask_base past_landmarks_base = is_landmark_base & ~mask_base gate_bucket = max_groups - 1 softmax_groups_base = torch.where( current_base | past_landmarks_base, torch.full_like(group_ids_base, gate_bucket), group_ids_base) # Every structural tensor is shared across heads. ``expand`` retains a # stride-zero view instead of materializing H copies of the T² IDs. group_ids = group_ids_base.expand(B, H, T, T) softmax_groups = softmax_groups_base.expand(B, H, T, T) mask = mask_base.expand(B, H, T, T) current = current_base.expand(B, H, T, T) past_landmarks = past_landmarks_base.expand(B, H, T, T) # Stable softmax independently within each block, with all gates and the # current block sharing one final bucket. Using finite minima avoids the # undefined (-inf)-(-inf) path in masked scatter groups. floor = torch.finfo(scores.dtype).min masked_scores = scores.masked_fill(mask, floor) group_shape = (B, H, T, max_groups) maxima = scores.new_full(group_shape, floor) maxima.scatter_reduce_(-1, softmax_groups, masked_scores, reduce="amax", include_self=True) selected_max = torch.gather(maxima, -1, softmax_groups) exponentials = torch.exp(masked_scores - selected_max).masked_fill(mask, 0) denominators = scores.new_zeros(group_shape) denominators.scatter_add_(-1, softmax_groups, exponentials) conditional = exponentials / torch.gather( denominators, -1, softmax_groups).clamp_min( torch.finfo(scores.dtype).tiny) # Scatter each landmark gate back onto the ID of its preceding block. gate_probability = scores.new_zeros(group_shape) gate_probability.scatter_add_( -1, group_ids, conditional * past_landmarks.to(conditional.dtype)) block_probability = torch.gather(gate_probability, -1, group_ids) past_tokens = ~(mask | past_landmarks | current) weights = torch.where( current, conditional, torch.where(past_tokens, conditional * block_probability, torch.zeros_like(conditional))) output = torch.matmul(weights, v) return (output, weights) if return_weights else output class GlimmerAttention(nn.Module): """Released Muse Glimmer attention, scaled in width but not in structure.""" def __init__(self, cfg: Config, layer_idx: int): super().__init__() if cfg.n_heads % cfg.n_kv_heads: raise ValueError("Glimmer n_heads must be divisible by n_kv_heads") self.cfg = cfg self.local = layer_idx % 4 != 3 q_width = cfg.n_heads * cfg.head_dim kv_width = cfg.n_kv_heads * cfg.head_dim self.q_proj = nn.Linear(cfg.d_model, q_width, bias=False) self.k_proj = nn.Linear(cfg.d_model, kv_width, bias=False) self.v_proj = nn.Linear(cfg.d_model, kv_width, bias=False) self.gate_proj = nn.Linear(cfg.d_model, q_width, bias=False) self.o_proj = nn.Linear(q_width, cfg.d_model, bias=False) self.qk_norm = WeightlessRMSNorm(cfg.rms_norm_eps) def attention_mask(self, length, device): """Build the training mask on demand, not once per model layer. Decode does not use this path: it carries a KV cache and constructs a one-row validity mask. Eagerly allocating an SxS mask in every layer nevertheless made even constructing an 8K--16K decode model consume gigabytes before export. Keeping the quadratic training mask lazy separates that training/prefill problem from the O(S) decode graph. """ row = torch.arange(length, device=device)[:, None] col = torch.arange(length, device=device)[None, :] keep = col <= row if self.local: keep = keep & ((row - col) < self.cfg.glimmer_window) mask = torch.zeros(length, length, device=device) return mask.masked_fill(~keep, float("-inf")) def forward(self, x, cos, sin, landmarks=None): B, T, _ = x.shape H, KH, Dh = self.cfg.n_heads, self.cfg.n_kv_heads, self.cfg.head_dim q = self.q_proj(x).view(B, T, H, Dh).transpose(1, 2) k = self.k_proj(x).view(B, T, KH, Dh).transpose(1, 2) v = self.v_proj(x).view(B, T, KH, Dh).transpose(1, 2) q = self.qk_norm(q) * self.cfg.qk_scale_factor k = self.qk_norm(k) if self.local: # global layers are intentionally NoPE q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) repeats = H // KH k, v = repeat_kv(k, repeats), repeat_kv(v, repeats) # Preserve the compact dense spelling used by the architecture export # fixtures and existing 256/512-token training runs. At useful context # lengths, however, never construct an SxS mask for ordinary fp32 # training: local layers are O(T*window), and global layers use fixed # query blocks with an O(T*chunk) causal mask. if self.cfg.landmark_attention and not self.local: if landmarks is None: raise ValueError("landmark Glimmer requires a landmark mask") # The dense grouped-softmax path is a training/reference graph. # Long recurrent inference uses the landmark index + selected KV # blocks and is lowered separately. max_groups = ((self.cfg.seq_len + self.cfg.landmark_stride - 1) // self.cfg.landmark_stride + 2) def attend(qvalue, kvalue, vvalue, marks): return landmark_grouped_attention( qvalue, kvalue, vvalue, marks, max_groups, dynamic_qk=self.cfg.dynamic_qk) if (torch.is_grad_enabled() and (q.requires_grad or k.requires_grad or v.requires_grad)): # The explicit reference rule has several T² score/weight # slabs. Recompute them in backward instead of retaining them # alongside all four model layers. from torch.utils.checkpoint import checkpoint o = checkpoint(attend, q, k, v, landmarks, use_reentrant=False) else: o = attend(q, k, v, landmarks) elif T > 1024 and self.local: o = sliding_window_attention( q, k, v, self.cfg.glimmer_window, dynamic_qk=self.cfg.dynamic_qk, ) elif T > 1024: o = chunked_causal_attention( q, k, v, dynamic_qk=self.cfg.dynamic_qk) else: mask = self.attention_mask(T, x.device) if self.cfg.dynamic_qk: scores = dynamic_i8_qk(q, k) * (Dh ** -0.5) scores = scores + mask o = torch.matmul(torch.softmax(scores, dim=-1), v) else: o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) o = o.transpose(1, 2).contiguous().view(B, T, -1) o = o * torch.sigmoid(self.gate_proj(x)) return self.o_proj(o) class GlimmerBlock(nn.Module): def __init__(self, cfg: Config, idx: int): super().__init__() self.input_norm = CenteredRMSNorm(cfg.d_model, cfg.rms_norm_eps) self.attn = GlimmerAttention(cfg, idx) self.post_attn_norm = CenteredRMSNorm(cfg.d_model, cfg.post_norm_eps) self.pre_ffn_norm = CenteredRMSNorm(cfg.d_model, cfg.rms_norm_eps) self.ffn = SwiGLU(cfg) self.post_ffn_norm = CenteredRMSNorm(cfg.d_model, cfg.post_norm_eps) if cfg.uses_per_layer: self.ple_gate = nn.Linear(cfg.d_model, cfg.ple_dim, bias=False) self.ple_proj = nn.Linear(cfg.ple_dim, cfg.d_model, bias=False) self.ple_norm = RMSNorm(cfg.d_model) def forward(self, x, cos, sin, ple=None, landmarks=None): x = x + self.post_attn_norm( self.attn(self.input_norm(x), cos, sin, landmarks)) x = x + self.post_ffn_norm(self.ffn(self.pre_ffn_norm(x))) if ple is not None: g = F.gelu(self.ple_gate(x)) x = x + self.ple_norm(self.ple_proj(g * ple)) return x class TinyLM(nn.Module): def __init__(self, cfg: Config): super().__init__() self.cfg = cfg if cfg.architecture not in ("tinylm", "glimmer"): raise ValueError(f"unknown architecture {cfg.architecture!r}") mixer_indices = cfg.mamba_set | cfg.abc_set if any(index < 0 or index >= cfg.n_layers for index in mixer_indices): raise ValueError("mixer layer index is outside n_layers") if cfg.mamba_set & cfg.abc_set: raise ValueError("a layer cannot be both Mamba and ABC") if cfg.architecture == "glimmer": if cfg.arm in ("fatembed", "bigcore"): raise ValueError(f"arm {cfg.arm!r} is not defined for Glimmer") if cfg.mamba_set or cfg.abc_set or cfg.attn_window: raise ValueError("Glimmer has its own layer schedule; " "mamba_layers/abc_layers/attn_window must be empty") if cfg.d_model % cfg.n_heads or cfg.head_dim % 2: raise ValueError("Glimmer requires d_model/n_heads and an even head_dim") if not 0 < cfg.glimmer_window <= cfg.seq_len: raise ValueError("glimmer_window must be in [1, seq_len]") if cfg.landmark_attention: if cfg.landmark_stride < 2: raise ValueError("landmark_stride must be at least 2") if not 0 <= cfg.landmark_token_id < cfg.vocab_size: raise ValueError("landmark_token_id is outside the vocabulary") if cfg.landmark_topk < 1: raise ValueError("landmark_topk must be positive") elif cfg.landmark_attention: raise ValueError("landmark attention currently requires Glimmer") if cfg.architecture == "glimmer": self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model) self.tok_emb_norm = WeightlessRMSNorm(cfg.rms_norm_eps) # Muse Glimmer does not tie input and output embeddings. self.head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False) elif cfg.arm == "fatembed": self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.table_width) self.emb_down = nn.Linear(cfg.table_width, cfg.d_model, bias=False) self.head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False) else: self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model) self.head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False) self.head.weight = self.tok_emb.weight # tied if cfg.uses_per_layer: # Context-aware half of the per-layer input: one projection of the # token embedding, reshaped to (layers, ple_dim) and normed per slice. self.ple_model_proj = nn.Linear(cfg.d_model, cfg.n_layers * cfg.ple_dim, bias=False) self.ple_proj_norm = RMSNorm(cfg.ple_dim) if cfg.arm == "ple": self.ple_table = nn.Embedding(cfg.vocab_size, cfg.n_layers * cfg.ple_dim) block_cls = GlimmerBlock if cfg.architecture == "glimmer" else Block self.blocks = nn.ModuleList([block_cls(cfg, i) for i in range(cfg.n_layers)]) if cfg.loops > 1 and cfg.feedback == "shift": self.fb_norm = RMSNorm(cfg.d_model) self.fb_gate = nn.Linear(2 * cfg.d_model, cfg.d_model) self.fb_proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False) self.fb_alpha = nn.Parameter(torch.tensor(0.1)) self.fb_start = nn.Parameter(torch.zeros(cfg.d_model)) elif cfg.feedback not in ("none", "shift"): raise ValueError(f"unknown feedback {cfg.feedback!r}") self.out_norm = RMSNorm(cfg.d_model, eps=(cfg.rms_norm_eps if cfg.architecture == "glimmer" else 1e-6)) self.apply(self._init) for block in self.blocks: if (isinstance(getattr(block, "attn", None), ABCAttention) and block.attn.cfg.abc_control == "linformer"): nn.init.xavier_uniform_(block.attn.position_control.weight) for n, p in self.named_parameters(): # Scale down residual-writing projections, GPT-2 style. Preserve # the historical broad suffix rule for old checkpoints; Glimmer's # q/k/v/gate all end in `_proj` and must not be swept into it. residual = ((n.endswith("attn.o_proj.weight") or n.endswith("ffn.down.weight")) if cfg.architecture == "glimmer" else (n.endswith("proj.weight") or n.endswith("down.weight"))) if residual: nn.init.normal_(p, std=0.02 / math.sqrt(2 * cfg.n_layers)) if cfg.arm == "fatembed": # Keep post-projection activations at the same scale as the other # arms' embeddings, otherwise this arm is handicapped by init alone. nn.init.normal_(self.emb_down.weight, std=cfg.table_width**-0.5) for block in self.blocks: # The per-layer branch ends in an RMSNorm, which would undo the small # residual init above and inject unit-scale noise from step 0. Zeroing # the norm gain makes the branch start as an exact no-op, so every arm # begins from the same function and the comparison measures learning # rather than initialisation luck. if cfg.uses_per_layer: nn.init.zeros_(block.ple_norm.weight) rope_theta = (cfg.glimmer_rope_theta if cfg.architecture == "glimmer" else cfg.rope_theta) cos, sin = build_rope(cfg.seq_len, cfg.head_dim, rope_theta, "cpu") self.register_buffer("cos", cos, persistent=False) self.register_buffer("sin", sin, persistent=False) def _init(self, m): if isinstance(m, nn.Linear): nn.init.normal_(m.weight, std=0.02) elif isinstance(m, nn.Embedding): nn.init.normal_(m.weight, std=0.02) def forward(self, idx, targets=None, last_logits_only=False, logits_from=None): cfg = self.cfg x = self.tok_emb(idx) if cfg.architecture == "glimmer": x = self.tok_emb_norm(x) elif cfg.arm == "fatembed": x = self.emb_down(x) ple = None if cfg.uses_per_layer: B, T = idx.shape ple = self.ple_model_proj(x) * (cfg.d_model**-0.5) ple = self.ple_proj_norm(ple.view(B, T, cfg.n_layers, cfg.ple_dim)) if cfg.arm == "ple": # embed_scale = sqrt(ple_dim), applied to the table rather than # baked into init -- undocumented in Gemma's config but load-bearing. table = self.ple_table(idx).view(B, T, cfg.n_layers, cfg.ple_dim) ple = (ple + table * (cfg.ple_dim**0.5)) * (2**-0.5) landmarks = (idx == cfg.landmark_token_id if cfg.landmark_attention else None) x_in = x for loop in range(cfg.loops): if loop > 0 and cfg.feedback == "shift": # u_t = e_t + alpha * g_t * W_s RMSNorm(s_{t-1}), with e_t the # previous pass's output here and s_{t-1} its output at t-1. start = self.fb_start.view(1, 1, -1).expand(x.shape[0], 1, -1) previous = torch.cat((start, x[:, :-1]), dim=1) r = self.fb_norm(previous) gate = torch.sigmoid(self.fb_gate(torch.cat((x, r), dim=-1))) x = x + self.fb_alpha * gate * self.fb_proj(r) elif loop > 0: x = x + x_in for i, block in enumerate(self.blocks): block_ple = None if ple is None else ple[:, :, i] if cfg.architecture == "glimmer": x = block(x, self.cos, self.sin, block_ple, landmarks) else: x = block(x, self.cos, self.sin, block_ple) x = self.out_norm(x) if last_logits_only and logits_from is not None: raise ValueError("last_logits_only and logits_from are mutually exclusive") if last_logits_only and targets is not None: raise ValueError("last_logits_only cannot be used with targets") if last_logits_only: x = x[:, -1:, :] elif logits_from is not None: if not 0 <= logits_from < x.shape[1]: raise ValueError("logits_from is outside the active sequence") x = x[:, logits_from:, :] if targets is not None: targets = targets[:, logits_from:] logits = self.head(x) if cfg.architecture == "glimmer": logits = logits * cfg.output_multiplier cap = cfg.final_logit_softcapping if cap > 0: logits = torch.tanh(logits / cap) * cap loss = None if targets is not None: loss = F.cross_entropy( logits.view(-1, cfg.vocab_size), targets.reshape(-1), ignore_index=-1 ) return logits, loss # ---- parameter accounting ------------------------------------------------- # Three tiers matching the ESP32's three, by ACCESS PATTERN not just speed: # core -- dense, random, every token -> SRAM-resident (the scarce budget) # stream -- the output head: dense but read as one sequential scan per token # -> costs bandwidth, not SRAM; can live off-chip # table -- sparse, one row per token -> memory-mapped flash # `core` deliberately EXCLUDES the head. Lumping the head in makes a large # vocabulary look unaffordable when it is merely slow, and blocks the whole # cheap-table-via-big-vocab design from being built at all. See src/budget.py. def param_budget(self): table = 0 if self.cfg.architecture == "glimmer": # Untied input embeddings are sparse: one row read per token. table += self.tok_emb.weight.numel() if self.cfg.arm == "ple": table += self.ple_table.weight.numel() if self.cfg.arm == "fatembed": table += self.tok_emb.weight.numel() for block in self.blocks: if (isinstance(getattr(block, "attn", None), ABCAttention) and block.attn.cfg.abc_control == "linformer"): table += block.attn.position_control.weight.numel() stream = self.head.weight.numel() seen, total = set(), 0 for p in self.parameters(): if id(p) in seen: continue # tied weights counted once seen.add(id(p)) total += p.numel() return {"core": total - table - stream, "stream": stream, "table": table, "total": total} @torch.no_grad() def generate(self, idx, max_new_tokens, temperature=0.8, top_k=40): for _ in range(max_new_tokens): idx_c = idx[:, -self.cfg.seq_len :] logits, _ = self(idx_c) logits = logits[:, -1, :] / temperature if top_k: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) logits[logits < v[:, [-1]]] = -float("inf") probs = F.softmax(logits, dim=-1) idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1) return idx def make_model(arm, target_core, base: Config = None, verbose=True, fixed_ffn=None): """Build `arm`. Default: solve ffn_hidden so every arm hits the same compute-core budget (core now excludes the output head -- see param_budget). Without this the comparison is worthless: each arm's plumbing costs a different amount of dense parameters, and the winner would just be whichever got a fatter FFN. fixed_ffn: skip the solver and pin ffn_hidden. Used by the corrected table-scaling sweep, where the point is to hold the FFN fixed and let core float with ple_dim -- so growing the table never cannibalises compute. The table's isolated contribution is then read as (ple - ple_notable) at each ple_dim, both sharing the same fixed FFN. """ cfg = Config(**{**(base.__dict__ if base else {}), "arm": arm}) if fixed_ffn is not None: cfg.ffn_hidden = fixed_ffn model = TinyLM(cfg) if verbose: b = model.param_budget() print(f"[{cfg.architecture}/{arm}] d_model={cfg.d_model} layers={cfg.n_layers} " f"ffn={cfg.ffn_hidden} ple_dim={cfg.ple_dim} core={b['core']:,} " f"stream={b['stream']:,} table={b['table']:,} total={b['total']:,}") return model table_budget = cfg.vocab_size * cfg.n_layers * cfg.ple_dim if arm == "bigcore": # Spend the table budget on width instead, so this arm's core equals every # other arm's core+table. Searched, since core scales ~quadratically in d. best = None for d in range(cfg.d_model, 8 * cfg.d_model, cfg.n_heads): trial = Config(**{**cfg.__dict__, "arm": "baseline", "d_model": d, "ffn_hidden": 2 * d}) if TinyLM(trial).param_budget()["core"] <= target_core + table_budget: best = trial else: break cfg = best else: lo, hi = 1, 64 * cfg.d_model while lo < hi: mid = (lo + hi + 1) // 2 cfg.ffn_hidden = mid if TinyLM(cfg).param_budget()["core"] <= target_core: lo = mid else: hi = mid - 1 cfg.ffn_hidden = lo model = TinyLM(cfg) if verbose: b = model.param_budget() print( f"[{cfg.architecture}/{arm}] d_model={cfg.d_model} layers={cfg.n_layers} ffn={cfg.ffn_hidden} " f"core={b['core']:,} stream={b['stream']:,} table={b['table']:,} " f"total={b['total']:,}" ) return model