# Stage 9 · Modern LLM Primitives (`SmolLM2-135M`: RoPE + GQA + RMSNorm + SwiGLU) *Measurements on MacBook Pro, Apple M3 Pro (18-core GPU, 18 GB), Headless Chrome 158 (WebGPU on Metal), AC power, Low Power Mode off. All 363 intermediate tensors, 151 SHA-256 weight digests across 6 quantized precisions, and greedy/sampled/speculative tokens verified against PyTorch (`pnpm compare --model smollm2`).* ![Stage 9 SmolLM2-135M decode throughput, FlashAttention prefill, and split-multi speculative decode on M3 Pro](m3-pro/smollm2.png) ## Extending the engine beyond GPT-2 Upstream Stages 1–5 targeted GPT-2 small's older primitives (learned positional embeddings, LayerNorm, GELU, standard MHA, bias-heavy dense projections). Porting the same hand-written WGSL + tensor-by-tensor PyTorch verification discipline to `HuggingFaceTB/SmolLM2-135M` replaces nearly every architectural building block (`weights/smollm2/config.json`): | Primitive | GPT-2 small | SmolLM2-135M | | --- | --- | --- | | Checkpoint dtype | `F32` (124M params, 498 MB) | `BF16` (`269 MB` on disk → `538 MB` in `fp32`) | | Tokenizer | GPT-2 `vocab.json` + `merges.txt` | Hugging Face `tokenizer.json` ByteLevel BPE + `added_tokens` ([src/tokenizer_hf.ts](../src/tokenizer_hf.ts)) | | Positional encoding | Learned `wpe` added to `wte` | Non-interleaved Rotary Position Embeddings (`rotate_half`, `rope_theta = 100000`) ([rope_qkv.wgsl](../src/engine/kernels/rope_qkv.wgsl)) | | Normalization | LayerNorm (`ln_1`, `ln_2`, `ln_f`) | RMSNorm (`eps = 1e-5`, zero mean subtraction/bias) ([rmsnorm.wgsl](../src/engine/kernels/rmsnorm.wgsl)) | | Attention | 12-layer MHA (`12 Q / 12 KV` heads, `head_dim = 64`) | 30-layer **3:1 GQA** (`9 Q / 3 KV` heads, `head_dim = 64`, 37% smaller KV) | | Feed-forward | 2-matrix GELU MLP (`768 ↔ 3072`) | 3-matrix **SwiGLU** (`gate`, `up`, `down`, `576 ↔ 1536`, `silu(gate) * up`) ([swiglu.wgsl](../src/engine/kernels/swiglu.wgsl)) | | Vocab / tied head | `50,257 × 768` | `49,152 × 576` (BF16 tied word embeddings) | ## Implementation & numerical stability findings 1. **BF16 safetensors decoding ([src/safetensors.ts](../src/safetensors.ts)):** Added native `BF16` support (`bf16ToF32` bit shift) so Hugging Face `model.safetensors` loads cleanly in the browser without offline re-exporting to FP32. 2. **RMSNorm associativity around extreme outliers ([rmsnorm.wgsl](../src/engine/kernels/rmsnorm.wgsl), [rmsnorm_parallel.wgsl](../src/engine/kernels/rmsnorm_parallel.wgsl)):** SmolLM2 exhibits sharp intermediate residual activations (`~20,000+` magnitude in middle layers). A strictly left-to-right scalar sum across 576 elements drifted beyond `1e-4` relative tolerance vs PyTorch; accumulating in 16-element chunks and using `1.0 / sqrt(...)` matched PyTorch closely across all 30 layers (`worst h.12.resid_mid at 38.7%` of tolerance in naive mode). 3. **3:1 GQA generalization across all 7 non-flash attention kernels:** Updated `attention_scores{,_cached,_blocked}.wgsl` and `attention_mix{,_cached,_blocked,_split}.wgsl` with `n_kv_head` (`kv_h = h / (n_head / n_kv_head)`); `attention_flash*.wgsl` and `kv_append*.wgsl` already parameterized `n_kv_head` cleanly. 4. **Full PyTorch validation suite (`python/dump_smollm2_reference.py`, `pnpm compare --model smollm2`):** - `363 / 363` tensor checks pass across naive, fast, blocked, split, `split-multi`, `flash`, and `fp16` KV modes. - `151 / 151` SHA-256 weight digests match PyTorch across `fp16`, `int8`, `int8-tensor`, `int8-mixed`, `int4`, and `int4-mixed`. - `64 / 64` & `96 / 96` greedy tokens match PyTorch, `2,200 / 2,200` sliding-context sampled tokens stay bit-exact under speculative drafting, and `--inject eps` fails at `h.0.ln_1` as expected. - `tests/smollm2.test.ts` covers Hugging Face tokenizer encoding/decoding and `BF16` decoding (`22` tests; full unit suite `83 / 83` passing). ## M3 Pro performance (`docs/m3-pro/stage9/`) ### Decode across precisions (`1,000` new tokens, PyTorch greedy match verified on every run) | Precision | Model MB | Read/token | Decode 16 / 256 / 1k (tok/s) | Speedup vs `fp32` | | --- | ---: | ---: | ---: | ---: | | `fp32` | 538.1 MB | 538.1 MB | 109.1 / 110.5 / **110.5 tok/s** | 1.00x | | `fp16` | 269.1 MB | 269.1 MB | 147.8 / 149.9 / **149.9 tok/s** | 1.36x | | `int8-mixed` | 163.6 MB | 163.6 MB | 165.0 / 164.6 / **164.6 tok/s** | 1.49x | | `int4-mixed` | 116.5 MB | 116.5 MB | 179.2 / 175.6 / **175.6 tok/s** | 1.59x | | `int4` | **75.8 MB** | **75.8 MB** | 185.6 / 182.7 / **182.7 tok/s** | **1.65x** | **Why depth limits single-row decode speedup relative to GPT-2:** SmolLM2 has `30` transformer layers instead of `12` (`453` dispatches per decode step unfused, `423` with FlashAttention vs `159` / `147` on GPT-2). On `smollm2` with `int8-mixed` and empty-dispatch timing (`2.0 ms` floor measured for 453 empty dispatches), fixed per-dispatch command overhead becomes a larger share of the step as weights shrink from `538 MB` to `76 MB`, capping `int4` near `183 tok/s` while GQA (`23.0 kB/pos` in `fp16` KV) and FlashAttention (`5.30 ms` at `16` pos → `6.40 ms` at `980` pos) keep context scaling compact. ### Prefill (`1,000` tokens) & Speculative Decode (`256` new tokens, `split` → `split-multi`) - **Prefill (`1,000` tokens):** `166.9 ms` (`fp32 fast`) → `150.4 ms` (`fp32 flash`) → `129.9 ms` (`fp16 fast`) → **`122.3 ms` (`fp16 flash`, `8,177 tok/s`)**. - **Speculative decode (`split-multi`):** - `fp16`: `code` `195 tok/s` (`1.56x`), `list` **`502 tok/s` (`3.54x`)**, `loop` **`596 tok/s` (`4.40x`)**. - `int8-mixed`: `code` `250 tok/s` (`1.77x`), `list` `500 tok/s` (`3.51x`), `loop` **`664 tok/s` (`4.24x`)**. - `int4-mixed`: `code` **`327 tok/s` (`1.95x`)**, `list` **`586 tok/s` (`3.50x`)**, `loop` **`877 tok/s` (`5.25x`, `8.79 tok/pass`)**. Raw benchmarks: [docs/m3-pro/stage9/](m3-pro/stage9).