Skip to content

WIP: resident MiMo-V2.6-Flash-MOPD engine and full KV cache - #677

Closed
beamivalice wants to merge 2 commits into
ddalcu:mainfrom
beamivalice:codex/mimo-v26-wip
Closed

beamivalice wants to merge 2 commits into
ddalcu:mainfrom
beamivalice:codex/mimo-v26-wip

Conversation

@beamivalice

@beamivalice beamivalice commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Ports the complete resident MiMo-V2.6-Flash-MOPD path from Sushi: native MXFP4 expert banks, source FP8 trunk/QKV, attention and FP32 routing, MiMo-ViT, and three MTP heads. EXL3 packs and expert streaming are excluded.

The KV system is included in this WIP:

  • KV8 default, bounded sliding rings with absolute offsets, and reserved global KV capacity.
  • Packed prefill slices, fused sliding band/sink prefill, M5 matmul2d and SIMD split-K decode, and per-row decode attention during verification with in-place rollback.
  • Prompt-end, fork and message-boundary ring checkpoints; prefix reuse, trimming and checkout; SSD ring files and manifest v9 restore.
  • Ring/checkpoint/scratch memory accounting, adaptive prefill admission, and up to four independent decode slots.

The original checkpoint's text plus experts alone occupy 158.1 GiB. This is a handoff for the maintainer's 256GB Mac; the development machine has 128GB. The expanded KV port is unvalidated WIP, as requested. Earlier test results for the smaller port do not establish that this expanded implementation works.

Bring-up commands, implementation details and the unrun ring/restart scenarios are in docs/reference.md under MiMo V2.6 Flash. Full-model correctness, restore/rollback behavior, peak memory and performance remain to be established there.

Port source FP8 projections, native MXFP4 expert loading, MiMo attention and routing, image input, and three MTP heads from Sushi. Keep existing KV/SDPA storage while full-model and long-context validation continue on 256GB hardware.

Validated on M5 Max 128GB with MLX 0.32.3: ReleaseFast build, full Zig suite, independent tiny references, and HTTP MTP/cache lifecycle checks. EXL3 and expert streaming are excluded.
Bring over bounded sliding rings, retained and persisted ring checkpoints, packed asymmetric prefill/decode attention, row-wise speculative attention, in-place rollback, KV8 defaults, reservation, batching and memory accounting. Adapt the cache interfaces to mlx-serve media spans and layout fingerprints.

This expanded port is unvalidated WIP for 256GB bring-up. No EXL3 pack or expert streaming code is included.
@beamivalice beamivalice changed the title WIP: native resident MiMo-V2.6-Flash-MOPD engine WIP: resident MiMo-V2.6-Flash-MOPD engine and full KV cache Oct 1, 2026
@beamivalice
beamivalice marked this pull request as ready for review October 2, 2026 02:17

ddalcu commented Oct 2, 2026

Copy link
Copy Markdown
Owner

🤖 MLXServe-PRBot — code review

Head d529015. It's out of draft but self-declared unvalidated, so this can't be approved yet. One MiMo-V2.6 port (engine, vision, MTP, KV) in one PR is the right shape. What has to happen before it can land:

  1. It rewrites shared code every model runs through. This is not additive. src/prefix_cache.zig is +2480/−376, src/transformer.zig +3961/−365, src/kv_disk_cache.zig +787/−202 (new manifest version), plus generate.zig, scheduler.zig, server.zig and chat.zig. Every qwen3_5/qwen4/gemma prefix-cache restore, SSD-tier restore and decode tick goes through those lines. "Full-model correctness remains to be established" covers MiMo. It does not cover the regression risk to every arch already on main. The existing suites must pass on this head against non-MiMo packs, not just zig build test: tests/test_prefix_cache_workloads.sh, test_prefix_cache_disk.sh, test_hybrid_reuse_equivalence.sh, test_batched_equivalence.sh and test_vision_prefix_cache.sh. Post the results.
  2. The manifest bump is a migration. Existing users' SSD entries were written at the old manifest. Say what happens to them at v9: refused, rebuilt, or misread. Add a test that an old-manifest entry is skipped and never restored into a new layout.
  3. New paths need to be gated so main's archs stay byte-identical. Ring checkpoints, fork/message-boundary checkpoints and the new decode kernels should key on the MiMo arch predicate, the way longCtxGated() scopes qwen4's mechanisms. If any of them change behaviour for existing archs, that is a separate change with its own evidence.
  4. Evidence once it runs. The checklist calls it a handoff for a 256 GB Mac. When it runs, it needs correctness (fixture parity against your dump scripts), peak resident memory, and decode/prefill throughput with hardware and method. MXFP4/FP8 and the speculative heads make this a performance-relevant arch.

