Skip to content

perf(qwen4): route Flash-Next expert Gate+Up prefill through A8 on M5 - #4320

Merged
jundot merged 3 commits into
jundot:mainfrom
DT-HJ:feat/qwen4-exp-routed-a8-r2
Oct 7, 2026
Merged

jundot merged 3 commits into
jundot:mainfrom
DT-HJ:feat/qwen4-exp-routed-a8-r2

Conversation

@DT-HJ

@DT-HJ DT-HJ commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

qwen35_oq_a8_enabled already accelerates eligible dense Q4/Q5 projections. This PR extends the same opt-in to the routed Q4/GS64 Gate+Up projections used by Qwen3.8-Flash-Next (qwen4_exp) on M5. Those projections ran through A16 gather_qmm before.

The Gate+Up now runs on INT8 operands with SwiGLU fused into the epilogue. The Down projection stays on the existing A16 path. The existing qwen35_oq_a8_enabled and qwen35_oq_a8_min_tokens settings are reused, so there is no new setting. The admin API, the web UI and the macOS app expose them for qwen4_exp only (an exact match, not qwen4*).

Approach

Q4/GS64 checkpoint weights
  -> Stage A: quantize token rows to INT8 once
  -> existing routed tile scan
  -> Q4 -> INT8 fragments
  -> INT8 x INT8 -> INT32
  -> GS64 affine correction + fused SwiGLU
  -> existing A16 Down
  • Stage A runs once per token row, not once per route. The kernel reads the quantized rows through row_map, so top-k replication does not multiply the quantization cost.
  • The kernel reads the checkpoint's [E, N, G] scale/bias tensors in place and stages the current tile's metadata in about 10 KiB of threadgroup memory. No persistent transposed copy exists.

Scope

  • Routed A8 applies to qwen4_exp only, and only for affine Q4 / GS64 with BF16 or FP16 metadata, fused gate+up experts and plain SwiGLU. The call must be a sorted prefill with at least 128 tokens per sequence. qwen35_oq_a8_min_tokens can raise this floor but not lower it.
  • These stay on A16: the Down projection, decode, verify, the MTP draft head, expert offload, other bit widths and group sizes, and clamped or unknown activations.
  • The settings gate accepts exactly qwen4_exp in addition to the existing qwen3_5* / qwen3_6* / qwen3_8* prefixes. ANE prefill stays unavailable for qwen4_exp, and the A8/ANE conflict check is unchanged.

Enabling

The per-model A8 setting tags only the loaded model's eligible routed modules. Changing the setting or the minimum-token floor reloads the engine. The MTP draft head is excluded, and OMLX_M5_GATHER_QMM_A8=0 disables the routed path.

A per-instantiation canary keeps the existing A16 path if the kernel cannot be validated. Routing/dispatch exceptions also fall back to A16, with one warning per exception type.

Performance

M5 Max 128 GiB, mlx 0.32.3, Qwen3.8-Flash-Next-oQ4e-mtp, prefix cache off, 8192-token prefill chunks. Dense oQ A8 is on in both columns; "Existing A8" has the routed Gate+Up declining at its entry point, which runs within 2% of main. Two independent 6-pair alternating A/B runs, 12 pairs in total. Prefill in tok/s.

Prompt Existing A8 Routed A8 Gain
1K 1936 2057 +6.1%
4K 2930 3152 +7.7%
8K 2929 3155 +7.8%
16K 2851 3031 +6.3%
32K 2765 2946 +6.5%
64K 2617 2803 +6.9%
128K 2542 2716 +6.8%

The two runs differed by about one percentage point at some lengths; the table reports the pooled result. 64K and 128K use the same setup and design (two independent 6-pair runs, 12 pairs each), measured in a later session. The gain stays at +6.9% and +6.8% there, with the same 8192-token prefill chunks.

Median TTFT improved from 24.52 s to 22.90 s at 64K and from 50.58 s to 47.38 s at 128K.

  • Coverage: at 4K, routed A8 runs on 48/48 backbone MoE layers. Down, the MTP draft head, decode and verify stay on A16. Toggling the setting through the admin API (OFF, ON, OFF, ON, OFF, ON) reloads the engine each time, shows 48/48 layers when ON and 0 routed A8 calls when OFF.
  • Memory: no persistent memory overhead was measured. Settled active memory was 97.882 GiB in both conditions and peak memory was 102.44 GiB. At 64K and 128K the peak was 102.25 and 104.2 GiB in both conditions.
  • Quality: activation quantization changes numerics, as with the existing dense oQ A8 path. Across 24 sequences / 114,688 positions, the NLL delta was +0.0032 nats/token with a 95% CI of [-0.0020, +0.0084], top-1 agreement 0.919 and mean KL 0.072. No NaN/Inf was observed. The sample did not detect a statistically significant NLL regression, although it cannot rule out roughly a +0.84% PPL increase at the upper end of the interval.

