@tryhamster/gerbil 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +18 -16
  2. package/dist/cli.mjs +1 -1
  3. package/dist/cli.mjs.map +1 -1
  4. package/dist/gpu/hooks.d.mts +3 -3
  5. package/dist/gpu/hooks.mjs +5 -5
  6. package/dist/gpu/hooks.mjs.map +1 -1
  7. package/dist/index-Dgmb2kE3.d.mts.map +1 -1
  8. package/package.json +1 -2
  9. package/docs/PROJECT-STATE.md +0 -321
  10. package/docs/adding-a-model-family.md +0 -280
  11. package/docs/ai-sdk.md +0 -205
  12. package/docs/architecture/README.md +0 -84
  13. package/docs/architecture/caching.md +0 -227
  14. package/docs/architecture/inference.md +0 -176
  15. package/docs/architecture/overview.md +0 -189
  16. package/docs/architecture/streaming.md +0 -261
  17. package/docs/architecture/webgpu.md +0 -213
  18. package/docs/browser.md +0 -762
  19. package/docs/cli.md +0 -155
  20. package/docs/embeddings.md +0 -156
  21. package/docs/frameworks.md +0 -90
  22. package/docs/gerbil-site-native-migration.md +0 -217
  23. package/docs/gpu-engine/architectures.md +0 -398
  24. package/docs/gpu-engine/ir.md +0 -372
  25. package/docs/gpu-engine/kernels.md +0 -718
  26. package/docs/gpu-engine/paper.html +0 -1759
  27. package/docs/gpu-engine/paper.md +0 -2109
  28. package/docs/gpu-engine/safetensors.md +0 -312
  29. package/docs/gpu-engine/tokenizer.md +0 -302
  30. package/docs/kernel-research-queue.md +0 -85
  31. package/docs/mcp-client.md +0 -224
  32. package/docs/mcp.md +0 -109
  33. package/docs/memory-rag.md +0 -91
  34. package/docs/memory.md +0 -301
  35. package/docs/metal-safari-intel.md +0 -190
  36. package/docs/mobile-failure-diagnosis.md +0 -124
  37. package/docs/mobile.md +0 -99
  38. package/docs/observability.md +0 -230
  39. package/docs/onnx-removal-plan.md +0 -339
  40. package/docs/repl.md +0 -473
  41. package/docs/research/autoresearch-portable.md +0 -933
  42. package/docs/research/dispatch-reduction-hivemind.md +0 -84
  43. package/docs/research/ios-safari-model-caching.md +0 -117
  44. package/docs/research/mobile-webgpu-speed-fusion.md +0 -135
  45. package/docs/research/native-stt-model-selection.md +0 -49
  46. package/docs/research/native-tts-model-selection.md +0 -90
  47. package/docs/research/native-vs-chromium-decision.md +0 -152
  48. package/docs/research/nemotron-mamba2-inference.md +0 -910
  49. package/docs/research/qwen35-multimodal.md +0 -293
  50. package/docs/research/qwen36-gemma4-targets.md +0 -337
  51. package/docs/research/sota-embedding-models.md +0 -179
  52. package/docs/research/sota-mobile-models-2026.md +0 -263
  53. package/docs/research/sota-modality-models.md +0 -202
  54. package/docs/research/tps-baselines.md +0 -71
  55. package/docs/research/webgpu-m4-reference.md +0 -104
  56. package/docs/site-update-plan.md +0 -155
  57. package/docs/skills.md +0 -261
  58. package/docs/structured-output.md +0 -123
  59. package/docs/stt.md +0 -111
  60. package/docs/tools.md +0 -304
  61. package/docs/tts.md +0 -147
  62. package/docs/vision.md +0 -158