Merges cleanly with main.


Generated by Claude Code

@ddalcu ddalcu added enhancement New feature or request engine model-support labels Oct 2, 2026 — with Claude
ddalcu added a commit that referenced this pull request Oct 2, 2026
Head k reads the trunk's final-normed hidden at p and token p+k+1 (SGLang's
multi-layer EAGLE for MiMo); drafts chain only through tokens, so a round
runs head 0 on its committed rows and head i on draft i. The head module is
@beamivalice's from PR #677, adapted to the mlx-lm pack layout (split
q/k/v, affine or bf16 projections through Transformer.qmatmul) and to the
coarse draft readout bound at load. The verify rolls back by KV truncate:
the trunk is attention-only, and a snapshot made every KV write copy its
whole buffer.

The tiny oracle now renders the heads from the reference's own modules
(forked RNG, so the trunk fixture is unchanged) and `mimo mtp heads` tracks
them across rounds, wrong drafts and rollbacks.

M5 Ultra, greedy: code 74 -> 98 tok/s (80% per draft), prose 74 -> 89;
sampled creative text stays at serial. tests/test_mimo_v2.sh 22/22,
unit suite 2899 passed, 0 failed.
ddalcu added a commit that referenced this pull request Oct 4, 2026
)

* perf(h3): keep the text encoder, DiT and Turbo LoRA resident between requests while memory allows

MiniMax-H3 reloaded everything per request. The text encoder, the whole DiT (no AdaLN
precompute, so it serves any schedule) and the adapter stack now stay loaded while the engine
is loaded and the whole set fits in live free memory plus what the cache already holds.
Otherwise the cache is released and the staged plan runs. Any other load that would be refused
for memory, and a long prefill that does not fit, release it first.

A second Turbo render at 640x384, 22 frames: 8.1 s -> 5.9 s.

MLX_SERVE_H3_RESIDENT=0 turns it off; --ane-video runs staged. test_h3_resident.sh counts the
cache hits from the log, checks identical pixels, and that no LoRA leaks into a plain request.

* feat(mimo_v2): serve MiMo-V2.6-Flash in mlx-lm's pack layout

MiMo-V2.6-Flash (309B-A15B) rides existing arms: gpt_oss's sink attention,
now reading every geometry per layer (global 4 / sliding 8 KV heads,
K 192 / V 128, RoPE on 64 channels, two thetas, V scaled before caching),
and laguna's sigmoid MoE binding with the router widened to f32 at load.
`mimo_v2_flash` parses as the same arch.

The pack layout is mlx-lm's (ml-explore/mlx-lm#1219), so community MLX
packs load here and ours load in mlx-lm. tests/convert_mimo_v2.py writes
it from the release: MXFP4 experts restacked byte for byte, the FP8 fused
QKV dequantized per tensor-parallel slab and split, the trunk at 8 bits
with mlx-lm's per-module quantization entries. The release itself is
refused by name.

A template that renders tool calls but never names a 'tool' role (MiMo's
generic role header) now keeps tool results as native turns instead of
rewriting them into user turns.

Parity: a tiny random MiMo in the release's storage against the
checkpoint's own modeling code (min cos 0.9993, argmax 46/46), on our
pack and on mlx-lm's conversion of the same release. Live:
tests/test_mimo_v2.sh 20/20 on the converted MOPD pack.

* perf(mimo_v2): fused 192/128 sink attention for prefill, fp4 MoE decode, MXFP4 NAX gather

Prefill attention for both MiMo layer kinds runs our flash kernel
(msv_attn_p256), now templated on the q/k and v head widths with a sink
seed (m = sink, l = 1); MLX has no fused kernel at 192/128 and fell back
to the composed path. 5.6k-token prefill 1521 -> ~2440 tok/s on the M5
Ultra, the kernel pinned against MLX sdpa with sinks (causal, banded,
cache prefix) and the tiny fixture moved to the real head shape.

