ds4 icon indicating copy to clipboard operation
ds4 copied to clipboard

Add ROCm MXFP4 routed expert kernels

Open jyatesdotdev opened this issue 4 months ago • 9 comments

Summary

  • add resident ROCm MXFP4 x Q8_K kernels for routed expert gate/up and down projections
  • coalesce decode weight reads across wave32 lanes and unpack MXFP4 nibbles with register permutations
  • keep gate/up and down reductions register-resident on gfx1151
  • route two-to-four-token MXFP4 batches through the direct kernels instead of partially filled expert tiles
  • extend the independent CPU-oracle ROCm test across 1, 2, 3, 4, 5, 32, 128, and 512 tokens
  • report MXFP4 routed weights as 4-bit metadata and compile Strix Halo host objects with PIC

This is intentionally stacked on ds4f-mxfp4. It does not include SSD-selected-expert changes, MTP or distributed protocol work, or the Q8 prequant restoration already covered by #623.

Correctness

The focused head 7d63867 was built and tested independently on both Strix Halo systems, max and max2, with Radeon 8060S Graphics / gfx1151:

make -j1 strix-halo HIPCC=/opt/rocm-therock/bin/hipcc
LD_LIBRARY_PATH=/opt/rocm-therock/lib make test-mxfp4-rocm HIPCC=/opt/rocm-therock/bin/hipcc

Both full ROCm builds passed. Every synthetic gate/up, SwiGLU, and down result matched the CPU oracle with zero tolerance failures at all eight token counts. Worst observed absolute error was 2.15e-6. Counts 2 through 4 cover the new direct tiny-batch route, while count 5 verifies the transition back to expert-sorted tiles.

The optimization was also checked against the production Flash model. Baseline and optimized first-frontier logits were byte-identical across 129,280 values, including the same argmax.

Default-backend checks passed:

  • macOS build of ds4, ds4-server, ds4-bench, ds4-eval, and ds4-agent
  • ds4-eval extractor self-tests and ds4-agent tests
  • layer packing: 97/97
  • multi-GPU placement: 98/98
  • GPU argument and CLI tests
  • scalar MXFP4 dot test: 4/4

Full-model performance

These are controlled A/B measurements from the production integration tree with the same 0731 MXFP4 model, dual-host 0:21 / 22:output split, resident weights, and runtime configuration. Only the MXFP4 kernel variant or tiny-batch dispatch changed between each before and after point.

Workload Before Optimized Change
Single-token decode 11.35 tok/s 14.56 tok/s +28.3%
Two-token aggregate 11.13 tok/s 14.88 tok/s +33.7%
Four-token aggregate 17.01 tok/s 23.61 tok/s +38.8%

A live OpenAI-compatible request after deployment decoded at 14.86 tok/s. The single-token gate kernel uses 52 VGPR / 38 SGPR and the down kernel uses 32 VGPR / 24 SGPR; neither spills or uses private memory. The batched down specialization uses 32 VGPR / 27 SGPR with no spills.

The performance run uses the Q8 prequant path from #623; disabling that path remains substantially slower. This PR does not duplicate #623.

Q4_K comparison on the same PR head

To keep the causal scopes separate, the MXFP4 parent-versus-head A/B above measures this PR. The following compares the Q4_K and MXFP4 routed-expert format paths using the same exact build from head 7d63867.

A tensor-level audit of the two 0731 artifacts found identical tensor names and shapes. All 1,199 non-routed tensor payloads were byte-identical; the remaining 129 tensors were the routed-expert weights encoded as Q4_K or MXFP4. All 58 common metadata records were also byte-identical; Q4_K carries four additional imatrix-provenance records.

Metric Q4_K MXFP4 MXFP4 vs Q4_K
GGUF size 153.33 GiB 145.26 GiB -5.26%
Planner model allocation, coordinator / worker 79.16 / 74.69 GiB 75.03 / 70.75 GiB -4.13 / -3.94 GiB
Frozen strict sanity checks 23/24 23/24 same pass set
4K prefill 72.11 tok/s 75.19 tok/s +4.3%
4K steady decode 7.80 tok/s 8.17 tok/s +4.7%
First generated token 128.403 ms 122.529 ms -4.6%

Performance values are medians of three alternating runs per format with a fixed 4K prefill and 256-token decode, warm resident weights loaded from local SSD, fresh processes and format-specific KV state, the same dual-host 0:21 / 22:output split, and MTP disabled. Startup time is excluded.

A single paired 32K control reproduced the same direction and magnitude: MXFP4 improved prefill by 4.3%, steady decode by 4.7%, and first-token latency by 4.5%. Because this was one pair rather than three alternating pairs, it is treated only as a corroborating long-context check.

These absolute performance values are not directly comparable to the production-integration figures above: this section uses the exact PR-head build and a different fixed-token benchmark shape. It compares format paths and does not attribute the Q4_K-to-MXFP4 difference to this PR.

The 24-case suite is a targeted regression check, not evidence that either format is generally higher quality or that the formats are equivalent. Both passed the same 23 cases, and neither produced a repetition failure.

jyatesdotdev avatar Aug 02 '26 18:08 jyatesdotdev

I have two strix halos and wanted to run the MXFP4 variant, so spent a decent amount of time working with Codex (Sol 5.6) to get this working. I have more unrelated changes for getting MTP working across the systems and I'd like to see how difficult it would be to enable RDMA over thunderbolt (though that later part involves way more than just this repository). Let me know if you'd like any changes for this PR!

jyatesdotdev avatar Aug 02 '26 18:08 jyatesdotdev

Also note the current numbers are from iommu=pt, I'm testing now with it off, which should produce better numbers. I'm going to be daily driving this on my own hardware for a while, so I'll report back if there are any quality issues. I'm using pi for my harness.

jyatesdotdev avatar Aug 02 '26 20:08 jyatesdotdev

Follow-up to my earlier IOMMU note: amd_iommu=off produced a modest, repeatable speedup.

These are optimized deployment results, not standalone #656 throughput. The tested build combines the resident ROCm MXFP4 routed-expert kernels from this PR with the restored Q8 prequant decode path from #623. No #623 code is included in this PR.

The A/B held the binaries, local-NVMe GGUF, Fedora kernel 7.1.5-101.fc43, model split, and benchmark flags fixed across the reboot. The only configuration change was iommu=pt versus amd_iommu=off; both retained the same 126,976 MiB GTT and page settings.

  • two Radeon 8060S / gfx1151 systems
  • layers 0:21 / 22:output
  • 32-bit distributed activations
  • 4096-token local/distributed prefill chunks, window 3
  • 128 greedy decode tokens at 2K, 8K, and 32K
  • one warm-up followed by three measured runs per configuration
  • table reports medians
Context iommu=pt prefill / decode amd_iommu=off prefill / decode Prefill / decode delta
2K 67.70 / 10.67 tok/s 69.07 / 10.95 tok/s +2.0% / +2.6%
8K 84.08 / 10.15 tok/s 88.40 / 10.47 tok/s +5.1% / +3.2%
32K 114.88 / 9.58 tok/s 120.99 / 9.93 tok/s +5.3% / +3.7%

All 18 dumped frontier-logit files were byte-identical at each matching context across every repetition and both boot modes, so this affected performance rather than model output.

On these systems, amd_iommu=off disables the NPU/SVA path. The result points to a roughly 3% platform-level decode gain and up to 5% longer-prefill gain; it does not indicate a change in the MXFP4 kernel itself.

jyatesdotdev avatar Aug 02 '26 20:08 jyatesdotdev

Follow-up on commit 7d63867, which contains the focused MXFP4 optimization:

  • coalesces MXFP4 weight reads across wave32 lanes and performs nibble unpacking with register permutations;
  • keeps gate/up, SwiGLU, and down reductions register-resident on gfx1151;
  • routes 2–4 token batches through direct kernels instead of partially filled expert-sorted tiles;
  • introduces no register spills or private-memory use.

The CPU-oracle test now covers 1, 2, 3, 4, 5, 32, 128, and 512 tokens. All cases passed, with worst observed absolute error of 2.15e-6; production first-frontier logits were byte-identical across 129,280 values.

Controlled parent/head results were:

  • single-token decode: 11.35 → 14.56 tok/s (+28.3%);
  • two-token aggregate: 11.13 → 14.88 tok/s (+33.7%);
  • four-token aggregate: 17.01 → 23.61 tok/s (+38.8%).

The Q4_K and IOMMU measurements in the PR are additional format/platform context and are not attributed to this commit.

jyatesdotdev avatar Aug 03 '26 01:08 jyatesdotdev

@antirez any chance for a review or comment? Curious to know what you think and if I should spend some more time improving this! Thanks!

jyatesdotdev avatar Aug 03 '26 18:08 jyatesdotdev

@kyuz0 tagging you as well since you've done a lot of work in this area, would appreciate a look at this!

jyatesdotdev avatar Aug 05 '26 23:08 jyatesdotdev

Thank you! I'll take a look this weekend, this is great! In general, I would like to see if we can push performance a bit more, there ought to be some space!

kyuz0 avatar Aug 06 '26 21:08 kyuz0

I agree! I was able to get some level of RDMA working via a thunderbolt 5 (GPU-accessible zero-copy NHI messaging, one level below true GPU-to-GPU RDMA, which eliminated most transport copying), but the serial model split had almost no transport latency left to recover, and direct GTT kernel output was slightly slower, so I didn't get much improvement in TPS there. I'm still working on kernel optimizations, so hopefully I'll find some more room!

jyatesdotdev avatar Aug 07 '26 00:08 jyatesdotdev

Update after splitting the follow-up work into separate review scopes:

  • #656 remains the focused MXFP4 routed-expert PR. Its public head is still rocm-mxfp4-pr at 7d63867; the performance and correctness claims in this PR remain attributable only to that MXFP4 work.
  • The Q/KV launch fusion is now separate PR #730. rocm-qkv-kv-rope-fusion is one focused commit (c0cc54d) directly atop ds4f-mxfp4. It has no source dependency on #656 and applies to both Q4_K and MXFP4 DeepSeek V4 models.
  • The descriptor-framed v3/NHI work remains an integration branch only. rocm-mxfp4-experts at b6c6edb contains the broader experimental transport stack and is not part of #656 or #730.

For reference, the Q/KV fusion in #730 removes one ROCm launch per decoded layer. A controlled full-model TCP-v3 A/B across the two Strix Halo hosts measured:

  • server decode throughput: 14.57487 -> 14.60320 tok/s (+0.1944%)
  • combined GPU stream time per token: -0.2175% (throughput-equivalent +0.2180%)
  • sampled QKV segment: -1.3762%
  • all 40 responses / 3,200 completion tokens had the same normalized response SHA-256; the strict differential suite was bit-exact, including YaRN and fallback cases

This keeps the Q/KV result and the experimental NHI work out of the performance attribution and review scope for #656. Further MXFP4 kernel experiments will remain focused on the #656 path.

jyatesdotdev avatar Aug 07 '26 01:08 jyatesdotdev

@antirez not sure if you'd had a chance to look through this yet or do any testing, but I'm currently working through another round with Fable this time to see if I can increase the speed. It seems to think it's possible to get up to 40ish TPS with parallel mixed experts so that each GPU is running in parallel rather than serially, which joined with my NHI work in another project (https://github.com/jyatesdotdev/strix-rdma), might be possible?

jyatesdotdev avatar Aug 09 '26 19:08 jyatesdotdev

@antirez not sure if you'd had a chance to look through this yet or do any testing, but I'm currently working through another round with Fable this time to see if I can increase the speed. It seems to think it's possible to get up to 40ish TPS with parallel mixed experts so that each GPU is running in parallel rather than serially, which joined with my NHI work in another project (https://github.com/jyatesdotdev/strix-rdma), might be possible?

I'm not antirez, but I want to look at this and fully test it, we can get it merged. I haven't had a chance as I planned this weekend as there is quite a lot going on, but please can you keep working on optimising performance?

Is this work only affecting MXFP4, or is the performance work also affecting the other quants?

kyuz0 avatar Aug 10 '26 17:08 kyuz0

@antirez not sure if you'd had a chance to look through this yet or do any testing, but I'm currently working through another round with Fable this time to see if I can increase the speed. It seems to think it's possible to get up to 40ish TPS with parallel mixed experts so that each GPU is running in parallel rather than serially, which joined with my NHI work in another project (https://github.com/jyatesdotdev/strix-rdma), might be possible?

I'm not antirez, but I want to look at this and fully test it, we can get it merged. I haven't had a chance as I planned this weekend as there is quite a lot going on, but please can you keep working on optimising performance?

Is this work only affecting MXFP4, or is the performance work also affecting the other quants?

@kyuz0 I'm sorry, got you mixed up! No worries, and yup I'm going to keep trying to improve performance. I was able to nearly double prefill at least with the latest commits (I'll publish some benchmarks). Decode is proving to be more difficult to improve, and the best I've gotten so far is 14 tokens/s (and MTP doesn't seem to bring any gains, if anything it decreases decode).

I'm also limited by only using thunderbolt, because I'm using dual framework desktops, and I'm not willing to strap an addon card to the chassis for real RDMA. I'm not sure if proper RDMA is even possible with just thunderbolt, though I've gotten NHI to work, it's not real GPU-to-GPU.

I've been trying to limit this PR to just MXFP4, though without touching the code other quants use, I might have hit a limit with how far I can go. I'll publish a bunch of details on what I've tried so far a bit later.

This PR https://github.com/antirez/ds4/pull/730 does touch more than just MXFP4, though the increase I got there is really minimal.

jyatesdotdev avatar Aug 10 '26 19:08 jyatesdotdev

Here is a snapshot for the resource usage on a test run I did: https://snapshots.raintank.io/dashboard/snapshot/OZOcNCdSiBXxbd9OA3DWxcD9ft9pfdIr?from=2026-08-15T21:28:11.955Z&to=2026-08-15T22:28:11.955Z&timezone=browser&refresh=10s

Note the prefill is tiny because the prompt was tiny.

Better test for prefil, nearly 200 tok/s prefill.

https://snapshots.raintank.io/dashboard/snapshot/ezRVtKFlnPK0scfdXrgd6e1S8XTIRdSB

I'm running a loop to see if I can improve prefill even more, but if not, I'll just monitor this PR for @kyuz0 and @antirez, or comments from anyone else. Just let me know if anything needs changing or if you'd like me to run more tests and/or gather data.

Also if anyone is interested in the models I've been using for this; a mix of Fable, Sol 5.6, and Kimi K3.

Also, here is a log of the work if anyone is interested https://jyates.dev/records/ds4-strix-halo-optimization.

jyatesdotdev avatar Aug 15 '26 22:08 jyatesdotdev

Just did another test.. between 260-300 tok/s prefill! Low context decode at 15 tok/s, but decays quickly to 12.6 tok/s. Seeing if I can fix that, then I'll do one more force push to this branch and keep the changes as limited as possible. I told my agent to rebase which is why you now see a bunch of commits not related to MXFP4 work in this PR now, but I'll fix that.

jyatesdotdev avatar Aug 16 '26 18:08 jyatesdotdev

QA results — ROCm MXFP4 PR (restructured branch)

Scope: upstream/ds4f-mxfp4 (80df56a) + 10 commits, MXFP4-only diff (9 source files + Makefile). Ran the QA_BEFORE_RELEASES.md sections applicable to a ROCm routed-MoE kernel PR.

  • Commit under test: branch tip (post-reword)
  • Hardware: 2x Strix Halo Framework Desktop (Radeon 8060S, gfx1151), ROCm TheRock toolchain
  • GGUF: DeepSeek-V4-Flash-MXFP4Experts-F16HC-F16Compressor-F16Indexer-Q8Attn-Q8Shared-Q8Out-chat-v2-mxfp4-0731.gguf (~79 GB)

Section 1 — build sanity

  • make clean && make strix-halo on Strix Halo: 0 warnings, 0 errors.
  • make cpu compile check: 0 warnings.
  • git diff --check: clean.
  • ./ds4 --help / --help distributed: render cleanly. (Distributed options live in the CLI at this branch vintage; ds4-server has none.)
  • Note: the branch base (ds4f-mxfp4 @ 80df56a) does not link on the TheRock toolchain without this PR — 9be8ca5 adds ROCM_HOST_CFLAGS=-fPIC ("make Strix host objects position independent for TheRock linking"). Verified by building the base tree with and without the flag.

Section 2 — core regression

make test-rocm (new target added in this PR; CUDA-specific sampling/session binaries are not part of it):

  • ds4-eval --self-test-extractors: PASS
  • ds4_agent_test: PASS
  • tests/test_layer_pack: 97/97
  • tests/test_engine_mgpu_placement: 98/98
  • tests/test_gpu_args: PASS
  • q4k-dot-test, mxfp4-dot-test: PASS (4/4)
  • tests/test_gpu_args_cli.sh: PASS=32 FAIL=12 — identical on the unmodified base (ROCm builds do not advertise --gpu-vram, --gpu-devices, --cuda-tensor-parallel; pre-existing, not a regression).
  • One pre-existing upstream warning in tests/test_q4k_dot.c (strict-aliasing), unchanged by this PR.
  • ds4_test model sections (--logprob-vectors, --local-golden-vectors): not runnable on a single Strix Halo — the release MXFP4 GGUF (~79 GB) exceeds one node's usable VRAM (~65 GiB); full residency requires the two-node topology used below.

Section 9 — ROCm kernel gate

  • make test-mxfp4-rocm: PASS, zero failures for mid and out at 1, 2, 3, 4, 5, 32, 128, 512 tokens (superset of the required 1/3/32/128/512).
  • Repeated at the production tensor shape (-DMODEL_DIM=7168 -DN_EXPERT=8): PASS.
  • Occupancy/path variants DS4_ROCM_ENABLE_MXFP4_TILE4, DS4_ROCM_ENABLE_MXFP4_ROW64, DS4_ROCM_MXFP4_DOWN_RGROUP=4: bitwise OK (memcmp against the default path's outputs — same accumulation order by construction).

End-to-end (two-node distributed, full residency)

This model only fits distributed on this hardware, which is also the production topology:

  • PR build, worker (node A, layers 22:output) + coordinator (node B, layers 0:21), --temp 0 --nothink, 200-token generation: coherent output, prefill: 27.24 t/s, generation: 8.15 t/s (CLI distributed mode, TCP transport, short context).
  • The base branch cannot run this GGUF on ROCm at all (gpu layer 0 ffn batch encode failed) — this PR is the enablement, so there is no same-hardware ROCm baseline to diff against.
  • The base CPU backend also rejects the file (unsupported gate/up expert tensor type), so a CPU golden-reference comparison is not available for this checkpoint. The synthetic CPU-oracle gate above is the bit-level evidence.
  • The §9-named q2-imatrix GGUF is not present on this host; the release MXFP4 GGUF was used instead.

SSD streaming — known pre-existing gap, out of scope

ROCm SSD streaming for Flash-family models is broken at the branch base for all routed quants, before any of these commits:

Config base @ 80df56a this PR
Q4_K-experts GGUF, --ssd-streaming fails: missing compact selected experts … full expert table is not mapped identical failure
MXFP4 GGUF, --ssd-streaming fails: rocm prefill failed runs, but output is wrong

Root cause is in the ROCm streaming machinery, not the quant kernels: main already carries the fix class via PR #623 ("ROCm: restore DeepSeek V4 Flash decode performance and Q4 SSD streaming", merged as 6841f07), which ds4f-mxfp4 does not contain. Declared out of scope for this PR; revisit after the target branch picks up main. One follow-up noted for that future work: with MXFP4 the broken cache state is computed on (garbage out) rather than erroring — worth a hard-fail guard.

Performance evidence

Measured during the campaign on the production pair (same kernels as this branch):

  • Gate/up tile kernel grid order (default-on here): 247.7 → 222 ms/call.
  • Occupancy variants (env-gated here): 10.5k-token production probe 46.7 → 44.2 s prefill (TILE4 + DOWN_RGROUP=4).
  • Decode-side structural variants (register prefetch, LDS staging, rows-per-warp) were implemented and measured neutral-to-negative (15.11 t/s baseline vs 14.94 / 11.18 / 14.43) and deliberately excluded.

Sections not applicable to this diff

Metal (4, 5), CUDA (8), GLM (6 — no GLM code touched), distributed server/KV-disk (10, 11), server APIs (12), agent TUI (13), downloads (14), DSpark (post-dates the branch base). Speed is within expected variance for the same hardware/model (§15, per numbers above).

jyatesdotdev avatar Aug 16 '26 22:08 jyatesdotdev

@antirez, @kyuz0; sorry for all the churn. This PR won't be touched again unless you request changes. I'll be opening PRs for the other performance improvements (if they still hold on main).

jyatesdotdev avatar Aug 16 '26 22:08 jyatesdotdev

Format A/B benchmark on this exact branch (two-node gfx1151 pair, Thunderbolt, coordinator layers 0:21 / worker 22:output, distributed CLI, identical ~7.5k-token prompt, temp 0, --transport auto, no MTP/speculative stack — this branch measures the kernels as shipped here):

expert format prefill decode
MXFP4 (this PR) 162.00 t/s 7.86 t/s
Q4_K (same branch, imatrix GGUF) 89.13 t/s 7.47 t/s

+82% prefill, +5% decode for the MXFP4 format on identical hardware and settings.

Context for the read-out:

  • Prefill is where the MXFP4 expert kernels (this PR) do the work: chunked expert batches are large, the format's smaller weight footprint + the exact-rows kernels' bandwidth profile compound, and the distributed pipeline keeps both hops busy.
  • Decode at this vintage is single-token and dominated by dense attention/matmul, so the expert format barely matters — the decode-side story for MXFP4 (speculative k-row spans, MTP verify batching) is deliberately not in this PR; it stacks on top separately.
  • Reminder from the QA comment: without this PR the branch cannot run the MXFP4 GGUF on ROCm at all (gpu layer 0 ffn batch encode failed), so the A/B's baseline for the format itself is "does not run" — the Q4_K column is the same-branch speed reference, not a like-for-like alternative.
  • Bitwise exactness vs the one-row reference holds at both production shapes (tests in the PR; see the QA comment for the full matrix).

jyatesdotdev avatar Aug 18 '26 03:08 jyatesdotdev

Is anyone else interested in testing this?

jyatesdotdev avatar Aug 20 '26 00:08 jyatesdotdev

Is anyone else interested in testing this?

I'd love to, I was waiting to see if you'd rebase it on main, however, since I have other patches I don't really want to port to the ds4f-mxfp4 branch.. Can I ask what the exact reason is it's on that branch? Seems like at least some MXFP4 support was merged already, right?

jessa0 avatar Aug 20 '26 04:08 jessa0

That's fair, let me see if I can do that, I'll give it a shot this weekend! At the time this seemed like the best branch to target but I'll see where main is now.

jyatesdotdev avatar Aug 20 '26 05:08 jyatesdotdev