Repository navigation
HIP: native Zig engine for Qwen3.5 MLX affine on RDNA2 / RDNA3 - #490
Closed
BlivionIaG wants to merge 176 commits into
Closed
BlivionIaG wants to merge 176 commits into
BlivionIaG wants to merge 176 commits into
Conversation
…and tf-hip-test zig/src/hip mirrors zig/src/cuda: the entry points declared by hand from ROCm's ABI (checked on 7.14), the device, memory, streams, modules, launches, cooperative grids and graphs. zig/build/hip.zig builds each zig/kernels/hip source into one offload bundle for gfx1030, gfx1100 and gfx1151 (-Dhipcc, or -Dhsaco for prebuilt ones). Stream-less fills and device copies finish before they return, so a non-blocking stream's next kernel cannot race them. tf-hip-test passes info, smoke, graph, cooperative, image and overhead on a Radeon PRO V620 (gfx1030) and a W7800 (gfx1100); zig build test passes.
…ry a GPU family zig/kernels/hip/rocm holds the Python ROCm extensions' kernels as they are (rocm-pr 7a0ab2a). capi.hip puts their launchers behind a C ABI that reports errors instead of throwing; ops.hip adds the torch ops between them with torch's rounding and libm calls (embedding rows, casts, silu products, the attention gate, prefill RoPE, conv and DeltaNet gate, cache writes, the MoE route plan). zig/build/hip.zig builds them with the extensions' own hipcc flags into libtf_rdna2.so (gfx103x, dot2) and libtf_rdna3.so (gfx11 / gfx12, WMMA); the binary embeds both and opens its GPU's from memory. tf-hip-test library passes on a V620 and a W7800.
…against the Python engine zig/src/hip/ops.zig launches the kernel library with its shapes checked and its scratch from a per-forward arena, making the Python wrappers' choices the same way (dot2 splits, the RDNA2 decode tile's fp16 output, the cast to the activation dtype). tools/zig/qwen_rocm_dump.py dumps the Python ROCm engine's affine products and per-layer residuals as fixtures; tf-hip-test affine matches all 126 cases (bits 2 to 8, groups 32 to 128, 1 to 300 rows) bit for bit on a V620 (fp16) and a W7800 (bf16).
…rwards, bit-exact layer by layer zig/src/families/qwen35 reads a Qwen3.5 / 3.6 MLX checkpoint as the Python ROCm loader does (every tensor byte-identical on seven checkpoints, dense, MoE and MTP heads), uploads it, and runs the Python forward on the kernel library: prompt spans with the prefill formulas, lane windows with the decode kernels and per-row states for the commit, the routed experts, and the draw rule on the host. tf-qwen35-test layers runs a prompt and three greedy steps of Qwen3.5-0.8B 8-bit against tools/zig/qwen_rocm_dump.py: every layer's residual, the final rows, the logits and the tokens equal on a V620 (gfx1030) and a W7800 (gfx1100).
…on engine's engine.zig holds a loaded model on one device (library, stream, scratch, pinned ids and logits) and runs prompts and shared windows; hip_lanes.zig is the lane core's backend over it: a stream's caches each, every round's windows in one forward, each row drawn on the host at the engine's keyed position, a window kept whole unless the round trims it. tf-qwen35-test lanes runs a prompts file through the core. Every checkpoint matches the Python engine layer by layer on a V620 and a W7800 (0.8B 8-bit, 4B 3-bit, 9B 4- and 6-bit, 27B 4-bit, 35B-A3B 4-bit MoE); four prompts' 64-token replies equal its generate, greedy and sampled, alone and together. qwen_rocm_dump.py gains generate, the replies' reference.
…idates in one pass Every window width keeps a row's bits, so the backend declares 16-row windows and the core shares rounds between streams (and copies context drafts into them). The keyed draw takes its top_k + 8 candidates in one pass instead of sorting the vocabulary. Four 64-token replies of Qwen3.5-0.8B on a V620: 241 tok/s together against 126 alone, greedy and sampled, each equal to the Python engine's.
native/hip.zig opens Qwen3.5 / Qwen3.6 MLX checkpoints (qwen3_5, qwen3_5_moe) on the lane core over the HIP backend, behind the same lane host as Metal; zig build native on Linux builds tensorfold-native with it. The server's key-file checks read file metadata with statx on Linux (fstat and stat elsewhere), the one macOS-only call on its path. The family imports core's safetensors reader alone, so the server's tokenizer stays in one module. Serving Qwen3.5-0.8B 8-bit on a V620 answers chat completions at 122 tok/s.
…al one mtp.zig runs the checkpoint's MTP head as the Python drafter: the last kept final row and the token after it, normed and projected (fc_e, fc_h; an unquantized fc through an fp32 row projection), the head's gated attention over the chain's own cache, its MLP or experts, the final norm and the logits; each draft drawn with the request's sampling at its slot. The backend holds a stream's drafts for its next window, keeps the last kept final row for the head, and commits the rows a shared round's draft request names before its keep. Scratch for multi-row windows counts every linear layer's per-row states. Qwen3.5-9B 4-bit with its head: four 64-token replies equal the Python engine's serial ones, greedy and sampled, alone and together.
The lane core carries a request's history_len and shared_prefixes to its backend, and the host reports the tokens a backend reused. The HIP backend keeps a stream's caches at the cuts (the shared prefixes, the history, the prompt's end) within a byte budget, and a later prompt with a kept prefix copies them in and prefills only the rest: a resumed reply equals a fresh one and the Python engine's. memory.zig ports the Python plan: the largest window where the scratch and every lane's caches plus a kept copy fit beside the weights and the reserve; the server refuses a --context that does not fit and prints the plan. Stream caches are sized per request.
# Conflicts: # zig/src/families/qwen35/engine.zig # zig/src/families/qwen35/hip_lanes.zig
…n without host round trips Two kernels draw a round's rows on the GPU: argmax with torch's rule (a NaN wins, else the first maximum) and the top_k + 8 candidates by value then id (a monotone 16-bit key, two histogram passes, one ordered compaction), so a round reads back ids or candidate pairs instead of whole logits rows; the keyed choose stays on the host. A greedy MTP chain feeds each step's argmax to the next step's embedding on the device and reads the drafts once. Replies stay equal to the Python engine's (0.8B and 9B with its head, greedy and sampled, alone and together).
The device code builds per GPU family as hipcc --genco code objects with the library's own flags (the same device code), embedded in the binary; launches.zig and affine_launch.zig port every launcher the engine uses (the affine row, lane and GEMM tiles and their RDNA2 paths, routed experts, norms, conv, RoPE, attention's decode walk and prefill tile, the recurrence, MoE routing, every torch-op kernel) with the same grids, blocks, shared memory and arguments, symbols resolved by name when the family loads. TF_HIP_LAUNCH=library keeps the C launchers for an A/B. The byte table of the RDNA2 8-bit wide path is filled per device. Affine products, layers and replies stay equal to the Python engine on a V620 and a W7800 (0.8B, and the 35B MoE).
# Conflicts: # zig/src/families/qwen35/engine.zig # zig/src/families/qwen35/hip_lanes.zig
…engine's tp rccl.zig opens RCCL through dlopen (all-reduce, all-gather, broadcast on the engine's stream); link.zig hands rank 0's unique id to the other ranks over TCP and then carries its commands. slicing.zig cuts each rank's share of the host tensors as slicing.py does: heads and rows per rank, o, out and down by input groups returning fp32 shares, KV heads replicated past their count, experts by rank with the shared one on rank 0 and a remap, the vocabulary rows of the head. reduce.zig sums the shares as the Python ROCm engine does (one fp32 all-reduce at two ranks, the rank-order sum past two) and the residual adds the sum to its widened self, rounding once; the MoE share follows _run_share. Rank 0 runs the lane core; worker.zig mirrors its steps. At tp 2 on two V620s, 64 to 128-token replies of the 0.8B, 4B, 9B (4- and 6-bit), 27B and 35B-A3B equal the Python engine's tp 2 replies, greedy and sampled, alone and together; layer by layer equal for the 0.8B and the 35B. The slices equal slice_for_tp's bytes at tp 2, 4 and 8. Programs that start RCCL keep glibc's own signal stacks (std_options.signal_stack_size = null) so its threads start.
The lane backend keeps prompts, the MTP head and device draws, and under tensor parallelism sends every step to the other ranks (prefill, verify, each commit's keep, release, stop); worker.zig runs them on ranks above 0 over the new engine. The ranks' vocabulary slices are joined on the device for the drawer. The MTP head and kept prompts stay off under tensor parallelism for now.
A round's window forward and its logits projection are captured per shape (each window's stream and rows) on the second sighting and replayed after: the rounds' scratch repeats its addresses, the entry keeps the arena's mark and the windows' snapshots for the commit, and a stream's graphs go with its caches. The cache write reads its slots on the device (kv_write_at, the same copy), so a replay writes the round's positions. A failed capture keeps that shape eager; TF_HIP_GRAPHS=0 turns graphs off. Qwen3.5-0.8B on a W7800: the same replies with and without graphs; the host's launch time per round falls from 1.7 ms to 0.06 ms.
A round's forward and projection replay from its shape's graph; the device draw runs after the graph on the round's scratch. Stream caches carry the serial graphs key them by and a freed stream drops its graphs. Graphs stay off under tensor parallelism (its collectives run between the layers).
The prefill conv takes a thread a (row, channel) with each output's sum unchanged, and writes the new window beside the old (every row reads the old) before it replaces the cache's. The MoE route places a round's pairs in one pass with a cursor an expert instead of counting each pair's earlier ones.
…en rows at a time The route counts each segment of pairs by expert in shared memory, takes an expert's prefix over the segments and places every segment's pairs in order: the same stable plan in a few hundred steps a thread. The router's blocks stage their 8 token rows in shared memory and each wave reads its expert row once for them; every logit keeps moe_router_kernel's sum. Qwen3.6-35B-A3B, 2,048-token prompt on a V620: 1,445 tok/s (from 1,352), every layer of a 600-token prompt equal to the Python engine's.
…'s bits prefill.hip's tile takes 64 query rows a block (fa_prefill takes 16) over the same 64-key tiles: a score keeps fa_pair's four accumulators over the head dimension, staged 64 dimensions at a time, the tile's online softmax stays one row a thread, and each output's key-ordered sum and rescale are fa_prefill's. A 16-bit cache with whole 64-wide head chunks takes it (TF_FA_WIDE=0 keeps the 16-row tile). Qwen3.6-35B-A3B on a V620, 32,768 prompt tokens: 41.4 s from 49.6; every layer of a 600-token prompt still equal to the Python engine's.
…still a row a thread
…jor probabilities
…l, for accuracy against a reference
…ax in registers q is rounded to fp16 once and stays in swizzled LDS, a tile's scores never leave registers (a row's keys on 16 lanes, max and sum by shuffles), and the probabilities reach PV as fp16 key pairs. Not bit-equal to fa_prefill: accuracy is measured against the high-precision reference.
A prompt's router no longer reads each expert row per 8 rows; short rows (a head's q or k) no longer take a 256-thread block each. The norm keeps rms_kernel's sums, so its bits are the same.
affine_gemm_block replaces affine_dot2_block on both activation types, dense and routed. Its outputs are the same bits; the work around the dot2s is spread differently: - x is shared inside a quad of lanes through DPP (the FP16 dot2c takes it in the instruction on RDNA2, a v_mov a row on gfx11), so a lane reads a third of the LDS bytes of the 8 x 8 tile; - the row sums of x come from their own threads, and a group's bias term runs a stage after its scale term; - the code words and the rows of x of two stages are fetched at once, scales and biases with them, and the codes become pairs with a few bit operations; - a wave whose rows are all past the end (a routed item's few rows) does no dot2. TF_AFFINE_GEMM=old keeps affine_dot2_block in the Zig launches and the library. tf-hip-test gemm [reps] [filter] times both tiles on the projection shapes of Qwen3.6-35B-A3B, Qwen3.5-9B and Qwen3.8-27B (routed experts included) and checks each against a float64 dequant(W) . x on sampled outputs; gemm sweep runs ragged shapes of every width and group, relaunching the new tile to catch a race. V620, best of 5, TFLOPS old -> new: 35B qkv m2048 18.1 -> 26.9, o m8192 17.7 -> 27.0, routed gate_up (2k prompt) 9.1 -> 16.6, routed down 9.2 -> 15.9, 9B gate_up m2048 16.8 -> 22.1, 27B down m2048 16.6 -> 22.5. Prefill of the 35B: 2048 tokens 1404 -> 1890 tok/s, 8192 tokens 1161 -> 1480; of the 9B: 857 -> 1205 and 779 -> 1055.
This was referenced Oct 12, 2026
ashhart
pushed a commit
that referenced
this pull request
Oct 16, 2026
… and model checks The HIP branch's engine (#490) on #463's runtime and the kernel launches of #617 and #621: the lane rounds with MTP drafts, the paged attention cache and the radix prompt cache (#625), chunked prompts (#623), CUDA-graph rounds, the memory plan, and tensor parallelism over RCCL (comm/: the library, the rank link, the group). The native server takes it with `zig build native-hip -Dhip-arch=...` and the serve flags it lists (#624); `tf-qwen35-test` runs the model checks on a GPU. `zig build test` compiles both against stub kernels. The engine reads the policy (`--policy`, TF_POLICY) once and hands the kernels `Launcher.Choices`; a GPU other than the one the kernels were built for is refused with both names. round_shape.zig stays in the family: its only reader is the plan.
ashhart
pushed a commit
that referenced
this pull request
Oct 16, 2026
… and model checks The HIP branch's engine (#490) on #463's runtime and the kernel launches of #617 and #621: the lane rounds with MTP drafts, the paged attention cache and the radix prompt cache (#625), chunked prompts (#623), CUDA-graph rounds, the memory plan, and tensor parallelism over RCCL (comm/: the library, the rank link, the group). The native server takes it with `zig build native-hip -Dhip-arch=...` and the serve flags it lists (#624); `tf-qwen35-test` runs the model checks on a GPU. `zig build test` compiles both against stub kernels. The engine reads the policy (`--policy`, TF_POLICY) once and hands the kernels `Launcher.Choices`; a GPU other than the one the kernels were built for is refused with both names. round_shape.zig stays in the family: its only reader is the plan.
BlivionIaG
added a commit
to BlivionIaG/TensorFold
that referenced
this pull request
Oct 20, 2026
… and model checks The HIP branch's engine (ashhart#490) on ashhart#463's runtime and the kernel launches of ashhart#617 and ashhart#621: the lane rounds with MTP drafts, the paged attention cache and the radix prompt cache (ashhart#625), chunked prompts (ashhart#623), CUDA-graph rounds, the memory plan, and tensor parallelism over RCCL (comm/: the library, the rank link, the group). The native server takes it with `zig build native-hip -Dhip-arch=...` and the serve flags it lists (ashhart#624); `tf-qwen35-test` runs the model checks on a GPU. `zig build test` compiles both against stub kernels. The engine reads the policy (`--policy`, TF_POLICY) once and hands the kernels `Launcher.Choices`; a GPU other than the one the kernels were built for is refused with both names. round_shape.zig stays in the family: its only reader is the plan.
BlivionIaG
added a commit
to BlivionIaG/TensorFold
that referenced
this pull request
Oct 20, 2026
… and model checks The HIP branch's engine (ashhart#490) on ashhart#463's runtime and the kernel launches of ashhart#617 and ashhart#621: the lane rounds with MTP drafts, the paged attention cache and the radix prompt cache (ashhart#625), chunked prompts (ashhart#623), CUDA-graph rounds, the memory plan, and tensor parallelism over RCCL (comm/: the library, the rank link, the group). The native server takes it with `zig build native-hip -Dhip-arch=...` and the serve flags it lists (ashhart#624); `tf-qwen35-test` runs the model checks on a GPU. `zig build test` compiles both against stub kernels. The engine reads the policy (`--policy`, TF_POLICY) once and hands the kernels `Launcher.Choices`; a GPU other than the one the kernels were built for is refused with both names. round_shape.zig stays in the family: its only reader is the plan.
This was referenced Oct 20, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this changes
Adds a native HIP backend to the Zig engine:
tensorfold-nativeserves the Qwen3.5 family on AMD Radeon GPUs.prompt cache and
--tp 1/2/4/8over RCCL.Kernels are code objects embedded in the binary and launched from Zig, as on CUDA. The CUDA and Metal sources are upstream's, byte for byte.
serveflagsThe HIP engine takes upstream's flags:
--tp(now 1, 2, 4 or 8),--rank,--master,--master-port,--checkpoint-slots,--mtp-drafts(at most 3 on HIP),--mtp-confidence,--device,--prompt-cache-giband--parallel.--backendgainsrocm. Memory follows the CUDA variables:TENSORFOLD_MEMORY_RESERVE_GIB, andTENSORFOLD_HIP_MEMORY_LIMIT_GBas CUDA'sTENSORFOLD_CUDA_MEMORY_LIMIT_GB.One flag is new,
--policy key=value,...(orTF_POLICY), for the HIP engine's run choices:matrixautoon,off, orautoto follow the tuning table.graphsautoautois on at tp 1, off under tp.prefill_stepkernels,stream,gemm,fuse,gdnautoreferenceswaps in reference kernels (all, or one family), for checking.attention,launchauto,zigf32drops the 64-row attention tile;librarylaunches through C.rccl_libHow it's built
names; unknown GPUs are refused.
--policyplus the MTP and prompt-cache flags, resolved once at open, logged, and sent by rank 0 tothe other ranks.
core/quant/):detect,read, tp slices,uploadand an fp64reference. Todaymlx.ziganddense.zig; the model never names a format.template <Decoder, Act, Dot, Epilogue>. A new format adds a decoder, a new instruction adds a Dot.(op, format, path, shape) → kernelby cost from a per-GPU table, one kernel family per path at anyrow count (
check --explain-kernelsprints the choices).buffer. A speculative round is two replays: verify, then the MTP drafts.
linear-state snapshot. Under tp, rank 0 owns the tree.
core/admission.zig, now shared): measured weights, scratch sized byrunning the real forwards on a counting stream, and a startup check that held bytes equal the plan.
--parallel autoserves what fits (up to 8); a fixed
--parallel Nthat does not fit is refused. A draft window keeps recurrenceinputs, not a state copy per row, and the keep replays them: the same bits for about 2 % of the memory.
graph replay. Accuracy is measured against an fp64 CPU forward of the same checkpoint (
tools/truth/).flowchart TB subgraph Server["tensorfold-native (rank 0 serves HTTP)"] API[OpenAI / Anthropic routes] --> Host[lane host: chunked prompt fill, cancel] Host --> Core[lane core: rounds, drafts, keeps] end Core --> Backend[HIP lanes backend] Backend --> Radix[radix prompt cache<br/>pages + linear snapshots] Backend --> MTP[MTP head<br/>rank 0 only] Backend --> Fwd[forward: prefill chunk / round window] Backend -. "steps of rank 0 (prefill, verify, keep, pages, snapshots)" .-> Followers[ranks 1..N-1] Fwd --> Ops[Ops: project, attention, recurrence, moe, norms] Ops --> Reg[registry: op, format, path, shape → kernel<br/>under Caps and Policy] Reg --> CO2["gfx1030 code object<br/>fp16, dot2"] Reg --> CO3["gfx11 code object<br/>bf16, dot2 + WMMA"] Ops --> RCCL[RCCL: rank-order sums, gathers] Followers --> RCCLNot met yet:
(101 → 126) and four streams at tp 4 (218 → 268).
stream 126 against 149 tok/s. Every other rank's traffic crosses the CPU's root ports. (Before ACS-off applied to both
switches it was 694 tok/s, as with P2P off.)
graphs=on).Engine checks, one GPU (
tf-qwen35-test check, one process a model; W7800 with matrix cores on)Matrix cores off on the W7800 (0.8B 8-bit, 9B 4-bit MTP, 9B 8-bit, 27B 4-bit): the same KL and top-1 digits as on; prefill 2k 17,429 → 12,708, 2,106 → 1,312, 2,100 → 1,313, 629 → 394 tok/s; decode within 5 %.
Engine checks under tp (invariants and speed; accuracy is checked at tp 1)
Served (
tensorfold-native serve; decode:tools/bench_openai.py,tools/bench_concurrent.py, 256 tokens; prefill:serve_prefill.py, cold, median of 3)Qwen3.8-27B matrix (ddalcu MLX builds with the MTP head; served as above; prefill only without drafts)
Receipt
(be6b679). Zig 0.17.0, ROCm 7.14, Linux 7.1.7.
capped at 180 W).
tools/mlx_requant.py).27B 2-bit is
lukaskremla/Qwen3.8-27B-2bit-MLX-TextOnly.below 4, memory capped it (V620 4-bit tp 1: 2; V620 6-bit tp 1: 1; W7800 8-bit tp 1: 2, the fp32 copy of the bf16 embedding
costing 2.5 GiB) and the 4-stream column ran that many at once. V620 6-bit tp 1 has no prefill row: a 65,600-token window
does not fit one 32 GB card. W7800 4-bit tp 2 with matrix cores on is pieced together: decode from a clean rerun, prefill from the first run
(measured after a stray server on that GPU was gone); its 4-stream and alone/serial runs were cut by a host reset.
checkinvariant passes on every row; every served--alone --serialcomparison is equal(34 a configuration).
zig build teston Metal 111/111 steps (with the HIP mock-library host tests) andtest-golden; Linux host tests pass except upstream'sdirect_ioO_DIRECT test, which fails the same way on upstream main;
tf-hip-test runtimeandkernelspass on gfx1030 andgfx1100, and
checkpasses on both GPUs and at tp 2, at be6b679 too;lean_check.pyadds no problems.engine by (35B-A3B 2-bit fp64 perplexity 67.8 against 4.77 at 4-bit). vLLM was stopped before a result.
Checklist
"draft": false, a resumed prompt equals a fresh one, and concurrent equals solo.zig build testruns the HIP host tests on any host, macOS included, against a stand-in libamdhip64;
tf-hip-testandtf-qwen35-testare separate programs that need an AMD GPU.