mlx-bun 0.0.7 → 0.0.9

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 (138) hide show
  1. package/README.md +112 -20
  2. package/docs/design/batching-v2-plan.md +515 -0
  3. package/docs/design/bucketing-stage.md +196 -0
  4. package/docs/design/compat-cli-surface-design.md +11 -11
  5. package/docs/design/diffusion-gemma-port.md +602 -0
  6. package/docs/design/docs-reorg-plan.md +1 -1
  7. package/docs/design/dreaming-nightly-pipeline.md +291 -0
  8. package/docs/design/dspark-speculative-decoding.md +106 -0
  9. package/docs/design/generic-model-support.md +381 -0
  10. package/docs/design/memory-inference-path.md +422 -0
  11. package/docs/design/memory-synthesis.md +287 -0
  12. package/docs/design/minicpm5-decode-megakernel.md +484 -0
  13. package/docs/design/mlx-lm-tool-parity-plan.md +535 -0
  14. package/docs/design/orpo-dynamic-lambda.md +41 -0
  15. package/docs/design/orpo-training.md +35 -5
  16. package/docs/design/parallel-slots.md +12 -1
  17. package/docs/design/parity-tier-dag.md +13 -5
  18. package/docs/design/spec-decode-larger-targets.md +229 -0
  19. package/docs/design/tauri-desktop-app.md +2 -2
  20. package/docs/design/the-dreaming-handoff.md +141 -0
  21. package/docs/design/the-dreaming-master-plan.md +446 -0
  22. package/docs/design/write-pipeline-entity.md +468 -0
  23. package/docs/investigations/curve-bisector-routing.md +1 -1
  24. package/docs/investigations/decode-roofline-lookagain.md +262 -0
  25. package/docs/investigations/dspark-handoff.md +58 -0
  26. package/docs/investigations/kernel-perf-review-2026-07.md +92 -0
  27. package/docs/planning/PRODUCT_ROADMAP.md +2 -2
  28. package/docs/planning/curve-sampler-research-plan.md +331 -0
  29. package/docs/planning/memory-docs-and-dag-plan.md +185 -0
  30. package/docs/planning/pi-integration-review.md +178 -0
  31. package/docs/planning/release-notes-v0.0.9.md +122 -0
  32. package/docs/planning/web-ui-pass-plan.md +213 -0
  33. package/docs/planning/website-readme-pass-plan.md +224 -0
  34. package/docs/reference/cli.md +255 -0
  35. package/docs/reference/embedding.md +7 -2
  36. package/docs/reference/library-api.md +22 -3
  37. package/docs/reference/memory.md +5 -5
  38. package/docs/reference/models.md +137 -0
  39. package/docs/reference/orpo-quickstart.md +6 -0
  40. package/docs/reference/server-api.md +187 -9
  41. package/docs/reference/server-config.md +40 -9
  42. package/docs/reference/training.md +25 -11
  43. package/package.json +1 -1
  44. package/src/anthropic.ts +22 -0
  45. package/src/assets/curve-designer.html +1 -1
  46. package/src/chat-template.ts +25 -7
  47. package/src/cli.ts +1029 -86
  48. package/src/config.ts +54 -3
  49. package/src/diffusion/diffusion-generate.ts +436 -0
  50. package/src/download.ts +99 -8
  51. package/src/embed.ts +77 -0
  52. package/src/eval/perplexity.ts +164 -0
  53. package/src/eval/runner.ts +19 -7
  54. package/src/eval/tasks/bfcl.ts +1 -1
  55. package/src/generate.ts +196 -19
  56. package/src/harness-pi.ts +43 -17
  57. package/src/index.ts +2 -0
  58. package/src/lora.ts +2 -2
  59. package/src/memory/article.ts +558 -0
  60. package/src/memory/chunk-validation.ts +150 -0
  61. package/src/memory/chunk.ts +305 -12
  62. package/src/memory/cluster.ts +344 -17
  63. package/src/memory/coverage.ts +134 -0
  64. package/src/memory/crosslink.ts +0 -0
  65. package/src/memory/db.ts +184 -45
  66. package/src/memory/entity.ts +203 -0
  67. package/src/memory/gate.ts +187 -0
  68. package/src/memory/history.ts +152 -0
  69. package/src/memory/ingest.ts +324 -11
  70. package/src/memory/model.ts +321 -0
  71. package/src/memory/normalize.ts +671 -0
  72. package/src/memory/parse.ts +22 -0
  73. package/src/memory/pipeline.ts +242 -30
  74. package/src/memory/prompts.ts +42 -0
  75. package/src/memory/query.ts +334 -0
  76. package/src/memory/reconcile.ts +734 -0
  77. package/src/memory/redirect.ts +108 -0
  78. package/src/memory/reindex.ts +325 -0
  79. package/src/memory/resolve.ts +307 -0
  80. package/src/memory/route.ts +272 -0
  81. package/src/memory/schedule.ts +6 -4
  82. package/src/memory/stages.ts +774 -0
  83. package/src/memory/synthesize.ts +1629 -20
  84. package/src/memory/tools.ts +446 -96
  85. package/src/memory/vault.ts +462 -35
  86. package/src/memory/wikify.ts +1057 -16
  87. package/src/mlx/ffi.ts +11 -0
  88. package/src/mlx/ops.ts +113 -0
  89. package/src/model/compiled-decode.ts +43 -8
  90. package/src/model/diffusion-gemma.ts +1026 -0
  91. package/src/model/factory.ts +35 -8
  92. package/src/model/flash-attention.ts +4 -2
  93. package/src/model/fused-decode-kernel.ts +14 -7
  94. package/src/model/fused-mlp-kernel.ts +169 -0
  95. package/src/model/fused-swiglu-kernel.ts +240 -0
  96. package/src/model/gemma4-base.ts +62 -6
  97. package/src/model/gemma4.ts +33 -2
  98. package/src/model/minicpm5.ts +106 -8
  99. package/src/model/qwen3.ts +276 -0
  100. package/src/model/steel-linear-kernel.ts +96 -0
  101. package/src/model/support.ts +45 -7
  102. package/src/model/universal/archs.ts +332 -0
  103. package/src/model/universal/dense.ts +576 -0
  104. package/src/model/universal/modules.ts +163 -0
  105. package/src/model/universal/rope.ts +366 -0
  106. package/src/pi-provider.ts +1 -1
  107. package/src/pi-terminal.ts +29 -8
  108. package/src/pi-web.ts +19 -2
  109. package/src/quantize/config-writer.ts +1 -1
  110. package/src/registry.ts +215 -7
  111. package/src/responses.ts +23 -0
  112. package/src/sampler.ts +220 -9
  113. package/src/serve/batch-scheduler.ts +272 -80
  114. package/src/serve/generation-gateway.ts +90 -18
  115. package/src/server.ts +643 -50
  116. package/src/spec/drafter.ts +81 -49
  117. package/src/spec/dspark/data-dflash.ts +156 -0
  118. package/src/spec/dspark/data.ts +201 -0
  119. package/src/spec/dspark/generate-dflash.ts +193 -0
  120. package/src/spec/dspark/generate.ts +290 -0
  121. package/src/spec/dspark/loss.ts +213 -0
  122. package/src/spec/dspark/module-dflash.ts +361 -0
  123. package/src/spec/dspark/module.ts +540 -0
  124. package/src/spec/dspark/sample.ts +112 -0
  125. package/src/spec/generate.ts +40 -19
  126. package/src/status-page.html +1 -1
  127. package/src/tokenizer.ts +7 -0
  128. package/src/train/diffusion-lora.ts +216 -0
  129. package/src/train/flash-cce.ts +70 -15
  130. package/src/train/fuse.ts +243 -0
  131. package/src/train/index.ts +3 -0
  132. package/src/train/job.ts +8 -0
  133. package/src/train/loss.ts +289 -30
  134. package/src/train/prefix-shared.ts +33 -5
  135. package/src/train/segmented.ts +67 -11
  136. package/src/train/trainer.ts +92 -28
  137. package/src/vision/diffusion-vision.ts +620 -0
  138. package/src/web/skills/memory/SKILL.md +40 -17