Regression check: Qwen3.8-27B

Jundot/Qwen3.8-27B-oQ4e-mtp is a dense model, so the new routed path does not run. A8 is on for both builds, two live servers alternating, 6 pairs per length. Median prefill in tok/s:

Prompt main PR
1K 1013 1013
4K 1159 1158
8K 1178 1179
16K 1155 1155

All measured differences were within noise. Full logits (1K/4K/8K), the last-position logits and 16 greedy tokens were identical, and so were the Q4/Q5 A8 dispatch counters and memory. As a sanity check, disabling A8 changes the logits hash.

Reproduction

Base 79f4488e, PR head bb7973d9, all native extensions built (OMLX_WITH_CUSTOM_KERNEL=1 pip install -e .). 64K and 128K were measured at the PR head. 1K to 32K were measured on an earlier revision of this branch; the later revisions differ only in two comments, a SwiftUI view and a unit test, with no runtime Python change.

Server: omlx serve --model-dir <dir containing Qwen3.8-Flash-Next-oQ4e-mtp> with the per-model settings qwen35_oq_a8_enabled: true and qwen35_oq_a8_min_tokens: 128, prefix cache off, one request at a time, temperature 0, MTP and expert offload off. Each sample is one streamed request with max_tokens=1, and PP/s is usage.prompt_tokens divided by TTFT.

Conditions: dense oQ A8 is on in both. The baseline keeps the routed Gate+Up on the existing A16 path, and the PR condition runs it on A8. This is not an A8 on/off comparison. With public settings, start the server with OMLX_M5_GATHER_QMM_A8=0 for the baseline: I checked with call counters that this gives 0 routed A8 calls and unchanged dense A8 calls.

My numbers come from a small harness that is not part of this PR. It switched the condition per request inside one server process by making the routed Gate+Up decline at its entry point, alternating AB/BA with a distinct salted prompt per request, after one warm-up request per condition and length. Each prompt length has two independent runs (fresh server each) of 6 pairs, 12 pairs in total.

Validation

  • Routed A8 kernel tests: checkpoint metadata layout, staged vs scalar parity, the real Flash-Next shape, partial/skewed/empty-expert routes, more than 32768 routed rows, canary decline.
  • Dispatch tests: both prefill call sites, fallback for short sequences, decode and verify, MTP exclusion, expert offload fallback.
  • Settings tests: admin API validation for qwen4_exp (qwen4 and qwen4_exp_x are rejected), engine reload signature, web save/restore (tests/qwen_oq_a8_ui.test.cjs) and the macOS gate (ModelSettingsScreenVMTests, 25 tests).
  • GitHub CI (no native extensions built): 16,391 passed, 1,369 skipped, 0 failed. On an M5 Max with the native extensions built, the full default unit suite reported 17,235 passed / 7 failed. The same seven tests fail on the base commit (test_deepseek_v4_dspark x5, test_dflash_muse_glimmer, test_integrations).

Screenshots

Web admin

Model settings of qwen3.8-flash-next-oQ4e-mtp, Experimental Features. The toggle in the After image is switched on in the dialog (not saved) to show the minimum-token field.

Before (main): no A8 control for qwen4_exp.

Before: model settings without the Qwen INT8 Activation Prefill control

After (this PR):

After: model settings with the Qwen INT8 Activation Prefill toggle and minimum prompt tokens

macOS app

Model settings of qwen3.8-flash-next-oQ4e-mtp (Advanced, Experimental). The toggle is off in both images.

Before (main): no A8 row for qwen4_exp.

Before: macOS model settings without the Qwen INT8 Activation Prefill row

After (this PR): the row is the first item under Experimental. The macOS row used to sit inside the ANE-backend condition, which Flash-Next does not meet, so this PR moves the A8 rows out of it. The Qwen ANE Prefill row keeps its existing condition and stays hidden for qwen4_exp.

After: macOS model settings with the Qwen INT8 Activation Prefill row

Checklist

  • I read CONTRIBUTING.md.
  • I understand every change in this PR and can explain it in review.
  • For UI or UX changes, I attached before and after screenshots.

🤖 Generated with Claude Code

hjlee and others added 2 commits October 6, 2026 18:44
An INT8-activation variant of the sorted routed-expert gather_qmm for M5.
Packed Q4 codes are decoded into INT8 fragment registers and multiplied with
the INT8 x INT8 -> INT32 tensor op, with the GS64 affine correction per group
and an optional SwiGLU epilogue (gate/up -> [M, N / 2]). Stage A runs once per
token row and the kernel reads the rows through the route map.