@@ -1,321 +0,0 @@
1
- # Gerbil — Project State & Architecture Decision
2
-
3
- **As of 2026-06-14.** The single authoritative snapshot. When something here conflicts
4
- with an older doc, this wins. Supersedes scattered findings in `docs/research/*` and
5
- the paper's roadmap. **Newest material is §12** (native audio begins — Moonshine STT
6
- + Kani-TTS-2 NanoCodec decoder; Gemma 4 E2B text decode; on-device memory/RAG; the
7
- text+ViT autoresearch campaign; gerbil-site live on the native engine). §11 captured
8
- EmbeddingGemma on-device, LFM2.5, the SPM tokenizer fix, MLX/DWQ loader, progress fix.
9
-
10
- ---
11
-
12
- ## 1. What Gerbil is
13
-
14
- A local LLM inference library that runs models in the browser and Node on a
15
- **single native WebGPU engine** behind one task API (no fallback lane — §2). The
16
- headline achievements this cycle: the from-scratch native engine **works on mobile**
17
- (iPad/iOS Safari 26.5+, WebKit) — previously it crashed — a desktop optimization
18
- pass roughly doubled its throughput, and the engine went **multimodal natively**:
19
- text embeddings ship (Qwen3-Embedding-0.6B) and the Qwen3.5 vision encoder is built
20
- **bit-exact vs HuggingFace** (vision LM-integration is phase 2).
21
-
22
- ## 2. The decided architecture — NATIVE-ONLY (owner decision, overrides the panel)
23
-
24
- **Decision (owner, 2026-06-13):** Gerbil is a single native WebGPU engine. **No
25
- tfjs fallback lane** — a permanent fallback "assumes defeat to begin with." The
26
- panel proposed keeping tfjs as a breadth lane; the owner rejected that. Instead:
27
-
28
- - **Launch set = text + vision + embeddings, ALL native.** One model per modality
29
- by default, expandable to other families via the add-model-family process.
30
- - **Audio (TTS/STT) is deferred, not delegated to tfjs** — it ships later as
31
- small *native* models (candidates under eval: VibeVoice-1.5B, OmniVoice,
32
- dots.tts-soar for TTS — IF they publish safetensors; Moonshine for STT). "What's
33
- the big deal" — launching without audio is fine; a permanent second engine is not.
34
- - **tfjs is at most temporary dev scaffolding, not a destination.** It may stay
35
- briefly to keep desktop demos working during the native build, but it is being
36
- removed, not kept as a lane. `chrome-backend.ts` is deleted outright.
37
- - **Vision uses Qwen3.5's OWN built-in ViT** (we currently skip its 192MB tower) —
38
- one multimodal model, not a separate vision model. Stop dropping it "like idiots."
39
- - **A thin onnxruntime-web bridge is a break-glass option only** — used solely if
40
- a needed model has no extractable weights AND no native alternative. Not a lane.
41
-
42
- **Status update (2026-06-13):** both next modalities have landed natively.
43
- **Embeddings ship** (Qwen3-Embedding-0.6B, validated). The **vision encoder is
44
- DONE** — the Qwen3.5 ViT runs natively and is **bit-exact vs HF transformers 5.12**
45
- (per-token cosine 1.000000). The earlier "parallel attention kernel first" gate was
46
- based on a misread of dead code (§5): the attention kernel was already parallel, and
47
- non-causal was a one-line `is_causal` flag, not a rewrite. The remaining vision work
48
- is **LM-side integration** (M-RoPE, token splice, image preprocessing) — phase 2,
49
- plumbing over a verified core. Audio follows once a native small model is validated.
50
-
51
- ## 3. Capability matrix (what's true today)
52
-
53
- Native-only. The "tfjs lane" is gone — tfjs is temporary dev scaffolding being
54
- removed (§2), not a capability path.
55
-
56
- | Modality | Native status |
57
- |---|---|
58
- | Text | ✅ ~51 tok/s mobile (sustained 200-tok), ~207 desktop, bit-correct |
59
- | Text (alt family) | ✅ **LFM2.5-350M LANDED** (`Lfm2ForCausalLM`, hybrid conv/attn): ~600 tok/s desktop (2.8× Qwen), ~46 tok/s mobile, ~199MB q4, no new kernels |
60
- | Embeddings | ✅ **DONE + ON iPad** — **EmbeddingGemma-300M** (bidirectional Gemma3 encoder, 173MB MLX-4bit) runs on iPad Safari; cos=1.00000 vs NumPy ref, Mars/bread margin >0.1, dim 768. First non-Qwen embedder. (Qwen3-Embedding-0.6B still works on desktop but OOMs iPad at 1.2GB BF16.) |
61
- | Vision (image) | ✅ **END-TO-END DONE** — Qwen3.5 ViT, bit-exact vs HF (cosine 1.000000); `describeImage()` word-identical to HF; runs on iPad |
62
- | Text model families (Llama/Mistral/Gemma) | 🟢 cheap — now usually **Tier-1, generator-only, NO new kernels** (kernel library saturated for standard transformers) |
63
- | Text (Gemma 4 E2B) | ✅ **COHERENT on q4** (`gemma4.ts`): "capital of France"→"Paris", ~83 tok/s, all 35 layers cos≥0.998 vs MLX-LM. PLE, KV-share (20 layers), proportional/dual-theta RoPE, GeGLU, `Softcap`, double-wide MLP, V-norm, per-node `attn_scale`, head_dim-512 attention. **PLE CPU-streamed (0 MB GPU)** — not GPU-sharded |
64
- | STT | 🟢 **Moonshine native LANDED** (`moonshine.ts`, `moonshine-executor.ts`, `moonshine-stt.ts`): raw-waveform Conv1d front-end (no FFT/log-mel), bit-exact `CrossAttention` kernel (max|err|<2e-4, cos≥0.9999), dual-graph encode-once/frozen-K-V/AR-decode, interleaved RoPE. Encoder cos≈0.990 vs HF; transcript substring-matches HF refs. **Whisper(ONNX) stays as multilingual / no-GPU fallback** (`src/core/stt.ts`) |
65
- | TTS | 🟡 **Kani-TTS-2 partial** (`kani_tts.ts`): NanoCodec decoder (FSQ + causal HiFi-GAN) **LANDED + validated bit-exact** (`test-nanocodec-decode.mjs`, gate err<1e-3, measured ~4.2e-6). LFM2-350M codec-LM backbone scaffolded; **AR-loop glue remaining** (frame positions + learnable RoPE + 4-token-frame decode). License: kani-tts-2-en = LFM1.0/other; 450m variant = Apache |
66
- | Memory / RAG | ✅ **SHIPPED** (`src/memory/`, `@tryhamster/gerbil/memory`): vector store (in-memory/IndexedDB/file), token-budgeted `recall()`, chunking, redaction, native EmbeddingGemma adapter. 12/12 tests. No new kernels |
67
- | No-WebGPU / old devices | not targeted — engine throws a clear error rather than degrading |
68
-
69
- ## 4. Performance baselines (re-confirm before quoting)
70
-
71
- | Platform | Config | Decode tok/s | Note |
72
- |---|---|---|---|
73
- | M4 Max, node-dawn | optimized | ~207 | re-confirm on a cooled run; numbers between commit 2f0cabc and the isMetalBackend fix are invalid |
74
- | iPad (iOS 26.5) native | batch-all | ~41 (cooled, consistent) | NOT thermal — confirmed; Dawn-tuned autoresearch wins did NOT transfer to Metal (was ~51 pre-optimization) |
75
- | iPad native, submit floor | group=1 awaited | 6–8 | proven-correct floor |
76
- | iPad transformers.js (same model) | WebGPU | 7–12 | ~5× slower than native |
77
-
78
- ## 5. Vision — DONE at the encoder level (bit-exact vs HF)
79
-
80
- The native Qwen3.5 vision encoder is **built and validated bit-exact** against HF
81
- transformers 5.12: **per-token cosine = 1.000000, max abs err ~5e-6**. Exposed as
82
- `engine.encodeImage(patches, gridTHW)` → merged image tokens `[rows, 1024]`. See
83
- paper §22 and `src/gpu/architectures/qwen3_5_vision.ts`, `src/gpu/vision-executor.ts`,
84
- `src/gpu/vision-preprocess.ts`.
85
-
86
- The earlier strategy panel claimed native vision was blocked on a single-threaded
87
- attention kernel. **That was wrong** — it read `src/gpu/kernels/wgsl/attention.wgsl`,
88
- a STALE reference file **not imported anywhere** (kernels are embedded strings in
89
- `registry.ts`; the dead `.wgsl` files have been deleted). What actually shipped:
90
-
91
- 1. **The live attention kernel was already parallel** — `WGSL_ATTENTION` is a
92
- tiled, online-softmax (flash-attention-style) kernel. No thread-0 serialization,
93
- no rewrite needed.
94
- 2. **Non-causal was a one-line flag.** An `is_causal` uniform
95
- (`S_eff = is_causal ? min(S, causal_limit) : S`) makes it bidirectional for the
96
- ViT; text stays causal by default. Done.
97
- 3. **Patch-embed was NOT a new Conv3d kernel.** Patches arrive pre-flattened to
98
- `[N, 1536]` from the host image processor, so the 5-D unfold/Conv3d collapses to
99
- a plain `MatMul` + `AddBias`. New ops added were small: `AddBias`, `GeluErf`
100
- (exact-erf merger GELU), `ApplyRotaryEmb` (2D rotary), `SliceCols` (fused-QKV
101
- split) — plus host-side pos-embed/rotary precompute (grid-only, bit-exact).
102
- 4. **A real bug surfaced during validation:** `WGSL_GELU` returned NaN for large
103
- args on Metal/Dawn (`x³` overflow into fast-math `tanh`); fixed by clamping the
104
- inner arg to ±15.
105
-
106
- **Net: vision is done at the encoder level.** Remaining work is **LM-side
107
- integration** (M-RoPE, image-token splice into the text stream, pixel→patch
108
- preprocessing) — phase 2, bounded plumbing over a verified numerical core. The
109
- ViT prefill runs through the same parallel attention as text, so there is no
110
- separate mobile attention risk; on-device ViT speed is a measure-when-integrated
111
- item, not a feasibility gate.
112
-
113
- ## 6. Build sequence (ordered)
114
-
115
- 1. ~~**Native embeddings**~~ — **DONE.** Qwen3-Embedding-0.6B (`Qwen3ForCausalLM`): last-token EOS pooling + `L2Norm` tail. Validated: dim 1024, unit norm, cos(similar)=0.81 > cos(unrelated)=0.56. Confirmed causal-LM-pooling. `engine.embed()`.
116
- 2. ~~**OPFS model cache**~~ — **resolved differently: OPFS removed.** Main-thread OPFS `createWritable` is broken on iOS (leaves unclearable junk that fills the quota). The loader is now **Cache-API-only**. Durable iOS caching needs a PWA (§ paper 24, `docs/research/ios-safari-model-caching.md`), not OPFS.
117
- 3. ~~**Native vision encoder**~~ — **DONE, bit-exact vs HF** (§5). Remaining: LM-side integration (M-RoPE, token splice, image preprocessing) — phase 2.
118
- 4. **Vision LM integration (phase 2)** — splice `encodeImage()` tokens into the text stream: M-RoPE position assignment, placeholder-token splice, host pixel→patch preprocessing. Plumbing over a verified encoder.
119
- 5. **Close the mobile WebKit correctness/perf sweep** — `?group=N` + Test-R bisect on real iOS 26.5 for a stable fast-and-correct submit config above the group=1 floor; re-measure desktop.
120
- 6. **Llama/Mistral/Gemma graph generator** — ~90% is the existing qwen2 generator; unlocks most of the HF text zoo. Low risk, high ROI.
121
- 7. **Remove tfjs scaffolding** — delete `chrome-backend.ts`. The engine is native-only; tfjs was temporary dev scaffolding, not a kept lane.
122
- 8. **Audio, native (deferred, not delegated)** — TTS: **OmniVoice** (Qwen3 backbone + codec decoder — mostly the existing text path + a decoder). STT: **Moonshine** (lean encoder-decoder; raw-waveform Conv1d frontend, no log-mel Conv2d; needs a parallel CrossAttention kernel). Ship once a native small model clears the mobile bar.
123
-
124
- ## 7. What NOT to build
125
-
126
- - **A second permanent engine / kept tfjs lane** — the architecture is native-only across text + vision + embeddings. tfjs is temporary scaffolding being removed, not a breadth lane.
127
- - **A Conv3d/unfold patch-embed kernel for the ViT** — not needed; patches arrive pre-flattened, so patch-embed is a plain MatMul + AddBias (§5).
128
- - **A heavyweight native TTS pipeline with custom vocoder kernels now** — audio is deferred; when it lands, OmniVoice's Qwen3 backbone reuses the text path. A thin onnxruntime-web bridge stays break-glass-only.
129
- - **A general Conv2d kernel / Whisper-on-native** — Moonshine's raw-waveform Conv1d avoids the log-mel Conv2d.
130
- - **An OPFS write path on iOS** — main-thread `createWritable` is broken; durable caching is a PWA concern, not an OPFS one.
131
- - **Trusting stale tok/s numbers** between 2f0cabc and the isMetalBackend fix.
132
-
133
- ## 8. Open spikes (measure before committing)
134
-
135
- - ~~**Embedder pooling direction**~~ — RESOLVED: causal-LM last-token (EOS) pooling, validated.
136
- - ~~**Parallel non-causal attention feasibility for the ViT**~~ — RESOLVED: the live attention kernel was already parallel; non-causal is a one-line `is_causal` flag; the encoder is bit-exact. Remaining ViT spike: **on-device ViT prefill speed on a real iPad** (measure when LM-integration lands; not a feasibility gate).
137
- - **Mobile WebKit submit config** — does `?group=N`/Test-R land a stable fast config above the group=1 floor on iOS 26.5? The critical path.
138
- - **Vision LM-integration correctness** — M-RoPE + token splice must stay bit-exact end-to-end (image+text), not just at the encoder boundary.
139
- - **Native audio on mobile** — OmniVoice (codec-decoder) and Moonshine (CrossAttention kernel) latency/correctness once a candidate is validated.
140
- - **Autoresearch on-device tax** — desktop kernel wins did NOT transfer to mobile (41 vs 51); the loop needs a mobile-validation leg, possibly per-backend tunings.
141
-
142
- ## 9. Decision log (this cycle)
143
-
144
- - Mobile native inference fixed (four-bug diagnosis: jetsam memory, WebKit visibility, attention race, detection predicate). See `docs/mobile-failure-diagnosis.md`, paper §17–19.
145
- - Desktop 145→~207 via autoresearch (paper §20).
146
- - **Architecture decision: NATIVE-ONLY** across text + vision + embeddings; no tfjs fallback lane; `chrome-backend.ts` to be deleted (paper §23).
147
- - **Native embeddings shipped** — Qwen3-Embedding-0.6B, last-token EOS pool + L2Norm, validated (paper §21).
148
- - **Native vision encoder shipped** — Qwen3.5 ViT, bit-exact vs HF transformers 5.12 (cosine 1.000000); LM-integration is phase 2 (paper §22). Supersedes the earlier "skip the ViT" stance (`docs/research/qwen35-multimodal.md`).
149
- - **Vision feasibility corrected** — attention was already parallel (panel read a dead `.wgsl` file); non-causal is a one-line flag (paper §22–23, §5 above).
150
- - **OPFS removed** — main-thread `createWritable` broken on iOS; Cache-API-only loader; durable caching needs a PWA (`docs/research/ios-safari-model-caching.md`, paper §24).
151
- - Modality model picks (`docs/research/sota-modality-models.md`); chromium decision (`docs/research/native-vs-chromium-decision.md`); site update plan (`docs/site-update-plan.md`).
152
-
153
- ---
154
-
155
- ## 10. 2026-06-13 evening — multimodal milestone + in-flight work (CAPTURE)
156
-
157
- **Major wins this session (all committed to `feat/webgpu-engine-mobile`):**
158
-
159
- - **Native VISION end-to-end DONE & validated bit-exact** (commit `5fed12b`). `engine.describeImage({pixels,width,height})` → coherent description. Validated vs HF transformers 5.12 on `examples/skelly.png`: 7/7 checks — encoder cosine 1.000000, M-RoPE 3D position ids EXACT, spliced embeds cosine 1.0, first-token exact, full greedy description WORD-IDENTICAL to HF for 201 chars ("This is a detailed black-and-white line drawing of the skeleton of a fox…"). New ops: `MRoPE`, `EmbedSplice`, host image preprocessing (smart-resize/normalize/patchify in `vision-preprocess.ts`). Text path unchanged (M-RoPE on linear positions reduces to 1D RoPE).
160
- - **Native EMBEDDINGS** (earlier commit): Qwen3-Embedding-0.6B works on DESKTOP (cosine 0.81>0.56). BUT **not iPad-viable** — only BF16 (~1.2GB, OOMs on-device) or a broken MLX-DWQ. → Pivot below.
161
- - **`is_causal` flag** on f32 attention (from vision) now unlocks **bidirectional encoders**.
162
-
163
- **The 51-vs-41 mobile throughput question — RESOLVED: NOT a regression.** t15 hit 51.7 on a 200-token sustained run; the 38-41 readings were 60-token runs (more warmup overhead/token). A fresh 200-token sustained run on the CURRENT (post-autoresearch-optimization) engine **hit ~51 again**. So the Dawn-tuned wins did NOT regress mobile; sustained mobile decode is ~51 tok/s. Lesson: benchmark with enough tokens (≥200) to be representative.
164
-
165
- **IN-FLIGHT / NOT YET MERGED (future-me: merge these):**
166
- - **LFM2.5-350M** — ✅ **LANDED** on `feat/webgpu-engine-mobile` (commit `3c4bac8`). Tier-1, no new kernels. **~600 tok/s desktop (2.8× Qwen3.5's ~213), ~199MB q4 (half Qwen), coherent, bit-exact vs NumPy ref.** Files: new `src/gpu/architectures/lfm2.ts` (824 lines), registered `Lfm2ForCausalLM`, LFM2 CANONICAL_KEYS, loader key-mapper. TWO GENERAL FIXES worth keeping: (1) effective FF dim is 4608 not config's 6656 (`block_auto_adjust_ff_dim` rounding — `multiple_of(⌊2/3·6656⌋)`); (2) **the "garbage output" was the CHAT TEMPLATE, not the graph** — LFM2.5 ships its template as a `chat_template.jinja` sidecar (absent from tokenizer_config.json), so the engine fell back to Qwen ChatML which auto-injects an empty `<think>` → newline loop. Fix: fetch the `.jinja` sidecar + gate think-injection on the template actually emitting `<think>`. This fix helps ANY model with a jinja sidecar. Verdict: LFM2.5 is a viable faster/smaller text-default alternative to Qwen — user picks.
167
- - **EmbeddingGemma-300M** — ✅ **LANDED + CONFIRMED ON iPad** (commit `4874d01`, see §11). The iPad-ready embedding model (~173MB q4, MTEB 68.36, standard MLX-4bit). Bidirectional Gemma3 encoder — needs the new generator + a MeanPool kernel + dual-theta RoPE + 2 Dense head layers + the MLX-detection loader fix (research found: detector requires `mode:"affine"` but standard MLX converts omit it → silently fall to F32; and DWQ vs standard MLX are config-indistinguishable → the DWQ-garbage trap). See `docs/research/sota-embedding-models.md`.
168
-
169
- **iPad harness:** dashboard at `https://<lan-ip>:8766/` with Text/Vision/transformers.js/Storage-probe/Clear-cache/Stop-queue buttons, live results table, `/results` + `/enqueue` + `/clear-queue` endpoints. Embeddings button removed until EmbeddingGemma lands. TODO: show generated text in the results + default Text benchmark to 200 tokens (representative); wire the Vision button to `describeImage` (needs browser ImageBitmap/Canvas→pixels decode).
170
-
171
- **iOS caching:** OPFS removed (main-thread createWritable broken on iOS, left unclearable junk). Durable cache needs a PWA (persist() only granted when installed). See `docs/research/ios-safari-model-caching.md`. Deferred.
172
-
173
- **Native modality scorecard (as of §10):** text ✅, vision ✅ (end-to-end bit-exact), embeddings ✅ desktop / iPad-pending (EmbeddingGemma building), LFM2.5 text-alt ✅ (pending merge). Audio (TTS/STT) deferred to native OmniVoice/Moonshine. **The native-only multimodal engine is real.** **→ All "pending/building" items above have since landed; see §11.**
174
-
175
- ---
176
-
177
- ## 11. 2026-06-14 — EmbeddingGemma on-device, LFM2.5 landed, loader hardening (CAPTURE)
178
-
179
- The §10 in-flight items all landed on `feat/webgpu-engine-mobile`. New wins this session
180
- (paper §25–§30 document each in depth):
181
-
182
- - **EmbeddingGemma-300M LANDED and CONFIRMED RUNNING ON iPad Safari** (commit `4874d01`).
183
- First **non-Qwen** embedding family — a real **bidirectional Gemma3 encoder**
184
- (`src/gpu/architectures/gemma3_encoder.ts`, `generateGemma3EncoderGraph`): 24 pre-norm
185
- blocks, GQA 3q/1kv head_dim 256, per-head q/k-norm, **dual-theta RoPE** (sliding θ=10000
186
- / full θ=1e6 selected per layer from `layer_types`), GeGLU MLP, Gemma's **four-norm
187
- sandwich**, embed ×√768, tail **MeanPool → Dense0(768→3072) → Dense1(3072→768) → L2Norm**.
188
- **173 MB at MLX-4bit** (vs the abandoned 1.2 GB Qwen3-Embedding that OOM'd iPad).
189
- Two new kernels only: **MeanPool**, **Scale** (`kernels/registry.ts`). Validated
190
- **cos=1.00000 vs an independent NumPy reference** (`scripts/engine/test-embedding-gemma-reference.py`),
191
- reference gate `cos>0.95`; semantic test asserts a Red-Planet query is closer to two
192
- Mars docs than to a bread doc by **>0.1 cosine margin**, unit-norm dim-768, no NaN. The
193
- engine **generalizes across embedding families**, not just Qwen.
194
-
195
- - **SPM tokenizer fix (load-bearing, cross-family)** (`src/gpu/tokenizer.ts`). Gemma's
196
- `tokenizer.json` is `type:"BPE"` but **SentencePiece-flavored** (▁/U+2581 spaces, raw
197
- UTF-8 tokens, array-form merges, `<0xHH>` byte-fallback). The byte-level (`Ġ`) BPE path
198
- was char-splitting every word → semantically dead embeddings that still passed norm/NaN
199
- checks. Auto-detected `spmMode` (structural: `" "→"▁"` Replace normalizer **or**
200
- `byte_fallback && "▁the" in vocab`) now drives encode/decode/merges; **Qwen/LFM2 stay
201
- byte-level** (no model-name list — they just don't match). Lesson: `type:"BPE"` ≠
202
- byte-level BPE; any SentencePiece-lineage family (Gemma/Llama/Mistral) needs this path.
203
-
204
- - **MLX-4bit loader hardened** (`src/gpu/model-loader.ts`). (1) Detection broadened to
205
- accept mode-less `{bits:4, group_size}` configs (standard mlx-lm omits `mode`). (2) A
206
- `VERIFIED_MLX_REPOS` allowlist (currently `mlx-community/embeddinggemma-300m-4bit`) gates
207
- mode-less configs. (3) **Explicit DWQ reject** — DWQ repos carry an identical
208
- `{bits:4,group_size}` config but pack weights that dequant to garbage, so they're rejected
209
- by repo-name substring (`includes("dwq")`). Codifies the MLX-DWQ-garbage trap. (4) Gemma's
210
- `(1+weight)` RMSNorm absorption is **baked by the loader even for MLX** (mlx-lm pre-absorbs
211
- +1 for Qwen3.5 but NOT for Gemma — the Gemma branch deliberately omits `&& !isMLX`).
212
-
213
- - **Progress-reporting fix** (commit `682a09b`, `model-loader.ts`). The bar froze at
214
- "10% discovering weight files" because the gap between that emit and the first download
215
- chunk (index probe + 2 header range-requests + first-byte latency) emitted nothing. Now
216
- emits "Reading {file} header" + "Downloading {file} (0/{N} MB)" up front. **Affected every
217
- model**; fixed universally.
218
-
219
- - **LFM2.5-350M landed** (commit `3c4bac8`) — Tier-1, no new kernels, ~600 tok/s desktop /
220
- ~46 tok/s mobile, ~199 MB q4. The general jinja-sidecar chat-template fix from it helps any
221
- model shipping `chat_template.jinja`.
222
-
223
- - **Cross-device multi-modal parity.** Text (Qwen3.5 ~51 tok/s, LFM2.5 ~46 tok/s), vision
224
- (Qwen3.5 ViT `describeImage`), and embeddings (EmbeddingGemma) **all now run natively on
225
- iPad Safari** — the native engine reaches transformers.js-path modality coverage on the
226
- modalities that matter, without the mobile crashes and ~5× faster. **Remaining native gap:
227
- audio** — TTS via OmniVoice (in progress), STT via Moonshine (not started).
228
-
229
- - **Effort-tier shift.** Adding a new TEXT family is now usually **Tier-1: generator only, no
230
- new kernels** — the kernel library has saturated for standard transformers (Llama/Mistral/
231
- Gemma-text reuse existing ops). New kernels are needed only for genuinely novel ops (SSM,
232
- PLE, new norms, cross-attention). See `docs/adding-a-model-family.md`.
233
-
234
- - **Site migration assessment** written: `docs/gerbil-site-native-migration.md` (how the
235
- marketing/docs site can move its in-browser inference from the transformers.js/ONNX worker
236
- to the native engine, modality-by-modality, with the no-fallback device-coverage tradeoff
237
- stated plainly). Assessment only — the site repo was not modified.
238
-
239
- ---
240
-
241
- ## 12. 2026-06-14 — native audio begins, Gemma 4, memory/RAG, autoresearch campaign (CAPTURE)
242
-
243
- This session pushed past the §11 "multimodal parity minus audio" milestone. Paper
244
- **§31–§35** document each in depth. The decided order from §6 (audio last, native not
245
- delegated) held — and audio is now *under way natively*, not deferred to tfjs.
246
-
247
- - **Native STT — Moonshine LANDED** (`src/gpu/architectures/moonshine.ts`,
248
- `moonshine-executor.ts`, `moonshine-stt.ts`; paper §31). Chosen over Whisper to avoid
249
- a log-mel/Conv2d front-end: it consumes **16 kHz PCM directly** through three strided
250
- `Conv1d`s (downsample 384×, ~41.6 frames/s) — new kernels `Conv1dFull`, `GroupNorm`,
251
- `Tanh`, `Transpose`. The real new attention primitive is **`CrossAttention`**
252
- (`WGSL_CROSS_ATTENTION`, tiled online-softmax), validated **bit-exact vs NumPy**
253
- (`test-crossattention.mjs`: max|err|<2e-4, cos≥0.9999). Runtime is a **dual graph**:
254
- `MoonshineEncoderExecutor.encode()` runs the front-end + bidirectional encoder once and
255
- freezes per-decoder-layer K/V; `MoonshineSTT.transcribe()` runs greedy AR decode with
256
- self- + cross-attention into that frozen K/V. **Interleaved RoPE** (`ROPE_INTERLEAVED_SPEC`,
257
- adjacent-dim pairing) vs the default split-half. Validation: encoder cos≈0.990 vs HF
258
- (source comment); `test-moonshine-transcribe.mjs` asserts transcript contains HF-ref
259
- substrings; RTF/4-bit size are computed-and-reported, not hardcoded-asserted.
260
- **Whisper(ONNX) stays the multilingual / no-WebGPU fallback** (`src/core/stt.ts`,
261
- `WhisperSTT`) — separate, untouched.
262
-
263
- - **Native TTS — Kani-TTS-2 (partial)** (`src/gpu/architectures/kani_tts.ts`; paper §32).
264
- The hard novel piece — the **NanoCodec decoder** (FSQ 4×4 levels `[9,8,8,7]`, mixed-radix
265
- base `[1,9,72,576]` + causal HiFi-GAN, rates `[7,7,6,3,2]`, hop 1764 @ 22050 Hz) — is
266
- **implemented and validated bit-exact** (`test-nanocodec-decode.mjs`, gate `err<1e-3`,
267
- measured ~4.2e-6 vs MLX). New kernels: `FSQDequant`, `HalfSnake1d`,
268
- `ConvTranspose1dDepthwise`. The backbone is **LFM2-350M** (`KaniTTS2ForCausalLM`, audio
269
- tokens above the text vocab, 4/frame); `generateKaniTtsGraph` **deliberately throws** —
270
- remaining is the frame-position + learnable-RoPE + 4-token-frame AR-decode glue (most
271
- block math reused from `lfm2.ts`). License: **kani-tts-2-en = LFM1.0 (other)**, NanoCodec
272
- = NVIDIA OML; the **450m variant is Apache** (same arch).
273
-
274
- - **Gemma 4 E2B — text decode COHERENT on real q4 weights** (`src/gpu/architectures/gemma4.ts`;
275
- paper §33). **Tier-2**, no MatFormer/AltUp/LAuReL. **PLE** (2nd embedding gathered per
276
- token, per-layer gate+GELU+multiply+project+norm+residual), **KV-cache sharing** (E2B: 35
277
- layers, last **20** shared via graph-rewire, no kernel change), **proportional RoPE**
278
- (rotate 0.25·head_dim=64 dims but inv_freq over full head_dim denom; dual-theta 1e6/1e4),
279
- **GeGLU**, and a new **`Softcap`** kernel (`cap·tanh(x/cap)`, cap=30) on final logits.
280
- Generates coherently ("The capital of France is" → "Paris") at ~83 tok/s; all 35 layers
281
- match an MLX-LM reference cos≥0.998 with identical argmax (`test-gemma4-perlayer.mjs`).
282
- Structural validation **67/67** (`test-gemma4-graph.mjs`; 942 nodes); softcap kernel
283
- separately validated (`test-gemma4-softcap.mjs`, max err<1e-4). **PLE is CPU-streamed, not
284
- GPU-sharded**: the ~1.17 GB q4 PLE table stays CPU-resident (**0 MB GPU**) and the executor
285
- streams per-token rows each step — Gemma 4's intended flash design, mobile-viable, and it
286
- sidesteps the per-binding cap. Coherence required four fixes: per-node `attn_scale`=1.0
287
- (HF scaling=1.0; default 1/√head_dim keeps other models byte-identical), parameter-free
288
- V-norm, double-wide MLP on the KV-shared layers, and head_dim-512 support in the flash
289
- attention kernel (second per-thread accumulator + smem-capped tiling, 16 KB invariant kept).
290
-
291
- - **On-device Memory / RAG SHIPPED** (`src/memory/`, `@tryhamster/gerbil/memory`; paper §34).
292
- Pluggable vector store (`InMemoryStore` / `IndexedDBStore` / `FileStore`), token-budgeted
293
- `recall()` (default 1024-token greedy pack, ~4-chars/token, returns `{context, records,
294
- tokensUsed}`), overlapping-window chunking (1000/200), write-time redaction (regex →
295
- `[REDACTED]` or fn), and a `createGerbilEmbedder()` adapter over **native EmbeddingGemma**.
296
- **12/12 tests** (`src/memory/memory.test.ts`). No new kernels — a clean consumer of the
297
- embedding modality.
298
-
299
- - **Autoresearch TPS campaign — 3 more batches** (`scripts/engine/results.jsonl`,
300
- `scripts/engine/chart.html`; paper §35), M4 Max / node-dawn. Verified peaks:
301
- **Qwen3.5-0.8B 219→~234 tok/s**, **LFM2.5-350M 624→~672 tok/s**, **ViT encode
302
- 581.8→~502 ms (−~14%)**, **`describeImage` 37.0→42.0 tok/s (+13.5%)** — all kept changes
303
- bit-exact (merged cos 1.0, e2e 7/7). **The winning lesson (sharpened):** desktop wins come
304
- only from eliminating **large wide reads on poorly-occupied kernels** (fused conv+activation,
305
- vec4 + register-blocked + f16-mixed ViT matmul, `MatMul+AddBias→MatMulBias`); **pure
306
- dispatch-count cuts on already-tuned kernels are noise** (butterfly reduce, subgroup
307
- shuffle, bigger N-tiles all reverted). The INT4 matmuls and Mamba SSM sit at the
308
- **bandwidth floor** — the remaining headroom is **mobile**, not desktop (several
309
- reverted-on-desktop fusions are *predicted mobile wins*; the loop's next leg is a
310
- mobile-validation pass).
311
-
312
- - **gerbil-site is LIVE on the native engine.** The marketing/docs site's in-browser
313
- inference now runs on the native WGSL engine (no longer the transformers.js/ONNX worker)
314
- for the migrated modalities — see `docs/gerbil-site-native-migration.md`. (The §11 entry
315
- was an assessment-only; this cycle it went live.)
316
-
317
- **Native modality scorecard (as of §12):** text ✅ (Qwen3.5, LFM2.5), text-alt families 🟢
318
- Tier-1, Gemma 4 E2B 🟡 (decode validated, sharding gates real weights), vision ✅ (Qwen3.5
319
- ViT, on iPad), embeddings ✅ (EmbeddingGemma, on iPad), **STT ✅ native (Moonshine) + Whisper
320
- fallback**, **TTS 🟡 (Kani NanoCodec decoder validated, backbone AR loop pending)**, memory/RAG
321
- ✅ shipped. **Audio is no longer the deferred gap — STT is native; TTS is one AR-loop away.**
@@ -1,280 +0,0 @@
1
- # Adding a Model Family to the Gerbil WebGPU Engine
2
-
3
- This is the repeatable process for teaching the native WebGPU engine a new model
4
- architecture. The engine is **not** Qwen-specific — it's a registry of graph
5
- generators over a family-agnostic IR and kernel library. Adding a family is
6
- usually "write one generator + register it," and only occasionally "write a new
7
- kernel."
8
-
9
- > TL;DR effort tiers:
10
- > - **Tier 1 (hours):** the model is Llama-like (standard transformer). Reuse existing ops; write a config→IR generator. Llama, Mistral, Gemma-text, Phi, Qwen all live here.
11
- > - **Tier 2 (days):** the model has one novel op (a new norm, sliding-window attention, a gate) OR new per-node params on existing kernels. Write the generator + 1–2 WGSL kernels.
12
- > - **Tier 3 (weeks):** the model has a fundamentally new computation (SSM/Mamba, MoE routing, dual-graph encoder-decoder, codec decoder). New kernels + executor support. Qwen3.5's Mamba-2 path was Tier 3.
13
-
14
- > **Repeatable SOP:** for the step-by-step loop use the `add-model-family` skill
15
- > (`.claude/skills/add-model-family/SKILL.md`). This doc is the reference; the
16
- > skill is the procedure. Both encode the lessons in "Lessons from production"
17
- > below — read that section first.
18
-
19
- ---
20
-
21
- ## Lessons from production (read first)
22
-
23
- A wave of families was added against this framework — Qwen3.5 (Mamba-2 SSM + ViT),
24
- LFM2.5 (hybrid conv/attn), EmbeddingGemma (bidirectional Gemma3 encoder), Moonshine
25
- STT (CrossAttention + dual-graph), Kani-TTS (LFM2 codec-LM + NanoCodec decoder),
26
- Gemma 4 E2B (PLE CPU-streaming + proportional RoPE + double-wide MLP + value-norm +
27
- head_dim-512). What actually mattered:
28
-
29
- | Family | Arch string | Tier | What was new |
30
- |---|---|---|---|
31
- | Qwen2/3 | `Qwen2/3ForCausalLM` | 1 | baseline standard transformer (the template) |
32
- | Qwen3-Embedding | `Qwen3ForCausalLM` (embedding flag) | 1 | `SliceLastRow`→`L2Norm` pooling tail, no new kernels |
33
- | Qwen3.5 | `Qwen3_5ForConditionalGeneration` | 3 | Mamba-2 SSM kernels + ViT encoder (`VisionExecutor`) |
34
- | LFM2.5 | `Lfm2ForCausalLM` | 2 | short-conv/attention hybrid; `out_proj`→`o_proj` rename |
35
- | EmbeddingGemma | `Gemma3TextModel`/`Gemma3Model` | 2 | bidirectional encoder (`causal:false`) + mean-pool + dense tail |
36
- | Moonshine STT | `MoonshineForConditionalGeneration` | 3 | new `CrossAttention` kernel; dual-graph (encoder+decoder) executor |
37
- | Kani-TTS | `KaniTTS2ForCausalLM` | 3 | LFM2 codec-LM backbone + NanoCodec decoder (FSQ + causal HiFi-GAN) |
38
- | Gemma 4 E2B | `Gemma4ForConditionalGeneration` | 2 | PLE CPU-streaming, proportional/partial RoPE, value-norm, head_dim-512, double-wide MLP, per-layer scalar — all via per-node attrs + loader hooks |
39
-
40
- 1. **VERIFY FIRST against the live checkpoint.** Fetch the live `config.json` and
41
- range-read the safetensors header (keys/dtypes/shapes) BEFORE writing anything.
42
- Confirm the arch string, dims, quant format, and classify every op. Do NOT
43
- trust assumptions from sibling models: Gemma4 had no MatFormer though Gemma3n
44
- did; OmniVoice's codec is diffusion not AR; MLX repos ship the ViT under a
45
- different key prefix (`vision_tower.*`) than HF bf16 (`model.visual.*`), and the
46
- LM under `language_model.model.*` (MLX) vs `model.language_model.*` (GPTQ/HF).
47
- Watch for **nested config** — Qwen3.5/Gemma4 put the text tower under
48
- `text_config`.
49
- 2. **Prefer per-node params over new kernels.** Most "novel" behavior is a new
50
- parameter on an existing kernel. Add it to the WGSL `Params` struct and read it
51
- in `buildParams` with a **default that reproduces the old behavior
52
- byte-identically** (`attn_scale ?? 1/sqrt(head_dim)`), so every existing caller
53
- is unchanged. Gemma4's attn_scale=1.0, partial RoPE
54
- (`rope_dim/rope_half/rope_denom/rope_active_pairs`), and per-layer `Scale`
55
- (loader-patched from `layer_scalar_key`) all landed this way — zero new attention
56
- kernels.
57
- 3. **Validate with a LOAD-ONCE reference harness — the make-or-break lesson.** Dump
58
- the HF/MLX reference activations to disk ONCE
59
- (`{tokens, per_layer_last[L][hidden], argmax, logits_top}`), then iterate
60
- engine-only in SECONDS via a single `engine.create()` + `rawForward()` +
61
- per-layer `debugReadBuffer` cosine loop (`test-gemma4-perlayer.mjs`). Reloading
62
- the 2.5GB model every cycle made Gemma4 cost an hour per iteration. Localize
63
- divergence to the exact layer/op. Set `GERBIL_NO_ACT_POOL=1` when reading early
64
- activations (the pool aliases buffers). Gate on coherent generation — bit-exact
65
- is not the bar for lossy quants.
66
- 4. **No-regression suite is mandatory for shared-kernel changes.** Keep all
67
- existing models bit-exact: `test-q4-generate`, `test-vision-e2e`,
68
- `test-crossattention`, `test-nanocodec-decode`, the embedding test, and the fast
69
- `test-gemma4-perlayer`. The byte-identical-default pattern (lesson 2) is what
70
- keeps these green.
71
- 5. **Big tensors: shard or stream.** Per-buffer caps are ~256MB
72
- (`maxBufferSize`) / ~128MB (`maxStorageBufferBindingSize`) on iPad. Shard the
73
- embedding if vocab×hidden exceeds the cap; for vocab-scale auxiliary tables keep
74
- them CPU-resident and stream per-layer slices. Gemma4's ~1.17GB PLE table has
75
- **0 MB GPU residency** — the loader builds a `PleSource`, diverts it from the
76
- weights map, and the executor uploads only the needed `[T, width]` rows per step.
77
- 6. **Merge additively, never commit node_modules.** Registry/IR/index conflicts are
78
- always additive — keep ALL families/ops from both sides. Use targeted `git add`,
79
- never `git add -A`.
80
-
81
- ---
82
-
83
- ## The architecture
84
-
85
- When a model loads, `model-loader.ts` reads `config.json` → `architectures[0]`
86
- (e.g. `"LlamaForCausalLM"`) and looks it up in the registry:
87
-
88
- ```
89
- src/gpu/architectures/index.ts → ARCHITECTURES: Record<string, GraphGenerator>
90
- ```
91
-
92
- A `GraphGenerator` turns the raw HF config into a `ModelGraph` (the IR):
93
-
94
- ```ts
95
- type GraphGenerator = (
96
- config: Record<string, unknown>,
97
- dtype?: "f32" | "q4", // q4 = on-the-fly INT4 quantization
98
- groupSize?: number, // INT4 group size (default 128)
99
- kvDtype?: "f32" | "f16", // KV cache precision
100
- ) => ModelGraph;
101
- ```
102
-
103
- The `ModelGraph` is `{ tensors, nodes, executionOrder, inputs, outputs, config, capabilities, architecture }`.
104
- The executor (`executor.ts`) consumes it generically: it allocates buffers
105
- (liveness-pooled), compiles one pipeline per node from `KERNEL_REGISTRY`, and
106
- dispatches in `executionOrder`. **The generator never touches WebGPU** — it only
107
- describes the computation.
108
-
109
- ---
110
-
111
- ## Step-by-step
112
-
113
- ### 1. Identify the family and check op coverage
114
-
115
- Read the model's `config.json` and its modeling code on HuggingFace. Classify
116
- every layer's ops and check them against what the engine already has
117
- (`KERNEL_REGISTRY` in `src/gpu/kernels/registry.ts`):
118
-
119
- **Implemented ops (reuse freely):** `Embedding`, `EmbeddingInt4`, `MatMul`,
120
- `MatMulInt4`, `Add`, `Mul`, `Scale` (per-element, loader-patchable scalar),
121
- `RMSNorm`, `LayerNorm`, `RoPE` (with optional partial-rotary attrs
122
- `rope_dim/rope_half/rope_denom/rope_active_pairs`), `Attention` (causal *and*
123
- bidirectional via the `causal` flag — set `causal: false` for an encoder/ViT;
124
- takes a per-node `attn_scale` defaulting to `1/sqrt(head_dim)`, plus
125
- `sliding_window`), `CrossAttention` (encoder-decoder), `Softmax`, `SiLU`,
126
- `SwiGLU`, `GELU` (tanh approx), `GeluErf` (exact erf), `AddBias` (row-broadcast
127
- bias), `ApplyRotaryEmb` (precomputed-cos/sin `rotate_half`), `SliceCols`
128
- (column-range extract, e.g. split a fused QKV), `L2Norm` (row-wise, embedding
129
- tail), `ResidualRMSNorm`, `KVCacheAppend`, `MambaSSM`, `CausalConv1d`,
130
- `SigmoidGate`, `ConvStateUpdate`, `SliceLastRow`, and codec ops
131
- (`Conv1d`/`ConvTranspose1d`/`Snake1d`, FSQ) for audio decoders.
132
-
133
- If the model only uses these → **Tier 1**. If it needs something new → note it;
134
- you'll write a kernel in Step 5.
135
-
136
- **Embedding models** are Tier 1: an embedding model (e.g. Qwen3-Embedding-0.6B,
137
- which is `Qwen3ForCausalLM`) is the causal-LM forward pass with a different tail —
138
- pass the `embedding` flag to `generateQwen2Graph` to swap `lm_head` for the
139
- `SliceLastRow` (last-token EOS pool) → `L2Norm` tail. No new kernels (paper §21).
140
-
141
- **Vision-capable checkpoints** (e.g. Qwen3.5) ship a ViT in the same weights; the
142
- encoder is a separate graph (`qwen3_5_vision.ts`) run by `VisionExecutor`, already
143
- built and bit-exact vs HF (paper §22). Patches arrive pre-flattened, so the
144
- patch-embed is a plain `MatMul` + `AddBias` — no Conv3d kernel.
145
-
146
- **Exotic features that need new work (flag early):**
147
- - Sliding-window / local attention (needs an attention kernel variant)
148
- - Mixture-of-Experts routing (`MoERouter`/`ExpertMatMul` are stubbed, not built)
149
- - Novel normalization (e.g. QK-norm, per-head norm) — new kernel
150
- - MatFormer / elastic parameters (Gemma 3n) — needs slicing logic + a loader story
151
- - Attention logit soft-capping (Gemma 2/3) — small kernel tweak
152
- - Non-RoPE position encodings
153
-
154
- ### 2. Map config → dimensions
155
-
156
- Every generator starts by pulling dimensions from the raw config. Copy the block
157
- from `src/gpu/architectures/qwen2.ts` and adjust names to the new model's config:
158
-
159
- ```ts
160
- const hidden_size = rawConfig.hidden_size as number;
161
- const num_layers = rawConfig.num_hidden_layers as number;
162
- const num_heads = rawConfig.num_attention_heads as number;
163
- const num_kv_heads = (rawConfig.num_key_value_heads as number) ?? num_heads; // GQA
164
- const intermediate_size = rawConfig.intermediate_size as number;
165
- const vocab_size = rawConfig.vocab_size as number;
166
- const context_length = (rawConfig.max_position_embeddings as number) ?? 32768;
167
- const rms_norm_eps = (rawConfig.rms_norm_eps as number) ?? 1e-6;
168
- const rope_base = (rawConfig.rope_theta as number) ?? 1_000_000.0;
169
- const head_dim = (rawConfig.head_dim as number) ?? Math.floor(hidden_size / num_heads);
170
- const tieWordEmbeddings = (rawConfig.tie_word_embeddings as boolean) ?? false;
171
- ```
172
-
173
- Watch for family differences: **head_dim is often NOT hidden_size/num_heads**
174
- (Gemma sets it explicitly); GQA means `num_kv_heads < num_heads`; some families
175
- have **QKV projection bias** (Qwen2 does, Llama/Gemma don't).
176
-
177
- ### 3. Write the generator
178
-
179
- Create `src/gpu/architectures/<family>.ts` exporting
180
- `generate<Family>Graph(...)`. Use the local `addTensor`/`addNode` helpers (they
181
- also push to `executionOrder`). The per-layer skeleton, following qwen2.ts:
182
-
183
- 1. **Embedding** — `Embedding`/`EmbeddingInt4` reading `input_ids` + `CANONICAL_KEYS.EMBED`.
184
- 2. **Per layer** (loop `num_layers`):
185
- - input RMSNorm → Q/K/V projections (`MatMulInt4`) → RoPE → `KVCacheAppend` → `Attention` → output projection → residual `Add`
186
- - post-attn RMSNorm → gate/up projections → `SwiGLU` → down projection → residual `Add`
187
- - (use `ResidualRMSNorm` to fuse the residual+norm where the family allows)
188
- 3. **Final norm** (`RMSNorm`).
189
- 4. **`SliceLastRow`** on the final hidden state → **lm_head** (`MatMulInt4`) → `logits`.
190
- The `[1, vocab]` logits + SliceLastRow are mandatory (saves ~485MB at long
191
- context and skips the full-vocab prefill matmul — see paper §18). Honor
192
- `tieWordEmbeddings` (reuse embed weights for lm_head).
193
-
194
- Declare intermediate tensors with `storage: "activation"` — the executor pools
195
- them automatically; don't manage buffers yourself. Set `capabilities`
196
- (`text`, `vision`, `moe`) and return the graph.
197
-
198
- ### 4. Register it
199
-
200
- In `src/gpu/architectures/index.ts`:
201
-
202
- ```ts
203
- import { generateLlamaGraph } from "./llama.js";
204
- export const ARCHITECTURES = {
205
- // ...existing...
206
- LlamaForCausalLM: generateLlamaGraph,
207
- MistralForCausalLM: generateLlamaGraph, // Mistral == Llama arch
208
- };
209
- ```
210
-
211
- One generator can serve a whole family — Llama, Mistral, and many fine-tunes
212
- share `LlamaForCausalLM`.
213
-
214
- ### 5. Weight key mapping
215
-
216
- The loader maps HF safetensors keys → canonical names via a `HFKeyMapper`
217
- (`createDefaultHFKeyMapper` strips the `model.` prefix). If the new family names
218
- weights differently, supply a mapper or set `safetensorsKey` on each `addTensor`.
219
- `CANONICAL_KEYS` has helpers (`qProj(i)`, `layerInputNorm(i)`, `EMBED`,
220
- `LM_HEAD`, …) — reuse them so the loader and generator agree.
221
-
222
- ### 6. Write any new kernel (only if Step 1 flagged one)
223
-
224
- Add to `src/gpu/kernels/registry.ts`: a WGSL string + a `KernelSpec`
225
- (`shaderCode`, `entryPoint`, `bindings`, `getDispatchSize`, `buildParams`), then
226
- register it in `KERNEL_REGISTRY` under your new `OpType` (add the op to the union
227
- in `ir.ts`). **Mobile constraints (WebKit/iPad):** workgroup memory ≤ 16 KB
228
- (`maxComputeWorkgroupStorageSize`); no `enable f16` (use packed `pack2x16float`);
229
- clamp `exp()` for Metal fast-math; avoid `select()` (use if/else). See the
230
- attention kernels for the safe patterns and the two-phase reduction.
231
-
232
- ### 7. Validate correctness (do not skip)
233
-
234
- 1. **Reference activations:** adapt `scripts/engine/test-reference.py` to dump the
235
- new model's logits + key intermediate activations from HF transformers.
236
- 2. **Compare:** run `engine.integrityCheck()` (weights + isolated dispatches +
237
- pipeline probes) and diff the engine's logits against the reference. Match the
238
- argmax and check sums within tolerance.
239
- 3. **Coherence:** generate from a fixed prompt at temperature 0 and confirm
240
- sensible text (the `scripts/engine/test-q4-generate.mjs` pattern).
241
- 4. **Cross-platform:** the desktop (Dawn) and mobile (WebKit) outputs must be
242
- byte-identical — queue an iPad run via the harness (`scripts/engine/ipad-queue.json`).
243
-
244
- ### 8. Mobile / download budget checks
245
-
246
- - **Download size at q4** is the headline mobile metric — report it.
247
- - **Per-buffer limit:** iPad `maxBufferSize` defaults to 256MB and
248
- `maxStorageBufferBindingSize` to 128MB. A single weight tensor (often the
249
- embedding) must fit — shard it if the model's vocab×hidden exceeds the cap.
250
- - **maxSeqLen policy:** the engine clamps iOS to 512 by default; large contexts
251
- multiply KV-cache memory.
252
-
253
- ---
254
-
255
- ## Worked example: the smallest possible new family (Llama)
256
-
257
- Llama is Qwen2 minus QKV bias. The fastest path:
258
- 1. Copy `qwen2.ts` → `llama.ts`, rename the export.
259
- 2. Remove the QKV-bias tensors/handling (Llama has none).
260
- 3. Confirm head_dim, GQA (`num_key_value_heads`), and `tie_word_embeddings` from config.
261
- 4. Register `LlamaForCausalLM`/`MistralForCausalLM` → `generateLlamaGraph`.
262
- 5. Validate against a reference (Step 7). No new kernels needed — Tier 1.
263
-
264
- This single generator unlocks Llama, Mistral, and every model that ships as
265
- `LlamaForCausalLM` on HuggingFace.
266
-
267
- ---
268
-
269
- ## Checklist
270
-
271
- - [ ] Classified every op; new ops listed (or confirmed none)
272
- - [ ] `generate<Family>Graph` written, dimensions mapped from config
273
- - [ ] GQA / head_dim / QKV-bias / tied-embeddings handled
274
- - [ ] `SliceLastRow` + `[1, vocab]` logits in place
275
- - [ ] Registered in `ARCHITECTURES`
276
- - [ ] Key mapping verified (loader finds every weight)
277
- - [ ] New kernels (if any) respect the 16 KB / no-`enable f16` / clamped-`exp` mobile rules
278
- - [ ] Validated vs HF reference (logits argmax + coherence)
279
- - [ ] Desktop and iPad outputs byte-identical
280
- - [ ] Download size at q4 reported; largest weight fits the 256MB/128MB buffer caps