@@ -0,0 +1,262 @@
1
+ # Decode perf "look again" — adversarial re-exam of the M=1 floor claim (2026-07-01)
2
+
3
+ **Machine:** Apple M1 Max, 32 GB (MacBookPro18,2), `sysctl` verified. All eval-DB
4
+ rows are also M1 Max — same box. **All numbers below are directional (session,
5
+ loaded-machine caveat); quotable numbers remain benchmark.sh-gated.** GPU idle
6
+ verified before every probe (one contaminated bandwidth run was discarded and
7
+ re-run; another agent's `bun test` was live during it).
8
+
9
+ **Mandate:** re-attack the PLAN-archive megakernel post-mortem conclusion —
10
+ "mlx per-op decode = 4.62 ms vs ~4.5 ms pure weight-read floor (~0.12 ms
11
+ overhead, near optimal)" — the way the ORPO backward was attacked.
12
+
13
+ ## Verdict up front
14
+
15
+ **The floor claim was wrong.** The ~4.5 ms "pure weight-read floor" for CPM5 was
16
+ never derived from measured bandwidth and overstates the true floor by ~70%:
17
+
18
+ - CPM5 reads **0.694 GB** of weights/token (safetensors-header accounting:
19
+ 0.448 GiB layers + 0.198 GiB untied lm_head; the 0.198 GiB embed table is
20
+ row-gathered, not streamed). The old "~1 GB" figure counted the embed table.
21
+ - Measured achieved bandwidth on this M1 Max: **~337 GB/s raw streaming read**
22
+ (4 GiB bf16 sum), **~250–295 GB/s in mlx's own `quantized_matmul` GEMV** at
23
+ decode shapes (large matrices). 4.5 ms for 0.694 GB implies 154 GB/s — no
24
+ measurement supports that.
25
+ - True CPM5 floor: **~2.6 ms/tok** at GEMV-achieved BW (~2.1 ms at raw-read BW).
26
+ Production-shaped decode measures **4.06 ms/tok**. That is **~64% of the
27
+ measured roofline**, not 97%.
28
+
29
+ The megakernel was still right to shelve (it was slower for its own reasons),
30
+ but "mlx is already at the floor" is false for every model except the 12B.
31
+ There is ~1.4 ms/tok recoverable on CPM5 (+35–55%), ~5–7 ms on e4b (+30–50%),
32
+ ~8 ms on the 26B (+40–60%), and ~3 ms (~9%) on the 12B.
33
+
34
+ Two inconsistencies in the record corroborate that the old floor was never
35
+ measured: `megakernel-perf.ts`'s own comment says "floor ~394 tok/s" (2.54 ms —
36
+ 0.694 GB at the M4 Pro's 273 GB/s spec sheet), while the post-mortem says
37
+ ~4.5 ms; and the production eval-DB h2h rows (255–266 tok/s = 3.76–3.92 ms)
38
+ were ALREADY faster than the claimed 4.5 ms "floor" when the post-mortem was
39
+ written.
40
+
41
+ ## 1. Measured bandwidth (this machine, idle, `decode-roofline-bw.ts`)
42
+
43
+ | probe | result |
44
+ |---|---|
45
+ | raw streaming read, bf16 sum 1/2/4 GiB | 299 / 320 / **337 GB/s** |
46
+ | qmv 4-bit GEMV 540 MiB (12B tied head) | 2.12 ms → **268 GB/s** |
47
+ | qmv 4-bit GEMV 360 MiB (e4b tied head) | 1.31 ms → **289 GB/s** |
48
+ | qmv 4-bit GEMV 108 MiB (CPM5 head) | 0.45 ms → **249 GB/s** |
49
+ | qmv 8-bit GEMV 60 MiB | **295 GB/s** |
50
+ | qmv 4-bit GEMV 32 MiB (12B MLP) | **256 GB/s** |
51
+ | qmv 4-bit GEMV 3.8 MiB (CPM5 MLP) | 0.022 ms → **183 GB/s** |
52
+ | qmv 4-bit GEMV 1.3 MiB (small qkv) | 0.013 ms → **100 GB/s** |
53
+ | bf16 GEMV 113 MiB | **296 GB/s** |
54
+ | dependent tiny-op chain (in one eval) | **~10–15 µs/op** incl. host encode |
55
+
56
+ GEMVs were chained back-to-back inside one eval over distinct matrix copies
57
+ (cycling ≥ SLC) — the in-step cost, not eval round-trip latency. Methodology
58
+ trap worth recording: mlx is lazy — disposing unevaluated outputs silently
59
+ skips their compute; the first draft of this probe "measured" 4.4 TB/s.
60
+
61
+ So: mlx's `qmv_fast` reaches **74–88% of raw machine bandwidth on large
62
+ matrices** and degrades hard below ~10 MiB (fixed per-kernel cost). Small-model
63
+ decode is a mix of both regimes.
64
+
65
+ ## 2. Weights + KV bytes per decode token (safetensors headers, exact)
66
+
67
+ | model | streamed weights/tok | how |
68
+ |---|---|---|
69
+ | CPM5-1B | **0.694 GB** | 0.448 layers + 0.198 lm_head (untied; embed row-gathered) |
70
+ | e4b | **3.536 GB** | 2.547 layers + 0.664 tied head + 0.082 altup; 2.789 GiB per-layer embeds are ROW-gathered; vision/audio 0.891 GiB untouched |
71
+ | 12B | **8.860 GB** | 7.255 layers + 0.996 tied head |
72
+ | 26B-A4B | **3.444 GB** | 1.597 dense + 0.730 tied head + 8/128 × 14.091 GiB experts (top_k 8 of 128, all 30 layers) |
73
+
74
+ KV read/token (bf16): CPM5 24.6 KB/pos (24L·2kv·128d); e4b 7 full + 35
75
+ sliding@512 (2kv·256d) → 45 MB @600, 154 MB @8k; 12B 8 full + 40 sliding@1024
76
+ (8kv·256d) → 236 MB @600, 872 MB @8k; 26B 5 full + 25 sliding@1024 → 147 MB @600.
77
+
78
+ ## 3. Roofline table (floor at 270 GB/s GEMV-achieved; ceiling at 337 GB/s raw)
79
+
80
+ Measured with `decode-roofline-step.ts` (mirrors generateInner's pipelined
81
+ loop; greedy; bf16 KV; clearCache cadence; two passes each; uncompiled arm
82
+ unless noted).
83
+
84
+ | model @ctx | bytes/tok | floor ms (270) | ceiling tok/s (337) | measured ms (tok/s) | GPU ms | host graph ms | read ms | % of floor-roofline |
85
+ |---|---|---|---|---|---|---|---|---|
86
+ | CPM5 @132 | 0.70 GB | 2.58 | 483 | 4.06 (246) | 3.0 | 1.0 | 0.02 | **64%** |
87
+ | CPM5 @4k | 0.80 GB | 2.94 | 424 | 5.03 (199) | 4.0 | 1.0 | 0.02 | **58%** |
88
+ | e4b @600 | 3.58 GB | 13.3 | 94 | 18.9 (53.0) | 15.1 | 3.6 | 0.03 | **70%** |
89
+ | e4b @600 compiled | 3.58 GB | 13.3 | 94 | 18.1 (55.2) | 16.8 | 1.2 | 0.03 | 73% |
90
+ | e4b @8k | 3.69 GB | 13.7 | 91 | 21.3 (46.9) | 17.4 | 3.5 | 0.03 | **64%** |
91
+ | e4b @8k compiled | 3.69 GB | 13.7 | 91 | 21.5 (46.5) | 20.2 | 1.3 | 0.03 | 64% |
92
+ | 12B @600 | 9.10 GB | 33.7 | 37 | 36.8 (27.2) | 33.0 | 3.4 | 0.03 | **92%** |
93
+ | 12B @8k | 9.73 GB | 36.0 | 35 | 37.5–40.9 (26.6–24.4) | 33.2–36.1 | 3.4 | 0.03 | **~93%** |
94
+ | 12B @8k compiled | 9.73 GB | 36.0 | 35 | 39.4–41.6 | 37.0–39.7 | 1.9 | 0.03 | (thermal drift muddies the arm A/B) |
95
+ | 26B @600 | 3.59 GB | 13.3 | 92 | 21.5–22.3 (46.5–44.8) | 17.3 | 3.7 | 0.02 | **60–62%** |
96
+
97
+ (12B pass-to-pass drift @8k was ~8% — machine warming across the long runs;
98
+ within-run medians are the trustworthy split.)
99
+
100
+ **The inversion:** the bigger the model, the closer to the roofline. The 12B's
101
+ GPU time IS the bandwidth floor (its GEMVs are all in the 250–295 GB/s regime
102
+ and its dispatch count amortizes); the small/sparse models leave 30–40% on the
103
+ table. The old conclusion was accidentally ~true for the 12B only — it was
104
+ derived on CPM5, where it is most wrong.
105
+
106
+ ## 4. Gap decomposition
107
+
108
+ Per-step wall time = GPU step + host graph build + readback, **serial** (PLAN's
109
+ structural finding re-confirmed: async_eval hides only the ~0.03 ms token read,
110
+ never the graph build — measured directly in every row above).
111
+
112
+ **(a) Weight+KV read floor** — §3 table. Dominant everywhere; the only true
113
+ "physics".
114
+
115
+ **(b) GPU overhead above floor** (dispatch gaps + small-GEMV inefficiency +
116
+ elementwise/norm/rope kernels):
117
+ - CPM5: 0.4 ms @132 rising to 1.0 @4k (KV-append/attention kernels are in the
118
+ 100–183 GB/s small-buffer regime).
119
+ - e4b: **1.8 @600 → 3.7 ms @8k** — the worst dense offender. 42 layers of
120
+ per-layer-input machinery (gate/proj GEMVs ~1–2 MiB each = the 100 GB/s
121
+ regime, ×42), altup ops, KV-share plumbing → dispatch count several hundred
122
+ per token at ~5–15 µs each.
123
+ - 12B: ~0 (at floor).
124
+ - 26B: **~4.0 ms** — gather-qmm expert GEMVs: each expert slice is ~3.3 MiB
125
+ (2816×704×3 mats, 4-bit) read at the ~180 GB/s small-buffer rate, ×8 experts
126
+ ×30 layers, plus router argpartition/take chains.
127
+ - Corroboration: the dependent tiny-op chain costs ~10–15 µs/op; a ~200–400
128
+ dispatch decode step predicts 2–5 ms of pure serialization if nothing
129
+ overlaps, consistent with the observed overheads.
130
+
131
+ **(c) Host JS loop** — the single biggest NON-physics term across models:
132
+ graph build 1.0 ms (CPM5) / 3.4–3.7 ms (e4b, 12B, 26B) per token, serial with
133
+ the GPU. Sampler readback is already free (0.02–0.03 ms, pipelined).
134
+ clearCache cadence already mlx-lm-faithful.
135
+
136
+ **(d) Compiled decode reality check** (suspect d):
137
+ - e4b (whole-graph form): graph 3.5→1.2 ms but GPU +1.7 ms (the concat-fetch
138
+ materializes each growing cache's window every step) → net **+3.6% @600,
139
+ ~0 @8k**. The trade is real and grows with context.
140
+ - 12B (segmented form): **@600 it compiles NOTHING** — sliding rings only
141
+ enter ring phase at offset ≥ window (1024), and the 8 full-attention layers
142
+ are concat-phase (never compiled) forever. So at short context the default
143
+ MLX_BUN_COMPILED_DECODE=1 delivers zero and the full 3.4 ms host tax stands.
144
+ @8k it halves the host term (3.6→1.9 ms); net effect within thermal noise
145
+ today, historically +0–1%.
146
+ - CPM5 / Qwen / 26B-MoE: **no compiled decode exists at all** (gemma4-dense
147
+ gate in generate.ts:512-516). CPM5 pays 25% of its step in host graph build.
148
+
149
+ ## 5. Suspect-by-suspect verdicts (2026-07-01 kernel review)
150
+
151
+ **(a) Backlog #4 — fused decode kernel's 6 ensureRowContiguous copies/layer/step: CONFIRMED structurally.**
152
+ `fused-decode-kernel.ts:227,234` build both kernels with
153
+ `ensureRowContiguous: true`; the dispatch site passes step-padded fetch VIEWS,
154
+ non-contiguous whenever offset < capacity → mlx copies all six
155
+ packed/scales/biases arrays per quantized full-attention layer per step.
156
+ Order-of-magnitude at 12B @8k (8-bit KV): ~38 MB/layer × 8 full layers ≈
157
+ 300 MB/step ≈ 1–2 ms ≈ 3–5% — matches the review's 1–3% @8k and grows linearly
158
+ with context. Note this only helps the kv=config arm, which today is SLOWER
159
+ than bf16 KV (eval DB: 12B @16k 24.7 vs 27.3; CPM5 209 vs 255) — this fix
160
+ narrows the quantized-KV speed tax, it does not move the bf16 headline.
161
+
162
+ **(b) qmv_fast port → live kernel: NOTHING TO FLOW.** Live weight GEMVs go
163
+ through `ops.quantizedMatmul` (gemma4-base.ts:121,198) = mlx's own `qmv_fast`
164
+ — the thing the megakernel port was catching up TO (0.70→0.94x, never above
165
+ 1.0). The live perf kernel (fused SDPA) already uses the same quantized.h qdot
166
+ pattern (fused-decode-kernel.ts:47-55 comment, predates the megakernel per
167
+ PLAN.md:1109-1130). Review's claim verified correct; no action.
168
+
169
+ **(c) "Megakernel could win at M=K": AGREE WITH THE REVIEW — recorded
170
+ misleadingly.** The post-mortem's own numbers show the megakernel losing at
171
+ M=1 even with zero barriers (4.95 vs 4.62) on the atomic-coherence tax and a
172
+ 0.94x GEMV. At M=K, mlx ALSO amortizes: the live spec-decode verify is already
173
+ one batched forward sharing the weight read, and mlx's steel GEMM kernels are
174
+ strongest exactly at small-M GEMM. Nothing measured supports the megakernel
175
+ overtaking at M=K. The banked learning should read: "M=K amortizes the
176
+ per-forward fixed cost for ANY engine; the megakernel's specific coordination
177
+ primitives were measured net-negative." The real M=K lever is the small-L
178
+ flash-decoding SDPA kernel (review opportunity) + spec decode.
179
+
180
+ **(d) Compiled decode: see §4(d).** On by default where applicable, but it
181
+ delivers far less than its billing: nothing at 12B short-context (window
182
+ phase-gating), a wash on e4b @8k (concat tax), absent on CPM5/MoE. The 3.4 ms
183
+ host term it was built to kill is still ~85–100% alive at short context.
184
+
185
+ **(e) e4b prefill gap: NOT REPRODUCIBLE ON THIS MACHINE — the RESULTS.md row
186
+ is suspect, profile on the other laptop before building anything.**
187
+ - RESULTS.md says e4b prefill 304 (ours) vs 373 (mlx-lm). This machine's eval
188
+ DB has NO such rows (e4b prefill rows: ours 505–725 tok/s @600–16k; the only
189
+ oracle e4b rows are @24–31 ctx where "prefill tok/s" is meaningless).
190
+ - Measured today, same prompt, this machine: ours 689 tok/s @3266 (probe,
191
+ in-process), mlx-lm 715–763 tok/s @3266 (two runs, cross-process). Gap ≈
192
+ −4 to −10% directional, thermally muddy — nowhere near −20%.
193
+ - Flag arms @2048: FUSED_GELU=0 changes prefill ~nothing (2.31→2.36 s) but
194
+ costs −7% DECODE (18.4→19.9 ms — the fused GeGLU is a decode win); fused
195
+ SDPA off: no prefill change.
196
+ - Conclusion: the 304/373 row most likely came from the M4 Pro or a stale
197
+ build. Re-benchmark there before spending on backlog #10. (Also noted: the
198
+ oracle venv's mlx-lm cannot even load the 12B — `gemma4_unified not
199
+ supported` — so the 12B baseline rows came through some other path.)
200
+ - Bonus decode observation while pairing: mlx-lm e4b decode measured 61.3
201
+ tok/s over 8 tokens but 34.0 tok/s over 64 tokens in back-to-back runs —
202
+ cross-process decode comparisons at this granularity are thermal noise;
203
+ trust the recorded paired result (−5% @short) and the in-process split.
204
+
205
+ ## 6. Ranked fix plan (estimated wins are directional, this machine)
206
+
207
+ 1. **Kill/hide the serial host graph-build tax** — the largest cross-model,
208
+ non-physics term (CPM5 25%, e4b 17%, 26B 17%, 12B 9% of step):
209
+ 1a. **CPM5 (and Qwen): extend CompiledDecode beyond gemma4.** CPM5 is
210
+ dense, no per-layer inputs, no MoE — the EASY shape (whole-graph, no
211
+ concat-tax caveat beyond growing KV, same as 12B's ring layers after
212
+ window). Worth ~0.8 ms/tok ≈ **+20–25% CPM5 decode**. Effort M.
213
+ 1b. **Research spike: overlap graph build with the GPU instead of
214
+ compiling it away.** Today asyncEvalAll(step n+1) blocks until step n
215
+ drains and the build happens outside that window. If the build of step
216
+ n+2 can run while step n's buffer drains (build-two-ahead, or move the
217
+ blocking wait off the loop thread), the host term hides under the GPU
218
+ for EVERY model with zero numerics risk — this would also beat mlx-lm's
219
+ loop, which pays the same serial cost (their pybind build is just
220
+ cheaper). Effort S to spike, M to land. **This is the "no way we can't
221
+ be faster" candidate.**
222
+ 1c. **e4b: SharedKv segmented compile plumbing** (already-scoped review
223
+ item) so e4b gets graph 3.5→~1.2 without the whole-graph concat tax:
224
+ ~**+10–12% e4b**, more at long context. Effort L.
225
+ 1d. **12B short-context: compile the concat phase too** (or accept 1b as
226
+ the fix). The current segmented form compiles nothing below the 1024
227
+ window and never compiles the 8 full-attention layers. ~+9% @600.
228
+ 2. **26B GPU overhead (~4 ms/tok over floor):** profile gather-qmm expert
229
+ reads (each expert slice ~3.3 MiB → the ~180 GB/s small-buffer regime);
230
+ candidates: expert-contiguous layout so 8 experts read as fewer/larger
231
+ spans, the open perf-kernel enablement (review #7, +1–3%), router-chain op
232
+ fusion. Potential **+15–25% 26B decode** if expert reads reach big-GEMV
233
+ bandwidth. Effort M (profile first).
234
+ 3. **e4b GPU overhead (1.8–3.7 ms):** dispatch-count reduction on the
235
+ per-layer-input machinery (the ~1–2 MiB gate/proj GEMVs and altup
236
+ elementwise chains; batch the 42 per-layer gate GEMVs into one [42·width]
237
+ GEMM where semantics allow). **+8–15% e4b.** Effort M–L.
238
+ 4. **Backlog #4 (ensureRowContiguous full-capacity buffers + activeN):**
239
+ validated; ~3–5% on the kv=config arm @8k, ~4x that @32k. Small, safe,
240
+ makes quantized KV stop losing to bf16 on speed. Effort S.
241
+ 5. **CPM5 @4k KV-path overhead (GPU 3.0→4.0 ms while KV adds only 0.35 ms of
242
+ bytes):** the attention/append kernels at CPM5's small KV shapes run in the
243
+ ~100–180 GB/s regime; candidates: the existing fused-decode kernel path for
244
+ CPM5 (currently gemma-shaped sites only?) or upstream sdpa-vector tuning.
245
+ ~+10% CPM5 @4k+. Effort M (profile first).
246
+ 6. **Spec decode (M=K)** remains the only lever that beats the 12B's
247
+ bandwidth wall (weight read shared across K tokens) — unchanged priority,
248
+ now with the roofline to prove why nothing else can.
249
+
250
+ ## Probes added (scripts/experiments/, tsc-clean)
251
+ - `decode-roofline-bw.ts` — machine bandwidth: raw read, decode-shaped qmv
252
+ GEMV (multi-copy, one-eval chaining), bf16 GEMV, dispatch chain.
253
+ - `decode-roofline-step.ts` — factory-generic pipelined decode split
254
+ (graph/dispatch/read) with `--compiled` arm, any model/context.
255
+
256
+ ## Standing-rule notes
257
+ - Pre-existing tsc error in `src/eval/runner.ts:161` (kvBits on a Pick union)
258
+ in Josh's working tree — not introduced here, not fixed here (outside the
259
+ edit boundary for this task).
260
+ - RESULTS.md "Direct" table's e4b prefill row contradicts this machine's eval
261
+ DB (no supporting rows) — per the verify-against-evaldb rule it needs a
262
+ machine label or a re-run on the M4 Pro.
@@ -0,0 +1,58 @@
1
+ # DSpark — handoff
2
+
3
+ **State:** faithful DSpark (DFlash KV-injection + Markov + confidence) is **built
4
+ and proven architecturally correct** (overfit τ=3.24, paper-range). It does not
5
+ yet net a speedup on e4b — that's a data-scale + target-speed problem, not an
6
+ architecture problem. Full design + measured numbers:
7
+ [docs/design/dspark-speculative-decoding.md](../design/dspark-speculative-decoding.md).
8
+
9
+ ## What happened (short version)
10
+ - Built v1 first as a single-vector shortcut — it dropped the paper's core KV
11
+ injection and was never really DSpark. Chunk (τ≈1.26) and article (τ≈1.16)
12
+ runs on it were misleading.
13
+ - Rebuilt the **faithful** DFlash (multi-layer H_ctx injected into every draft
14
+ layer, 5 layers) in parallel `*-dflash.ts` files (v1 kept as baseline; repo
15
+ stays green).
16
+ - Found + fixed an **off-by-one in the p^t target** (TV loss trained against a
17
+ distribution shifted one token — present in v1 too, so all prior τ were bogus).
18
+ - **Overfit test settled it:** 3 articles, eval on same → per-pos ~0.75, τ=3.24.
19
+ The architecture reaches the paper's numbers; the plateau at ~0.17 on 160
20
+ articles is data-starvation, not capacity (confirmed: width 1024 vs 2560 both
21
+ plateau ~0.17).
22
+ - **Target-speed is the other half.** Measured decode: e4b 45.9, 12b 27.5, 27B
23
+ ~15 tok/s. The fixed draft overhead only amortizes on a slow target — so e4b
24
+ is ~worst-case for spec decode; the **27B agentic workload is the real target**
25
+ (τ≈3 there could plausibly net ~2–3× → 15 → ~35–45 tok/s).
26
+
27
+ ## Verified / working
28
+ - Parity-safe `hiddenTap` multi-layer extraction (`gemma4.ts`), no-op when off.
29
+ - `trim(n, bypass=true)` physical-slice rollback past the sliding window (`gemma4-base.ts`) — lossless gate held on 6K context.
30
+ - CPU smoke 16/16 (`dspark-dflash-smoke.ts`): KV-injection forward, autograd, inference, multi-layer variable-context data round-trip.
31
+ - Training `--resume` (warm-start from checkpoint) — the GPU runs kept getting killed ~step 5000; resume survives that.
32
+
33
+ ## Next (in priority order)
34
+ 1. **Retarget to a slow model (27B or 12b).** The drafter reads dims from the
35
+ model + tapLayers is config, so it ports — but needs regen+train on that
36
+ model. 27B on 32GB is memory-tight (17.75GB weights); may need the serve
37
+ process stopped to free the ~14GB for regen. This is where a real speedup lives.
38
+ 2. **Scale training data** — thousands of on-distribution generations (not 160)
39
+ to lift generalizing τ toward the overfit ~0.75.
40
+ 3. **Tighten the draft inference loop** — per-position host syncs + double 262K
41
+ LM-head make the draft heavy; needed for τ to translate to wall-clock.
42
+ 4. **Finish the paper:** RNN head (Eq 6), STS calibration (§3.2.1), hardware-aware
43
+ prefix scheduler (Alg 1 — single-user = confidence-scheduled draft-length pruning).
44
+ 5. **Rename** `dflash`→`dspark` (faithful module IS DSpark; v1 = legacy single-vector).
45
+
46
+ ## Key files
47
+ `src/spec/dspark/{module,data,generate}-dflash.ts`, `{loss,sample}.ts`;
48
+ `src/model/gemma4.ts` (hiddenTap), `gemma4-base.ts` (trim bypass);
49
+ `scripts/dspark-{regen,train,measure}-dflash.ts`, `dspark-dflash-smoke.ts`.
50
+
51
+ ## Memory / gotchas
52
+ - `dspark-drafter-built-v1`, `dont-inflate-scope-build-the-paper` (the lesson:
53
+ build the paper's mechanism first — the faithful build was ~1hr; the wrong
54
+ builds cost the session).
55
+ - e4b hidden_size = **2560** (not 2816 — a different config block). Module reads dims live.
56
+ - Memory admission guard (`server.ts:1538`) rejects `prompt+max_tokens > maxSafeContext`
57
+ because a mid-gen GPU OOM SIGKILLs the server. 27B/32GB caps ~22.5k; a client
58
+ sending `max_tokens=64k` trips it — lower max_tokens (or make it a runtime stop).
@@ -0,0 +1,92 @@
1
+ # Kernel/perf deep review — 2026-07-01 (condensed, tracked record)
2
+
3
+ A 25-agent adversarially-verified review of every Metal/fused kernel and
4
+ training memory path (7 areas; every suspected bug survived an independent
5
+ refutation pass before making this list). Raw structured output (all seven
6
+ area reviews + full mechanisms): `reports/kernel-perf-review-2026-07-01.json`
7
+ (gitignored, local). This file is the durable record.
8
+
9
+ ## Area verdicts (one line each)
10
+
11
+ - **flash-CCE head** (steel fwd + H-tiled bwd): done unusually well — verbatim
12
+ vendored MLX steel machinery, exact-by-default backward with autograd + FD
13
+ parity — marred by decision drift: the PLAN-decided 1.35× filter win was
14
+ never landed and the in-code comments argued three contradictory positions
15
+ (comments fixed 2026-07-01; the FLIP itself is still backlog #1).
16
+ - **Training flash-attention kernel**: faithful port with exemplary post-bug
17
+ discipline, correctly opt-in — but it copies a naive oracle (~30× slower)
18
+ and its tests covered none of the production configs (extended 2026-07-01:
19
+ D=256, sliding-window, non-tile T; ≥2K e4b revalidation still Josh-gated).
20
+ - **Inference fused paths**: disciplined and honest (everything measured,
21
+ gated, losses documented) — one real latent bug (fixed) + the open 26B
22
+ perf-kernel checkbox.
23
+ - **Quantized-KV attention**: line-faithful ports, tol=0 oracle gates, no
24
+ materialized dequant on the serving path — optiq's streaming per-layer
25
+ conversion was only half-ported (fixed 2026-07-01) and FUSED_DECODE×
26
+ compiled-decode composes unsafely (OPEN — see below).
27
+ - **Training memory machinery (segmented backward)**: the strongest subsystem
28
+ reviewed — the mlx_vjp-per-segment design is the correct primitive, disposal
29
+ exception-safe in all five classes.
30
+ - **Metal infra + megakernel learnings**: apply() is careful post-incident
31
+ design; the megakernel was shelved on decisive numbers, but the banked
32
+ "could win at M=K" learning is recorded misleadingly (decode look-again
33
+ agrees: re-word it — mlx amortizes at M=K too).
34
+ - **Cross-cutting flags**: unusually disciplined for a 65-flag surface — but
35
+ the --l2 tier promise was violated by its own default (FIXED 2026-07-01:
36
+ perf kernel demoted to --l3) and the v1 batch scheduler lacked the serial
37
+ loop's optimizations (batching-v2 wave, in flight).
38
+
39
+ ## Confirmed bugs — status ledger
40
+
41
+ FIXED in commit 381382c (2026-07-01): same-ms batch seed collision ·
42
+ streaming per-layer KV-quant conversion · segmented compiled-decode mid-step
43
+ double-write · --l2 tier violation (perf kernel → l3; evidence: the frozen
44
+ "optiq" goldens were mlx-bun's own compat engine, gate was ≥56/64 argmax) ·
45
+ generate --l2/--l3 silent L1 degrade · unguarded TRAIN_ATTN=flash on Gemma ·
46
+ evalSftLoss error swallowing · tokens_per_sec metric · inverted comments
47
+ (gemma4.ts:298, flash-cce filter trio) · silent steel fallback (now warns;
48
+ H%128 throw narrowed) · flash-attn test blindness.
49
+
50
+ STILL OPEN: **FUSED_DECODE=1 inside whole-graph compiled decode** bakes the
51
+ tile loop at trace-time N — q-cat adapters grow N per step under shapeless
52
+ replay, so the newest KV rows are silently never attended (gemma4-base.ts
53
+ quantizedSdpaTiled; deferred for file-ownership at fix time — guard the combo
54
+ or make the tile loop trace-safe).
55
+
56
+ ## The ranked optimization backlog (task #12)
57
+
58
+ 1. **[S] Land the coeff filter at eps~1e-5** (+ measure blockMax skip on real
59
+ data) — 1.35× ORPO head backward, ALREADY MEASURED
60
+ (flash-cce-filter-realdata.ts, PLAN.md "filter-on-real-data"); gates:
61
+ E4B=1 rerun + teacher-forced grad fidelity + eps=0 byte-identical.
62
+ 2. **[M] planSegments full-attention isolation** — e4b@8K ~17.5→10 GB;
63
+ unblocks 8K training on the 24 GB M4 Pro.
64
+ 3. **[S] Auto-dispatch the training head by M** — exact fused QM head for
65
+ short-M (~1.9×: 481 ms vs 934 ms at e4b M=512), flash only when memory
66
+ demands; both heads already share the fusedRespLogpMean interface.
67
+ 4. **[S] Fused decode full-capacity KV buffers + activeN** — kills 6
68
+ ensureRowContiguous copies/layer/step; 1-3% @8k, ~4× that at 32k.
69
+ 5. **[M] Collapse per-token host syncs in the spec/DSpark loop** — ~2γ+1
70
+ round-trips → ~2 per verify cycle; directly attacks DSpark's fixed draft
71
+ overhead.
72
+ 6. **[M] Pipeline the batched decode loop + clearCache cadence** — folded into
73
+ the batching-v2 wave (docs/design/batching-v2-plan.md).
74
+ 7. **[S] Enable the 26B perf kernel** (open PLAN Phase E box; oracle frozen).
75
+ 8. **[S] Bound the SFT segmented head** — replace full-[M,V] responseOnlyCe in
76
+ the segmented head vjp; ~2-4 GB peak on long-response e4b SFT.
77
+ 9. **[S] Segmented-step overhead pass** — detachLeaf single-copy, one evalAll
78
+ barrier/segment, memoize the CPM5 prefix block-sparse mask.
79
+ 10. **[M] e4b prefill gap** — profile-first; NOTE: the decode look-again could
80
+ NOT reproduce RESULTS.md's 304-vs-373 row on the M1 Max (no eval-DB
81
+ backing) — re-bench on the M4 Pro before building anything.
82
+
83
+ ## Superseding context: the decode roofline look-again
84
+
85
+ The review's framing assumed the megakernel post-mortem's "M=1 decode is at
86
+ the floor". The follow-up investigation (docs/investigations/
87
+ decode-roofline-lookagain.md) OVERTURNED that: only the 12B is at the wall
88
+ (~92-93% of measured roofline); CPM5 58-64%, e4b 64-70%, 26B 60-62%, with the
89
+ host JS graph build as the #1 recoverable term. Its ranked fixes (CPM5
90
+ compiled-decode port; build-ahead graph overlap spike; 26B gather-qmm
91
+ bandwidth; e4b dispatch batching) COMPOSE with the backlog above and should be
92
+ sequenced first where they overlap.
@@ -423,9 +423,9 @@ Examples:
423
423
 
424
424
  ```sh
425
425
  mlx-bun --model gemma-4-12b --context 65536
426
- mlx-bun serve --no-ui --port 8090
426
+ mlx-bun serve --no-ui --port 8080
427
427
  mlx-bun pi --model qwen-profile
428
- mlx-bun harness pi --base-url http://localhost:8090/v1
428
+ mlx-bun harness pi --base-url http://localhost:8080/v1
429
429
  ```
430
430
 
431
431
  ## Research loop behind the product