The kernel reads the checkpoint's own [E, N, G] scale/bias tensors: each
threadgroup stages the metadata of its 64 weight rows in threadgroup memory
(10 KiB for K = 2560, at most 16 KiB), so no transposed copy is needed. Models
with G not a multiple of 4 or above 64 take scalar loads of the same layout.

A canary on the production instantiation declines to the caller's A16 path if
the kernel cannot run or is wrong on a toolchain. Nothing calls it yet.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Qwen MoE prefill on M5 now runs the routed-expert Gate+Up of a model that
enabled qwen35_oq_a8_enabled on the INT8-activation kernel, with the SwiGLU in
the epilogue; the Down projection keeps the A16 path.

The opt-in is per model, like the dense oQ A8 kernels: apply_qwen35_oq_a8_patch
tags the backbone SwitchGLU modules of the loaded model, so a model loaded with
the setting off is never routed and the existing reload signature already
covers the setting. The MTP draft head is excluded by identity (the head the MTP
integration itself finds), and modules attached later stay A16.

Eligible calls: affine Q4 / GS64 fused gate+up with bf16/fp16 metadata, plain
SwiGLU, at least 128 tokens per sequence (the model's qwen35_oq_a8_min_tokens
can raise this floor). Decode, verify, short prefill, other bit widths and group
sizes, clamped activations and expert-offload modules return None and the
callers keep the A16 path. An exception falls back to A16 with one warning per
exception type.

Both prefill call sites are covered: SwitchGLU.__call__ (below 1024 tokens) and
the weighted-sum path (every larger chunk). Tests assert that an eligible call
reaches the A8 kernel at each site, so a silent fallback cannot pass.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@DT-HJ DT-HJ changed the title feat(qwen): INT8-activation routed gate/up with fused SwiGLU for Qwen3.8-Flash-Next prefill on M5 perf(qwen4): route Flash-Next expert Gate+Up prefill through A8 on M5 Oct 6, 2026
@DT-HJ
DT-HJ force-pushed the feat/qwen4-exp-routed-a8-r2 branch from 7efe045 to f55fc2f Compare October 6, 2026 12:55
The routed-expert Gate+Up A8 path was validated together with the existing
dense oQ A8 path, so Qwen3.8-Flash-Next (config model type qwen4_exp) uses the
existing qwen35_oq_a8_enabled / qwen35_oq_a8_min_tokens settings instead of a
separate routed-only toggle. Those settings were refused for qwen4_exp by the
admin API, the web UI and the macOS app, leaving model_settings.json as the only
way to enable the feature.

The three gates (settings validation, recipe/profile feature check, UI
visibility) now accept the exact family qwen4_exp, not every qwen4*, since only
that checkpoint family is validated. The ANE prefill backend and VLM MTP
drafter checks are unchanged, so ANE prefill stays unavailable for qwen4_exp
and the existing A8/ANE conflict still applies.

Tests cover accepted/rejected families, min_tokens preservation, the ANE
conflict, the reload signature toggle, the web gate (including a save and
restore round trip) and the macOS gate. They also pin the existing dense plan
contract so reviewers can see the supported range: affine Q4 and Q5 at GS64
get an A8 plan, Q6 and Q8 and N values that do not tile (Qwen3.8's N=48
in_proj_a / in_proj_b) do not. The English hint (web and macOS default string)
now names the Flash-Next routed expert Gate+Up scope; other locales keep their
existing, still accurate text.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@DT-HJ
DT-HJ force-pushed the feat/qwen4-exp-routed-a8-r2 branch from f55fc2f to bb7973d Compare October 6, 2026 13:19
@DT-HJ
DT-HJ marked this pull request as ready for review October 6, 2026 13:59
@DT-HJ

DT-HJ commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor Author

I also tested routing the expert Down projection (down_proj) through A8 as a follow-up to this PR.

On the same M5 Max setup, this gives another ~1.9–2.2% end-to-end prefill throughput over #4320 at 16K–128K. Incremental quality vs #4320 was ΔNLL +0.00083 nats/token (95% CI [-0.0033, +0.0049]), with no significant regression in the checks I ran.

I'm keeping it separate so this PR can stay focused. The Down path is already implemented and validated separately; once #4320 lands, I'll rebase it onto main, rerun the final checks, and open it as a follow-up PR.

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

I ran this on an M5 Max with Qwen3.8-Flash-Next-oQ4e-mtp. Compared to main with the same A8 setting, prompt processing went from 3186 to 3414 tok/s at 8K and from 2927 to 3152 tok/s at 32K, about 7% faster in every run. All 48 MoE layers used the new path, decode speed stayed the same, and the outputs looked normal.

It only kicks in when the A8 setting is turned on, so the risk stays small. Thanks for the thorough benchmarks and the before/after screenshots for both the web UI and the app; they made this easy to review. I'll follow up on main with a small cleanup to trim some of the comments and tests. LGTM, merging.

