mlx-bun 0.0.4

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 (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +362 -0
  3. package/THIRD_PARTY_LICENSES.md +41 -0
  4. package/bin/mlx-bun.mjs +32 -0
  5. package/docs/curve-designer.html +303 -0
  6. package/docs/design/adapters-end-to-end.md +201 -0
  7. package/docs/design/compat-cli-surface-design.md +227 -0
  8. package/docs/design/docs-reorg-plan.md +152 -0
  9. package/docs/design/hlg-sampling.md +340 -0
  10. package/docs/design/memory-system.md +339 -0
  11. package/docs/design/optimization_plan.md +344 -0
  12. package/docs/design/parallel-slots.md +515 -0
  13. package/docs/design/runtime-isolation.md +247 -0
  14. package/docs/design/segmented-backward-training.md +508 -0
  15. package/docs/investigations/chunk-finetune-experiment.md +84 -0
  16. package/docs/investigations/curve-bisector-routing.md +123 -0
  17. package/docs/investigations/curve-runs/bisector-route.json +98 -0
  18. package/docs/investigations/curve-runs/bisector-trace.json +1393 -0
  19. package/docs/investigations/curve-runs/curve-terrain.json +1179 -0
  20. package/docs/investigations/curve-runs/curve-terrain.svg +42 -0
  21. package/docs/investigations/curve-terrain.html +105 -0
  22. package/docs/investigations/expert-offload-single-user-moe.md +292 -0
  23. package/docs/investigations/hlg-ab.html +34 -0
  24. package/docs/investigations/hlg-explorer.html +238 -0
  25. package/docs/investigations/hlg-figs/cliff.svg +1 -0
  26. package/docs/investigations/hlg-figs/cross.svg +1 -0
  27. package/docs/investigations/hlg-figs/edges.svg +1 -0
  28. package/docs/investigations/hlg-figs/k20-grids.svg +1 -0
  29. package/docs/investigations/hlg-figs/k20-peaks.svg +1 -0
  30. package/docs/investigations/hlg-figs/lw-curve.svg +1 -0
  31. package/docs/investigations/hlg-figs/terrain.svg +1 -0
  32. package/docs/investigations/hlg-report.html +262 -0
  33. package/docs/investigations/hlg-runs/hlg-ab.json +149 -0
  34. package/docs/investigations/hlg-runs/hlg-blind-prompts.md +87 -0
  35. package/docs/investigations/hlg-runs/hlg-blind.json +107 -0
  36. package/docs/investigations/hlg-runs/hlg-cliff.json +197 -0
  37. package/docs/investigations/hlg-runs/hlg-cross.json +505 -0
  38. package/docs/investigations/hlg-runs/hlg-edge.json +388 -0
  39. package/docs/investigations/hlg-runs/hlg-eval1.json +25 -0
  40. package/docs/investigations/hlg-runs/hlg-frontier.json +86 -0
  41. package/docs/investigations/hlg-runs/hlg-grid.json +242 -0
  42. package/docs/investigations/hlg-runs/hlg-grid2.json +343 -0
  43. package/docs/investigations/hlg-runs/hlg-lw-coarse.json +110 -0
  44. package/docs/investigations/hlg-runs/hlg-map.json +383 -0
  45. package/docs/investigations/hlg-runs/run0-original.log +159 -0
  46. package/docs/investigations/hlg-runs/runA-recommended.log +131 -0
  47. package/docs/investigations/hlg-runs/runAA-cliff-cpm5.log +26 -0
  48. package/docs/investigations/hlg-runs/runAB-grid2-e4b.log +18 -0
  49. package/docs/investigations/hlg-runs/runAC-peak-e4b-partial.log +25 -0
  50. package/docs/investigations/hlg-runs/runAD-ab-samples.log +8 -0
  51. package/docs/investigations/hlg-runs/runAE-edge-e4b.log +51 -0
  52. package/docs/investigations/hlg-runs/runAF-logit-calibration.log +10 -0
  53. package/docs/investigations/hlg-runs/runAG-eval-config2.log +16 -0
  54. package/docs/investigations/hlg-runs/runB-gain-variants.log +192 -0
  55. package/docs/investigations/hlg-runs/runC-pivots.log +162 -0
  56. package/docs/investigations/hlg-runs/runD-oetf.log +132 -0
  57. package/docs/investigations/hlg-runs/runE-eotf.log +162 -0
  58. package/docs/investigations/hlg-runs/runF-shaper-working.log +86 -0
  59. package/docs/investigations/hlg-runs/runG-shaper-sweep.log +101 -0
  60. package/docs/investigations/hlg-runs/runH-wsweep.log +176 -0
  61. package/docs/investigations/hlg-runs/runI-asweep.log +176 -0
  62. package/docs/investigations/hlg-runs/runJ-knobmap.log +49 -0
  63. package/docs/investigations/hlg-runs/runK-frontier.log +19 -0
  64. package/docs/investigations/hlg-runs/runL-widemap.log +65 -0
  65. package/docs/investigations/hlg-runs/runM-frontier-emb.log +15 -0
  66. package/docs/investigations/hlg-runs/runN-verify.log +116 -0
  67. package/docs/investigations/hlg-runs/runO-frontier-seed5000.log +15 -0
  68. package/docs/investigations/hlg-runs/runP-grid-AxSm.log +15 -0
  69. package/docs/investigations/hlg-runs/runQ-grid-tgW.log +15 -0
  70. package/docs/investigations/hlg-runs/runR-blind-transcript.log +79 -0
  71. package/docs/investigations/hlg-runs/runS-cross-coherence.log +33 -0
  72. package/docs/investigations/hlg-runs/runT-cross-cpm5.log +33 -0
  73. package/docs/investigations/hlg-runs/runU-cross-12b.log +33 -0
  74. package/docs/investigations/hlg-runs/runV-lw-e4b.log +22 -0
  75. package/docs/investigations/hlg-runs/runW-lw-12b.log +22 -0
  76. package/docs/investigations/hlg-runs/runX-lw-cpm5.log +22 -0
  77. package/docs/investigations/hlg-runs/runY-cliff-e4b.log +26 -0
  78. package/docs/investigations/hlg-runs/runZ-cliff-12b.log +26 -0
  79. package/docs/investigations/hlg-sampling-investigation.md +970 -0
  80. package/docs/investigations/lab-build-journal.md +157 -0
  81. package/docs/investigations/pi-builtin-investigation.md +308 -0
  82. package/docs/investigations/starter-model-port-handoff.md +323 -0
  83. package/docs/planning/IDEAS.md +26 -0
  84. package/docs/planning/PRODUCT_ROADMAP.md +426 -0
  85. package/docs/planning/ResearchTopics.md +119 -0
  86. package/docs/planning/chunk-task-roadmap.md +77 -0
  87. package/docs/planning/journal.md +155 -0
  88. package/docs/reference/distribution.md +121 -0
  89. package/docs/reference/embedding.md +168 -0
  90. package/docs/reference/library-api.md +153 -0
  91. package/docs/reference/server-api.md +224 -0
  92. package/docs/reference/server-config.md +243 -0
  93. package/docs/segmented-backward-handoff.md +148 -0
  94. package/package.json +68 -0
  95. package/src/anthropic.ts +491 -0
  96. package/src/chat-template.ts +186 -0
  97. package/src/cli.ts +1075 -0
  98. package/src/config.ts +229 -0
  99. package/src/curve-sampler.ts +122 -0
  100. package/src/dataset/generators.ts +1087 -0
  101. package/src/dataset/index.ts +12 -0
  102. package/src/dataset/job.ts +81 -0
  103. package/src/dataset/llm.ts +71 -0
  104. package/src/dataset/registry.ts +528 -0
  105. package/src/download.ts +283 -0
  106. package/src/eval/README.md +86 -0
  107. package/src/eval/kl-prompts.ts +29 -0
  108. package/src/eval/kl.ts +294 -0
  109. package/src/eval/quality-db.ts +92 -0
  110. package/src/eval/runner.ts +102 -0
  111. package/src/eval/score.ts +49 -0
  112. package/src/eval/tasks/bfcl.ts +500 -0
  113. package/src/eval/tasks/gsm8k.ts +85 -0
  114. package/src/eval/tasks/hashhop.ts +109 -0
  115. package/src/eval/tasks/humaneval.ts +252 -0
  116. package/src/eval/tasks/ifeval.ts +354 -0
  117. package/src/eval/tasks/mmlu.ts +145 -0
  118. package/src/evaldb.ts +199 -0
  119. package/src/expert-offload-build.ts +77 -0
  120. package/src/expert-offload.ts +61 -0
  121. package/src/expert-trace.ts +67 -0
  122. package/src/fit.ts +254 -0
  123. package/src/generate.ts +451 -0
  124. package/src/harness-pi.ts +177 -0
  125. package/src/hf-push.ts +628 -0
  126. package/src/index.ts +22 -0
  127. package/src/jobs/db.ts +139 -0
  128. package/src/jobs/index.ts +29 -0
  129. package/src/jobs/job-entry.ts +106 -0
  130. package/src/jobs/runner.ts +304 -0
  131. package/src/jobs/sse.ts +114 -0
  132. package/src/jobs/types.ts +58 -0
  133. package/src/kv-store.ts +185 -0
  134. package/src/lora.ts +314 -0
  135. package/src/md-modules.d.ts +7 -0
  136. package/src/mlx/array.ts +237 -0
  137. package/src/mlx/autograd.ts +267 -0
  138. package/src/mlx/checkpoint.ts +116 -0
  139. package/src/mlx/compile.ts +158 -0
  140. package/src/mlx/custom-vjp.ts +140 -0
  141. package/src/mlx/ffi.ts +433 -0
  142. package/src/mlx/metal-kernel.ts +130 -0
  143. package/src/mlx/ops.ts +707 -0
  144. package/src/mmap.ts +90 -0
  145. package/src/model/batched-mask.ts +204 -0
  146. package/src/model/batched-rotating.ts +300 -0
  147. package/src/model/compiled-decode.ts +681 -0
  148. package/src/model/factory.ts +27 -0
  149. package/src/model/fingerprint.ts +33 -0
  150. package/src/model/flash-attention.ts +674 -0
  151. package/src/model/fused-decode-kernel.ts +305 -0
  152. package/src/model/fused-geglu-kernel.ts +87 -0
  153. package/src/model/gemma4-base.ts +1616 -0
  154. package/src/model/gemma4.ts +1012 -0
  155. package/src/model/generated/gemma4-12b.ts +526 -0
  156. package/src/model/generated/gemma4-26b.ts +500 -0
  157. package/src/model/generated/gemma4-e4b.ts +757 -0
  158. package/src/model/generated/index.ts +18 -0
  159. package/src/model/minicpm5.ts +278 -0
  160. package/src/model/qwen3-delta.ts +224 -0
  161. package/src/model/qwen3_5.ts +429 -0
  162. package/src/model/support.ts +46 -0
  163. package/src/native-pack.ts +152 -0
  164. package/src/pi-provider.ts +95 -0
  165. package/src/pi-terminal.ts +264 -0
  166. package/src/pi-web.ts +924 -0
  167. package/src/preflight.ts +123 -0
  168. package/src/prompt-cache.ts +113 -0
  169. package/src/quantize/allocator.ts +627 -0
  170. package/src/quantize/calibration.ts +180 -0
  171. package/src/quantize/config-writer.ts +132 -0
  172. package/src/quantize/index.ts +57 -0
  173. package/src/quantize/job.ts +136 -0
  174. package/src/quantize/quantizer.ts +462 -0
  175. package/src/quantize/safetensors-writer.ts +171 -0
  176. package/src/quantize/sensitivity.ts +234 -0
  177. package/src/registry.ts +336 -0
  178. package/src/responses.ts +774 -0
  179. package/src/safetensors.ts +158 -0
  180. package/src/sampler.ts +517 -0
  181. package/src/serve/batch-scheduler.ts +362 -0
  182. package/src/serve/generation-gateway.ts +160 -0
  183. package/src/server.ts +1891 -0
  184. package/src/spec/drafter.ts +261 -0
  185. package/src/spec/generate.ts +221 -0
  186. package/src/status-page.html +497 -0
  187. package/src/tokenizer.ts +38 -0
  188. package/src/tool-call.ts +242 -0
  189. package/src/train/dataset.ts +461 -0
  190. package/src/train/export.ts +32 -0
  191. package/src/train/forward.ts +229 -0
  192. package/src/train/index.ts +43 -0
  193. package/src/train/job.ts +148 -0
  194. package/src/train/lora-params.ts +194 -0
  195. package/src/train/loss.ts +342 -0
  196. package/src/train/merge.ts +195 -0
  197. package/src/train/optimizer.ts +176 -0
  198. package/src/train/rank.ts +101 -0
  199. package/src/train/segmented.ts +520 -0
  200. package/src/train/trainer.ts +600 -0
  201. package/src/tui.ts +161 -0
  202. package/src/vision/embedder.ts +168 -0
  203. package/src/vision/preprocess.ts +247 -0
  204. package/src/vision/prompt.ts +158 -0
  205. package/src/vision/siglip.ts +599 -0
  206. package/src/web/app.html +2471 -0
  207. package/src/web/skills/web-research/SKILL.md +44 -0
  208. package/src/web/skills.ts +59 -0
  209. package/src/web-tools.ts +426 -0
  210. package/src/weights.ts +91 -0
@@ -0,0 +1,323 @@
1
+ # Handoff: the sub-GB starter model port (publishing gate 1)
2
+
3
+ *2026-06-12. Goal: a runnable sub-gigabyte model so first run is
4
+ chatting in ~1 minute (PLAN Phase 16 starter item; publishing gate).
5
+ This document is the complete implementation plan. Read PLAN.md's
6
+ "Reference environment" + Phase 14 first. Written from live
7
+ inspection of the actual model configs (HF API) and our porting
8
+ infrastructure — every claim below was verified, not remembered.*
9
+
10
+ ---
11
+
12
+ ## 0. CRITICAL DISCOVERY — read before starting
13
+
14
+ **Qwen3.5-0.8B is NOT a vanilla transformer.** Its config
15
+ (`model_type: qwen3_5_text`, fetched 2026-06-12) reveals the
16
+ qwen3-next hybrid lineage:
17
+
18
+ - **24 layers: 18 `linear_attention` + 6 `full_attention`**
19
+ (`full_attention_interval: 4`). The linear layers are **gated
20
+ DeltaNet**: causal conv (kernel 4), 16 key heads × 128, 16 value
21
+ heads × 128, recurrent state in **float32** (`mamba_ssm_dtype`).
22
+ - Full-attention layers: 8 heads / 2 KV heads, head_dim 256,
23
+ **partial rotary 0.25**, **interleaved MRoPE** (sections
24
+ [11,11,10]), theta 1e7, **`attn_output_gate: true`**.
25
+ - `tie_word_embeddings`, vocab 248,320 (embeddings quantized 8-bit),
26
+ hidden 1024; bundled `mtp.safetensors` (1-layer MTP head) and a
27
+ 201 MB `optiq_vision.safetensors` sidecar; per-tensor mixed quant
28
+ (some projections 8-bit).
29
+
30
+ This is a **major port**: a DeltaNet recurrence + conv-state cache is
31
+ a new cache *kind*, a new prefill strategy, and new numerics
32
+ (float32 state) — none of which our Gemma-shaped pipeline has.
33
+
34
+ **MiniCPM5-1B-OptiQ-4bit, by contrast, is textbook `llama`**
35
+ (config verified the same way): 24 layers, plain GQA 16/2 heads,
36
+ head_dim 128, standard RoPE theta 5e6 with **no scaling**, SiLU MLP,
37
+ RMSNorm, untied embeddings, vocab 130,560, 0.92 GB. Every mechanism
38
+ it needs already exists in our gemma4 port (GQA attention, RoPE,
39
+ RMSNorm, quantized linear) — minus Gemma's quirks (no sliding
40
+ windows, no softcapping, no per-layer embeds, no QK-norm... verify
41
+ QK-norm against the oracle, llama has none).
42
+
43
+ **Recommendation: split the work.**
44
+ - **Track A (the publishing gate): port MiniCPM5-1B.** Days, not
45
+ weeks. Capability is respectable (52% MMLU, 30.28 OptiQ score —
46
+ Josh's screenshot from the OptiQ site) and the starter's job is
47
+ tour-guide + fast first impression.
48
+ - **Track B (Phase 14 proper, after publishing): port Qwen3.5.**
49
+ It is the MTP home and a flagship family — it deserves the real
50
+ multi-week effort, not a deadline squeeze.
51
+
52
+ Josh decides; both tracks are specified below. The shared recipe
53
+ (§2) applies to either.
54
+
55
+ ---
56
+
57
+ ## 1. Machine + reference environment logistics
58
+
59
+ - **The oracle lives on the M4 Pro dev machine** —
60
+ `/Users/joshrossi/Code/mlx-lm/.venv` (mlx 0.31.2, mlx-lm 0.31.3,
61
+ mlx-optiq 0.2.1). The M1 Max cloud box (where the 2026-06-12
62
+ session ran) does NOT have it: `tests/paths.ts` →
63
+ `ORACLE_PYTHON` resolves there only on the M4 Pro. **Do parity
64
+ work on the M4 Pro**, or replicate the venv on the M1 Max first
65
+ (pip install mlx==0.31.2 mlx-lm==0.31.3 mlx-optiq==0.2.1).
66
+ - Oracle source to read (M4 Pro, site-packages):
67
+ - Track A: `mlx_lm/models/llama.py` (the reference llama graph).
68
+ - Track B: `optiq/mlx_lm_patches/qwen3_5_text.py` (registered via
69
+ optiq's MODEL_REMAPPING — see PLAN Phase 14), plus mlx-lm's
70
+ `models/qwen3_next.py` for the gated-DeltaNet reference
71
+ implementation, and `optiq/runtime/mtp/` (defer MTP, but its
72
+ `trace_parity.py` encodes load-bearing invariants).
73
+ - Downloads (sub-GB, fine to do from a session):
74
+ - `mlx-bun get mlx-community/MiniCPM5-1B-OptiQ-4bit` (0.92 GB)
75
+ - `mlx-bun get mlx-community/Qwen3.5-0.8B-OptiQ-4bit` (0.89 GB)
76
+ - Remember `HF_HUB_DISABLE_XET=1` applies to *python* tooling only;
77
+ our downloader speaks plain HTTPS already.
78
+ - Goldens are **machine-specific** (`goldenOutDir()`: flat reference
79
+ set on the M4 Pro, `goldens/<machine-key>/` elsewhere — logit
80
+ goldens are bit-exact only on the GPU that produced them).
81
+
82
+ ---
83
+
84
+ ## 2. The shared porting recipe (how gemma4 was done — follow it)
85
+
86
+ Every step below exists for gemma4; the port is "do the same for the
87
+ new family." File references verified 2026-06-12.
88
+
89
+ ### Step 2.1 — Config loading (`src/config.ts`)
90
+ `loadModelConfig()` currently normalizes gemma4's config.json into
91
+ `ModelConfig` (nested `text` block: layerTypes, heads, dims, rope,
92
+ quant overrides). Add a per-family branch keyed on `model_type`:
93
+ - llama (MiniCPM5): flat config — map hidden_size, heads/kv-heads,
94
+ head_dim, intermediate, rms eps, rope theta, vocab, tie flag,
95
+ num_hidden_layers, layerTypes = all "full_attention".
96
+ - qwen3_5: `text_config` nesting; layer_types as shipped
97
+ (linear_attention/full_attention); linear_* dims; mrope params;
98
+ partial_rotary_factor; attn_output_gate; mamba dtype.
99
+ - Keep `quantization` parsing (per-tensor overrides like
100
+ `embed_tokens: {bits: 8}` — qwen uses them heavily; check
101
+ `quantFor()` already resolves path-keyed overrides).
102
+ - **`modelType` drives everything downstream** — registry already
103
+ stores it (that's how the CLI's `startsWith("gemma4")` filter
104
+ works).
105
+
106
+ ### Step 2.2 — Model graph (`src/model/<family>.ts`)
107
+ Pattern from `gemma4.ts`/`gemma4-base.ts`: the base file holds
108
+ config-independent machinery (QuantizedLinear/QuantizedEmbedding
109
+ loaders, KVCache/RotatingKVCache, RMSNorm, rope helpers) — REUSE it.
110
+ A new family file defines Attention/MLP/Layer/Model classes that
111
+ `Weights.open()` feeds by tensor path. Key contract points:
112
+ - `makeCache()` returns the per-layer cache array `generate()`
113
+ threads through.
114
+ - `forwardLayers()` shape must match what compiled-decode segments
115
+ expect — but **do NOT wire compiled-decode/fused kernels for the
116
+ new family initially**: `generate()` gates them; ship the naive
117
+ path first, parity gates every optimization later (that is the
118
+ testing-strategy contract).
119
+ - Weight path prefixes differ per family (llama:
120
+ `model.layers.N....`; qwen3_5: `language_model.model.layers...` —
121
+ verify against `model.safetensors.index.json`).
122
+
123
+ ### Step 2.3 — Factory (`src/model/factory.ts`)
124
+ `createModel()` currently returns `Gemma4Model` (generated
125
+ specializations subclass it). Introduce a `Model` interface (the
126
+ methods server/generate actually use: forward, makeCache, config,
127
+ weightsBytes, dispose...) and dispatch on `config.modelType`. The
128
+ generated-specialization map stays gemma-only.
129
+
130
+ ### Step 2.4 — Tokenizer + chat template
131
+ - `src/tokenizer.ts` uses @huggingface/tokenizers over
132
+ `tokenizer.json` — both models ship one (qwen's is 20 MB; load
133
+ time worth checking). Verify BOS/EOS handling: qwen3_5
134
+ eos 248044; MiniCPM5 bos 0 / eos in generation_config.
135
+ - `src/chat-template.ts` renders `chat_template.jinja` via
136
+ @huggingface/jinja — qwen ships chat_template.jinja (7.8 KB;
137
+ includes `enable_thinking`-style hybrid switches — render with
138
+ thinking OFF for the starter; MiniCPM5's template TBD from its
139
+ tokenizer_config).
140
+ - Tool-call grammar: gemma's `parseToolCalls` markers are
141
+ family-specific (`src/tool-call.ts`). Qwen uses hermes-style
142
+ `<tool_call>` JSON; MiniCPM5 TBD. Starter can ship text-only chat
143
+ first; the pi session needs tool calls to be USEFUL, so budget it.
144
+
145
+ ### Step 2.5 — Parity harness (the correctness contract)
146
+ Mirror `scripts/regen-parity-goldens.ts` + `tests/parity.test.ts`
147
+ for the new family (paths in `tests/paths.ts` — add SNAPSHOT_<fam>):
148
+ - **Tier a (bit-exact ids)**: oracle generates 100 greedy tokens +
149
+ per-step argmax + full last-position logits for the first N steps
150
+ (f32 .bin). Our side must match token-for-token, logits within
151
+ the established tolerance, on the same GPU.
152
+ - Oracle command shape: the venv python with mlx-lm generate (Track
153
+ A) or optiq's patched loader (Track B — needs
154
+ `optiq.mlx_lm_patches` import side effects; read how their CLI
155
+ registers MODEL_REMAPPING and replicate in the regen script).
156
+ - Then the e2e suite: prefill masks (L>1), decode loop, KV-quant
157
+ tiers (Track A can reuse kv-quant goldens pattern; Track B's
158
+ linear layers have NO KV — see §4.3).
159
+ - Suite must stay green throughout: `bun test` (157+ tests).
160
+
161
+ ### Step 2.6 — Integration sweep (easy to forget — grep targets)
162
+ All the places hardcoding the gemma4 family, verified present today:
163
+ 1. `src/cli.ts` — THREE `modelType.startsWith("gemma4")` filters
164
+ (resolveModelAuto ×2 paths + ls capability column) → a shared
165
+ `SUPPORTED_FAMILIES` predicate in one place.
166
+ 2. `src/cli.ts` starter constant: `starterRepo =
167
+ ".../gemma-4-e4b-it-OptiQ-4bit"` → the new sub-GB repo.
168
+ 3. `src/fit.ts` `recommendedRepoId()` — tiers stay Gemma (the
169
+ starter is not the recommendation), but the starter download in
170
+ resolveModelAuto switches.
171
+ 4. **`src/fit.ts` `kvGeometry()` assumes gemma layer types**
172
+ (`sliding_attention` / full): llama = all-full (works via the
173
+ full branch — verify window handling degrades correctly);
174
+ qwen3_5 `linear_attention` layers have constant-size state, not
175
+ token-proportional KV — fit's KV-growth math needs a family
176
+ branch or the 0.8B's max-safe-context will be nonsense.
177
+ 5. `src/server.ts` /stats KV accounting + /library `supported`
178
+ flag + the registry `paramCount` parse (works off safetensors
179
+ headers — verify for the new index layout).
180
+ 6. Status page + README copy that says "Gemma".
181
+ 7. Vision sidecar guard: qwen's `optiq_vision.safetensors` must NOT
182
+ be loaded (registry already separates sidecarBytes; confirm the
183
+ loader skips non-gemma sidecars rather than erroring).
184
+
185
+ ### Step 2.7 — Starter-flow wiring + docs-grounded tour guide
186
+ - Swap `starterRepo` (§2.6.2) and keep the background-download of
187
+ the recommended Gemma.
188
+ - The "tour guide" system prompt (PRODUCT_ROADMAP first-run UX):
189
+ preload README/server-api/pi docs into the starter's system
190
+ prompt so a ~1B model answers mlx-bun questions grounded instead
191
+ of hallucinating. Suggested: a `docs/tour-guide.md` baked via
192
+ text import, used as default system prompt ONLY for the starter
193
+ model + surfaced in the chat UI's system field.
194
+ - E2E: fresh-machine simulation (`HOME=$(mktemp -d)` breaks
195
+ keychain/HF paths — instead point `cacheDir`/registry at a temp
196
+ hub via env or test flags; the downloadModel `cacheDir` option
197
+ already exists).
198
+
199
+ ---
200
+
201
+ ## 3. Track A step-by-step: MiniCPM5-1B (`llama`) — the gate
202
+
203
+ Estimated: 2–4 focused sessions. Order matters; each step has a gate.
204
+
205
+ 1. **Download + inspect** (30 min): `mlx-bun get
206
+ mlx-community/MiniCPM5-1B-OptiQ-4bit`; dump
207
+ `model.safetensors.index.json` tensor names; diff against
208
+ mlx-lm `llama.py` expectations; note quant per-tensor overrides
209
+ in config. Gate: full tensor-name → module mapping written down.
210
+ 2. **Oracle goldens first** (1–2 h, M4 Pro): extend
211
+ regen-parity-goldens with `--model` + plain mlx-lm loader; run
212
+ against MiniCPM5; commit goldens. Doing this FIRST means every
213
+ subsequent step has a target. Gate: oracle generates coherent
214
+ text (also validates the artifact itself).
215
+ 3. **Config branch** (§2.1) + **weights mapping**: llama branch in
216
+ loadModelConfig; confirm `Weights.open` mmaps the single 650 MB
217
+ shard fine. Gate: registry `scan` shows correct params/quant.
218
+ 4. **Model graph** (`src/model/llama.ts`): embed → N×(RMSNorm →
219
+ GQA attn (RoPE theta from config) → residual → RMSNorm → SiLU
220
+ MLP → residual) → final norm → lm_head (untied). Reuse
221
+ QuantizedLinear/KVCache/rope from gemma4-base — llama needs the
222
+ non-Gemma variants (no embed scaling, no softcap, no QK-norm,
223
+ no pre/post-feedforward norms — READ the oracle line by line;
224
+ Gemma habits are the bug farm here). Gate: tier-a parity, 100/100
225
+ greedy ids + logit tolerance.
226
+ 5. **Factory interface** (§2.3) + integration sweep (§2.6). Gate:
227
+ full suite green; `mlx-bun serve minicpm` chats coherently;
228
+ `/chat` works; fit/library/status pages sane.
229
+ 6. **Tool calls + template** (§2.4): render template with tools,
230
+ implement the family's tool-call markers in tool-call.ts, e2e
231
+ via the existing server-tools test pattern. Gate: pi session
232
+ round-trips one read/bash tool call on the starter.
233
+ 7. **Starter wiring** (§2.7) + benchmark rows (`mlx-bun benchmark
234
+ minicpm`) + fresh-machine e2e. Gate: cold start → chatting
235
+ under ~2 min on decent broadband, big model streaming behind.
236
+ 8. **Ship gate**: PLAN updated, suite green, both testers' machines
237
+ happy → publish.
238
+
239
+ ---
240
+
241
+ ## 4. Track B step-by-step: Qwen3.5-0.8B (`qwen3_5`) — Phase 14 proper
242
+
243
+ Estimated: 2+ weeks calibrated against the gemma port. The order
244
+ isolates the novel machinery so parity bisects cleanly.
245
+
246
+ 1. **Read the oracle deeply** (M4 Pro): optiq's `qwen3_5_text.py` +
247
+ mlx-lm `qwen3_next.py`. Write a NOTES file mapping every module:
248
+ in_proj_qkv/in_proj_ba, causal conv1d, gated delta rule
249
+ (decay a, beta b, state S update S = a·S + v·kᵀ, out = S·q —
250
+ verify exact form from source, do NOT trust this sketch),
251
+ norm-then-gate output path, full-attn blocks with partial
252
+ rotary + interleaved MRoPE + output gate, shared input/output
253
+ embeddings.
254
+ 2. **Oracle goldens + per-layer fixtures**: beyond tier-a ids,
255
+ dump PER-LAYER activations from the oracle for one short prompt
256
+ (the gemma port's most valuable debugging tool — bisects which
257
+ layer diverges). The optiq loader must be driven through their
258
+ MODEL_REMAPPING registration.
259
+ 3. **Config branch** (§2.1): text_config nesting, linear_* dims,
260
+ mrope_section/interleaved, partial_rotary_factor 0.25,
261
+ attn_output_gate, full_attention_interval, mamba_ssm_dtype.
262
+ 4. **New cache kind** (`src/kv-store.ts` + model file): linear-attn
263
+ layers carry `(conv_state[K=4 window], S[float32 16×128×128])`
264
+ per layer — constant size, no growth, no quantization, must
265
+ survive `generate()`'s dispose/trim/cache-reuse contract
266
+ (PromptCache stores caches by token prefix — linear state is
267
+ prefix-dependent, so prefix reuse REMAINS VALID only on exact
268
+ prefix; trimming is NOT possible → mark these caches
269
+ non-trimmable and let PromptCache fall back to full re-prefill
270
+ when a partial-prefix hit would require trim).
271
+ 5. **DeltaNet prefill**: reference implements chunked scan in pure
272
+ mlx ops — port that first (correctness), no custom kernels.
273
+ float32 state in a bf16 graph: respect mamba_ssm_dtype or
274
+ parity will drift.
275
+ 6. **Full-attention blocks**: GQA 8/2 with head_dim 256, partial
276
+ rotary (first 64 dims of 256), interleaved MRoPE sections
277
+ [11,11,10] (text-only collapses to standard positions — verify
278
+ how the oracle treats pure-text), attn_output_gate (sigmoid gate
279
+ on attn output — read source), theta 1e7.
280
+ 7. **Graph assembly + tier-a parity** (the long haul): per-layer
281
+ fixture bisection. Numeric hot spots from the gemma experience:
282
+ norm epsilon placement, residual dtype, rope sign/interleave,
283
+ quantized-embedding dequant scaling.
284
+ 8. **KV-quant for the 6 full layers** (kv_config.json ships in the
285
+ repo), fit.ts geometry branch (linear state = constant bytes).
286
+ 9. **Tokenizer/template/tools** (§2.4) — template has hybrid
287
+ thinking switches; starter runs non-thinking
288
+ (chat_template kwargs equivalent: `enable_thinking: false`).
289
+ 10. **MTP (`mtp.safetensors`) — DEFER** to its own phase per PLAN
290
+ 14(b): start at optiq `runtime/mtp/trace_parity.py`. Greedy-MTP
291
+ must be token-identical to greedy non-MTP by construction.
292
+ 11. **Vision sidecar — DEFER** (Phase 12 bucket, third vision arch).
293
+ 12. Integration sweep (§2.6), benchmark, starter wiring if Track B
294
+ ends up being the starter after all.
295
+
296
+ ---
297
+
298
+ ## 5. Exit criteria (both tracks)
299
+
300
+ - Tier-a parity: 100 greedy ids bit-exact vs oracle + logit deltas
301
+ within the established tolerance, committed goldens + regen
302
+ script, runs in CI suite behind `snapshotAvailable()` guards.
303
+ - Full existing suite stays green at every commit (house rule).
304
+ - `mlx-bun benchmark <model>` rows recorded (decode + prefill +
305
+ peak) on at least the M4 Pro and M1 Max.
306
+ - Fresh-machine first-run e2e: starter chatting, recommended model
307
+ background-streaming, status page sane, pi tool round-trip.
308
+ - PLAN.md updated with findings (negative results included — e.g.
309
+ any oracle deviations discovered, like the Phase 11 ones).
310
+
311
+ ## 6. Open questions for Josh
312
+
313
+ 1. **Track A vs B for the gate** — recommendation is A
314
+ (MiniCPM5) for publishing speed; B proceeds afterward as Phase
315
+ 14 on its own clock. Decide before work starts.
316
+ 2. MiniCPM5's hybrid `<think>` mode (the OptiQ page's
317
+ `enable_thinking` note): starter ships non-thinking — confirm.
318
+ 3. Should the starter stay on disk as the permanent "fallback +
319
+ tour guide" (current plan) or be deleted once the big model
320
+ lands? (Current code keeps it; ~1 GB.)
321
+ 4. Publishing mechanics can proceed in parallel with the port
322
+ (npm `files` allowlist, un-`private` the package, repo
323
+ visibility decision for the native pack) — green-light?
@@ -0,0 +1,26 @@
1
+ # Ideas
2
+
3
+ Framing, positioning, and vision notes for mlx-bun — the "what is this, really"
4
+ captures. Technical prototype theses live in [ResearchTopics.md](ResearchTopics.md);
5
+ work in flight lives in [PLAN.md](../../PLAN.md).
6
+
7
+ ---
8
+
9
+ ## Positioning: what mlx-bun is becoming
10
+
11
+ Two phrases that capture the thesis — especially **mlx-bun × Lucien**:
12
+
13
+ 1. **"A truly local model in a deeper sense."**
14
+ Not just local *compute* (runs on your Mac, nothing leaves it) — local to
15
+ *you*: grounded in your own context and memory, not only your hardware.
16
+
17
+ 2. **"The best model at being yours."**
18
+ Not the best model in the absolute / benchmark sense — the best at *being
19
+ yours*. A small local model, fine-tuned and wired to your personal memory,
20
+ can lose every general benchmark and still win the only one that matters here.
21
+
22
+ **The connection — Lucien × mlx-bun.** Lucien (the Dreaming) is the synthesized,
23
+ persistent memory of *you*; mlx-bun is the local, private model runtime.
24
+ Combined: a model that runs entirely on your machine **and** is continuously
25
+ grounded in your own accumulated context — local in both senses, and yours in a
26
+ way no hosted frontier model can be.