Single-token MXFP4 expert decode is two dispatches (moe_fp4.zig: gate+up
+SwiGLU, down + score-weighted sum), four rows per simdgroup off one
register copy of x. Decode forward 14.65 -> 14.22 ms. Multi-row widths
keep MLX's sorted path: generalizing the one-row-per-simdgroup gatherQmv
family to MXFP4 made a 4-row verify 49 ms against 28 ms.

The NAX sorted gather takes MXFP4 banks through an Fp4Q policy (e8m0
scale, no biases), canaried against MLX's fp gather within 1/64 of
peak: prefill 7% faster in an interleaved A/B.

Also: the mlx-lm-layout-first rule for new model support in AGENTS.md.

* perf(mimo_v2): fp4 MoE decode kernels take two-row verify widths

The kernels serve any token count (each row its own top-k); the MoE
dispatch sends them 1-2 rows. A 2-row verify forward 22.5 -> 21.7 ms;
3+ rows keep MLX's sorted gather, which reads an expert shared by rows
once (an owner-slot dedupe inside the kernels measured slower).

* perf(mimo_v2): draft with the checkpoint's three MTP heads

Head k reads the trunk's final-normed hidden at p and token p+k+1 (SGLang's
multi-layer EAGLE for MiMo); drafts chain only through tokens, so a round
runs head 0 on its committed rows and head i on draft i. The head module is
@beamivalice's from PR #677, adapted to the mlx-lm pack layout (split
q/k/v, affine or bf16 projections through Transformer.qmatmul) and to the
coarse draft readout bound at load. The verify rolls back by KV truncate:
the trunk is attention-only, and a snapshot made every KV write copy its
whole buffer.

The tiny oracle now renders the heads from the reference's own modules
(forked RNG, so the trunk fixture is unchanged) and `mimo mtp heads` tracks
them across rounds, wrong drafts and rollbacks.

M5 Ultra, greedy: code 74 -> 98 tok/s (80% per draft), prose 74 -> 89;
sampled creative text stays at serial. tests/test_mimo_v2.sh 22/22,
unit suite 2899 passed, 0 failed.

* perf(mimo_v2): split-K decode and verify attention for the global layers

MLX's vector kernel at q/k 192, v 128 re-reads a KV head's keys once per
query head (16 per group here) and declines verify windows (rows x GQA >
32) to its composed path. dec_attn.zig puts the group's heads, times the
query positions, in the rows of one MMA tile: a 32-key tile staged once per
threadgroup, key slices merged in threadgroup memory, splits merged in a
second dispatch.

M5 Ultra forward, same session: 4-row verify 35.9 -> 29.6 ms at 8k keys,
49.8 -> 33.5 at 32k, 69.1 -> 35.0 at 64k; one row 15.48 -> 15.22 at 8k
(median of 3), 17.27 -> 16.41 at 32k, 19.2 -> 17.4 at 64k. The sliding
layers stay on MLX, which wins at 128 keys. Parity is no worse than 2x
MLX's bf16 error against fp32 attention. Unit suite 2901 passed;
tests/test_mimo_v2.sh 22/22.

* fix(mimo_v2): size the MTP history stash for prompt-lookup rounds

A lookup round commits up to 14 drafts, but the stash's host copy of the
committed ids held MAX_DEPTH + 1 (9). Past that the ReleaseFast write ran
into the generator's ForwardCtx, and the next verify spliced a garbage
`vision_embeddings` handle and segfaulted. The stash and the merged history
now take the larger of the two round caps.

tests/test_mimo_v2.sh [9]: a whole-file edit that engages lookup drafts
(segfault before, 24/24 after).

* perf(mimo_v2): cap MTP draft depth at the head count

A draft past MiMo's last head re-runs that head at the same position and
can never be accepted; the auto cap (6) allowed it. The generator now takes
the head's own limit (`MtpHeadRef.maxDepth`). The auto-depth policy had not
been going past 3 on the measured workloads, so this changes no measured
number; it stops a wasted verify row whenever it would.

