"""Decoder-only transformer, Llama-style, in Flax. Modern internals (not GPT-2): RMSNorm, rotary position embeddings (RoPE), SwiGLU MLP, no biases anywhere, pre-norm blocks, tied input/output embeddings. Written to compile cleanly under jit on a single TPU chip in bf16. """ from __future__ import annotations import os import flax.linen as nn import jax import jax.numpy as jnp import numpy as np from config import ModelConfig # GPU-only perf path. The default attention (below) materializes the full # [B, H, T, T] score matrix in float32 for every layer; on the Kaggle T4x2 that # is ~8.85GB of activations, which both OOMs micro=8 AND makes the step # memory-bound (measured 16 TFLOP/s == 2xT4 fp32 peak, i.e. tensor cores idle). # FUSED_ATTENTION=1 routes through jax.nn.dot_product_attention, whose GPU lowering # is a fused flash-attention kernel: it never materializes the T x T scores and # has the causal mask + softmax-stability baked in. Gated by env so the SAME # model.py pulled by the TPU (bfloat16) supervisor stays byte-for-byte unchanged # on its proven path — the flag is only ever set by the Kaggle GPU launcher. _FUSED_ATTENTION = os.environ.get("FUSED_ATTENTION", "0").strip() == "1" # GPU-only matmul precision. A standalone fp16 4096^3 GEMM microbenchmark on the # Kaggle T4 measured 31 TFLOP/s with jax.lax.Precision.DEFAULT but only 23.7 with # the implicit precision=None path our Dense/einsum layers were using — i.e. XLA # was picking a slower fp32-accumulation matmul algorithm (3 passes) instead of a # single HMMA tensor-core kernel. Forcing DEFAULT (fastest / tensor-core) on every # matmul is a measured ~1.3x. Gated so the TPU bfloat16 path is byte-for-byte # unchanged (there DEFAULT is already optimal and this env is never set). _GPU_PERF = os.environ.get("GPU_MATMUL_FAST", "0").strip() == "1" _PREC = jax.lax.Precision.DEFAULT if _GPU_PERF else None # remat (activation checkpointing) is DECOUPLED from the matmul-precision win. # Measured on 2xT4: with fused attention the model uses only ~36% of 16GB VRAM at # micro=8, so trading compute for memory via remat is pure waste — it added ~33% # recompute and dropped throughput (14.7K vs the no-remat path). Only turn it on if # a genuinely large micro-batch needs the headroom. Defaults OFF; opt in via env. _REMAT = os.environ.get("GPU_REMAT", "0").strip() == "1" def _rope_freqs(seq_len: int, head_dim: int, theta: float) -> tuple[jnp.ndarray, jnp.ndarray]: """Precompute cos/sin tables for rotary embeddings. Shape [seq_len, head_dim].""" inv_freq = 1.0 / (theta ** (np.arange(0, head_dim, 2, dtype=np.float32) / head_dim)) t = np.arange(seq_len, dtype=np.float32) freqs = np.outer(t, inv_freq) # [seq, head_dim/2] emb = np.concatenate([freqs, freqs], axis=-1) # [seq, head_dim] return jnp.asarray(np.cos(emb)), jnp.asarray(np.sin(emb)) def _rotate_half(x: jnp.ndarray) -> jnp.ndarray: half = x.shape[-1] // 2 x1, x2 = x[..., :half], x[..., half:] return jnp.concatenate([-x2, x1], axis=-1) def _apply_rope(x: jnp.ndarray, cos: jnp.ndarray, sin: jnp.ndarray) -> jnp.ndarray: # x: [B, H, T, Dh]; cos/sin: [T, Dh] cos = cos[None, None, :, :] sin = sin[None, None, :, :] return x * cos + _rotate_half(x) * sin class RMSNorm(nn.Module): dim: int eps: float = 1e-5 @nn.compact def __call__(self, x): scale = self.param("scale", nn.initializers.ones, (self.dim,)) x32 = x.astype(jnp.float32) norm = x32 * jax.lax.rsqrt(jnp.mean(x32 * x32, axis=-1, keepdims=True) + self.eps) return (norm * scale).astype(x.dtype) class Attention(nn.Module): cfg: ModelConfig @nn.compact def __call__(self, x, cos, sin): cfg = self.cfg B, T, C = x.shape hd = cfg.n_embd // cfg.n_head dtype = jnp.dtype(cfg.dtype) dense = lambda feats, name: nn.Dense( feats, use_bias=False, dtype=dtype, precision=_PREC, kernel_init=nn.initializers.normal(stddev=0.02), name=name) q = dense(cfg.n_head * hd, "q")(x) k = dense(cfg.n_kv_head * hd, "k")(x) v = dense(cfg.n_kv_head * hd, "v")(x) q = q.reshape(B, T, cfg.n_head, hd).transpose(0, 2, 1, 3) k = k.reshape(B, T, cfg.n_kv_head, hd).transpose(0, 2, 1, 3) v = v.reshape(B, T, cfg.n_kv_head, hd).transpose(0, 2, 1, 3) # GQA: repeat kv heads to match q heads if needed. if cfg.n_kv_head != cfg.n_head: reps = cfg.n_head // cfg.n_kv_head k = jnp.repeat(k, reps, axis=1) v = jnp.repeat(v, reps, axis=1) q = _apply_rope(q, cos, sin) k = _apply_rope(k, cos, sin) if _FUSED_ATTENTION: # Fused flash-attention (GPU): no [B,H,T,T] materialization. Expects # [B, T, H, Dh]; softmax runs in fp32 internally so numerics match the # explicit-fp32 path below. is_causal bakes in the causal mask. qf = q.transpose(0, 2, 1, 3) kf = k.transpose(0, 2, 1, 3) vf = v.transpose(0, 2, 1, 3) out = jax.nn.dot_product_attention( qf, kf, vf, scale=hd ** -0.5, is_causal=True) out = out.reshape(B, T, C) return dense(cfg.n_embd, "o")(out) # Attention in float32 for numerical stability, causal mask. att = jnp.einsum("bhtd,bhsd->bhts", q, k, precision=_PREC).astype(jnp.float32) / jnp.sqrt(hd) mask = jnp.tril(jnp.ones((T, T), dtype=bool)) att = jnp.where(mask[None, None, :, :], att, jnp.finfo(jnp.float32).min) att = jax.nn.softmax(att, axis=-1).astype(dtype) out = jnp.einsum("bhts,bhsd->bhtd", att, v, precision=_PREC) out = out.transpose(0, 2, 1, 3).reshape(B, T, C) return dense(cfg.n_embd, "o")(out) class SwiGLU(nn.Module): cfg: ModelConfig @nn.compact def __call__(self, x): cfg = self.cfg dtype = jnp.dtype(cfg.dtype) hidden = cfg.ffn_hidden() dense = lambda feats, name: nn.Dense( feats, use_bias=False, dtype=dtype, precision=_PREC, kernel_init=nn.initializers.normal(stddev=0.02), name=name) gate = dense(hidden, "gate")(x) up = dense(hidden, "up")(x) return dense(cfg.n_embd, "down")(jax.nn.silu(gate) * up) class Block(nn.Module): cfg: ModelConfig @nn.compact def __call__(self, x, cos, sin): cfg = self.cfg x = x + Attention(cfg, name="attn")(RMSNorm(cfg.n_embd, cfg.rms_eps, name="ln1")(x), cos, sin) x = x + SwiGLU(cfg, name="mlp")(RMSNorm(cfg.n_embd, cfg.rms_eps, name="ln2")(x)) return x class GPT(nn.Module): cfg: ModelConfig @nn.compact def __call__(self, idx): cfg = self.cfg dtype = jnp.dtype(cfg.dtype) hd = cfg.n_embd // cfg.n_head wte = nn.Embed(cfg.vocab_size, cfg.n_embd, dtype=dtype, embedding_init=nn.initializers.normal(stddev=0.02), name="wte") x = wte(idx) cos, sin = _rope_freqs(cfg.seq_len, hd, cfg.rope_theta) cos, sin = cos[: idx.shape[1]].astype(dtype), sin[: idx.shape[1]].astype(dtype) # GPU-only: remat (gradient/activation checkpointing) on each Block. Recomputes # the block's forward during backward instead of storing its activations, cutting # per-layer activation memory ~n_layer-fold. That memory headroom is what lets us # raise micro-batch (micro=8 previously OOM'd at 10.26GB) so the per-layer GEMMs # go from tiny 4096x768 (very low T4 efficiency) to large ones that hit the ~31 # TFLOP/s the microbenchmark showed. Extra recompute FLOPs are cheap when the GPU # is overhead/efficiency-bound, not compute-bound. Gated: TPU path unchanged. block_cls = nn.remat(Block) if _REMAT else Block for i in range(cfg.n_layer): x = block_cls(cfg, name=f"h_{i}")(x, cos, sin) x = RMSNorm(cfg.n_embd, cfg.rms_eps, name="ln_f")(x) if cfg.tie_embeddings: # Biggest GEMM in the net (n_embd x vocab=32000). nn.Embed.attend uses # implicit precision=None -> the slow fp32-accum matmul branch on GPU; # do the tied projection explicitly so _PREC (DEFAULT/tensor-core on # GPU) applies. On TPU _PREC is None -> identical to wte.attend. logits = jnp.dot(x.astype(dtype), wte.embedding.T.astype(dtype), precision=_PREC) else: logits = nn.Dense(cfg.vocab_size, use_bias=False, dtype=dtype, precision=_PREC, name="lm_head")(x) return logits.astype(jnp.float32) def param_count(params) -> int: return int(sum(np.prod(p.shape) for p in jax.tree_util.tree_leaves(params)))