| """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 |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| _FUSED_ATTENTION = os.environ.get("FUSED_ATTENTION", "0").strip() == "1" |
|
|
| |
| |
| |
| |
| |
| |
| |
| _GPU_PERF = os.environ.get("GPU_MATMUL_FAST", "0").strip() == "1" |
| _PREC = jax.lax.Precision.DEFAULT if _GPU_PERF else None |
| |
| |
| |
| |
| |
| _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) |
| emb = np.concatenate([freqs, freqs], axis=-1) |
| 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: |
| |
| 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) |
|
|
| |
| 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: |
| |
| |
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| |
| |
| |
| |
| |
| |
| 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: |
| |
| |
| |
| |
| 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))) |
|
|