Skip to content

perf: optimize quantized inference fast paths - #113

Merged
Brooooooklyn merged 8 commits into
mainfrom
perf/quantized-inference-fastpaths
Aug 1, 2026
Merged

Brooooooklyn merged 8 commits into
mainfrom
perf/quantized-inference-fastpaths

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • restore affine QMM and GatherQMM outputs to the input activation dtype
  • prevent mixed BF16 activation / FP16 sidecar checkpoints from leaking FP32 through residuals and flat KV caches
  • make those checkpoints compatible with the two-byte paged KV cache
  • reorder affine Qwen3.5 q/gate projection operands once at load so decode uses contiguous query and gate slices without retaining a duplicate layout
  • keep measured sub-byte affine Qwen embeddings packed across flat, paged, MTP, and VLM inference; gather/dequantize only selected rows and use the packed tied head directly
  • make sym8 inference native-[N,K] only and remove the transposed-weight compatibility field, constructor, environment switch, and runtime branches
  • eagerly materialize already-retained plain-E4M3 BF16 compatibility weights during load and include them exactly once in resident-memory accounting
  • fail closed when dense-only Qwen3, Harrier, PaddleOCR-VL, or Qianfan/InternVL sources are asked to emit packed weights
  • keep Gemma4 dense-only PLE and discarded encoder/projector namespaces dense under every quant mode
  • preserve and coherently split Qwen3.5 MoE pre-stacked expert .weight/.scales/.biases groups
  • reject unsupported plain-Qwen3 quantized GGUF and packed Qwen3.5 GDN fixups from the header instead of writing unloadable artifacts or aborting across MLX FFI

This 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:

Metric Baseline Candidate Change
Decode 113.7 tok/s 237.9 tok/s 2.09x
TTFT 72.2 ms 47.5 ms -34.2%

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:

Run Fallback Optimized Change
5 x 256 tokens 64.56 tok/s 68.36 tok/s +5.9%
Reverse-order 3 x 512 tokens 57.44 tok/s 61.10 tok/s +6.4%

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:

Run Dense fallback Packed Change
3 x 512 tokens 249.21 tok/s 288.50 tok/s +15.8%
Reverse-order 3 x 512 tokens 248.48 tok/s 284.52 tok/s +14.5%

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):

Metric origin/main dual layout PR native-NK only Change
Model load 313.85 ms 233.44 ms -25.6%
Request wall 691.34 ms 659.31 ms -4.6%
Prefill 14,754 tok/s 14,796 tok/s +0.3%
Decode 204.48 tok/s 215.80 tok/s +5.5%
Active after load 1.506 GB 1.009 GB -497.6 MB (-33.0%)
Request peak 2.683 GB 2.185 GB -497.6 MB (-18.5%)

The 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:

Context Decode base -> PR Decode change Prefill change Request-wall change
1K 62.96 -> 63.30 tok/s +0.5% +1.8% +0.8%
4K 57.37 -> 55.37 tok/s -3.5% +0.1% -1.9%
8K 51.73 -> 53.11 tok/s +2.7% -1.6% -0.4%
16K 40.86 -> 43.38 tok/s +6.2% +4.2% +4.7%
32K 29.36 -> 26.41 tok/s -10.1% -3.9% -6.2%
64K 18.32 -> 17.38 tok/s -5.1% -2.5% -5.4%
100K 27.72 -> 26.50 tok/s -4.4% +4.6% +4.2%

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 exceptions now 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_ -- --nocapture
  • cargo test -p mlx-core affine_quantized_forward_restores_bfloat16_after_additive_bias -- --nocapture
  • cargo test -p mlx-core plain_fp8_ -- --nocapture
  • cargo test -p mlx-core q_gate_block -- --nocapture
  • cargo test -p mlx-core packed_qwen_embedding --lib
  • cargo test -p mlx-core quantized_embedding --lib
  • cargo 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 --nocapture
  • three fresh-process native-NK versus origin/main Qwen3.5 sym8 E2E pairs (exact output hash, cold 1K prefill, 128 generated tokens)
  • cargo clippy -p mlx-core --lib --tests -- -D warnings
  • cargo 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)
  • five real-model packages/privacy/__test__/classify.test.ts runs (BF16, affine, MXFP4, MXFP8, NVFP4; 2/2 each)
  • yarn build
  • cargo fmt --all -- --check
  • git diff --check

Note

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 --quantize before I/O, including when model_type is inferred from config.json. Adds quantization_supported on 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_proj groups while keeping .weight/.scales/.biases aligned, 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 affine q_proj) to avoid per-forward strided copies; plain E4M3 BF16 reconstructions are tracked and materialized at load via PlainFp8Residency. Harrier fails on nonempty quant metadata before safetensors load. MTP steppers take Embedding instead 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.

@cursor

cursor Bot commented Aug 1, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c4bac212-0cd9-4b83-b8f5-9bd22a57636d

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cursor

cursor Bot commented Aug 1, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@cursor

cursor Bot commented Aug 1, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@cursor

cursor Bot commented Aug 1, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@cursor

cursor Bot commented Aug 1, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@cursor

cursor Bot commented Aug 1, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@cursor

cursor Bot commented Aug 1, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread crates/mlx-core/src/convert.rs Resolved
@Brooooooklyn

Copy link
Copy Markdown
Contributor Author

Final update for e6136de:

  • Removed the production sym8 dual-layout compatibility path completely: no MLX_SYM8_DUAL_LAYOUT switch, optional transposed field, fallback constructor, duplicate allocation, or runtime branch remains. Qwen3.5 and Gemma4 now use one checkpoint-native [N,K] contract.
  • Qwen3.5 sym8 fresh-process A/B against origin/main preserved exact output hashes while improving median load time by 25.6%, request wall time by 4.6%, decode by 5.5%, and reducing active memory by 497.6 MB.
  • The exact Gemma-4-26B-A4B-Unsloth-MXFP4-mlx 1K-100K sweep preserved output hashes and memory behavior but did not show a consistent speedup, so the PR makes no Gemma MXFP performance claim.
  • CI run 30694939746 is fully green: Build, Rust Lint, cargo test, yarn build:ts and yarn test, and Publish all passed.

The branch is clean, synchronized with origin, non-draft, and mergeable.

@cursor

cursor Bot commented Aug 1, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@Brooooooklyn
Brooooooklyn merged commit 8ec1d5b into main Aug 1, 2026
7 checks passed
@Brooooooklyn
Brooooooklyn deleted the perf/quantized-inference-fastpaths branch August 1, 2026 12:47
robert-johansson pushed a commit to robert-johansson/mlx-node that referenced this pull request Aug 2, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant