Skip to content

Add MiMo V2.5 - #1219

Open
kernelpool wants to merge 9 commits into
ml-explore:mainfrom
kernelpool:add-mimo-v2
Open

kernelpool wants to merge 9 commits into
ml-explore:mainfrom
kernelpool:add-mimo-v2

Conversation

@kernelpool

@kernelpool kernelpool commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

EDIT: This has been updated to support MiMo-V2.6

Models

MiMo-V2.5-Pro (distributed)

mlx.launch --verbose --backend jaccl --hostfile hosts-jaccl.json --env MLX_METAL_FAST_SYNCH=1 -- /Users/optimus/repo/mlx-lm/mlx_lm/examples/sharded_generate.py --model /Users/optimus/models/catalyst/MiMo-V2.5-Pro-4bit --prompt "Who is Albert Einstein?" -m 1024                                 
[INFO] Running /Users/optimus/repo/mlx-lm/.venv/bin/python /Users/optimus/repo/mlx-lm/mlx_lm/examples/sharded_generate.py --model /Users/optimus/models/catalyst/MiMo-V2.5-Pro-4bit --prompt 'Who is Albert Einstein?' -m 1024 
[jaccl] Connection attempt 0 waiting 1000 ms
/Users/optimus/repo/mlx-lm/.venv/lib/python3.12/site-packages/transformers/modeling_rope_utils.py:936: FutureWarning: `rope_config_validation` is deprecated and has been removed. Its functionality has been moved to RotaryEmbeddingConfigMixin.validate_rope method. PreTrainedConfig inherits this class, so please call self.validate_rope() instead. Also, make sure to use the new rope_parameters syntax. You can call self.standardize_rope_params() in the meantime.
  warnings.warn(
/Users/optimus/repo/mlx-lm/.venv/lib/python3.12/site-packages/transformers/modeling_rope_utils.py:936: FutureWarning: `rope_config_validation` is deprecated and has been removed. Its functionality has been moved to RotaryEmbeddingConfigMixin.validate_rope method. PreTrainedConfig inherits this class, so please call self.validate_rope() instead. Also, make sure to use the new rope_parameters syntax. You can call self.standardize_rope_params() in the meantime.
  warnings.warn(
<think>The user is asking about Albert Einstein, one of the most famous scientists in history. This is a straightforward factual question.</think># Albert Einstein (1879–1955)

Albert Einstein was a German-born theoretical physicist, widely regarded as one of the most influential scientists in history. Here are some key highlights:

## Major Contributions

- **Special Theory of Relativity (1905):** Introduced the famous equation **E = mc²**, showing the relationship between mass and energy.
- **General Theory of Relativity (1915):** Redefined our understanding of gravity as the curvature of spacetime caused by mass and energy.
- **Photoelectric Effect:** Demonstred to quantum mechanics by explaining light as discrete packets (photons). This work earned him the **Nobel Prize in Physics in 1921**.
- **Brownian Motion:** Provided empirical evidence for the existence of atoms.

## Personal Life

- Born on **March 14, 1879**, in **Ulm, Germany**.
- He worked at the Swiss Patent Office before entering academia.
- Due to the rise of Nazism, he emigrated to the **United States** in 1933 and joined the **Institute for Advanced Study** in Princeton, New Jersey.
- He became a U.S. citizen in 1940.

## Legacy

Einstein's name has become synonymous with **genius**. His theories laid the groundwork for modern physics, influencing everything from GPS satellites to black hole research. Beyond science, he was also a vocal advocate for **civil rights, pacifism, and nuclear disarmament**.

He passed away on **April 18, 1955**, in Princeton, New Jersey.

Would you like to know more about any specific aspect of his life or work? 😊
==========
Prompt: 256 tokens, 62.765 tokens-per-sec
Generation: 384 tokens, 30.303 tokens-per-sec
Peak memory: 297.086 GB
[INFO] Node with rank 1 completed 
[INFO] Node with rank 0 completed 

MiMo-V2.5 (single node)

mlx_lm.generate --model /Volumes/WD_EXTRA/temp/MiMo-V2.5-4bit --prompt "Who is Ablert Einstein?" -m 1024
The repository /Volumes/WD_EXTRA/temp/MiMo-V2.5-4bit contains custom code which must be executed to correctly load the model. You can inspect the repository content at /Volumes/WD_EXTRA/temp/MiMo-V2.5-4bit .
 You can inspect the repository content at https://hf.co//Volumes/WD_EXTRA/temp/MiMo-V2.5-4bit.
You can avoid this prompt in future by passing the argument `trust_remote_code=True`.

Do you wish to run the custom code? [y/N] y
/Users/optimus/repo/mlx-lm/.venv/lib/python3.12/site-packages/transformers/modeling_rope_utils.py:936: FutureWarning: `rope_config_validation` is deprecated and has been removed. Its functionality has been moved to RotaryEmbeddingConfigMixin.validate_rope method. PreTrainedConfig inherits this class, so please call self.validate_rope() instead. Also, make sure to use the new rope_parameters syntax. You can call self.standardize_rope_params() in the meantime.
  warnings.warn(
==========
<think>The user is asking about Albert Einstein (they misspelled it as "Ablert"). I'll provide a comprehensive overview of who he was.</think># Albert Einstein (1879–1955)

Albert Einstein was a **German-born theoretical physicist**, widely regarded as one of the most influential scientists in history. Here are the key highlights of his life and work:

## Major Contributions
- **Special Theory of Relativity (1905)** – Introduced the famous equation **E = mc²**, showing the equivalence of mass and energy.
- **General Theory of Relativity (1915)** – Redefined our understanding of gravity as the curvature of space-time.
- **Photoelectric Effect** – Helped establish quantum theory by showing that light can behave as particles (photons). This work earned him the **Nobel Prize in Physics in 1921**.
- **Brownian Motion** – Provided evidence for the existence of atoms.

## Life Highlights
- **Born:** March 14, 1879, in Ulm, Germany
- **Education:** Studied at the Swiss Federal Polytechnic in Zurich
- **1905 "Miracle Year":** Published four groundbreaking papers that revolutionized physics
- **Emigrated to the U.S.** in 1933, fleeing the rise of Nazism, and joined the **Institute for Advanced Study** in Princeton, New Jersey
- **1939:** Signed a letter to President Roosevelt warning about the potential for atomic weapons, which contributed to the Manhattan Project (though Einstein himself did not work on it)
- **Died:** April 18, 1955, in Princeton, New Jersey

## Legacy
Einstein's work fundamentally changed our understanding of the universe — from the nature of light and gravity to the fabric of space and time. He remains a cultural icon of **genius and creativity**, and his name is virtually synonymous with intelligence.
==========
Prompt: 31 tokens, 23.129 tokens-per-sec
Generation: 413 tokens, 48.367 tokens-per-sec
Peak memory: 173.935 GB

MiMo-V2.6-Flash-RL (single node)

mlx_lm.generate --model /Volumes/WD_ULTRA/models/MiMo-V2.6-Flash-RL-mxfp4-q8 -p "The secret to baking a good cake is" -m 1024
==========
<think>The user seems to have an incomplete sentence. Let me provide a helpful response about baking a good cake.</think>It looks like your sentence got cut off! But I'd be happy to share some secrets to baking a great cake:

## 🎂 Secrets to a Good Cake

1. **Room temperature ingredients** – Butter, eggs, and milk should be at room temperature for better mixing and a smoother batter.

2. **Proper measuring** – Use a kitchen scale for accuracy, or the "spoon and level" method for dry ingredients.

3. **Don't overmix** – Overmixing develops too much gluten, leading to a tough, dense cake.

4. **Preheat your oven** – Always let it reach the right temperature before baking.

5. **Use quality ingredients** – Fresh baking powder/soda, real vanilla extract, and good butter make a noticeable difference.

6. **Don't open the oven too early** – This can cause the cake to collapse.

7. **Test for doneness** – A toothpick inserted in the center should come out clean or with a few moist crumbs.

8. **Let it cool properly** – Cool in the pan for 10 minutes, then transfer to a wire rack.

9. **Follow the recipe** – Especially when you're learning. Baking is more science than art!

10. **Practice** – Like anything, experience is the best teacher.

Would you like a specific cake recipe or tips for a particular type of cake? 🍰
==========
Prompt: 15 tokens, 66.672 tokens-per-sec
Generation: 312 tokens, 46.720 tokens-per-sec
Peak memory: 167.305 GB

@phpmac

phpmac commented Apr 28, 2026

Copy link
Copy Markdown

牛逼

chanunc pushed a commit to chanunc/local-llm-mac-studio that referenced this pull request Apr 30, 2026
Adds Xiaomi's `MiMoV2ForCausalLM` to the stack via vllm-mlx, with
the architecture file vendored from open PR
ml-explore/mlx-lm#1219 (single 556-line `mimo_v2.py` drop-in;
mlx-lm 0.31.3 only ships `mimo.py` and `mimo_v2_flash.py`). The
Ling thread-local-stream + inline-gen patches that are already in
the venv are sufficient — no MiMo-specific patches needed.

Loads cleanly. Tool-call format is Hermes-style XML (same body as
Qwen3-coder, wrapped in `<tool_call>` tags) so `--tool-call-parser
qwen3_coder` + `--reasoning-parser qwen3` is the right combo.

OpenCode bench result: not viable as an agent backbone in this
stack. Browse: 1/3 runs emit invalid tool call, 2/3 hit the 8K
output cap reasoning into oblivion. Search: 0/3 runs ever call a
tool — model burns all 8192 output tokens in `<think>` and never
exits to a tool call. Raw `/v1/chat/completions` with a single
tool *does* emit valid tool calls cleanly, so the issue is the
heavily-pruned 130-expert variant choking on OpenCode's 10-tool
catalog with thinking-on, not the server config.

Adds MiMo as a ⚠ / ⛔ row in the cross-model OpenCode end-to-end
table with the failure mode in the notes column. Full deployment
guide and caveats in `docs/models/model-summary-mimo-v2.5.md`.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@yohann-bearzi

yohann-bearzi commented May 2, 2026 •

Copy link
Copy Markdown

Tested on Mac Studio M3 Ultra 512 GB, mlx-lm installed from this branch.

Quantized MiMo-V2-Flash to 8-bit via mlx_lm.convert -q --q-bits 8 and ran generation:

  • Prompt: "The capital of France is"
  • Output: "Paris. \nThe capital of Germany is Berlin. \nThe capital of Italy"

Forward pass works, generation is coherent. Architecture instantiates cleanly from MiMo-V2-Flash's config (313 GB BF16 source).

Thanks for the contribution @kernelpool — great to have MiMo on Apple Silicon!

jundot added a commit to jundot/omlx that referenced this pull request Jul 28, 2026
Port the text-model implementation from mlx-lm PR #1219, with
oMLX runtime registration, model routing, and oQ integration.

Source: ml-explore/mlx-lm#1219
Upstream-Commit: 96dd6fc2e0d2a1c43fcbd5b3c4be7dee640ad304
Sofille65 added a commit to Odyssai-eu/OdyssAI-X that referenced this pull request Sep 29, 2026
…udio (1.54.0)

Serves MiMo-V2.6-Pro (70 layers, 384 experts, too big for one node) as a
distributed VL pool. Decided with Sophie 2026-09-29: tensor on 4 nodes by
default, pipeline also available; no ring for distributed models.

- vlm_runner: _shard_lm_mimo_tensor (mlx-vlm's MiMo has no shard(); follows
  the mlx-lm mimo_v2_flash shard of ml-explore/mlx-lm#1219): q/k/v
  all-to-sharded, o_proj sharded-to-all, per-head attention sinks sliced to
  the rank's heads, dense MLP split, routed experts sharded in place with one
  all_sum per MoE block. Split table _DIST_MODES per model type (first =
  default); RUNNER_SHARD_MODE picks tensor/pipeline. Pipeline honours
  RUNNER_LAYER_BOUNDS > RUNNER_RAM_WEIGHTS > even, like runner.py.
- auto_parallel: the shard-local swa_idx/ga_idx recompute now also matches
  the mlx-vlm MimoModel class (the isinstance only named the mlx-lm one, so a
  pipeline rank built its full-attention mask from a sliding-window cache:
  broadcast_shapes crash on a filled cache, reproduced by the oracle's
  negative control). compute_proportional_bounds moves here from runner.py
  so both runners share it.
- One RNG stream on every rank: mlx-vlm's stream_generate ignores a seed
  kwarg, so ranks sampled from their own process RNG at temperature > 0.
  Rank 0 draws a seed when the client sent none, an all_sum shares it.
- Audio: input_audio parts (mlx_vlm.server's OpenAI shape) are decoded to
  temp files and passed with num_audios; any other non-text part (video) is
  refused instead of silently dropped.
- api: VLM_DIST_SUPPORTED lists the splits per type (mimo_v2: tensor,
  pipeline); an explicit request mode overrides the type default. VL pools
  run over JACCL (coordinator + RDMA devices json, edge preflight), ring only
  on an explicit backend override; pipeline pools get per-rank wired-limit
  weights (_cluster_total_ram_bytes now takes the pool's own topology). The
  split and backend are persisted and restored.
- install-jaccl.sh also patches the mlx-vlm venv's libjaccl (peer death
  visible), which only the text venv had.
- diag/tp_oracle_mimo.py: first K layers, split vs one node, chunked prefill
  over the 128-token window then a cached decode step. MiMo-V2.6-Pro bf16,
  K=8: tensor 2 and 4 ranks top-1/top-5 equal, rel_err 4.7e-3, ranks
  bit-identical; pipeline 2 ranks bit-exact; negative control (global
  indices restored) crashes as before the fix.

Difficulty: 8, delivered

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ddalcu added a commit to ddalcu/mlx-serve 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants