Repository navigation
perf(qwen4): route Flash-Next expert Gate+Up prefill through A8 on M5 - #4320
Conversation
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>
7efe045 to
f55fc2f
Compare
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>
f55fc2f to
bb7973d
Compare
|
I also tested routing the expert Down projection ( 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 |
jundot
left a comment
There was a problem hiding this comment.
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.
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.
|
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. Method. The model is loaded in-process through 1. Teacher-forced plain text (10 documents of 14–19K tokens, 152,061 positions, 2048-token chunks, so A8 is active on every chunk):
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:
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 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. |
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
Summary
qwen35_oq_a8_enabledalready 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 A16gather_qmmbefore.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_enabledandqwen35_oq_a8_min_tokenssettings are reused, so there is no new setting. The admin API, the web UI and the macOS app expose them forqwen4_exponly (an exact match, notqwen4*).Approach
row_map, so top-k replication does not multiply the quantization cost.[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
qwen4_exponly, 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_tokenscan raise this floor but not lower it.qwen4_expin addition to the existingqwen3_5*/qwen3_6*/qwen3_8*prefixes. ANE prefill stays unavailable forqwen4_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=0disables 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.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.
Regression check: Qwen3.8-27B
Jundot/Qwen3.8-27B-oQ4e-mtpis 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:mainAll 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 headbb7973d9, 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 settingsqwen35_oq_a8_enabled: trueandqwen35_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 withmax_tokens=1, and PP/s isusage.prompt_tokensdivided 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=0for 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
qwen4_exp(qwen4andqwen4_exp_xare rejected), engine reload signature, web save/restore (tests/qwen_oq_a8_ui.test.cjs) and the macOS gate (ModelSettingsScreenVMTests, 25 tests).test_deepseek_v4_dsparkx5,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 forqwen4_exp.After (this PR):
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 forqwen4_exp.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 Prefillrow keeps its existing condition and stays hidden forqwen4_exp.Checklist
🤖 Generated with Claude Code