tests/test_mimo_v2.sh [8] asserts no round reports depth 6.

* perf(mimo_v2): opt-in nvfp4 decode copies of 8-bit attention weights

MLX_SERVE_DECODE_ATTN_QUANT_REQUANT=1 (LOSSY) extends decode-attn-quant to
8-bit affine attention: the weight is dequantized once and requantized to
the same nvfp4-g16 side copy the dense tail layers get, halving the ~4.8 GB
of attention MiMo reads per token. MiMo's verify windows read the copies
too, so MTP verifies against the distribution its serial steps would
produce.

M5 Ultra: a one-row forward 14.13 -> 12.16 ms, a 4-row verify 28.65 ->
26.94. Greedy text diverges from the 8-bit trunk within ~13 tokens
(chosen-token |dlogp| 0.034 while matched) with equally correct answers on
a 6-prompt check, but the MTP heads agree with it less (greedy code
acceptance 0.97/0.94/0.91 -> 0.91/0.81/0.65), so with MTP on it nets
-11% on greedy code, +3-8% on sampled text. Opt-in, not a default.

* docs(mimo_v2): MTP levers measured, the lookup stash overflow story and rule

* feat: mimo swift.

* perf(mimo_v2): NAX prefill attention, fused expert routing, sliding-ring KV

Prefill (cold, M5 Ultra, same pack vs oMLX 0.7.0):
- NAX tensor-unit flash attention at q/k 192 / v 128, ported from oMLX
  (src/nax_attention.zig, kernels/nax_*.metal): causal, in-kernel sliding
  window bound, sinks, ~8k-key passes with fp32 carry.
- Fused prefill expert reduce generalized from top-10/2560 to top-8/4096:
  MiMo took the composed unsort/multiply/sum chain (+3-4% prefill).
- Counting-sort route pack for prefill widths, bit-identical to MLX's
  stable argsort.
- Eval cadence and chunk cap read the score width (0 for MiMo): no more
  per-layer evals; wide 16384 rung for archs with no score tensor.
- Every arch reserves a multi-chunk prompt's KV up front (a grow copied
  the whole cache each chunk).
- gather_qmm_nax planner re-swept against mlx 0.32.3; MXFP4 canary now
  bit-equal to stock.
Result: 3210/3232/3271/3018/2630 tok/s at 4k/10k/16k/32k/64k vs oMLX
3158/3210/3244/3043/2655.

Sliding-ring KV (mlx-lm's RotatingKVCache layout):
- MiMo's 39 sliding layers keep window + 2048 rows (KVCache.updateSliding,
  entry.base); positions stay absolute. KV bill 222 KB -> 23 KB/token plus
  a per-slot ring term (slotFixedKvBytes).
- Prefix cache restores a ring only above its floor (ringRestores); the
  SSD tier skips rings; the hot-cache ask is one whole session.
- A 1M --ctx-size no longer zeroes the hot cache: a 62k agent turn reuses
  its prefix in 0.8 s (was ~27 s), and a 138k prompt is admitted.

Decode: stateless trunks batch-decode (forwardMoeBatchedRows), MTP falls
back to plain batched decode past two slots.

* feat(glm5_next): GLM-5.3-Flash support

TensorFold's MLX packs of Z.ai's GLM-5.3-Flash (GLM-5-Next) load and serve
text, thinking with reasoning_effort, and tool calls: KDA linear attention with
a per-core prefill recurrence, DSA sparse attention (indexer + absorbed latent
attention) inside mHC hyper-connections, 288-expert MoE, and the GLM chat
template, which needed jinja.cpp to read `x.0` as an attribute.

The app lists glm5_next packs as supported and names them "GLM"; bench.sh gets
a glm53-flash target. Parity: tests/dump_glm5_next_fixtures.py against
mlx-vlm; live: tests/test_glm5_next.sh.

* test(glm): pi agent matrix, exactness harness, smoke rows for MiMo/GLM/Ling

