mlx-bun 0.0.11 → 0.0.12

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 (81) hide show
  1. package/README.md +43 -13
  2. package/THIRD_PARTY_LICENSES.md +9 -0
  3. package/docs/design/colibri-glm52-port.md +1479 -0
  4. package/docs/design/pre-colibri-stabilization.md +329 -0
  5. package/docs/investigations/colibri-oracle-pin.md +1284 -0
  6. package/docs/investigations/indexshare-performance-spike.md +357 -0
  7. package/docs/planning/release-notes-v0.0.12.md +80 -0
  8. package/docs/reference/cli.md +28 -2
  9. package/docs/reference/distribution.md +25 -1
  10. package/docs/reference/embedding.md +5 -2
  11. package/docs/reference/features-matrix.md +4 -2
  12. package/docs/reference/library-api.md +41 -13
  13. package/docs/reference/models.md +49 -2
  14. package/docs/reference/server-api.md +90 -9
  15. package/docs/reference/server-config.md +21 -14
  16. package/docs/reference/training.md +10 -1
  17. package/package.json +1 -1
  18. package/src/anthropic.ts +54 -44
  19. package/src/chat-template.ts +155 -10
  20. package/src/cli.ts +127 -8
  21. package/src/config.ts +71 -26
  22. package/src/diffusion/diffusion-generate.ts +14 -8
  23. package/src/download.ts +103 -12
  24. package/src/eval/ifeval.ts +63 -120
  25. package/src/eval/runner.ts +14 -5
  26. package/src/eval/tasks/ifeval.ts +167 -31
  27. package/src/expert-io.ts +391 -0
  28. package/src/expert-residency.ts +1134 -0
  29. package/src/expert-usage.ts +415 -0
  30. package/src/generate.ts +114 -17
  31. package/src/hf-push.ts +1 -1
  32. package/src/index.ts +14 -2
  33. package/src/jobs/runner.ts +37 -18
  34. package/src/kv-store.ts +147 -8
  35. package/src/lora.ts +77 -14
  36. package/src/media-fetch.ts +198 -56
  37. package/src/mlx/array.ts +43 -0
  38. package/src/mlx/autograd.ts +51 -14
  39. package/src/mlx/checkpoint.ts +46 -13
  40. package/src/mlx/custom-vjp.ts +83 -35
  41. package/src/model/factory.ts +96 -5
  42. package/src/model/gemma4-base.ts +32 -0
  43. package/src/model/glm52-atlas.ts +511 -0
  44. package/src/model/glm52-cache.ts +706 -0
  45. package/src/model/glm52-config.ts +262 -0
  46. package/src/model/glm52-container.ts +305 -0
  47. package/src/model/glm52-coupling.ts +388 -0
  48. package/src/model/glm52-dsa.ts +602 -0
  49. package/src/model/glm52-expert-layout.ts +253 -0
  50. package/src/model/glm52-layout.ts +152 -0
  51. package/src/model/glm52-memory.ts +473 -0
  52. package/src/model/glm52-mla.ts +786 -0
  53. package/src/model/glm52-moe.ts +223 -0
  54. package/src/model/glm52-pilot.ts +537 -0
  55. package/src/model/glm52-reference.ts +445 -0
  56. package/src/model/glm52-residency.ts +557 -0
  57. package/src/model/glm52-resident-weights.ts +135 -0
  58. package/src/model/glm52-streamed-experts.ts +453 -0
  59. package/src/model/glm52-streamed-metal.ts +610 -0
  60. package/src/model/glm52-weights.ts +503 -0
  61. package/src/model/glm52.ts +1153 -0
  62. package/src/model/support.ts +8 -1
  63. package/src/native/expert_io.c +523 -0
  64. package/src/native-pack.ts +6 -4
  65. package/src/responses.ts +62 -49
  66. package/src/serve/batch-scheduler.ts +95 -16
  67. package/src/serve/generation-gateway.ts +41 -16
  68. package/src/server.ts +362 -81
  69. package/src/spec/glm52-mtp-source.ts +392 -0
  70. package/src/spec/serve-loop.ts +99 -18
  71. package/src/spec/source.ts +31 -6
  72. package/src/ssd-cache.ts +6 -2
  73. package/src/tool-call.ts +30 -2
  74. package/src/train/job.ts +0 -10
  75. package/src/train/lora-params.ts +17 -6
  76. package/src/train/trainer.ts +59 -26
  77. package/src/web/app.html +13 -2
  78. package/src/web/app.js +30 -3
  79. package/src/web/src/status.ts +51 -3
  80. package/src/web-tools.ts +54 -2
  81. package/src/weights.ts +82 -19
@@ -0,0 +1,1479 @@
1
+ # GLM-5.2 on a 32 GB Mac — native MLX port of the Colibri hierarchy
2
+
3
+ *2026-07-21. Source baseline: `JustVugg/colibri` at
4
+ `44e489b196c9b7876b3d37a0570ebf1c6f90f54c` (post-v1.0.0). This plan is
5
+ grounded in the local Colibri checkout, its C/Metal implementation and tests,
6
+ and mlx-bun's indexed call graph. The original inspiration is Apple's
7
+ [AFM 3 Core Advanced](https://machinelearning.apple.com/research/introducing-third-generation-of-apple-foundation-models)
8
+ flash-resident sparse model; Colibri is the concrete GLM-5.2 implementation.*
9
+
10
+ *Revised 2026-07-21 after review: the aspirational 2 tok/s warm target is set;
11
+ serial MTP moves onto the critical path as gate G4 and every later gate
12
+ measures with MTP on; batched multi-row MTP is descoped to post-release; the
13
+ G2 numeric parity contract is defined; the direct-Colibri baseline is reframed
14
+ as the bar the port is debugged against, not a go/no-go. Gates renumbered
15
+ G0-G8.*
16
+
17
+ ## Decision
18
+
19
+ **Yes: a native MLX port should be feasible within an approximately 25 GB
20
+ runtime budget, but embedding or launching Colibri from mlx-bun is not the
21
+ goal.** Direct Colibri already provides that runtime. Putting its executable
22
+ behind mlx-bun would add API/CLI/tooling consistency, but it would not improve
23
+ memory use, I/O, or generation speed. That is not enough value for this project.
24
+
25
+ The recommended path is therefore a native `Glm52Model` plus an explicit
26
+ Apple-oriented expert residency runtime. The pinned Colibri build remains an
27
+ **external executable oracle** for formats, logits/tokens, routing, cache traces,
28
+ memory, and performance; its code is studied and its behavior reproduced, not
29
+ shipped inside mlx-bun.
30
+
31
+ Colibri is also no longer accurately described as CPU-only. Its opt-in macOS
32
+ backend already creates `MTLStorageModeShared` buffers and registers aligned
33
+ expert slabs with `newBufferWithBytesNoCopy`; routed expert SwiGLU, fused decode
34
+ MLA, and large prefill GEMMs can run on Metal over unified memory. The MLX thesis
35
+ is to express the model and tensor runtime in MLX and the orchestration,
36
+ residency policy, serving, tooling, and UI in Bun while retaining Colibri's
37
+ disk/LRU/prefetch hierarchy. Performance gates choose the winning MLX/custom-
38
+ Metal implementation at each boundary; they do not cancel the port. The port
39
+ decision is settled: the direct-Colibri same-machine numbers recorded in G0
40
+ are the baseline the port is debugged against — a gap versus the oracle is a
41
+ bug to close, not a reason to stop.
42
+
43
+ This is not a small extension of the current Gemma expert-offload flag.
44
+ GLM-5.2 adds a new model graph (MLA, DSA, shared+routed MoE, MTP) and Colibri's
45
+ memory result depends on an explicit residency scheduler that mlx-bun does not
46
+ yet have.
47
+
48
+ The honest product contract is:
49
+
50
+ - **RAM:** target <=25 GB measured RSS/physical footprint on the target
51
+ machine — the M1 Max MacBook Pro with 32 GB, the only qualifying machine in
52
+ this project's fleet (the 24 GB M4 Pro is below the one-slot-per-layer floor
53
+ and out of scope) — including dense weights, expert slots, working buffers,
54
+ KV, Metal transient, the Bun server, and an OS reserve.
55
+ - **Disk:** roughly 370 GB for the converted checkpoint, with at least 400 GB
56
+ free for the ready-to-run artifact. Converting from source needs the output
57
+ plus one source shard at peak because Colibri converts and deletes one shard
58
+ at a time. Preflight (measured 2026-07-21): the target machine has ~556 GB
59
+ unallocated plus ~123 GB purgeable — ~679 GB practically available
60
+ (Finder's figure; macOS auto-purges snapshots/caches on demand). The
61
+ requirement is met on the internal SSD with wide margin. Re-verify at
62
+ download time; if an external drive were ever substituted, its measured
63
+ bandwidth (Thunderbolt caps near ~2.8-3 GB/s) would lower the cold-token
64
+ ceiling and must be entered into the resource plan.
65
+ - **Speed:** the aspirational optimization target—not a release gate—is
66
+ **>=2 tok/s warm on the M1 Max 32 GB with MTP on and quality-preserving
67
+ defaults**. No 32 GB Mac has ever been
68
+ measured by Colibri; the nearest primary-source datapoints (pinned checkout)
69
+ are: 0.05-0.1 tok/s cold on the author's 25 GB dev box — a ~1 GB/s WSL2
70
+ virtual disk, not a Mac (`docs/benchmarks.md:71`); 0.30 tok/s on a Mac Mini
71
+ M4 Pro 48 GB with Metal and a 6.59 GB/s SSD (`docs/benchmarks.md:90`);
72
+ 0.42 tok/s warm on an M4 Max 128 GB (CPU 0.30 -> Metal 0.42, MTP on,
73
+ `docs/metal.md:17`); 2.06 tok/s on an M5 Max 128 GB with a 46.9 GB learned
74
+ pin at 72.5% hit, MTP off (`docs/benchmarks.md:89`). The target decomposes
75
+ as a ~0.8-1 tok/s no-MTP base — the top edge of Colibri's own projection for
76
+ the 3-5 GB/s-NVMe / 32 GB class (`docs/benchmarks.md:72`) — multiplied by
77
+ MTP's measured 2.2-2.6 tok/forward (`docs/windows.md:88`,
78
+ `docs/benchmarks.md:92`). This is why serial MTP is a requirement on the
79
+ critical path, not a later optimization. If the target only closes with
80
+ quality-changing knobs (expert top-p, reduced top-k), that is a finding to
81
+ surface, not a default to ship.
82
+ - **Quality:** the default path keeps the checkpoint's precision and exact
83
+ top-8 router decisions. Cache-aware routing, top-p expert dropping, and
84
+ expert budgets remain explicit Lab experiments.
85
+
86
+ ## What Colibri is actually doing
87
+
88
+ GLM-5.2 has 78 main layers: three dense FFN layers followed by 75 sparse MoE
89
+ layers. Each sparse layer has 256 routed experts and activates eight per token;
90
+ the MTP head adds another 256-expert row. That is 19,456 expert instances.
91
+ Colibri keeps the always-used dense graph resident at int4 (about 9.9 GB) and
92
+ stores the roughly 370 GB routed-expert pool on disk.
93
+
94
+ The runtime is a hierarchy, not a large mmap:
95
+
96
+ ```text
97
+ router output (true top-8)
98
+ |
99
+ v
100
+ batch union of unique (layer, expert) requests
101
+ |
102
+ +--> pinned hot-store hit ----------------------+
103
+ +--> per-layer LRU hit -------------------------+--> expert compute
104
+ +--> miss -> bounded async pread -> work slot --+
105
+ |
106
+ +--> promote/evict LRU at a safe point
107
+
108
+ profile history -> startup pinning -> live LFRU repinning
109
+ next-layer router prediction ------> prefetch queue
110
+ RSS feedback ----------------------> shrink LRU capacity
111
+ ```
112
+
113
+ The load-bearing pieces are:
114
+
115
+ 1. **Streaming converter and container.** FP8 shards are converted one at a
116
+ time to symmetric int4/int8 or grouped-int4. Every expert is addressable
117
+ independently. Gate/up/down matrices and scales are laid out so a miss can
118
+ be served with a coalesced read. MTP experts stay int8 by default because
119
+ int4 MTP measured 0-4% acceptance.
120
+ 2. **Resident dense spine.** Embeddings, lm-head, attention, norms, the first
121
+ dense FFNs, routers, and shared experts remain resident. Only routed experts
122
+ enter the tier manager.
123
+ 3. **Compressed MLA KV.** Each token stores the 512-wide latent plus 64 RoPE
124
+ values rather than reconstructed per-head K/V (576 floats/token, about 57x
125
+ smaller than conventional KV for this geometry). DSA index state is stored
126
+ only on the full-indexer layers.
127
+ 4. **Per-layer bounded LRU.** Each sparse layer owns a fixed number of expert
128
+ slots. A hit updates a monotonic use clock. Misses load into working slots;
129
+ after compute, those slots swap into the least-recently-used cache slots.
130
+ The capacity is derived from the whole-process memory equation, not a fixed
131
+ expert count.
132
+ 5. **Pinned hot-store.** A separate non-evicted tier is seeded from persistent
133
+ `.coli_usage` counts. On macOS Colibri attempts to wire pinned slabs so the
134
+ memory compressor cannot turn a logical hit into a slow page-in.
135
+ 6. **Learning and live LFRU.** Every route increments persistent frequency,
136
+ recent heat, and last-access time. At safe turn boundaries, LFRU can replace
137
+ at most a few sufficiently colder pins; a 25%+4 hysteresis prevents
138
+ oscillation, and recent heat decays without erasing long-term history.
139
+ 7. **Hard RSS feedback.** The planner's estimate is not trusted blindly.
140
+ Colibri samples actual RSS and, above 102% of budget +300 MB, frees the
141
+ coldest LRU slabs in place and lowers the cache cap so they do not regrow.
142
+ 8. **Batch-union.** Prefill and speculative verification route all positions
143
+ first, deduplicate expert IDs per layer, load each unique expert once, and
144
+ run it over every row that selected it.
145
+ 9. **I/O/compute overlap.** A bounded worker pool performs positioned reads.
146
+ Resident experts are submitted for compute before miss reads finish; missed
147
+ experts join afterward. Linux can use io_uring; macOS uses positioned reads
148
+ and `F_NOCACHE`/the direct-I/O equivalent. The three expert matrices are read
149
+ together where the container permits.
150
+ 10. **Predictive prefetch.** `PILOT` applies the next layer's router to the
151
+ current post-attention state (measured 71.6% recall), and `COUPLE` uses
152
+ observed cross-layer route pairs. Real prefetch loads only future layers,
153
+ rechecks residency, and must never publish a partially filled slot.
154
+ 11. **Metal execution.** On Apple Silicon, Colibri batches routed SwiGLU work
155
+ over zero-copy aligned host slabs, fuses decode MLA attention, and runs
156
+ large prefill GEMMs on Metal. It submits resident work before disk reads to
157
+ overlap GPU execution with I/O; failures fall back per block.
158
+ 12. **MTP speculation.** The native MTP layer proposes tokens and the main
159
+ model verifies them in a batch. Draft and verify are forced onto the same
160
+ kernel family (`SPEC_PIN=1`), because changing accumulation order destroyed
161
+ acceptance. Grammar constrains the common target verification walk;
162
+ prompt lookup is an alternative model-free draft provider, with one
163
+ provider owning each request.
164
+ 13. **Persistent conversations and slots.** Compressed MLA/DSA state is
165
+ appended crash-safely and restored without re-prefill. The mux protocol
166
+ supports independent KV slots and continuously batches one decode row per
167
+ active slot; MTP is currently disabled in the mux path because it is not
168
+ ragged-safe.
169
+ 14. **Planner, diagnostics, and telemetry.** The runtime exposes dense/runtime/
170
+ expert/KV bytes, disk service vs foreground wait, LRU/pin hit rates, tier
171
+ maps, route heat, per-turn latency, queue state, and an explicit startup
172
+ refusal when even one expert slot per sparse layer cannot fit.
173
+ 15. **Expert observability and Atlas.** The live `EMAP` is one byte per expert:
174
+ tier plus a log-bucketed usage count; `HITS` is a per-turn routing bitmap.
175
+ Separately, the offline Atlas probe workflow builds replicated topic-affinity
176
+ vectors for experts and publishes them to the web visualization. These are
177
+ related data products, not one prefetch algorithm.
178
+
179
+ ## What unified memory changes — and what it does not
180
+
181
+ Apple unified memory removes a host-to-VRAM copy. It does **not** make the
182
+ roughly 370 GB expert file addressable as memory on a 32 GB machine. The useful
183
+ native hierarchy is therefore:
184
+
185
+ ```text
186
+ NVMe cold expert -> aligned resident shared-memory slot -> MLX/Metal consumer
187
+ | |
188
+ +-- optional mlock -------+
189
+ ```
190
+
191
+ There should be no fictional RAM-versus-VRAM capacity split on Apple Silicon.
192
+ A Metal-visible expert and a CPU-visible expert occupy the same physical DRAM.
193
+ The meaningful state is disk, resident, wired/pinned, loading, in-flight, or
194
+ evictable. MLX can operate on that shared storage, but the LRU still decides
195
+ which approximately 10-12 GB of experts may coexist with the ~9.9 GB dense
196
+ spine, KV, activations, runtime allocations, Bun, and the OS.
197
+
198
+ The current mlx-bun proof already wraps page-aligned host pointers as MLX arrays
199
+ without a copy. There is an important lifetime limit: `MlxArray.fromPointer`
200
+ requires its backing storage to outlive every MLX reference and retained Metal
201
+ command buffer, which is why the existing mmap stays mapped for the process.
202
+ Reusable LRU slots violate that assumption unless eviction is fenced. The first
203
+ native spike must prove one of these safe designs:
204
+
205
+ 1. native-owned fixed slabs registered once, never freed, whose contents are
206
+ overwritten only after an MLX/Metal completion fence and generation check;
207
+ 2. a custom Metal routed-SwiGLU kernel over registered slabs, with explicit
208
+ command-buffer completion outside MLX array ownership; or
209
+ 3. a new native external-buffer owner whose destructor and completion path never
210
+ call into JavaScript.
211
+
212
+ Ordinary per-miss MLX array creation/copy is not acceptable. Nor may lazy MLX
213
+ graphs retain an evicted slot. Layer-safe `eval`/synchronization, slot generation
214
+ tags, and stress tests are part of the correctness contract.
215
+
216
+ mlx-bun already exposes MLX allocator controls (`setMemoryLimit`, `clearCache`,
217
+ cached/peak memory counters). The 25 GB planner must reserve and cap this
218
+ allocator explicitly, clear reusable temporaries at measured safe points, and
219
+ still use real process physical footprint as the final guard. MLX's cache limit
220
+ is not a substitute for whole-process RSS/footprint control.
221
+
222
+ Potential Apple wins that require measurement:
223
+
224
+ - MLX quantized GEMM/SDPA and compiled graph paths for the resident dense spine;
225
+ - fewer framework crossings and better scheduling of MLA/DSA/shared-expert work;
226
+ - a routed-SwiGLU Metal kernel integrated with the same stream as the model;
227
+ - direct GPU consumption of a freshly loaded shared slab, with no staging copy;
228
+ - mlx-bun's existing batching, KV tiers, grammar, and speculative infrastructure.
229
+
230
+ Colibri already has a fused decode MLA command buffer and zero-copy expert
231
+ Metal kernel, so MLX does not win merely by using the GPU. It must beat or match
232
+ those paths on the same artifact. CPU workers must also wait passively: Colibri
233
+ measured active OpenMP spin stealing the shared SoC power/thermal budget and
234
+ severely throttling Metal.
235
+
236
+ ## Atlas, heat maps, and prefetch are three connected systems
237
+
238
+ The source separates concepts that the UI presents together:
239
+
240
+ - **Live cortex/heat map:** `eusage`, recent heat, last-access clocks, `EMAP`,
241
+ and `HITS` show every expert's residency and activity. Persistent
242
+ `.coli_usage` seeds auto-pin; recent heat plus recency drives live LFRU swaps.
243
+ - **Measured Expert Atlas:** a controlled offline sweep runs independent
244
+ topic-tagged prompts, normalizes for category size, requires cross-prompt
245
+ replication, and assigns per-expert topic-affinity/entropy. The published
246
+ `experts.json` powers labels and the Atlas visualization.
247
+ - **Runtime prefetch:** `PILOT` predicts the next layer with its router;
248
+ `PILOT_REAL` performs value-preserving speculative loads; `PILOT_TWO` adds the
249
+ shared-expert correction; `COUPLE` uses measured cross-layer route pairs.
250
+
251
+ In the inspected Colibri source, the offline topic Atlas is observability and
252
+ interpretability data; it does not directly choose `PILOT` loads. The native
253
+ port should faithfully reproduce all three. It may additionally test an
254
+ Atlas-informed cold-start prior—classify or fingerprint the prompt, then warm
255
+ likely topic specialists—but that is a new experiment, not a claimed Colibri
256
+ behavior. It must beat plain persistent usage/PILOT without changing router
257
+ decisions.
258
+
259
+ ## What mlx-bun already has
260
+
261
+ The codebase-memory graph confirms that the earlier AFM-3 investigation already
262
+ landed the essential Apple proof points:
263
+
264
+ - `src/expert-offload-build.ts` creates a page-aligned expert file.
265
+ - `src/expert-offload.ts` wraps that process-lifetime mmap as MLX arrays.
266
+ - `QuantizedSwitchLinear.load` redirects routed weights into the offload mmap;
267
+ `forward` still uses the bit-exact `mlx_gather_qmm` path.
268
+ - `MmapFile.advise(offset, length, MADV_DONTNEED)` already supports explicit
269
+ clean-page eviction by range.
270
+ - `src/expert-trace.ts` and the trace-analysis scripts measured expert skew and
271
+ cross-task hot-set overlap.
272
+ - The 26B experiment measured roughly 17.1 -> 4.2 GB resident with no short-run
273
+ decode regression and bit-exact output.
274
+ - The serving stack already has continuous batching, byte-capped prompt cache,
275
+ disk KV persistence, memory admission, structured output, prompt-lookup and
276
+ model-based speculative verification, OpenAI/Anthropic/Responses APIs,
277
+ telemetry, a web app, and an existing custom Metal-kernel wrapper.
278
+
279
+ That removes major uncertainty, but the current offload implementation is not
280
+ a GLM-5.2 residency manager:
281
+
282
+ - it maps one whole expert tensor and relies on macOS page-cache policy;
283
+ - it has no per-layer expert-ID -> slot table or deterministic byte cap;
284
+ - it does not stream expert scales/biases (acceptable for Gemma, not necessarily
285
+ for grouped GLM quantization);
286
+ - it does not coalesce gate/up/down reads or overlap them with resident compute;
287
+ - it has tracing but no persistent online usage profile, pinned tier, live LFRU,
288
+ pilot/coupling prefetch, or RSS feedback loop;
289
+ - it only plugs into Gemma's `QuantizedSwitchLinear` loader;
290
+ - mlx-bun has GLM-4 dense support, but no GLM-5.2 MLA, DSA, router, shared MoE,
291
+ or native MTP model class.
292
+
293
+ ## Native MLX architecture
294
+
295
+ Colibri stays installed and runnable on the development machine as a pinned
296
+ external oracle. We use its public artifact directly if the native loader can
297
+ consume it, and invoke direct Colibri only from explicit parity/benchmark
298
+ workflows. There is no Colibri child process, backend protocol adapter, vendored
299
+ runtime, or `--backend colibri` product surface in mlx-bun.
300
+
301
+ The implementation is one in-process MLX model with a native macOS residency
302
+ helper:
303
+
304
+ ```text
305
+ Glm52Model (MLX graph)
306
+ |
307
+ +-- MLA/DSA compressed caches
308
+ +-- resident dense/shared weights
309
+ +-- ExpertResidencyManager (TS policy + native storage/I/O/fences)
310
+ |
311
+ +-- fixed shared-memory slabs
312
+ +-- pread worker queue
313
+ +-- LRU/pin/LFRU/prefetch policy
314
+ +-- routed-SwiGLU Metal/MLX kernel
315
+ +-- route/heat/Atlas telemetry
316
+ ```
317
+
318
+ The public Colibri container should be supported in place so users do not need
319
+ a second 370 GB copy. A future mlx-bun-native layout is justified only by a
320
+ measured Mac I/O or kernel improvement and must remain stream-convertible one
321
+ shard at a time.
322
+
323
+ ### N1. GLM-5.2 graph
324
+
325
+ Add a dedicated `Glm52Model`; this is not the existing universal `glm4`
326
+ descriptor.
327
+
328
+ - Config fields: q/kv LoRA ranks; no-PE/RoPE/value head dimensions; first dense
329
+ layer count; 256 experts/top-8; correction bias; routed scale; shared experts;
330
+ DSA indexer schedule; MTP metadata; multiple EOS IDs.
331
+ - Attention: q-a -> norm -> q-b; kv-a -> latent norm; compressed MLA cache;
332
+ weight-absorption decode; reconstructed prefill fallback; partial interleaved
333
+ RoPE.
334
+ - DSA: indexer q/k/projection/norm, per-layer full/shared schedule, exact dense
335
+ fallback when the selected set covers the whole prefix.
336
+ - MoE: sigmoid scores plus correction bias for selection, un-biased gate weights,
337
+ true top-8, optional normalization/routed scale, shared expert in parallel.
338
+ - MTP: the 79th layer, `eh_proj`, norms, its independent partial KV row, and
339
+ batched verify integration.
340
+ - Cache types: `MLACache` and `DSAIndexCache`, including per-row extraction and
341
+ persistence state.
342
+
343
+ ### N2. Colibri-compatible quant/container support
344
+
345
+ Support the public artifact directly: per-expert gate/up/down tensors, packed
346
+ symmetric int4/int8, per-row or grouped scales, int8 MTP shards, and optional
347
+ indexer shards. Do not keep grouped scales resident merely because the Gemma
348
+ prototype did.
349
+
350
+ Two kernel paths are needed:
351
+
352
+ 1. a reference MLX composition for fixtures and parity work;
353
+ 2. a custom Metal routed-SwiGLU kernel reading Colibri slot slabs directly.
354
+
355
+ The latter preserves the one-read-per-expert layout. Repacking into three
356
+ projection-major MLX tensors would turn one coalesced expert read into three
357
+ reads or add a copy, defeating a central Colibri optimization.
358
+
359
+ ### N3. Explicit `ExpertResidencyManager` (hard gate)
360
+
361
+ State per sparse layer:
362
+
363
+ ```text
364
+ cold -> loading -> resident-LRU -> in-use -> resident-LRU
365
+ | |
366
+ +------> pinned <--------+
367
+ +------> evict-pending -> cold
368
+ ```
369
+
370
+ Required behavior:
371
+
372
+ - fixed byte budget and derived slots/layer;
373
+ - expert-ID -> slot lookup, monotonic LRU use clock, and a separate pinned set;
374
+ - a 64-unique working set for prefill/verify, bounded by actual union size;
375
+ - deduplicated concurrent loads and generation-tagged slots so stale workers
376
+ cannot publish into reused storage;
377
+ - aligned native slabs holding gate/up/down weights and scales;
378
+ - no slot reuse until the Metal/MLX consumer has completed;
379
+ - eviction at model-safe points, never while a lazy MLX command can retain the
380
+ buffer;
381
+ - real RSS/physical-footprint sampling and downward cap correction;
382
+ - startup refusal when dense + one slot/layer + working/KV/transient + OS reserve
383
+ exceeds the budget.
384
+
385
+ The implementation should reuse Colibri's small, well-tested LRU/LFRU policy
386
+ code through a native helper or a faithful TS port, while native aligned
387
+ allocation, `pread`, `F_NOCACHE`, `mlock`, and worker threads live in C/ObjC.
388
+ Blocking disk reads must not run on Bun's event loop.
389
+
390
+ The current process-wide mmap remains a useful reference backend:
391
+ explicit per-expert LRU can call `MADV_DONTNEED` on evicted ranges after an eval
392
+ barrier. It is a bring-up step, not the final 25 GB contract; the slab backend
393
+ is the deterministic Colibri-equivalent implementation.
394
+
395
+ ### N4. Scheduling and prediction
396
+
397
+ - Route the whole layer batch first, form the stable unique expert union, and
398
+ gather all rows/weights per expert.
399
+ - Submit resident experts and the shared expert before starting/waiting for miss
400
+ reads; submit missed experts in a second Metal command buffer and accumulate.
401
+ - Promote completed misses into LRU only after every consumer is done.
402
+ - Persist frequency counts atomically after each turn.
403
+ - Add startup `PIN=auto`, frequency/recency heat, decay, 25%+4 hysteresis, at
404
+ most four live swaps per safe-point pass, and optional wire/unwire.
405
+ - Port PILOT measurement first, hint-only prefetch second, real-load PILOT third,
406
+ and coupling/two-step prediction last. Every prefetch mode needs a paired
407
+ hit-rate, disk-byte, p95-latency, and tok/s A/B; Colibri itself warns that
408
+ prefetch can regress a saturated disk.
409
+
410
+ ### N5. Cache and continuous-batching contract
411
+
412
+ The current `Cache` protocol and `BatchScheduler` are integration targets, not
413
+ automatic compatibility. GLM-5.2 needs three explicit state families:
414
+
415
+ - `MLACache`: compressed latent plus decoupled RoPE state and offset;
416
+ - `DSAIndexCache`: only the indexer state required by that layer's full/shared
417
+ schedule;
418
+ - `MtpCache`: the MTP row's independent attention/cache state.
419
+
420
+ The serial versions must implement masking, state enumeration, trim/rollback,
421
+ disposal, and exact byte accounting without reconstructing full K/V for
422
+ storage. Then add a capability-based batched cache contract (names provisional)
423
+ rather than another list of scheduler class checks:
424
+
425
+ ```ts
426
+ interface BatchableCache extends Cache {
427
+ mergeRows(rows: Cache[]): void;
428
+ extractRow(row: number): Cache;
429
+ projectedBytes(tokens: number): number;
430
+ }
431
+ ```
432
+
433
+ Required scheduler work:
434
+
435
+ - recognize every GLM cache row as batchable only after all three cache types
436
+ implement merge/extract and per-row offsets;
437
+ - use compressed MLA+DSA+MTP byte projections in `#kvAdmits`, never the generic
438
+ full-K/V formula;
439
+ - preserve joiner prompt-cache reuse, FIFO admission, row-local sampling,
440
+ grammar state, stop sequences, errors, and cancellation;
441
+ - form the expert batch-union across all live rows so an expert is acquired once
442
+ per layer/step and released after the shared GPU completion fence;
443
+ - extract completed/cancelled rows without retaining an expert-slot lease or a
444
+ view into another row's cache;
445
+ - test mixed prompt lengths, join/leave churn, context limits, cancellation,
446
+ grammar rows, and a forced expert miss during a row eviction.
447
+
448
+ Serial correctness is allowed before these capabilities land. The final model
449
+ must not claim batching support until the gateway's `willBatch()` and cache
450
+ checks admit it for the correct reasons.
451
+
452
+ Implemented in G7b (2026-08-17): the structural capability uses
453
+ `makeEmptyBatch`, `mergeRows`, `extractRow`, `filterRows`, and
454
+ `projectedBytes`. GLM rows remain right-justified rank-3 latent/RoPE/DSA
455
+ tensors with explicit logical offsets; no full K/V appears at merge,
456
+ admission, extraction, or cancellation. Per-row RoPE and DSA selection preserve
457
+ mixed prompt lengths, while the streamed MLP receives the full live `[B,1,H]`
458
+ input and constructs one expert union. The scheduler awaits the async streamed
459
+ path before filtering any row, so eviction cannot outlive a layer's expert
460
+ completion. Native MTP retains `hasDraft` and routes serial; per-row MTP remains
461
+ the post-release N6 item.
462
+
463
+ ### N6. Native MTP contract
464
+
465
+ MTP is part of GLM-5.2, not a separately loaded assistant model. Integrate it
466
+ with mlx-bun's speculative framework through an in-process draft source that
467
+ shares the target model and reports no duplicate weight allocation.
468
+
469
+ Serial MTP is a hard requirement on the critical path (gate G4): the 2 tok/s
470
+ aspiration assumes its measured 2.2-2.6 tok/forward multiplier, and every
471
+ later gate validates its workload with MTP on.
472
+
473
+ Serial path:
474
+
475
+ - load MTP experts at int8 and include their row in the residency budget;
476
+ - draft up to the configured gamma, verify with the main model in one batched
477
+ forward, and trim target+MTP cache tails precisely after rejection;
478
+ - use the same request sampler and a `SPEC_PIN`-equivalent fixed kernel family
479
+ for draft and verify so accumulation drift does not destroy acceptance;
480
+ - integrate grammar-forced tokens and prompt-lookup/ngram drafts without
481
+ double-advancing caches;
482
+ - expose drafted, accepted, rejected, acceptance length, forwards saved, and
483
+ end-to-end speed—not acceptance alone.
484
+
485
+ Batched MTP across concurrent rows is descoped from the release critical path:
486
+ at 2 tok/s single-user it buys little, and Colibri itself keeps MTP out of its
487
+ mux path because it is not ragged-safe. It remains a documented post-release
488
+ milestone:
489
+
490
+ - add per-row native-draft state to the scheduler;
491
+ - cohort eligible rows into bounded speculative rounds, pad/mask verification
492
+ where draft lengths differ, and apply accept/rollback independently per row;
493
+ - ensure a cancelled or grammar-completed row cannot retain verification arrays,
494
+ cache tips, or expert leases;
495
+ - fall back to ordinary one-token decode for an individual ineligible row while
496
+ its siblings continue.
497
+
498
+ Telemetry and `/v1/models` must report the actual mode (`serial`, `batch`, or
499
+ `off`); it must never be silently disabled. Release (G8) requires serial MTP
500
+ and continuous batching to coexist — batched rows decode ordinary single
501
+ tokens — while per-row MTP under batching lands post-release.
502
+
503
+ ### N7. Persistence contract
504
+
505
+ Extend mlx-bun's versioned `kv-store` rather than inventing a parallel GLM
506
+ session format. Add cache-kind discriminators and snapshot/restore support for
507
+ MLA, DSA indexer, and MTP state; bump the format only if the existing v3 header
508
+ cannot remain backward-compatible.
509
+
510
+ Persist:
511
+
512
+ - token history and exact per-cache offsets/lengths;
513
+ - compressed MLA latent+RoPE tensors only;
514
+ - DSA index state only on layers that own it;
515
+ - the MTP cache row when enabled;
516
+ - model/artifact identity, quantization/layout version, context configuration,
517
+ and hashes needed to reject an incompatible restore.
518
+
519
+ Writes remain streaming, asynchronous, and crash-safe (`.tmp`, fsync, atomic
520
+ rename), materializing at most one tensor at a time. Restore must not build full
521
+ K/V or touch the expert file. Persistent expert usage/heat is a separate small
522
+ atomic profile: KV reset must not erase learned expert placement, and deleting
523
+ the usage profile must not invalidate a KV snapshot.
524
+
525
+ The existing prompt cache and SSD cold tier must receive accurate compressed
526
+ byte counts and support row extraction/demotion. Exit requires a restart at
527
+ multiple sequence lengths to produce the same next logits/tokens and cache
528
+ offsets as uninterrupted generation.
529
+
530
+ ### N8. Serving, library, and CLI parity contract
531
+
532
+ "API parity" means the generative surfaces mlx-bun already exposes, with the
533
+ same request validation, stream shapes, finish reasons, errors, and usage
534
+ accounting as other text models:
535
+
536
+ | Surface | GLM-5.2 requirement |
537
+ |---|---|
538
+ | `POST /v1/chat/completions` | streaming/non-streaming chat, tools, stops, sampling, usage, structured output |
539
+ | `POST /v1/completions` | raw-tokenized text completion, streaming/non-streaming |
540
+ | `POST /v1/messages` | Anthropic message/tool blocks and event stream |
541
+ | `POST /v1/responses` | input/instructions, tools, streaming, `previous_response_id` continuation |
542
+ | `GET /v1/models` | GLM identity, context, reasoning/MTP/batching capability truth |
543
+ | `GET /health`, `GET /stats` | readiness plus memory, scheduler, MTP, expert-tier and I/O telemetry |
544
+ | library `generate(...)` | tokens, samplers, grammar, stop callback, stats, disposal |
545
+ | `mlx-bun chat` / `serve` | the same model path—no special runner or backend flag |
546
+
547
+ Required request features are SSE/disconnect cancellation, greedy and sampled
548
+ decode, penalties/logit bias where that protocol accepts them, logprobs through
549
+ the existing serial lane, tool round-trips, JSON schema/grammar constraints,
550
+ stop sequences, prompt-cache reuse, usage accounting, and bounded concurrency.
551
+ The HTTP translators must remain model-agnostic; GLM-specific behavior belongs
552
+ below `GenerationGateway`.
553
+
554
+ This does **not** imply embeddings, image/audio input, LoRA hot-swap, training,
555
+ or adapter APIs for GLM-5.2. Those are different model capabilities and must be
556
+ advertised false/unsupported rather than faked. Existing non-generation admin,
557
+ memory, hub, and web routes must continue to work but require no GLM-specific
558
+ semantics.
559
+
560
+ ### N9. Observability, Atlas, and resource-planning contract
561
+
562
+ Add an expert block to `/stats` with budget/resident/wired/working/MLX-cache
563
+ bytes, LRU/pin capacity, hit/miss/prefetch counts, disk bytes/service/wait,
564
+ prefetch precision/recall, evictions, and pressure-driven cap changes. Serve the
565
+ packed per-expert tier/heat/hit map through a dedicated web data route so the
566
+ normal stats response does not carry 19,456 cells every poll.
567
+
568
+ The web experience includes:
569
+
570
+ - live layer x expert residency/heat cells and per-turn hit flashes;
571
+ - pinned/LRU/disk totals and pressure events;
572
+ - the offline replicated topic-affinity Atlas with provenance and confidence;
573
+ - I/O, cache, MTP acceptance, and latency timelines suitable for A/B runs.
574
+
575
+ `fit` and `doctor` expose the exact dense, expert-slot, 64-working-set,
576
+ MLA/DSA/MTP-per-slot, reconstructed-KV transient, MLX allocator, Bun, and OS
577
+ reserve equation. Startup refuses an impossible quality-preserving placement;
578
+ runtime physical-footprint feedback may shrink only the evictable LRU tier.
579
+
580
+ ### Proposed code map
581
+
582
+ Names are provisional, but ownership should remain this explicit:
583
+
584
+ | Area | Production location | Responsibility |
585
+ |---|---|---|
586
+ | Model/config | `src/model/glm52.ts`, `src/model/glm52-config.ts` | graph, routing, MLA/DSA, factory registration |
587
+ | Cache | `src/model/glm52-cache.ts` | serial/batched MLA, DSA and MTP state; byte projection |
588
+ | MTP | `src/model/glm52-mtp.ts`, `src/spec/` adapter | native drafting, verify, rollback, metrics |
589
+ | Container | `src/model/glm52-container.ts` | manifest/index validation and tensor/expert offsets |
590
+ | Residency policy | `src/expert-residency.ts` | LRU/pin/LFRU state machine, leases, learning, prefetch |
591
+ | Native boundary | `src/native/` plus Bun FFI binding | aligned slabs, `pread`, no-cache hints, wire/unwire, completion fences |
592
+ | Kernels | `src/model/glm52-kernels.ts` | reference MLX compositions and selected Metal kernels |
593
+ | Resource plan | existing fit/memory modules | 32 GB equation, startup refusal, pressure feedback |
594
+ | Serving | existing gateway/scheduler/server | cache capabilities, MTP batches, protocol-neutral generation |
595
+ | Atlas/UI | expert trace/analysis scripts + web | live map, offline affinity workflow, A/B telemetry |
596
+
597
+ Do not put HTTP request parsing, Atlas visualization, or LRU policy into the
598
+ native helper. Do not put disk I/O or blocking waits into MLX model methods or
599
+ the Bun event loop. The native boundary exposes leases/completion signals; Bun
600
+ owns policy and observability.
601
+
602
+ ### Test and workflow split
603
+
604
+ - **Every-commit, model-free:** synthetic container parsing, LRU/LFRU traces,
605
+ short reads/errors/cancellation, slot-generation races, cache merge/extract,
606
+ protocol regression, and memory-equation unit tests.
607
+ - **macOS Metal CI:** tiny routed-SwiGLU/MLA/DSA parity; repeated slot churn;
608
+ external Colibri `make check` and `metal-test` at the pinned commit. No model
609
+ download.
610
+ - **Tiny-model parity workflow:** deterministic generated GLM fixture for
611
+ teacher forcing, MTP accept/rollback, KV save/restore, and two-row batching.
612
+ - **Full-model manual workflow:** the public artifact on a cleared machine;
613
+ records commit/artifact/hardware/OS/settings, footprint/swap, cache/I/O,
614
+ tokens, latency and throughput. It never runs in an agent session or CI.
615
+ - **Release gate:** API conformance suites exercise the same server twice—one
616
+ ordinary supported text model and GLM-5.2—to prove the model did not fork the
617
+ HTTP contract.
618
+
619
+ ## What not to copy blindly
620
+
621
+ "Everything" means preserving every useful mechanism and every negative result,
622
+ not enabling every knob:
623
+
624
+ - CUDA multi-GPU, Linux io_uring, Windows shims, Power/AVX kernels, and NUMA are
625
+ not part of an Apple-only MLX runtime. Their *roles* map to Metal, a macOS I/O
626
+ worker, ARM kernels, and unified memory.
627
+ - `EXPERT_BUDGET` is quarantined upstream: tested settings damaged HellaSwag,
628
+ produced incoherent decode, broke MTP's draft/verify contract, and were not
629
+ faster. Keep it unshipped or behind an unmistakable research gate.
630
+ - `CACHE_ROUTE`, expert top-p, and reduced top-k change the model function. They
631
+ are Lab tier, default off, with KL and task-quality gates. Several of
632
+ Colibri's best small-RAM hit-rate numbers use expert top-p; progress toward
633
+ the 2 tok/s aspiration must not use them as defaults.
634
+ - PILOT real loads can evict useful experts on a misprediction. It is an A/B
635
+ optimization, not part of the correctness floor.
636
+ - MTP must not silently claim to be active under a scheduler that disables it.
637
+ - Colibri's projected cap was once wrong by tens of GB; the measured RSS guard
638
+ is mandatory for the 25 GB promise.
639
+
640
+ ## Risk register
641
+
642
+ | Risk | Earliest detection | Required mitigation |
643
+ |---|---|---|
644
+ | MLX retains an expert slot after policy release | G1 forced-churn poison/generation-tag test | explicit eval/completion fence; fixed native slab lifetime; never reuse on JS disposal alone |
645
+ | Lazy graph observes overwritten expert bytes | G1/G3 adversarial miss+evict trace | lease count plus slot generation checked before publish and before reuse |
646
+ | MLX allocator/transients break 25 GB | G1 counters, G5 physical-footprint trace | reserve allocator bytes, set limit, clear only at safe points, runtime LRU shrink |
647
+ | Prefetch saturates disk or evicts useful experts | G6 paired off/hint/real A/B | bounded queue, future-layer-only loads, residency recheck, default off unless positive |
648
+ | MTP accumulation drift collapses acceptance | G2 fixture, G4 oracle trace | fixed draft/verify kernel family and int8 MTP; acceptance + wall-time gate |
649
+ | Warm speed lands under the aspirational 2 tok/s on the target machine | G0 baseline, G5 measured speed | publish the measured gap; continue gap-vs-oracle debugging (pin quality, I/O overlap, MTP acceptance); never quality-changing knobs by default |
650
+ | Batched cache merge/extract corrupts row offsets | G7 tiny mixed-length/cancel workflow | capability-based cache contract, row ownership tests, serial differential oracle |
651
+ | Persistence silently restores wrong artifact/layout | G7 restore-negative tests | model/config/quant/layout identities and tensor hashes; fail before allocation |
652
+ | Expert policy changes model quality | every routing golden | true top-8 default; policy moves weights only; approximate routing Lab-only |
653
+ | HTTP behavior forks for GLM | G7 dual-model API conformance | keep translation above `GenerationGateway`; no GLM branches in protocol builders |
654
+ | Public artifact format moves | G0 manifest inventory, loader tests | pin supported layout versions; reject unknown; one-shard converter fallback |
655
+ | Atlas overstates expert specialization | G6 leave-one-prompt-out workflow | normalized independent probes and replication gate; provenance in UI |
656
+
657
+ ## Phased delivery and exit criteria
658
+
659
+ Critical path:
660
+
661
+ ```text
662
+ G0 oracle baseline
663
+ -> G1 safe shared slabs + kernel choices
664
+ -> G2 serial GLM graph + compressed caches
665
+ -> G3 full expert LRU execution
666
+ -> G4 serial native MTP
667
+ -> G5 <=25 GB full-model contract (MTP on)
668
+ +-> G6 learning / Atlas / overlap / prefetch --+
669
+ +-> G7 persistence / batching / APIs ----------+-> G8 release
670
+ ```
671
+
672
+ G6 and G7 may proceed independently after G5, but G8 requires both. No phase may
673
+ claim a later capability early: for example, G2 can be serial-only, G3 can run
674
+ without MTP, and G7 cannot claim batching merely because ordinary KV caches
675
+ batch.
676
+
677
+ ### G0 — establish the direct Colibri/Metal baseline
678
+
679
+ - Pin the external Colibri commit and record its license, public artifact
680
+ identity, file inventory, config, tokenizer, int8-MTP presence, and disk
681
+ envelope. Do not vendor it into mlx-bun.
682
+ - Build and run direct Colibri's model-free macOS workflow (`make -C c check`
683
+ and `make -C c metal-test`) without model downloads.
684
+ - Verify >=400 GB free on the target machine at download time (measured
685
+ 2026-07-21: ~556 GB unallocated + ~123 GB purgeable ≈ 679 GB practically
686
+ available — met on the internal SSD with wide margin).
687
+ - On the cleared M1 Max 32 GB machine, run the public artifact directly with
688
+ Metal and capture physical footprint, compression/swap, LRU/pin capacity,
689
+ hit rate, disk bytes/wait, first-token latency, and cold/warm tok/s — each
690
+ with MTP on and off.
691
+ - Export tiny deterministic GLM/quant/DSA/MTP and routing/cache-trace fixtures.
692
+
693
+ G0 inventory note (2026-07-21): the exact pin, artifact/layout contract, and
694
+ manual checklist are recorded in
695
+ [`../investigations/colibri-oracle-pin.md`](../investigations/colibri-oracle-pin.md).
696
+ Because the pinned Makefile writes ignored build artifacts and even creates a
697
+ configuration stamp while parsing, model-free oracle targets must run from a
698
+ temporary `git archive` extraction, not in the read-only checkout. The pinned
699
+ tiny generator covers GLM/MLA/DSA but does not emit a complete MTP layer; the
700
+ checked-in [`../../fixtures/colibri-glm52/`](../../fixtures/colibri-glm52/README.md)
701
+ package therefore contains a narrow exact-pin model-free capture for Python
702
+ quantization, Apple-ARM quantized matmul, DSA, LFRU, and elementary
703
+ RMSNorm/sigmoid. Its operator/router/LRU/MTP material is explicitly derived
704
+ scaffolding. It does **not** claim teacher-forced numeric GLM/MLA/MTP-head/KV
705
+ outputs or measured neural acceptance. Those require a real model oracle and
706
+ were the two remaining G0 blockers before the closure evidence below.
707
+
708
+ G0 closure (2026-07-22): both blockers are now closed. The complete public
709
+ artifact was run directly on the 32 GiB M1 Max with Metal unified-memory
710
+ zero-copy. Six matched fresh-process/direct-I/O cells (three MTP-off, three
711
+ MTP-on) and bounded same-process pairs with KV reset establish the explicit-LRU
712
+ cold/warm baseline. A measurement-only archived-copy build emitted 140
713
+ teacher-forced GLM/MLA/router/MTP/KV records twice, byte-identically; the
714
+ validated compact oracle is tracked under `fixtures/colibri-glm52/`. All 145
715
+ LFS payloads match pinned-revision SHA-256. For reproducibility, **cold** here
716
+ means a fresh process with an empty explicit LRU and macOS `F_NOCACHE`
717
+ (`DIRECT=1`), not an unrepeatable claim that no file on the machine had been
718
+ read since boot. **Warm** means request two in the same PID after RESET clears
719
+ KV but preserves the explicit expert LRU. In the authoritative three-process
720
+ per-mode matrix, fresh-turn throughput is 0.34 tok/s MTP-off versus 0.26 tok/s
721
+ MTP-on, with median peaks of 13.631/17.475 GB and no process swaps. MTP reduces
722
+ main forwards by 52% but adds 34.6% expert traffic and 29.1% wall time. Live
723
+ telemetry (~4.9 GB/s reads, 0 writes, 24% GPU, 16.1 GB/s unified-memory
724
+ bandwidth) confirms the initial optimization target is overlapped expert
725
+ delivery/residency rather than more arithmetic throughput.
726
+
727
+ The artifact lacks DSA indexers, so the direct public-artifact baseline
728
+ explicitly runs DSA-off. At G0's 128-token context this does not change
729
+ attention selection: the first 21 layers are full-attention layers and DSA's
730
+ `topk=2048` cannot prune such a short history. G2 retains the exact-pin
731
+ model-free DSA fixtures and will generate a **separate immutable indexer
732
+ overlay** by extracting only the indexer tensors from 20 pinned stock FP8
733
+ source shards (~99.90 GiB read, ~197 MB output). The overlay must never mutate
734
+ or duplicate the 357 GiB serving snapshot.
735
+
736
+ **Exit:** a reproducible same-machine oracle baseline is recorded — footprint,
737
+ hit rate, disk service/wait, TTFT, cold/warm tok/s, MTP on and off. These
738
+ numbers are the bar the port is debugged against for the rest of the program:
739
+ a gap versus direct Colibri is a bug to close, never a reason to cancel the
740
+ port. They also tell us early how much of the 2 tok/s aspiration comes from
741
+ matching the oracle versus beating it.
742
+
743
+ ### G1 — unified-memory MLX storage foundation
744
+
745
+ - Build a model-free synthetic expert file in Colibri's gate/up/down layout.
746
+ - Implement fixed aligned native slabs plus bounded positioned-read workers.
747
+ - Prove zero-copy MLX/custom-Metal consumption, command completion fencing,
748
+ generation-tagged slot reuse, eviction, and allocator-cache control.
749
+ - Benchmark Colibri Metal and candidate MLX paths for representative int4 dense
750
+ GEMM, routed SwiGLU at decode/prefill row counts, and MLA decode attention.
751
+ - Measure CPU/GPU power contention with passive workers; reject busy-spin.
752
+
753
+ **Exit:** no hidden expert copy, stale read, use-after-reuse, or monotonic memory
754
+ growth under forced churn. Select and record the fastest correct MLX/custom-
755
+ Metal execution path for each kernel shape, then proceed with the full port.
756
+
757
+ #### G1 implementation status (2026-07-22)
758
+
759
+ The agent-safe foundation is implemented and independently audited. A strict,
760
+ versioned model-free artifact preserves one-read contiguous gate/up/down bytes
761
+ and separately contiguous scales. The native helper owns fixed 16 KiB-aligned
762
+ slabs, uses a bounded `pthread_cond_wait` worker pool plus full positioned reads,
763
+ and exposes nonblocking Bun polling. Slot pointers are observable only through
764
+ matching generation-bound leases. GPU release requires the dependent lazy MLX
765
+ outputs, evaluates them, synchronizes their selected stream, and only then
766
+ publishes the slot as reusable; close refuses live leases.
767
+
768
+ The stress gate includes short-read/cancellation/error paths, post-close access,
769
+ stateful hit/miss/evict traces, 1,000 native reloads with stable addresses and
770
+ bounded RSS, 100 GPU-fenced reloads with flat MLX active+cache accounting, and a
771
+ reproduction of the lazy-graph poison race. Both stock MLX and custom Metal
772
+ consume the same slab, including a complete synthetic gate/up/down region.
773
+ The helper remains an internal, build-only G1 artifact via
774
+ `scripts/build-expert-io.sh`; G3/G8 integration will publish it in a newly
775
+ versioned native pack and update the distribution reference in the same change.
776
+
777
+ G1 closed on 2026-07-30 with the manual quiet-machine gates. After aligning
778
+ both harnesses to identical production shapes, a ten-warmup/fifteen-sample
779
+ matrix selected custom Metal for routed SwiGLU decode M=1: 4.282 ms versus
780
+ 5.099 ms for stock MLX (16.0% faster), with max absolute output delta
781
+ `2.33e-9` and relative RMSE `5.56e-7`. An independent three-warmup/eleven-
782
+ sample run also selected custom Metal by 5.4%. Stock MLX remains selected for
783
+ Q4 dense decode/prefill, routed M=11 ragged and M=32 prefill, and absorbed MLA
784
+ decode. Direct Colibri remains the same-shape performance oracle; the largest
785
+ observed residual is MLA decode at 1.014 ms direct versus 11.506 ms stock MLX.
786
+
787
+ The passive-worker matrix retained raw mactop samples for matched no-worker,
788
+ 1-, 2-, and 4-worker arms and repeated the worker arms in reverse order. No
789
+ monotonic CPU, GPU, or package-power increase appears as worker count rises,
790
+ confirming that the `pthread_cond_wait` pool does not busy-spin. Two workers
791
+ remain the bounded default. Swap was unchanged at 339.25 MiB through both
792
+ kernel runs. Raw artifacts are under `runs/colibri-g1/`.
793
+
794
+ ### G2 — native GLM-5.2 correctness spine
795
+
796
+ - Implement config, tokenizer/template, dense graph, MLA compressed KV, DSA,
797
+ router/shared MoE, and reference expert math against tiny fixtures.
798
+ - Add Colibri container parsing and per-tensor validation.
799
+ - Define the numeric parity contract before debugging begins: bitwise equality
800
+ where the math is deterministic (int4/int8 dequantization on identical
801
+ inputs, router top-8 selection, cache byte accounting); trajectory-level
802
+ equality for floating-point logits (tie-free greedy token match plus a
803
+ recorded max-logit-delta bound). Cross-implementation Metal accumulation
804
+ order is not expected to match bitwise by default — the SigLIP parity
805
+ investigation established sub-bf16 accumulation as an expected residual, not
806
+ a bug.
807
+ - *(Added 2026-07-22.)* Colibri shows the stronger contract is attainable by
808
+ construction: its Metal and CUDA tiers pin numerics to **dequant→f32
809
+ multiply-accumulate** and produce greedy outputs byte-identical to its CPU
810
+ engine (`docs/metal.md`). Our custom kernels adopt the same dequant→f32-MAC
811
+ discipline — the `SPEC_PIN` philosophy applied to the whole expert path.
812
+ Where we also match the oracle's accumulation semantics, the
813
+ greedy-trajectory gate hardens to a bitwise claim; the trajectory-level
814
+ bound remains the fallback only for paths whose accumulation order is not
815
+ ours to pin (e.g., stock MLX kernels on the dense spine).
816
+
817
+ **Exit:** layer/op goldens pass under the recorded contract; tiny-model teacher
818
+ forcing is 32/32 token-exact on a tie-free greedy trajectory against the pinned
819
+ Colibri engine; full-model dense/router probes match within the recorded
820
+ bounds.
821
+
822
+ #### G2 implementation status (2026-07-24)
823
+
824
+ The dedicated correctness path is implemented. `glm_moe_dsa` configuration is
825
+ parsed independently of the stale source-checkpoint FP8 metadata; the factory
826
+ has an artifact-aware `openModel()` entrypoint; the GLM fallback template pins
827
+ roles, thinking blocks, and tool formatting; and EOS IDs are the union of model
828
+ and generation configuration. A header-only catalog reads `out-*`,
829
+ `out-mtp-*`, and optional `out-idx-*` safetensors directly, infers Q4/Q8 from
830
+ payload/scale geometry, and validates every expected global, attention, dense,
831
+ shared, routed-expert, DSA, and MTP tensor before graph construction.
832
+
833
+ The MLX correctness backend opens those shards lazily on the CPU stream.
834
+ Colibri Q4 bytes are repacked lazily into MLX's uint32 affine layout with
835
+ `bias=-8*scale`; Q8 restores the signed two's-complement byte before applying
836
+ its scale. MLA stores only compressed latent and decoupled RoPE state, supports
837
+ reconstructed causal prefill and absorbed single-token decode, and gathers DSA
838
+ positions without first materializing full K/V. The DSA state is correctly one
839
+ shared `[B,T,index_head_dim]` key—not one key per index head—and implements
840
+ full-layer selection plus scheduled reuse. MoE routing uses biased sigmoid for
841
+ selection, lower expert ID for exact ties, unbiased sigmoid for execution,
842
+ routed scaling, and an unweighted shared expert.
843
+
844
+ Focused tests cover config/container failures, layout/dispatch, Q4/Q8
845
+ dequantization, reference f32 arithmetic, partial interleaved RoPE, compressed
846
+ cache bytes and trim, reconstructed/absorbed MLA equality, DSA threshold/ties,
847
+ sparse decode, exact row-wise fallback when a multi-token prefill crosses
848
+ `index_topk`, exact router ties, shared+routed composition, the template, and
849
+ independent one-layer dense and MoE host oracles. Header-only validation of
850
+ the pinned public artifact completed without executing the model and reported
851
+ 59,003 quantized tensors, 472 floats, 19,456 routed experts, MTP present, and
852
+ DSA absent.
853
+
854
+ The pinned 32-token gate is tracked as
855
+ `fixtures/colibri-glm52/tiny-teacher-forcing.json` and selected with
856
+ `MLX_BUN_GLM52_TINY_COLIBRI`. On 2026-07-24 an isolated Python 3.12 environment
857
+ with Torch 2.8.0, Transformers 5.12.0, and safetensors 0.8.0 ran the pinned
858
+ Colibri generator. Transformers' default grouped-MoE dispatcher has no Torch
859
+ 2.8 CPU kernel, so generation selected its mathematically identical eager
860
+ expert implementation; the resulting BF16 trajectory reproduced committed
861
+ `c/ref_glm.json` exactly.
862
+
863
+ The raw toy model was then converted with Colibri's own converter to the
864
+ production-relevant per-row Q4 direct format. Its 9/32 score against the BF16
865
+ trajectory is simply the quantized model differing from the source model; the
866
+ correct cross-engine oracle is the same Q4 bytes in both runtimes. An initial
867
+ default-vs-default comparison produced 26/32 because the two defaults did not
868
+ compute the same function: on Apple Silicon Colibri enables `IDOT=1`, which
869
+ quantizes each activation row to int8 before the packed-int4 dot product and
870
+ documents about 0.3% additional RMS error per matmul. The G2 contract instead
871
+ pins the quality-preserving dequant-to-f32-MAC path, selected in Colibri with
872
+ `IDOT=0`.
873
+
874
+ Under that matched contract, pinned Colibri C and mlx-bun are 32/32 on the same
875
+ Q4 artifact. An archive-only Colibri instrumentation build dumped all 8,192
876
+ f32 logits: max absolute delta is 1.3113e-6, mean absolute delta 2.1548e-7,
877
+ RMSE 2.7423e-7, and the minimum MLX top-two margin is 0.003425. The fixture
878
+ records exact commands, oracle flags, exact-path and default-IDOT trajectories,
879
+ numeric bounds, and raw/config/container hashes; the generated 353 KiB
880
+ container lives at `runs/colibri-glm52-tiny-i4` (gitignored). `IDOT` is now an
881
+ explicit approximate-performance candidate for a later quality/performance
882
+ gate, not the correctness oracle.
883
+
884
+ The production-artifact gate is also closed. The bounded runner opens only the
885
+ shard owning the cell under test and never constructs the full model, experts,
886
+ KV cache, tokenizer, or generation loop. On the captured real decode row,
887
+ layer 0's complete Q4 gate/up/down SwiGLU matched pinned Colibri `dense_mlp`
888
+ with `IDOT=0` at max absolute delta 5.2387e-9 and RMSE 9.7823e-10. The real
889
+ layer-3 and layer-77 routers reproduced every top-8 ID and `keff=8`; their
890
+ sigmoid max deltas were 4.7684e-7 and 7.1526e-7. Two fresh processes produced
891
+ identical numeric reports. This run caught a production-only loader defect
892
+ that the tiny artifact could not expose: MLX has no affine-dequant Metal kernel
893
+ for Colibri's logical whole-row group size 6144. Repeating the identical
894
+ per-row scale over supported 32-value groups preserves every dequantized value
895
+ and selects an available kernel. With the tiny artifact gate enabled, the
896
+ focused GLM suite is 55 pass, 0 fail after the fix.
897
+
898
+ The probe peaked at 1,566,883,896 MLX allocator bytes and 290,455,552 observed
899
+ process RSS; system free memory stayed at 78% and swap usage was unchanged.
900
+ The stable evidence and bounds are tracked in
901
+ `fixtures/colibri-glm52/production-probe.json`, with the reproducible runner at
902
+ `scripts/probe-colibri-glm52-production.ts`. G2 validates the complete MTP
903
+ container/config surface; serial MTP execution and rollback remain G4 under
904
+ the revised order.
905
+
906
+ ### G3 — native bounded LRU and slab execution path
907
+
908
+ - Add the native I/O helper, slot manager, LRU/pin states, RSS guard, batch-union,
909
+ and the winning batched routed-SwiGLU MLX/Metal kernel from G1.
910
+ - First run with pure LRU; add persistent auto-pin only after the baseline.
911
+
912
+ **Exit:** forced hit/miss/evict traces match a reference policy exactly; no
913
+ partial/stale slot can be observed under stress; quality-policy tokens match
914
+ direct Colibri for a tie-free trajectory.
915
+
916
+ #### G3 implementation status (2026-07-24, in progress)
917
+
918
+ The direct artifact now has one canonical routed-expert slot catalog and a
919
+ native multi-file scatter-read pool. Production Q4 experts occupy 18,939,904
920
+ aligned bytes; every MLX-addressed component has an independently page-aligned
921
+ offset. The 19,114 ordinary main experts use four positioned reads and the 86
922
+ shard-boundary cases use six, below the fixed eight-segment limit. Idle
923
+ generations can be decommitted without changing their virtual addresses, and
924
+ live pressure uses the process `phys_footprint` counter rather than historical
925
+ peak RSS.
926
+
927
+ The first policy implementation mirrors Colibri's physical tiers: one global
928
+ 64-slot working bank, fixed per-layer LRU slots, and a separate pinned bank.
929
+ Misses are promoted only after a shared GPU fence by swapping logical slot
930
+ roles with free/LRU destinations; expert payloads are never copied. Stable
931
+ row/rank batch union, reverse miss promotion, deterministic LRU ties, startup
932
+ refusal, failure drain/discard, and safe-point-only downward capacity
933
+ correction have focused tests.
934
+
935
+ An async GLM-only execution seam preserves the synchronous G2 model as the
936
+ oracle. Its stock-MLX candidate wraps packed slot bytes directly, submits
937
+ resident/shared work before miss reads, materializes each <=64-expert wave
938
+ before releasing leases, and composes rows in exact route order afterward.
939
+ The resident tensor source rejects routed-expert names, closing accidental
940
+ mmap fallback. The tiny direct Q4 container remains 32/32 token-exact through
941
+ this path. The bounded production layer-3 expert probe reproduces exact top-8,
942
+ matches the complete Colibri routed+shared output at max absolute delta
943
+ 1.8626e-9, and remains byte-identical after a forced LRU eviction with zero
944
+ swap growth. The custom M=1 Metal candidate is implemented and explicitly
945
+ selectable.
946
+
947
+ The production full-model trajectory now passes as well. A 32-token prefill
948
+ and one decode forward reproduce the tie-free Colibri token sequence
949
+ `[16,13]`, with margins 2.9581 and 7.0824. The direct streamed run ends at
950
+ 13,474,688,232 bytes physical footprint and 11,007,206,184 bytes MLX peak
951
+ allocation, with 64 working slots, 75 resident slots, and no loading or leased
952
+ slot left behind. Bring-up first exposed a G2-only memory amplification:
953
+ materializing the 154,880×6,144 signed-int8 embedding and output head as full
954
+ f32 tensors. The streamed source now gathers embedding rows before dequant,
955
+ evaluates the output head in bounded row tiles, uses MLX affine Q4 matmul for
956
+ the resident spine, and synchronizes each layer as a residency safe point.
957
+ A per-wave live guard records cumulative swap counters and aborts at a caller
958
+ bound. The passing non-cleared run recorded 397,148,160 bytes of system-wide
959
+ swapout while other applications were open; the strict cleared-machine
960
+ zero-swap contract remains G5. Evidence:
961
+ `fixtures/colibri-glm52/g3-full-model-trajectory.json`.
962
+
963
+ G3 closed on 2026-07-30 after the quiet kernel/power matrix selected custom
964
+ Metal for M=1 routed decode and stock MLX for ragged/prefill shapes. The final
965
+ adversarial code review found no numeric, alignment, ownership/UAF, or budget
966
+ blocker; its two cleanup-path findings were fixed before the focused/native
967
+ suite was rerun.
968
+
969
+ ### G4 — serial native MTP (requirement)
970
+
971
+ Serial MTP lands ahead of the memory contract because the 2 tok/s aspiration
972
+ assumes it, and because it changes the workload every later gate must
973
+ validate: verify forwards route a larger per-forward expert union, and the
974
+ verify batch plus the MTP row's KV live inside the 25 GB envelope.
975
+
976
+ - int8 MTP row sharing target weights, included in the residency budget;
977
+ - draft to the configured gamma, one batched verification forward, exact
978
+ target+MTP cache trim after rejection;
979
+ - the same request sampler and a `SPEC_PIN`-equivalent fixed kernel family for
980
+ draft and verify — accumulation drift destroys acceptance;
981
+ - grammar-constrained verification and the model-free prompt-lookup provider
982
+ without double-advancing caches or grammar state (one draft provider owns a
983
+ request);
984
+ - report drafted/accepted/rejected, acceptance length, tok/forward, forwards
985
+ saved, and end-to-end speed — not acceptance alone.
986
+
987
+ **Exit:** the accept/reject trace matches the direct-Colibri oracle for a
988
+ tie-free trajectory; measured tok/forward and a net end-to-end win over
989
+ MTP-off on the same artifact. All subsequent gates run with MTP on as the
990
+ default workload.
991
+
992
+ G4 closed on 2026-07-30. `Glm52NativeMtpProvider` runs the artifact's single
993
+ MTP layer in-process, shares the target embedding/output head/dense weights,
994
+ and gives the signed-int8 routed row its own bounded 24-working + 1-resident
995
+ expert tier. The 945,356,800-byte MTP expert slab and the remaining MTP
996
+ tensors are included in the main fixed-byte residency plan. Draft, verify,
997
+ accepted-row absorption, and rollback use the same request sampler and
998
+ row-independent custom Metal families (Q4 target and signed-Q8 MTP);
999
+ M=1/M=4 and M=1/M=3 row-stability tests lock that accumulation contract.
1000
+
1001
+ The cache state machine advances the MTP row once per proposal, retains the
1002
+ first true-target-conditioned row, discards the speculative tail, and rebuilds
1003
+ accepted rows from the target's verified hidden window. Thus target and MTP
1004
+ offsets remain aligned after partial or zero acceptance. Grammar remains in
1005
+ the existing constrained verify walk: proposals never advance the matcher,
1006
+ only target-accepted emitted tokens do. Prompt lookup remains the alternative
1007
+ model-free `DraftProvider`; exactly one provider owns a request, avoiding two
1008
+ independent draft histories or double cache/grammar advancement.
1009
+
1010
+ The direct `IDOT=0,SPEC_PIN=1` oracle and mlx-bun match all 64 target tokens
1011
+ and the tie-free first four acceptance rounds `[1,1,1,0]` (the first eight
1012
+ emitted tokens; minimum direct first-draft margin 3.5675). The complete direct
1013
+ acceptance trace is preserved but is not an exact cross-engine gate: direct
1014
+ Colibri reduces RMSNorm squared sums in float64, while the established MLX
1015
+ graph reduces in float32. That difference recurs through 78 layers and can
1016
+ change later MTP proposals without changing the target trajectory.
1017
+
1018
+ The separate-process production A/B is positive. MTP-on took 675.654 seconds
1019
+ for the exact 64-token trajectory versus 834.172 seconds off: 1.235x wall
1020
+ throughput, or 19.0% less generation time. It drafted 92 tokens, accepted 32,
1021
+ rejected 60, used 31 verify forwards, emitted 2.065 tokens per verify forward,
1022
+ and saved 32 target forwards. The completed MTP-on process footprint was
1023
+ 14,679,224,320 bytes, but the machine was not swap-cleared; this is G4
1024
+ correctness/performance evidence, not the G5 memory-contract result. Stable
1025
+ records: `fixtures/colibri-glm52/g4-direct-mtp-trace.json` and
1026
+ `fixtures/colibri-glm52/g4-native-mtp-e2e.json`.
1027
+
1028
+ ### G4R — prompt-seeded MTP research spike (deferred 2026-07-30)
1029
+
1030
+ G4 deliberately copies direct Colibri's decode-only MTP window: target prompt
1031
+ prefill is complete, but the independent MTP KV row begins with the first
1032
+ draft. That implementation is the control, not a permanent restriction.
1033
+ Josh explicitly deferred this optional research spike so G5 can measure the
1034
+ landed decode-only default first.
1035
+ Investigate a candidate that batch-seeds MTP KV from the already-computed
1036
+ prompt pairs `(token[i+1], target_hidden[i])` before drafting. It must reuse
1037
+ captured target hidden rows rather than rerun target prefill.
1038
+
1039
+ The oracle for this spike is emitted output, not Colibri's internal draft or
1040
+ acceptance trace. Promotion requires bit-for-bit target-output identity in the
1041
+ gated greedy and seeded-sampling cells, correct rollback/cancellation behavior,
1042
+ and a paired end-to-end wall-time win after charging the additional MTP
1043
+ prefill. Report TTFT, MTP-prefill time, decode and total time, acceptance,
1044
+ target forwards, footprint, and swap across short/long prompt and continuation
1045
+ cells. A decode-throughput or acceptance-only win is insufficient. If the
1046
+ candidate loses or exceeds the G5 envelope, retain the decode-only default and
1047
+ record the negative result.
1048
+
1049
+ ### G5 — 32 GB memory contract (measured with MTP on)
1050
+
1051
+ - Port the full resource equation and expose every line item.
1052
+ - Set a conservative one-slot, 4k-context quality preset for 32 GB machines;
1053
+ allow explicit overrides but refuse impossible starts.
1054
+ - Include MLX allocator cache/transients, native slabs, Bun, physical footprint,
1055
+ and the OS reserve; shrink only evictable LRU slots under real pressure.
1056
+ - Measure with MTP on: the verify batch, the MTP KV row, and the larger
1057
+ per-forward expert union are part of the accounted workload.
1058
+
1059
+ The header-only preflight now runs before resident weights or native slabs are
1060
+ opened. Its pinned-artifact MTP-on equation is:
1061
+
1062
+ | Process line item | Bytes |
1063
+ |---|---:|
1064
+ | Resident dense/shared/router/MTP weights | 10,877,286,144 |
1065
+ | Main expert slab: 64 working + 75 resident | 2,632,646,656 |
1066
+ | MTP expert slab: 24 working + 1 resident | 945,356,800 |
1067
+ | Target compressed MLA KV, 78 layers × 4k | 736,100,352 |
1068
+ | Decode-only MTP KV, 1 layer × 4k | 9,437,184 |
1069
+ | Reconstructed target K/V at 4k + verify rows | 537,395,200 |
1070
+ | Target verify + MTP draft visible rows | 4,508,672 |
1071
+ | MLX allocator/cache reserve | 4,294,967,296 |
1072
+ | Bun/native reserve | 536,870,912 |
1073
+ | Safety margin | 536,870,912 |
1074
+ | **Planned process** | **21,111,440,128** |
1075
+
1076
+ The 25 GiB process ceiling therefore retains 5,732,105,472 bytes of planned
1077
+ headroom. The process is never allowed to consume the remaining 7 GiB of the
1078
+ 32 GiB machine; that is the explicit OS reserve. The target verify union needs
1079
+ at most 32 of the 64 working slots and MTP reserves all 24 possible
1080
+ `topK × gamma` draft slots.
1081
+
1082
+ The manual gate uses separate fresh processes for MTP on and off. Each process
1083
+ runs a cold and then warm 128-token turn: request KV is rebuilt, while expert
1084
+ residency remains warm. It records task physical footprint, RSS, MLX active/
1085
+ cache/peak allocation, expert residency, `vm_stat` compressor occupancy, and
1086
+ swap every 15 seconds. Any swapout or footprint above 25 GiB aborts at the next
1087
+ token boundary; compressor occupancy may grow by at most a documented 256 MiB
1088
+ to tolerate unrelated system activity, and warm final footprint may exceed
1089
+ cold by at most 256 MiB. The first 64 tokens remain pinned to direct Colibri;
1090
+ the complete 128-token cold/warm and MTP-on/off outputs must be identical.
1091
+ Strict enforcement is the default. For a diagnostic before/after run,
1092
+ `--memory-mode observe` records the same violations and completes generation
1093
+ instead of aborting; its paired result is labeled `observed`, with a separate
1094
+ `strictContractSatisfied` field. Observation mode never silently changes the
1095
+ fixed thresholds.
1096
+
1097
+ Run from a cleared 32 GB M1 Max:
1098
+
1099
+ ```sh
1100
+ MODEL=/Users/joshrossi/.cache/huggingface/hub/models--mateogrgic--GLM-5.2-colibri-int4-with-int8-mtp/snapshots/3cc8db99b1b13fc79325d987ba3c1c430766b3b8
1101
+ LIBRARY="$PWD/dist-native/libmlx_bun_expert_io.dylib"
1102
+ test -f "$LIBRARY"
1103
+ mkdir -p runs/colibri-g5
1104
+ bun scripts/probe-colibri-glm52-g5-memory.ts --mode on --model "$MODEL" --library "$LIBRARY" --output runs/colibri-g5/mtp-on.json --trace runs/colibri-g5/mtp-on.memory.jsonl
1105
+ bun scripts/probe-colibri-glm52-g5-memory.ts --mode off --model "$MODEL" --library "$LIBRARY" --output runs/colibri-g5/mtp-off.json --trace runs/colibri-g5/mtp-off.memory.jsonl
1106
+ bun scripts/check-colibri-glm52-g5-memory.ts --on runs/colibri-g5/mtp-on.json --off runs/colibri-g5/mtp-off.json --output runs/colibri-g5/summary.json
1107
+ ```
1108
+
1109
+ For the explicit observational run requested on 2026-08-15, add
1110
+ `--memory-mode observe` to both probe commands. The fresh-process pair
1111
+ completed all four 128-token turns with exact direct-prefix, cold/warm, and
1112
+ MTP-on/off identity:
1113
+
1114
+ | Lane | Baseline footprint | Cold final | Warm final | Peak | Cold -> warm | Cold / warm e2e |
1115
+ |---|---:|---:|---:|---:|---:|---:|
1116
+ | MTP on | 0.078 GiB | 13.666 GiB | 13.688 GiB | 13.791 GiB | +23.1 MiB | 0.146 / 0.149 tok/s |
1117
+ | MTP off | 0.078 GiB | 12.564 GiB | 12.583 GiB | 12.644 GiB | +19.2 MiB | 0.127 / 0.114 tok/s |
1118
+
1119
+ Warm MTP-on was 1.306x MTP-off. Each MTP-on turn accepted 72/166 drafts,
1120
+ emitted 2.286 tokens per target forward, and saved 71 target forwards. Both
1121
+ peaks retained more than 11 GiB of headroom below the 25 GiB ceiling, but they
1122
+ remain below direct G0 warm throughput (~0.27 tok/s on and ~0.34 off).
1123
+
1124
+ The pair is intentionally not called a strict pass. Whole-system compressor
1125
+ growth peaked at 4.101 GiB, task-compressed growth at 1.806 GiB, and the
1126
+ MTP-off lane observed 6.8 MiB of swapout (MTP-on zero), so the checker reports
1127
+ `strictContractSatisfied: false`. These changes were bounded: the task ended
1128
+ near its observed compression maximum and final footprint changed by only
1129
+ 23.1/19.2 MiB across cold to warm rather than spiraling. The run also exposed
1130
+ two wiring gaps now closed: speculative/server and manual-probe paths hold a
1131
+ scoped MLX wired limit based on the complete streamed process plan, and native
1132
+ expert slots are wired before their read begins then unlocked before discard.
1133
+ Machine-local reports and 15-second traces are under `runs/colibri-g5/`.
1134
+
1135
+ **Exit:** startup and a 128-token run with MTP on remain <=25 GB measured
1136
+ footprint (small documented tolerance only), with flat memory and no
1137
+ compression spiral, swap/OOM kill, or hidden duplicate weights. Record cold
1138
+ and warm speed, MTP on and off, against the direct-Colibri G0 baseline.
1139
+
1140
+ ### G6 — Atlas, overlap, learning, and prefetch
1141
+
1142
+ - I/O worker pool, direct/no-cache reads, resident-first Metal submit, persistent
1143
+ usage, live LFRU repin, PILOT/coupling/two-step variants.
1144
+ - Emit live tier/heat/hit maps; port the controlled Atlas probe/analyze/validate
1145
+ workflow and expert-affinity visualization.
1146
+ - Treat any Atlas-informed topic warm-start as a separate new experiment.
1147
+
1148
+ Implementation status (2026-08-15): batch-union, bounded positioned-read
1149
+ workers, `F_NOCACHE`, and resident-first submission were already in the G3
1150
+ foundation. G6's first new slice adds one shared target/MTP `.coli_usage`
1151
+ ledger in the direct Colibri three-column format. It records every top-k route
1152
+ before union deduplication, keeps loaded long-term frequency separate from
1153
+ session heat/recency, and atomically publishes at generation safe points.
1154
+ The opt-in startup auto-pin consumer is also implemented: the direct 5k-history
1155
+ floor, 200k full-confidence point, half-tier share, and 0.5 GB minimum are
1156
+ preserved, while deterministic ties and exact Q4/Q8 slot costs keep the shared
1157
+ target/MTP plan within its hard floor. Selected pins are preloaded before the
1158
+ first forward. The opt-in live LFRU consumer preserves the direct uint32
1159
+ recency score, 25%+4 hysteresis, heat halving, and a single four-swap turn cap
1160
+ across target and MTP; logical role exchange avoids copying expert slabs.
1161
+ Residency maps expose tier plus frequency/heat/recency and aggregate hit/miss/
1162
+ repin counters. Neither learning policy is defaulted before its MTP-on A/B.
1163
+
1164
+ The paired runner charges policy I/O separately from demand while reporting
1165
+ both, including disk-service/foreground-wait and main/MTP layer-forward
1166
+ percentiles. It learns one MTP-on seed profile in a separate process and copies
1167
+ the identical seed into every control/candidate process:
1168
+
1169
+ ```sh
1170
+ MODEL=/Users/joshrossi/.cache/huggingface/hub/models--mateogrgic--GLM-5.2-colibri-int4-with-int8-mtp/snapshots/3cc8db99b1b13fc79325d987ba3c1c430766b3b8
1171
+ LIBRARY="$PWD/dist-native/libmlx_bun_expert_io.dylib"
1172
+ bun scripts/probe-colibri-glm52-g6-learning.ts \
1173
+ --model "$MODEL" --library "$LIBRARY" \
1174
+ --output-dir runs/colibri-g6-learning --memory-mode observe --repeats 3
1175
+ ```
1176
+
1177
+ One repeat is a harness shakeout only; the summary marks a policy decision
1178
+ eligible only at three or more fresh-process repeats. The runner refuses to
1179
+ overwrite an existing arm by default. Pass `--resume 1` to reuse completed
1180
+ lanes and preserve a failed lane while retrying it under an attempt suffix.
1181
+
1182
+ The default-eligible three-repeat run completed 2026-08-16 with exact tokens
1183
+ in all nine measured arm runs. Against control, startup auto-pin raised median
1184
+ warm hit rate from 1.66% to 9.62% and reduced disk GB/token by 8.02%, but it
1185
+ also read 3.329 GiB of policy data, increased median warm physical footprint
1186
+ from 13.694 to 17.032 GiB, added 526 ms to median model open, and reduced warm
1187
+ end-to-end throughput from 0.149 to 0.143 tok/s (-4.06%). Live LFRU made zero
1188
+ swaps on the repeated workload; its 0.148 tok/s median (-0.38% versus control)
1189
+ is run-order noise over the same startup placement rather than a live-policy
1190
+ win. Therefore `autoPin` and `liveRepin` remain off by default. Raw telemetry
1191
+ and the summary are machine-local under
1192
+ `runs/colibri-g6-learning-shakeout-2026-08-15/`.
1193
+
1194
+ The next slice isolates PILOT as measurement-only telemetry. Immediately after
1195
+ layer L attention, it feeds the raw residual through layer L+1's
1196
+ post-attention RMS norm and router, copies the predicted top-8 expert IDs, and
1197
+ scores them when layer L+1 produces its real route. The arm does not inspect
1198
+ residency, enqueue reads, alter routing, or mutate the expert plan. It preserves
1199
+ Colibri's `S <= 8` guard and reports selection precision/recall, exact rows,
1200
+ per-rank hits, per-layer quality, predictor latency, usable lead time, skipped
1201
+ wide calls, and abandoned predictions. The internal `pilotMeasure` runtime
1202
+ option is exposed by the probe harnesses only; it is not a serving default or
1203
+ public CLI surface. Deterministic tests cover scoring, rank accounting, the
1204
+ width guard, drain/reset behavior, and a two-layer streamed differential whose
1205
+ tokens/output match the no-PILOT path.
1206
+
1207
+ The paired runner keeps MTP on, alternates control/candidate order, refuses
1208
+ token drift and accidental overwrites, and supports resume/retry:
1209
+
1210
+ ```sh
1211
+ MODEL=/Users/joshrossi/.cache/huggingface/hub/models--mateogrgic--GLM-5.2-colibri-int4-with-int8-mtp/snapshots/3cc8db99b1b13fc79325d987ba3c1c430766b3b8
1212
+ LIBRARY="$PWD/dist-native/libmlx_bun_expert_io.dylib"
1213
+ bun scripts/probe-colibri-glm52-g6-pilot.ts \
1214
+ --model "$MODEL" --library "$LIBRARY" \
1215
+ --output-dir runs/colibri-g6-pilot --memory-mode observe --repeats 3
1216
+ ```
1217
+
1218
+ A one-repeat full-model shakeout completed 2026-08-16 with exact control and
1219
+ candidate tokens. Across 4,200 predictions / 16,650 scored rows per turn,
1220
+ top-8 precision and recall were 69.90%; predicted ranks 1-4 were cumulatively
1221
+ 87.08% precise and covered 43.54% of the actual top-8. Predictor latency was
1222
+ 36.95 ms p50 / 53.45 ms p95, while usable lead was 179.9 ms p50 / 219.7 ms
1223
+ p95 against ~92.7 ms candidate demand-read p95. Seventy-five wide-prefill calls
1224
+ (2,400 rows) were intentionally skipped and no predictions were abandoned.
1225
+ Candidate warm throughput was 1.009x control and final footprint increased
1226
+ about 3.5 MB, which shows no obvious one-run tax but is not a replicated
1227
+ performance result. The quality/lead signal advances the next experiment as a
1228
+ bounded, hint-only `PILOT_K=4`; real speculative loads remain a later,
1229
+ default-off A/B because rank 5-8 precision falls sharply and wrong loads can
1230
+ evict useful experts. Machine-local evidence is under
1231
+ `runs/colibri-g6-pilot-measure-shakeout-2026-08-16/`.
1232
+
1233
+ The bounded hint-only stage landed and completed a one-repeat MTP-on paired
1234
+ shakeout on 2026-08-16. A separate 4,096-job native advisory queue opens
1235
+ buffered hint descriptors while demand descriptors retain `F_NOCACHE`; on this
1236
+ path each nonresident top-4 candidate issues `F_RDADVISE` for its three scale
1237
+ tails only. Hints never allocate or publish expert slots, change LRU state, or
1238
+ alter routing. Both turns completed all 48,162 submitted hints (144,486
1239
+ operations / 1,972,715,520 advised bytes) with no drops, errors, or end-of-turn
1240
+ backlog, and candidate tokens exactly matched control. Warm logical demand
1241
+ bytes remained exactly 14,883,703,168 per token in both arms. Disk-service p95
1242
+ was 1.0065x control, foreground-wait p95 was 1.0193x, and warm throughput was
1243
+ 0.9746x (0.14031 -> 0.13675 tok/s); final physical footprint changed by only
1244
+ +3,817,328 bytes. The mechanism is therefore bounded and value-preserving, but
1245
+ this policy did not improve I/O or latency and remains default-off. One repeat
1246
+ is not a performance replication, and the negative shakeout does not justify
1247
+ promoting it to real speculative loads. The next prefetch work measures
1248
+ coupling and two-step predictor quality before revisiting real loads. Evidence
1249
+ is under `runs/colibri-g6-pilot-hint-k4-shakeout-2026-08-16/`.
1250
+
1251
+ The next measurement-only slice implements both remaining Colibri predictors
1252
+ without admitting speculative expert loads. `pilotTwoStep` duplicates the
1253
+ current sparse layer's shared-expert SwiGLU from the raw post-attention
1254
+ residual, adds that output to the residual, and applies the next layer's norm
1255
+ and router. It scores this route independently from the direct PILOT route and
1256
+ never feeds either result into routing, residency, or I/O. The dense-to-sparse
1257
+ boundary is direct-only because its source layer has no shared-expert block;
1258
+ two-step and hint-only modes are mutually exclusive so a baseline hint policy
1259
+ cannot be mistaken for a two-step result.
1260
+
1261
+ Cross-layer coupling is also observation-only. A target-tier route observer
1262
+ copies the full per-row router result before batch-union deduplication and tags
1263
+ it by segment, forward, row, and layer. The offline evaluator learns Colibri's
1264
+ raw `(source layer, delta, source expert) -> target expert` coactivation counts
1265
+ for deltas one and two, retains 16 candidates per source expert, and sums votes
1266
+ with deterministic expert-ID ties. Its default 70/30 temporal split trains and
1267
+ scores within the cold segment only, excluding the repeated warm turn. The
1268
+ held-out path deliberately does not marginal-backfill unseen coupled routes;
1269
+ an equal-budget marginal predictor is reported separately as the baseline.
1270
+ Route collection and both predictors remain internal, opt-in, and default-off.
1271
+
1272
+ The one-repeat MTP-on two-step shakeout kept both 128-token turns identical to
1273
+ control. Two-step raised top-8 precision/recall from 69.90% to 73.01% and
1274
+ exact rows from 5.35% to 7.90%, with 12.69 ms prediction p95 and 242.70 ms
1275
+ lead-time p95. That quality gain did not pay for its duplicated shared-expert
1276
+ work: warm throughput fell 10.13% from 0.14978 to 0.13461 tok/s. Logical demand
1277
+ bytes/token were bit-for-bit unchanged at 14,883,703,168 and final footprint
1278
+ changed by less than 1 MB. This is an observational cost/quality shakeout,
1279
+ not a replicated performance claim; two-step remains off. Evidence is under
1280
+ `runs/colibri-g6-pilot-two-step-shakeout-2026-08-16/`.
1281
+
1282
+ The independent coupling lane emitted 23,250 route records. Excluding warm,
1283
+ the cold trace contained 155 positions: 108 trained the coactivation table and
1284
+ 47 were held out, producing 22,766 `(layer, delta, expert)` entries. At budget
1285
+ 8, delta-1 coupling recalled 31.02% of actual experts versus a 22.96% marginal
1286
+ baseline, while delta 2 recalled 30.81% versus 23.15%. The learned signal is
1287
+ real, but the absolute quality is not useful for speculative I/O: even budget
1288
+ 32 reached only 57.35% / 56.74% recall, below direct PILOT's 69.90% at budget
1289
+ 8 while proposing four times as many experts. Coupling therefore remains off,
1290
+ and the completed predictor program does not advance to real loads. Evidence
1291
+ is under `runs/colibri-g6-coupling-shakeout-2026-08-16/`.
1292
+
1293
+ The Atlas implementation now pins Colibri's 10-category, three-independent-
1294
+ prompt matrix at source commit
1295
+ `ecade075cfc2eae684097ea7de5570c3786ce199`. The probe opens the streamed model
1296
+ once but gives every prompt a fresh KV cache and its own route segment. MTP,
1297
+ persistent usage, auto-pin, live repin, PILOT, hinting, thinking, and sampling
1298
+ are disabled; the observer records the full true-top-8 target route before
1299
+ batch-union deduplication. Reusing residency across prompts changes only where
1300
+ weights are found, not router decisions, and avoids thirty redundant 370 GB
1301
+ container opens. The pinned prompts render to 13-36 tokens with the artifact's
1302
+ tokenizer.
1303
+
1304
+ `src/model/glm52-atlas.ts` normalizes each expert count by that run's total,
1305
+ averages shares within a category, renormalizes to `p(topic|expert)`, computes
1306
+ normalized entropy/specialization, and requires the top topic to fire in at
1307
+ least two independent prompts. Validation is a strict global leave-one-prompt-
1308
+ out: the held-out route trace is absent from every category's specialist model,
1309
+ including the background distributions. The analyzer emits a detailed
1310
+ `atlas.json`, Colibri-compatible keyed `experts.json`, and a self-contained
1311
+ canvas affinity map whose position is the topic-vector barycenter and whose
1312
+ radius/opacity reflects specialization. Synthetic and CLI integration tests
1313
+ cover category-size normalization, the replication gate, held-out prediction,
1314
+ schema compatibility, and all three outputs.
1315
+
1316
+ The real 30-prompt sweep is the final G6 gate and remains a Josh-run long model
1317
+ job when it needs to be reproduced:
1318
+
1319
+ ```sh
1320
+ MODEL=/Users/joshrossi/.cache/huggingface/hub/models--mateogrgic--GLM-5.2-colibri-int4-with-int8-mtp/snapshots/3cc8db99b1b13fc79325d987ba3c1c430766b3b8
1321
+ LIBRARY="$PWD/dist-native/libmlx_bun_expert_io.dylib"
1322
+ bun scripts/probe-colibri-glm52-g6-atlas.ts \
1323
+ --model "$MODEL" --library "$LIBRARY" \
1324
+ --output-dir runs/colibri-g6-atlas --max-tokens 64
1325
+ bun scripts/analyze-colibri-glm52-g6-atlas.ts \
1326
+ --traces runs/colibri-g6-atlas/traces \
1327
+ --output-dir runs/colibri-g6-atlas/analysis
1328
+ ```
1329
+
1330
+ The sweep completed 2026-08-16 with all 30 prompts. It retained 13,236 experts
1331
+ after the >=2-prompt replication gate; 1,065 (8.05%) were strong specialists at
1332
+ the >=0.50 threshold. Strict global leave-one-prompt-out classification scored
1333
+ 29/30 (96.7%, chance 10.0%), exactly reproducing Colibri's published accuracy
1334
+ and closely reproducing its 13,260 retained / 1,041 strong (7.85%) population.
1335
+ The only miss was Chinese prompt 1 classified as poetry. The detailed JSON,
1336
+ Colibri-compatible `experts.json`, and interactive report are machine-local at
1337
+ `runs/colibri-g6-atlas/analysis/`.
1338
+
1339
+ The sweep is resumable with `--resume 1` and refuses mixed model/probe/options
1340
+ or incomplete trace/manifest checkpoints. No Atlas-informed warm-start is
1341
+ implemented or defaulted; that remains a separate experiment despite the
1342
+ successful label reproduction.
1343
+
1344
+ **Exit:** each lever has a paired cold/warm A/B with hit rate, disk GB/token,
1345
+ disk-service vs foreground-wait, p50/p95/p99 forward latency, and tok/s — all
1346
+ measured with MTP on (a lever that wins MTP-off but loses MTP-on is not a
1347
+ default). Only positive Apple results become defaults. Atlas labels reproduce
1348
+ across prompts; prefetch remains value-preserving and never changes selected
1349
+ experts. **Closed 2026-08-16:** all defaults remain conservative, the Atlas
1350
+ gate reproduced 29/30 held-out labels, and no speculative-load policy advanced.
1351
+
1352
+ ### G7 — persistence, concurrency, and full API parity
1353
+
1354
+ Serial MTP already landed in G4; this gate integrates everything around it.
1355
+
1356
+ - [x] **G7a compressed persistence (2026-08-17):** v3 adds `mla`, `mla-dsa`,
1357
+ and `mtp-mla` without a format bump. Atomic streaming save/async-save,
1358
+ clone, prompt/SSD bytes, restart trim classification, and verified
1359
+ copy-restore materialize only latent/RoPE/owning-layer-index tensors.
1360
+ Model/config/tokenizer identity and exact role/geometry reject drift
1361
+ before mmap. Tiny target forks match restored hidden state and offsets at
1362
+ dense/sparse prefix lengths; restored MTP state yields the same next
1363
+ drafts and offset. Focused gate: 42 tests, 881 assertions.
1364
+ - [x] **G7b continuous batching (2026-08-17):** structural batched-cache
1365
+ capability, compressed-byte admission, per-row merge/extract/filter and
1366
+ context limits, mixed-length RoPE/DSA parity, cross-row expert union, and
1367
+ join/leave/cancel are gated. Batched rows decode ordinary single-token;
1368
+ per-row MTP remains post-release (see N6). Gateway and stats report the
1369
+ actual `off`/`serial`/`batch` capability mode. Focused gate: 115 tests,
1370
+ 1,701 assertions.
1371
+ - [x] **G7c serving parity (2026-08-17):** chat/text completions, Anthropic Messages,
1372
+ Responses continuation, streaming/disconnect, tools, structured output,
1373
+ stops, sampling/penalties, serial logprobs, usage and truthful discovery;
1374
+ library `generate`, CLI chat/serve, health/stats. GLM-5.2 chat-template
1375
+ rendering, thinking-block policy per surface, and tool-call parsing are
1376
+ explicit work items. Implementation is now wired: the common generator
1377
+ awaits streamed expert forwards; `loadContext`, `openModel`, CLI serve/pi,
1378
+ and one-shot generate select the bounded Colibri runtime; native MTP is
1379
+ mounted by default; the GLM `arg_key`/`arg_value` format parses; and
1380
+ discovery/stats expose capabilities plus the exact resource plan. Tiny
1381
+ streamed HTTP gates cover all four protocols, SSE, and native MTP's
1382
+ `serial+spec` lane. The fresh real-artifact CLI gate passed health,
1383
+ discovery, stats, all four non-streaming protocols, and SSE under the
1384
+ exact 25 GiB contract; SSE terminated in `[DONE]`, chat/SSE reported
1385
+ `serial+spec`, and post-run scheduler rows returned to idle. The final focused
1386
+ static/synthetic sweep passes TypeScript plus 152 tests / 2,536
1387
+ assertions with zero failures.
1388
+
1389
+ **Exit:** uninterrupted vs restored next logits/tokens and offsets match at
1390
+ multiple sequence lengths; batched rows are parity-checked against serial rows
1391
+ under mixed lengths and cancellation (ordinary decode — batched MTP is
1392
+ post-release); both stream and non-stream protocol suites pass across all four
1393
+ generative HTTP surfaces. Unsupported non-generative GLM capabilities are
1394
+ advertised false, not emulated.
1395
+
1396
+ ### G8 — productization
1397
+
1398
+ - [x] **G8a acquisition/recovery/attribution (2026-08-17):** exact remaining
1399
+ disk preflight with complete/partial credit and a fixed 1 GiB reserve;
1400
+ resumable pinned-artifact command, 32 GB quickstart, recovery instructions,
1401
+ model lineage, and Colibri Apache-2.0 attribution. TypeScript plus 18
1402
+ downloader/lock tests / 56 assertions pass.
1403
+ - [x] **G8b operator UX and telemetry (2026-08-17):** artifact-aware CLI
1404
+ `fit` plus `/fit`, `/stats`, and status UI distinguish the ~357 GiB streamed
1405
+ artifact from resident weights, main/MTP slabs, compressed KV, and reserves.
1406
+ They label the measured 0.149 tok/s result, direct 0.27 tok/s control, and
1407
+ aspirational 2 tok/s separately. `/stats` and the UI expose last-turn
1408
+ main/MTP demand, hit rate, SSD bytes, residency, policy/forward telemetry,
1409
+ and repin events. `fit` is the diagnostic surface; no separate `doctor`
1410
+ command exists. TypeScript plus 55 focused tests / 1,910 assertions pass.
1411
+ - [x] **G8c curated evidence (2026-08-17):** `benchmarks/RESULTS.md` now
1412
+ contains the pinned oracle/quality gates, final artifact-aware resource plan,
1413
+ honest before/after memory caveat, cold/warm MTP speed and footprints,
1414
+ replicated expert-I/O/policy decisions, paired DSA matrix, and API smoke.
1415
+ Warm quality-preserving end-to-end throughput is recorded as 0.1487 tok/s,
1416
+ 7.43% of / 13.45x below the aspirational 2 tok/s target.
1417
+ - [x] **G8d release/docs closure (2026-08-17):** applicable reference sweep, native expert
1418
+ I/O packaging, and a fresh-machine command-path verification.
1419
+ - [x] Native pack v0.2.0 and compiled sidecar bundle include
1420
+ `libmlx_bun_expert_io.dylib`; isolated empty-cache extraction, MLX load,
1421
+ native expert read, compiled-binary, docs-map, TypeScript, and 74 focused
1422
+ tests / 4,335 assertions pass. Arm64 pack: 52,307,647 bytes, SHA-256
1423
+ `9bd3795c5ea8f52b18413501f2d68c32c264a20751302300a08dc04cd67df97c`.
1424
+ - [x] After explicit authorization, published the externally visible
1425
+ `native-v0.2.0` GitHub release. Both assets are uploaded; anonymous HTTP
1426
+ resolution and an empty-cache default-URL download/checksum/extraction
1427
+ passed with all five required files. G8 is closed.
1428
+ - Update README plus `docs/reference/{models,memory,cli,server-config,
1429
+ server-api,library-api,features-matrix}.md` in the same feature changes that
1430
+ add the corresponding flags, fields, routes, defaults, and limitations.
1431
+ - Keep the 32 GB quickstart, artifact/disk preflight, recovery/resume
1432
+ instructions, and explicit cold/warm expectations synchronized with code.
1433
+
1434
+ **Exit:** a new 32 GB user can go from adequate disk space to a working GLM-5.2
1435
+ chat with one documented command sequence; actual cold/warm performance on the
1436
+ M1 Max 32 GB with MTP on and quality-preserving defaults is recorded with
1437
+ provenance in `benchmarks/RESULTS.md`, including its gap to the aspirational
1438
+ 2 tok/s target; no default silently changes precision or routing.
1439
+
1440
+ ## Test matrix
1441
+
1442
+ | Gate | Direct Colibri oracle | Native MLX port |
1443
+ |---|---:|---:|
1444
+ | Colibri macOS `make check` + Metal tests | required | oracle only |
1445
+ | zero-copy slot lifetime/churn/fence stress | comparison | required |
1446
+ | tiny GLM op/layer/teacher-forcing goldens | fixture source | required |
1447
+ | same-artifact 32-token greedy stream | baseline | required |
1448
+ | <=25 GB on the cleared M1 Max 32 GB (MTP on) | baseline | required |
1449
+ | 128-token flat memory / no swap | baseline | required |
1450
+ | cold/warm hit, I/O, latency, tok/s report | baseline | required |
1451
+ | warm speed + gap to aspirational 2 tok/s, MTP on, quality-preserving defaults (M1 Max 32 GB) | baseline | required |
1452
+ | live heat map + offline Atlas replication | baseline | required |
1453
+ | MTP accept/reject trace + net speed | baseline | required |
1454
+ | MLA/DSA/MTP KV restart at short/mid/wrapped lengths | baseline | required |
1455
+ | 2/4-row merge/extract + mixed-length decode parity | comparison | required |
1456
+ | batched MTP mixed accept/reject/cancel trace | comparison | post-release |
1457
+ | chat/completions stream + non-stream | comparison | required |
1458
+ | text completions, Messages, Responses protocol suites | comparison | required |
1459
+ | tools, grammar, stops, penalties, usage, serial logprobs | comparison | required |
1460
+ | truthful model/stats capability discovery | comparison | required |
1461
+
1462
+ ## First implementation slice
1463
+
1464
+ Do not start by porting MLA. First establish the safe storage and execution
1465
+ foundation that the native MLX implementation requires:
1466
+
1467
+ 1. Build direct Colibri with Metal and measure the public GLM-5.2 artifact on
1468
+ the M1 Max 32 GB machine.
1469
+ 2. Generate a small local file in Colibri's expert layout; no model download is
1470
+ needed for this spike.
1471
+ 3. Add a Lab-only native fixed-slab/LRU harness with async positioned reads and
1472
+ both MLX/custom-Metal consumers.
1473
+ 4. Stress slot reuse and prove completion fences, zero-copy behavior, flat RSS,
1474
+ and deterministic LRU traces.
1475
+ 5. Benchmark representative expert/attention kernels against direct Colibri.
1476
+
1477
+ Then proceed to the GLM-5.2 graph and direct-container loader. A slow MLX
1478
+ composition is a reason to add or tune a custom Metal kernel behind mlx-bun's
1479
+ MLX model boundary, not a reason to abandon the Bun+MLX port.