@jundot
jundot merged commit 7ab0fd9 into jundot:main Oct 7, 2026
1 check passed
jundot added a commit that referenced this pull request Oct 7, 2026
Drop the GLM moe_router_rows kernel and its warm-up now that verify rows use the one-row router, and fold the new GLM router and routed A8 tests into the existing modules.
@AureliusClaw

Copy link
Copy Markdown
Contributor

An A8-on vs A8-off quality check on Flash-Next, as a complement to the routed-only comparison above (which had dense A8 on in both arms). Here both the dense and the routed path are toggled together, against the plain A16 path.

Setup. Mac Studio M5 Ultra, 256 GB. main b75060e (includes this PR) plus our local commits: #4070's batched-QSA decode, KV buffer sizing, and decode-side scheduling. None of them changes prefill arithmetic. Native kernels built (OMLX_WITH_CUSTOM_KERNEL=1). Qwen3.8-Flash-Next oQ4e, MTP head loaded, qwen35_oq_a8_min_tokens 128.

Method. The model is loaded in-process through VLMBatchedEngine with the server's per-model settings. apply_qwen35_oq_a8_patch runs once. Each document is then fed to two caches on the same weights, call by call: one with A8 off (OMLX_OQ_A8=0 and the routed tags raised above any length), one with A8 on. Sanity check: with both caches set to A16, KL is 0.0000 and top-1 agreement is 1.0000. The control is the A16 path of an older build without native kernels (main f3585e0 + the same commits), run on the same tokens. It shows how much an ordinary build-to-build change moves these numbers.

1. Teacher-forced plain text (10 documents of 14–19K tokens, 152,061 positions, 2048-token chunks, so A8 is active on every chunk):

A8 vs A16 A16 control: older build vs this build
NLL delta (nats/token, 95% CI over documents) −0.0014 [−0.0151, +0.0128] +0.018 [+0.004, +0.034]
mean KL 0.123 0.107 (top-64 truncated)
top-1 agreement 0.881 0.884

2. Decode after an A8 prefill, the way it is served: 10 chat prompts (the same documents as system prompts, 14–20K tokens) are prefilled with A8. A16's own greedy reply (128 tokens each, 1,280 positions) is then fed one token at a time, so decode stays on A16 in both arms and only the context differs:

A8 prefill vs A16 prefill A16 control
NLL delta +0.0025 [−0.0092, +0.0146] +0.0092 [+0.0023, +0.0186]
mean KL 0.012 0.011
top-1 agreement 0.972 0.970

On this model, top-1 agreement of about 0.88 on plain text is what any numerics change produces, not something specific to A8. A8's shift is the same size as the shift between two A16 builds, and the NLL shows no regression.

One pitfall for anyone repeating this: don't score the positions inside chat-template system or user turns. In plain A16, the same document scores 2.13 nats/token as raw text but 6.1 inside <|im_start|>system. The templated figure even moves with chunk size (8.7 nats in one 3K forward vs 6.1 in 2048-token chunks), while raw text is chunk-invariant (2.134 vs 2.135). Those positions are not trained targets, so their logits are off-distribution and very sensitive to numerics. My first pass scored them and showed a spurious +0.2 nats.

The documents are a private system prompt and private notes, so I can't attach them. The script (about 150 lines, in-process, no server) is available if it would help.

zviratko added a commit to zviratko/omlx-uplift that referenced this pull request Oct 9, 2026
check_all stopped at a bare per-patch 'error' when the drift gate
failed, but a PR that merged and whose surroundings then moved (path
relocate #4359, trim commits 726b866/5028a35/5a26a09) fails the gate
IN EXACTLY that shape — 6/17 files on a base that already carries every
line. The upstreamed probe lived only on the not-drifted path, so the
one class built to be retired stayed 'applied' and 'dev upgrade' died
on materialize of the stale diff.

Fix, two parts:
- check_all: on a gate-stage failure of an 'applied' source, probe
  _pr_merged_into_base (merged_at + ancestry/content evidence) BEFORE
  reporting the error; an affirmative verdict stamps obsolete (legal
  applied->obsolete edge), False/None keep the honest error — fail-safe
  rule unchanged.
- enabled_build_patches: skip obsolete entries — an obsolete patch is
  retired, not merely off; materializing it would abort the build or
  resurrect lines upstream trimmed away. dev status/expected_tip follow
  the same view.

Tests: 2 drift-gate regression tests (merged -> obsolete;
unmerged/inconclusive -> error, state untouched) + materialize-input
excludes-obsolete test; all three proven RED on the old production
code. 852 pytest + 352 node green.

Made under human guidelines with free tokens from local oMLX inference server
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.

3 participants