tests/glm_pi_matrix.sh runs pi on GLM-5.3 across every thinking level, KV
quant, prefix cache off and a narrow prefill chunk (two-turn task, hidden
checker); tests/analyze_pi_sessions.py scores any pi session dir for empty and
think-only turns, markup leaks, tool-arg schema errors and prefix reuse;
tests/glm_exactness.py checks greedy cold == warm == stream, logprobs,
seeded sampling, penalties and stop strings, and diffs configs by first
divergent token. The smoke matrix gains bailing_hybrid, mimo_v2 and glm5_next.

Records that GLM-5.3's long-prompt output moving with the prefill chunk width
is rounding, not carried state (a same-math kernel swap moves it as far), and
trims AGENTS.md under its 100k cap: the longest rows move verbatim to
docs/reference.md "AGENTS.md row detail".

* fix: tokenizer parity on code, streamed stop strings, completions frequency_penalty, pi thinking levels

- Tokenizer: the plain Llama-3 split regex (GLM-5.3, Llama 3, LFM2.5, K2) was
  served with Muse's cased grammar, splitting camelCase and `//!`; it is now
  the gpt2 grammar with 3-digit groups (the cased one needs `\p{Lu}` in the
  regex). BPE `ignore_merges` emits a vocab word whole, and `\p{N}` is a
  generated Unicode table instead of ASCII digits. Zero differing tokens vs HF
  on code for six tokenizer families (tests/test_tokenizer_hf_parity.sh).
- Streaming: a stop string spanning several tokens leaked its first bytes on
  chat, completions, messages and responses. `StopStream` holds a tail that
  could still begin a stop string and flushes it when generation ends.
- /v1/completions read `frequency_penalty` only when `repeat_penalty` was
  present but not a number; both surfaces now share `requestRepeatPenalty`.
- `mlx-serve launch pi` maps xhigh and max, so pi stops clamping max to high
  (Zig launcher and both Swift twins).

* fix(app): deleting a provider no longer crashes Settings

The Providers rows come from `ForEach($providerEntries) { $entry in }`, whose
binding reads the array by index; the delete closure removed the row and then
read `entry.id` again, which trapped on the last row and, on any other row,
cleared the next provider's model text. The closure now captures the id when it
is built and calls `SettingsFormState.removeProvider(id:)`. The Laya question
list had the same shape and gets the same fix.

* fix(gen): chat keeps running during media jobs; Hunyuan3D paint decimates before unwrap

A pi session on GLM-5.3 hung for 10+ minutes while its own asset script ran a
textured Hunyuan3D job: the paint stage handed xatlas the raw marching-cubes
mesh (900k faces at res 320), and the job held the inference thread for its
whole life, so no chat request was admitted or decoded.

- Paint decimates to upstream's 40k faces before the unwrap (vendored
  Fast-Quadric-Mesh-Simplification, lib/fqms, src/mesh_simplify.zig). A
  textured res-320 job now takes about a minute.
- The inference loop body is chatPass(.main). Every backend's per-step poll
  is Progress.boundary(), which runs chatPass(.yield) for as long as the step
  took before the cancel check. Qwen3-TTS now polls it every 8 frames.
- Pure-CPU stages (marching cubes, decimate + unwrap, renders, bake, inpaint,
  PNG/GLB) run on a worker via gen_sse.offload while chat keeps the thread.
- A running job's estimated peak is billed to chat admission
  (gen_reserve_bytes): Metal OOM is uncatchable.
- Chat decode clocks reset at each media boundary and at job end, so a media
  step never folds into the round-cost table as one slow spec round.

Tests: decimate unit tests, admissionFits, Progress.boundary/offload, the
TTS_TEST_MODEL-gated cancel test; tests/test_gen_chat_interleave.sh (chat
before gen, same image bytes, cancel, chat during the mesh job) and the
release-battery tests/test_gen_chat_mix.sh (two agents on Qwen3.8-27B +
DFlash beside image, speech, music and a textured mesh).

* feat(stable_audio): Stable Audio 3 sound effects (server, console, app)

Stable Audio 3 small (stabilityai/stable-audio-3-small-sfx) runs natively,
loading Stability's repo as published: model_config.json (no config.json,
classified by model_discovery.peekStableAudio3Config), PyTorch-named
model.safetensors and the t5gemma-b-b-ul2/ text encoder. src/stable_audio.zig
ports Stability's MIT MLX reference: T5Gemma encoder, 20-layer DiT, ping-pong
sampler, SAME-S decoder in the reference's even decode windows, unpatch to
44.1 kHz stereo. All activations f32.

