Repository navigation
perf: optimize quantized inference fast paths - #113
Conversation
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_275c4417-2fbd-4a54-8cc2-6369a5fa522b) |
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_3f5ff270-6f20-4438-ba57-27dd25aac210) |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_86e19676-a570-4d08-94ab-b46234614f80) |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_3b8d80ba-fb54-4d8d-9ddf-3c944ffac67f) |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_446ee803-3b4f-42cf-b5ab-f712f8dea76a) |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_31d7f3d8-48e4-4e48-9023-1af11f269e3d) |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_8cf7ed6b-3a67-4734-a3bd-33e2c21bee3b) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e6136de99c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Final update for e6136de:
The branch is clean, synchronized with origin, non-draft, and mergeable. |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_7ab491d4-b783-4c53-b30f-87bddc8b0059) |
Merge-forward of mirror/upstream (237ab8a, tag v0.0.10). 10 upstream commits: mlx-node#108/mlx-node#109 template-authoritative chat + continuation cache reuse, mlx-node#110 desktop control panel, mlx-node#111 gemma4 long-context decode, mlx-node#113 quantized inference fast paths. NOT a low-risk bump. crates/mlx-sys/src/lib.rs (+93), mlx_na_int8.cpp (+162), mlx_paged_*.cpp/.h (~550), and mlx_paged_stubs_linux.cpp (+24, our platform) all move; build.mjs rebuilds mlx-sys as a cargo dependency, so this reaches the binary GenMLX loads. 7 conflicts, then 38 rustc errors from API ripples that auto-merged cleanly into regions our fork also touches. Three ripple classes: mlx-node#113 Embedding refactor — project_logits_from_hidden and the forward/prefill family now take `embedding: &Embedding` instead of a raw weight + optional transposed twin. Adopted wholesale. inject_image_placeholders — now returns Result<Vec<u32>>; fork VLM call sites needed `?` (16 of the 38 errors, and NO resolver reported this class). ChatStreamChunk — gained three required fields; fork-added literals filled by mirroring the dense sibling's own values rather than blind-defaulting. THE TRANSPOSED EMBEDDING WEIGHT WAS NEVER OURS. It was flagged mid-merge as a lost fork perf patch; provenance says otherwise. The merge base already carried it (69 dense / 42 MoE occurrences), traced to upstream's own mlx-node#24, and upstream removed it in mlx-node#113. Our fork merely FOLLOWED that convention at call sites we added. Preserving it would have been a regression, not a rescue: Embedding documents `get_weight()` as a tripwire — "production inference must never call get_weight() on a packed embedding because that constructs a full [vocab, hidden] dequantization graph" — and mlx-node#113's `as_linear` routes packed checkpoints through mlx_quantized_matmul(transpose=true) so the dense table is never materialized. FORK PATCHES VERIFIED INTACT: genmlx-d3yn (one generation stream per model) — byte-exact. Stream::new sites 4/4 dense and 2/2 MoE vs HEAD; generation_stream refs 90/90 and 80/80. This is the patch most at risk of silent loss, and note it CANNOT be validated here: the leak is Metal-only (Stream::new collapses to the default stream without Metal), which is why it never reproduced on Thor. A green battery on a CUDA box proves nothing about it. mlx-cft4 (merged_qkvz in MoE weight loading) — was HALF-LOST and is restored. Upstream demoted apply_weights_moe_inner to a #[cfg(test)] wrapper and moved production loading into apply_weights_moe_inner_with_residency, which had no merged_qkvz param; our parameter survived only on the test-only wrapper while its consuming logic rode into the production body. Re-plumbed (:522, consumed :765). Left unfixed this would have silently corrupted MoE expert weight loading — no test would have caught it. genmlx-uhtp (mlx_report_error on paged-attn catch sites) — intact, rebased onto upstream's renamed context label. mlx gitlink UNCHANGED (fef8890f both sides — no nax replay needed). Superset invariant re-verified on freshly fetched refs after finding the first check ran against a stale up/main: `git cherry -v origin/main fef8890f up/main` -> 0 '+'. cargo check -p mlx-core --release: 0 errors. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Summary
[N,K]only and remove the transposed-weight compatibility field, constructor, environment switch, and runtime branches.weight/.scales/.biasesgroupsThis PR is being updated one independently validated optimization commit at a time. Each optimization must pass focused correctness tests and a same-model, same-prompt, fresh-process end-to-end A/B before it is pushed.
Root cause
MLX promotes affine QMM operands when activation and sidecar dtypes differ. BF16 activations with FP16 affine scales and biases therefore produce FP32 projection outputs. Several model-specific and generic Rust wrappers returned that promoted result directly, allowing FP32 to propagate into residuals, expert outputs, and KV caches.
End-to-end validation
Affected Qwen3.5 affine checkpoint, Apple M5 Max, deterministic 106-token prompt, five fresh-process 256-token generations:
The baseline paged-cache session fails because FP32 K/V is rejected. The candidate completes three fresh-process 128-token paged sessions with a median 203.7 tok/s decode.
For the affine q/gate layout, the same release binary was run with the load-time optimization enabled and with
MLX_DISABLE_QGATE_BLOCK_SPLIT=1. Every sample used the same Qwen3.5 4B affine-8 model, deterministic 106-token prompt, and a fresh child process/model load:For the packed embedding, the same release binary was run with the default path and with
MLX_DISABLE_PACKED_QWEN_EMBEDDING=1. The tested Qwen3.5 0.8B artifact has a tied 248,320 x 1,024 affine-6 embedding/head. Two counterbalanced batches of three fresh-process 512-token generations reproduced the win:The packed tensors occupy 206,602,240 bytes instead of a 508,559,360-byte BF16 table, preserving 288 MiB of unified memory. The policy deliberately leaves 8-bit and unmeasured modes dense: the affine-8 control was unchanged at 74.15 versus 74.21 tok/s (+0.08%, noise) across three fresh-process 256-token runs per condition.
For sym8 single-layout residency, the final PR release binary was compared directly with
origin/main. The Qwen3.5 0.8B sym8 artifact used exact 1,000-token model-template-rendered prompts, cold prefills (cached_tokens=0), and 128 deterministic output tokens in three counterbalanced fresh-process pairs. Every output had the same raw SHA-256 (a0c4739b...9eb):origin/maindual layoutThe artifact contains 497,614,848 bytes (474.56 MiB) of eligible int8 weights, matching the duplicate orientation removed from production ownership. There is no compatibility environment variable or optional layout left: Qwen3.5 and Gemma4 loaders, constructors, and forwards now have one native-
[N,K]contract. Independent low-level kernel profiling primitives remain test-only research tools and are not reachable from model loading.The requested Gemma-4-26B-A4B-Unsloth-MXFP4-mlx 1K-100K audit used three counterbalanced fresh-process pairs per context, exact model-provided template lengths, 128 deterministic output tokens, and no restored KV prefix. Every base/PR pair was raw-output hash-identical. This PR does not produce a consistent Gemma MXFP long-context speedup:
Request-active memory was identical and peak memory stayed within 0.13%. The mixed signs and run-level variance are consistent with noise on an MXFP/K path this PR does not materially change; no Gemma MXFP speedup is claimed from this sweep.
Plain E4M3 is a compatibility path: the runtime already retains BF16 reconstructions beside the serialized Uint8/scales, then uses dense matmul. This change makes those existing arrays part of the load-time materialization pass and resident-byte budget instead of letting the first turn evaluate a hidden lazy graph. Same-binary eager/deferred 128-token E2E runs produced exact output hashes. On the dense 4B artifact, eager materialization measured 1,158 ms load / 81.49 ms TTFT / 3,594 ms total versus 1,183 ms / 84.19 ms / 3,605 ms deferred. On the MoE artifact, eager measured 4,549 ms load / 557.41 ms TTFT / 7,401 ms total versus 4,551-4,585 ms / 577.41-585.41 ms / 7,430-7,452 ms deferred. Decode was unchanged within noise; the win is honest first-turn placement and correct unified-memory accounting.
The complete family/mode audit also found conversion contracts that looked supported but had no valid inference route. Explicit and auto-detected dense-only families now reject quantization before tensor/output work; Harrier also rejects nonempty quant metadata at load. Gemma4 no longer packs its dense-only PLE linears or discarded audio/vision namespaces. Pre-stacked Qwen MoE expert groups retain all quant companions. A real Qwen3.5 Q5_K GGUF that previously aborted with
Rust cannot catch foreign exceptionsnow exits 1 from the header, names the packed GDN projection that needs a lossless reinterleave, and writes no artifact. A real plain-Qwen3 Q4_K GGUF likewise exits 1 because that runtime is dense-only; floating Qwen3 and true hybrid Qwen3.5 detection remain allowed.Fresh-process final-addon smoke covered Qwen3 BF16; Qwen3.5 affine, sym8, MXFP, NVFP4+plain-E4M3; LFM2; Gemma4 affine+K, MXFP, NVFP4+plain-E4M3; and Qwen3.5 MoE MXFP. Every generative run reached its 64-token limit. Privacy-filter BF16, affine, MXFP4, MXFP8, and NVFP4 each passed the two public classification E2E tests.
All measured generations reached the requested token limit. Other candidates were tested and rejected before push: a plain-E4M3 transpose cache was neutral in its longer reverse-order run (-0.06%); affine GDN input-projection fusion improved median decode by only +0.45% and +0.74% across two E2E passes, which did not justify its ownership/persistence complexity; direct GDN depthwise convolution was about 4% slower; affine MLP gate/up fusion was only +0.1% to +1.5% in exact-shape operator tests; and a token-exact native-order fused affine qargmax was neutral at T=3 and 3% to 7% slower at T=5/6. A dense tied-head transpose cache also failed the E2E gate: ten sym8 AR pairs measured +0.44% median / +0.33% paired-median decode with 8/10 positive pairs, while ten BF16 MTP pairs measured +0.17% / +0.22% with 7/10 positive pairs; hashes, token counts, and routes were exact, but the gain was below the false-positive threshold. Static quant-mode C strings were also rejected after ten alternating affine Qwen pairs measured -0.25% paired median, and LFM2 stacked dense MLP weights were rejected because a +0.62% binary-A/B decode result cost 1.07 GB (+45.9%) active memory. Paged FP8 KV was excluded: the current scale contract is inverted for dequantization, online scale changes invalidate existing blocks, graph/readback paths reject FP8, and persistence does not record scale identity, so enabling it here would be a correctness change rather than a validated optimization.
Tests
cargo test -p mlx-core affine_q4_ -- --nocapturecargo test -p mlx-core affine_quantized_forward_restores_bfloat16_after_additive_bias -- --nocapturecargo test -p mlx-core plain_fp8_ -- --nocapturecargo test -p mlx-core q_gate_block -- --nocapturecargo test -p mlx-core packed_qwen_embedding --libcargo test -p mlx-core quantized_embedding --libcargo test -p mlx-core sym8_ --lib -- --nocapture(41 passed, 5 manual profiles skipped)MLX_SYM8_TEST_MODEL_PATH=... cargo test -p mlx-core --release --test qwen3_5_sym8_smoke -- --ignored --nocaptureorigin/mainQwen3.5 sym8 E2E pairs (exact output hash, cold 1K prefill, 128 generated tokens)cargo clippy -p mlx-core --lib --tests -- -D warningscargo test -p mlx-core --lib --no-fail-fast(2,618 passed, 59 ignored; two fixture assumptions were exposed by the new plain-Qwen3 guard, corrected to exercise the intended generic-architecture guards, and both focused reruns passed)vp test packages/cli/__test__/convert-cmd.test.ts --run(28 passed)packages/privacy/__test__/classify.test.tsruns (BF16, affine, MXFP4, MXFP8, NVFP4; 2/2 each)yarn buildcargo fmt --all -- --checkgit diff --checkNote
High Risk
Changes sym8 weight layout, conversion quantization gates, MoE sanitize, and MTP embedding plumbing across core load/inference paths; mistakes would produce unloadable checkpoints or silent numeric drift.
Overview
Tightens conversion and load contracts so dense-only runtimes (Qwen3, Harrier, PaddleOCR-VL, Qianfan/InternVL) reject
--quantizebefore I/O, including whenmodel_typeis inferred fromconfig.json. Addsquantization_supportedon recipes and universal Gemma4 exclusions for PLE and discarded encoder/projector tensors under every quant mode.Fixes Qwen3.5 MoE pre-stacked experts by splitting fused
gate_up_proj/down_projgroups while keeping.weight/.scales/.biasesaligned, replacing the old path that dropped quant companions.Inference fast paths: sym8 drops the duplicated
[K,N]operand and routes through native[N,K]GEMM/QMV FFI; affine gather-QMM and Qwen3.5 q/gate use load-time block layout (including affineq_proj) to avoid per-forward strided copies; plain E4M3 BF16 reconstructions are tracked and materialized at load viaPlainFp8Residency. Harrier fails on nonempty quant metadata before safetensors load. MTP steppers takeEmbeddinginstead of a raw weight tensor for lookups.Reviewed by Cursor Bugbot for commit fac7b59. Bugbot is set up for automated code reviews on this repo. Configure here.