- POST /v1/audio/sound-generations (prompt, duration_seconds (0,120], steps
  1-50, seed, stream): raw WAV of exactly the requested length or SSE. Fields
  are parsed as real JSON; a negative, fractional or quoted value is a named
  400. Models advertise "sound" beside "audio"; the speech and music
  endpoints name the new route. LAN sharing gates it like music.
- Console: generate_sound tool; speech selection no longer picks a sound model.
- App: Sound Effects tab in Audio, generate_sound chat tool, Model Browser
  group, config-less repo recognized on disk, sticky settings.
- skills/mlx-serve documents the endpoint; a test now fails when a /v1 route
  is missing from the skill.
- Fix: scopes released after the eval held every step's activations (a 120 s
  clip peaked at 45 GB); intermediates are freed before each eval now.
- One-file safetensors loader moved to model.zig (hunyuan3d keeps an alias);
  the WAV response tail and dated output paths are shared helpers.

Tests: parity oracles vs the reference in fp32 (tests/dump_stable_audio_fixtures.py,
SA3_*): tokens exact, T5 0.999999, DiT 0.99999, seeded 8-step sample 0.99999,
decode 1.000000; working-set bound, decodePlan, unpatch layout, config
validation, schedule; discovery, routing, LAN, strict params; Swift
SoundGenTests + media tool tests; console tests; tests/test_sound_gen.sh.

* fix: H3 keyframes on a resident encoder, logprobs behind a stop hold, tool-turn probe once

- minimax_h3: a second keyframe request on a resident text encoder unwrapped the
  unopened weights map; the tower loads only when the encoder has none.
  Guard: tests/test_h3_resident.sh [4]. The residency plan's byte figure is
  returned from h3ResidentFor and stamped only once the DiT is in.
- server: a streaming logprobs entry waits for its token's bytes; a stop-string
  hold keeps them back and a stop cut drops them (sentTokens). Guard:
  tests/test_logprobs.sh [4b].
- chat: templateRendersToolTurn is probed once at load (ChatConfig.renders_tool_turn).
- status: the gpuCoreCount test skips on a VM with no AGX entry.
- measurements removed from comments.

* feat(glm5_next): serve the pack's MTP head, with decode-width paths for verify windows

The checkpoint's `mtp.0` NextN layer drafts (src/glm_mtp.zig, the `.glm` arm of
generate.MtpHeadRef): eh_proj over the final-normed trunk row and the next token,
a plain pre-norm block built from the trunk's own DSA attention and routed MoE
over a one-layer KVCache, then norm and the trunk's lm_head. Loaded beside the
trunk from its weights through base-named loaders shared with the trunk
(loadDsaWeightsAt, loadRoutedMoeAt). Depth 3 by default (mtpDepth).

A verify window of 2..8 rows keeps the decode-width paths: one hcPre dispatch
over all rows (grid y = row, a counter word each, threadgroup cap probed once per
kernel), the fused MoE decode with slots sorted expert-major and dispatched
slot-major, the KDA decode step over the window with each row's state captured
in-kernel for the rollback, folded causal latent attention below the indexer
budget and the one-query select per row past it. Verify forwards carry
ForwardCtx.spec_verify; MiMo reads its lossy decode copies only there or at
decode width, never on a short prompt chunk (mimoDecodeCopies). The MXFP4 MoE
decode arm declines expert biases and a clamped SwiGLU (moeFp4DecodeEligible).
The MiMo MTP rollback keeps the live cache.step truncate sets.

Oracle: tests/dump_glm5_next_fixtures.py records mlx-vlm's glm5_next_mtp drafter
(logits, the trunk's hidden rows, the head's own pick margins) for the
`glm5_next MTP fixture` test; tests/test_glm5_next.sh [8] checks the head loads
and drafts live. GLM kernel tests drop their own MLX error latch.
Diagnostics: MLX_SERVE_DECODE_FWD_UBENCH_S=<rows>, MLX_SERVE_GLM_PROFILE.

* fix: issue where swift app would not auto-select model.
@ddalcu ddalcu closed this Oct 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants