Skip to content

hip: ROCm backend for AMD cards, running the CUDA kernels through hiprtc - #95

Merged
Vasyl-Trefilov merged 28 commits into
RustingStudio:mainfrom
hun:hip-backend
Nov 24, 2026
Merged

Vasyl-Trefilov merged 28 commits into
RustingStudio:mainfrom
hun:hip-backend

Conversation

@hun

@hun hun commented Nov 24, 2026

Copy link
Copy Markdown

--backend hip runs the same kernels as the CUDA backend on AMD cards, compiled at run time by hiprtc for the card's gfx target, so an AMD card no longer has to go through Vulkan. On the RX 9070 XT (gfx1201) with Qwen3.6-35B-A3B UD-Q4_K_XL, prefill at 8k tokens is 2652 tok/s against Vulkan's 2148-2152, because the prefill GEMM and attention run on the matrix cores (WMMA); calibrated decode is 205-219 tok/s against 163-199. Status, measurements and limits are in docs/HIP.md.

Review first: src/hip/mod.rs and src/hip/compat.h (the backend and the CUDA-to-HIP shims), the WMMA paths added to src/cuda/kernels.cu, and the last commit, which adapts the backend to main's kernel arguments after merging main. Inkling 2, Gyro and Hy4 have no HIP kernels yet and report that; --kv q4/q2 are refused on HIP.

Verified on gfx1201 with ROCm 7.2 after the merge: cargo test --release passes except spirv_is_fresh, which fails the same way on main with shaderc 2026.1 (src/vulkan is unchanged); the Qwen3.6 numbers above are from the merged build. Before the merge, greedy parity against Vulkan (tools/parity.py) and serve were checked on four local models, recorded in docs/HIP.md.

Hannes Klas added 14 commits November 24, 2026 06:18
Compiles src/cuda/kernels.cu at run time with hiprtc for the card's gfx target and launches it through
libamdhip64, both loaded by name (no ROCm headers, no hipcc, no C++ build step). Usage: --backend hip.

Device side: src/hip/compat.h is prepended to the source and supplies the CUDA intrinsics it uses
(__shfl_*_sync, __ballot_sync, __dp4a, __byte_perm, __vsub4/__vadd4, f16 conversions, __nanosleep, __trap)
from HIP, with __CUDA_ARCH__ at the pre-Volta level so the source takes its portable paths (per-lane shared
loads, plain copies, CUDA-core multiplicands). Kernels run as wave32, the assumption the source makes.
kernels.cu keeps one source for both backends; the five places that cannot be shared are behind STRATA_HIP,
so the CUDA build's preprocessed source is unchanged.

Host side: src/hip/{mod,ffi}.rs implement the same Backend trait as src/cuda, including the code-object cache,
the shared-memory ceiling (head_dim 256 prefill attention drops to a 16-key tile on RDNA's 64 KiB blocks), the
MTP and prompt paths and the expert cache.

Verified on RX 9070 XT (gfx1201, ROCm 7.2.3) with Qwen3.6-35B-A3B UD-Q4_K_XL: greedy output identical to the
Vulkan backend on three prompts, decode 159 tok/s (--mtp 2) vs 232 for Vulkan, prefill 492 vs 1458 tok/s
(matrix cores are the next step; docs/HIP.md).
gemm_q takes an AMD branch under GEMM_WMMA: D[16x16] += A * B^T through
__builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12 (the gfx11 form on RDNA3). Both operands are 16 rows of 16
halves, which is how the kernel already stages X (positions) and W (output rows) in shared memory, so the
tile loop and the epilogue keep their shape: a warp owns 32x32 outputs (2x2 tiles) in the big-tile kernel and
16x16 in the small-tile one; a lane supplies 8 halves of its own row of each operand (gfx12 splits k across the
two half-waves) and holds 8 results, column lane & 15, rows 8*(lane >> 4) + i.

Preflight on RX 9070 XT, Qwen3.6-35B-A3B UD-Q4_K_XL, pp 1024: 737 -> 1684 tok/s without MTP and 1569 with it,
against 1428 for the Vulkan backend; pp 4096: 2106 tok/s. Greedy output is bit-identical to the CUDA-core
prefill on 5 of 6 prompts, and the sixth differs at a near-tie (f16 tensor-core summation order), the same
class of difference the CUDA and Vulkan backends have.

kernels.cu keeps one source: the whole path is behind #if GEMM_WMMA, which is undefined for the CUDA build. The
preprocessed CUDA source is unchanged for GEMM_TC 0/1 x KV_Q8 0/1 x arch 700/750/800/900 (checked by diffing
clang -E output before and after). STRATA_HIP_WMMA=0 selects the CUDA-core multiplications, for A/B and as a
workaround.
…models

The step allocates nothing once the rope table exists, so the forward is captured (hipStreamBeginCapture) and
replayed: 174 -> 183 tok/s decode on Qwen3.6-35B-A3B. A rope table a capture lacks is deferred the way the CUDA
backend defers it (the kernel computes its own frequencies for that pass; the table is made after the capture
and the graph recaptured), and htod refuses to run inside a capture instead of failing deep in the driver.
STRATA_HIP_GRAPH=0 turns capture off.

Checked with --fixed-experts (deterministic placement) against the Vulkan backend: bit-identical greedy output
on Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B (dense) and Qwen3.8-27B (dense), and graph-on vs graph-off
bit-identical on three prompts. Dense prefill is 1.4x Vulkan's (705 vs 497 tok/s on the 27B), dense decode 10%
behind (memory-bandwidth bound); 35B decode is at parity with fixed placement (73.8 vs 72.3 tok/s).
htod goes through a 64 MB pinned ring for copies over 256 KB: the DMA reads one region while the host fills the
next, and a region is reused only after the event of the copy that read it completed. Smaller copies are queued
asynchronously on the stream instead of a synchronous memcpy after a full stream sync, and memset/memset(alloc)
are hipMemsetAsync on the stream -- the null-stream hipMemset could land after a copy queued for the same buffer,
which is what made the first version's upload look lost.

Graph recording is capped at 32 like the CUDA backend (step_rows keys one graph per combination of sequence
slots, each holding device memory).

calibrate --backend hip now measures chunk, MTP drafts and the short-prompt threshold and writes
strata-<model>-hip.json, which later runs read: on Qwen3.6-35B-A3B it picks chunk 4096 and --mtp 3 (prefill
2717 tok/s measured in calibration). With both backends calibrated, pp 1024 / tg 48: HIP 1577-2072 prefill and
188-222 decode, Vulkan 1344 and 195.
…not assumed)

The CUDA backend runs integer weight types as int8 mma.sync; porting that assumed NVIDIA's premises hold on
RDNA4, and they do not. Two probes, both model-free and committed under tools/hip, settle it:

- wmma_rate: v_wmma_i32_16x16x16_iu8 is only 2x v_wmma_f32_16x16x16_f16 on gfx1201 (137 vs 57 TMAC/s).
- wmma_rescale: in the kernel's inner-loop shape (2x2 tiles, four 16-deep k-steps from shared memory), int8
  without its epilogue takes 0.35x the time of f16 -- but the per-16-weight scale and min the K-quants carry
  cost a multiplication per result, and AMD's layout gives a lane 8 results in 8 different rows, so the fold
  is 8 scalar operations each. With a vector-friendly layout it is 6.6x slower than f16, with the source's
  layout 13-16x.

So GEMM_TC stays 0 on HIP: the prefill GEMM dequantizes to f16 in shared memory and runs on the f16 matrix
cores, which is what puts HIP ahead of Vulkan on prefill. docs/HIP.md records the numbers so the next person
does not repeat the port.
GET /v1/models, a non-streaming chat completion, a streaming one (SSE deltas) and a second turn that reuses the
prompt cache (prompt_tokens_details.cached_tokens = 16 of 51) all work on HIP with Qwen3.5-9B.
Benchmarks at 32k and 128k on the 35B model (pp and gen at both depths) plus a dense comparison, recorded in
docs/HIP.md. With placement equalised (--fixed-experts: same residents, no swaps) decode is at parity but
prefill loses 10% at 8k and 56% at 32k; at 128k HIP is 173 tok/s against Vulkan's 762.

Fitting the per-token cost against depth isolates it: HIP 572 -> 1389 us/token from 8k to 32k, Vulkan 516 -> 614,
so HIP's depth-dependent cost is 33 ns per position against 4 -- 8.4x -- and the same fit predicts the 128k
numbers within the spread. Only attention grows with depth, and the prefill attention is the one kernel family
still on the CUDA cores (the mma16816 emulation): the matrix-core port covered gemm_q only. Dense Qwen3.8-27B
shows the same shape (HIP ahead at 8k, behind at 32k).

Next: port attn_prefill_t to the gfx11/gfx12 WMMA the GEMM now uses.
ldsm4t's HIP branch loaded the high half of each transposed register two rows down instead of one, so the P*V
product on the CUDA cores paired key 2k with key 2k+2: every even key's V row was counted twice and every odd
one's never, while the softmax row sums still counted all of them. A long prompt's attention output was therefore
wrong on every head, silently -- HIP and Vulkan never disagreed on the token parity checks because those prompts
are shorter than the short-prompt threshold (32 tokens) and decoding runs `step`/`attn_rows`, which never reaches
attn_prefill_t. On CUDA the same line is a byte offset (`a + 2 * PQ`), which is one row for a u16 pointer; the HIP
port dropped the pointer arithmetic's unit.

Found with a new device test: `hip::tests::attn_prefill_matches_cpu` runs attn_prefill_m against a CPU reference
(q, k, v random, causal, four heads over two KV heads) at head_dim 128 and 256 and compares every element. Before
the fix it reports a max |diff| of 2.2e3 on an output whose values are ~0.05; after it, 1.2e-4 (f16 rounding of q,
k and the softmax weights). The same test pins the causal mask, the partial last query tile and both tile depths.

head_dim 256 needed its shared-memory size fixed in the same commit: the kernel takes a 16-key tile there
(FA_BK_FOR, as the CUDA build does on Turing's 64 KB blocks) while attn_prefill_m picked the depth by what fit,
which was 16 too but by a different rule; the launcher now mirrors the kernel's choice instead of guessing, so a
smaller allocation than the kernel addresses cannot come back.
attn_prefill_t's Q*K^T product was the last depth-dependent kernel family on the CUDA cores: it cost 8-11 ns per
position of prompt depth against Vulkan's 5.6, and prefill fell behind Vulkan as prompts grew (pp 32k 794 tok/s
against 1661). It now takes the same GEMM_WMMA instruction the prefill GEMM uses, one 16-query x 16-key tile per
instruction against the 16-half qs/ks rows.

The one thing the instruction does not give for free is where its results land: 8 per lane, column `lane & 15` and
rows `8*(lane>>4) + i`, while the softmax, the causal/QSA mask and the P*V step all read the m16n8k16 layout
(row g / g + 8, keys 2t / 2t + 1). So a warp writes its 16 x FA_BKL tile of f32 scores to a private staging tile
and reads back the four values each lane owns in the layout below, `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 +
2t + e]`; one __syncwarp() publishes it, since a warp only reads what it wrote itself. The staging tile
(FA_BQ x (FA_BKL + 8) floats) is added to the block's dynamic shared memory in hip::Gpu::attn_prefill_m only, so
attn_prefill_smem_bk stays shared with CUDA and Vulkan.

head_dim 256 takes 16 keys a step under STRATA_HIP (FA_BK_FOR, as the CUDA build already does on Turing's 64 KB
blocks): 32 keys with the staging tile need 78 KiB and a workgroup may use 64. At 128k depth the same build does
660 tok/s against Vulkan's 731 (it was 173 against 762), decode 48.3 against 44.2.

Measured on Qwen3.6-35B-A3B UD-Q4_K_XL, --mtp 0 --fixed-experts (same placement, same build, two runs each, one
process each):

  pp 8192   1308 / 1303 -> 2556 / 2558 tok/s   (Vulkan 2152 / 2148)
  pp 32768   794 /  776 -> 1677 / 1502 tok/s   (Vulkan 1661)

decode is unchanged (73-75 at 8k, 64-67 at 32k), and the depth slope of the per-token cost drops from 20-21 to
8-11 ns per position. HIP is now ahead of Vulkan at 8k and level at 32k; the P*V product below is the other half.

Verified three ways. `hip::tests::attn_prefill_matches_cpu` (added with the ldsm4t fix) covers this path at both
tile depths, 1.2e-4 / 1.7e-4 against a CPU reference. STRATA_HIP_WMMA=0 against this build gives bit-identical
greedy output on a 79-token prompt and on the pp 8k/32k runs, so the summation order change is below the token
decision. And greedy output is bit-identical to Vulkan on five long prose prompts (64-79 tokens, so through this
kernel) on the 35B and two on the dense 9B with --fixed-experts --mtp 0, where the pre-fix build disagreed on 2 of
2 long prompts tried. The CUDA build's preprocessed source is unchanged (clang -E over GEMM_TC{0,1} x KV_Q8{0,1} x
arch{700,750,800,900}: identical modulo blank lines and line markers).

docs/HIP.md: the long-prompt section now reports the A/B, the slopes and pp 128k (660 tok/s against Vulkan's 731,
up from 173 against 762), "Status" states what the parity check covers (bit-identical with --mtp 0; with the
calibrated drafts on, the two backends verify different batch shapes and 1 of 7 probes flips at a near-tie), and
"Next" is down to the P*V port and the side stream.
… gone

Both products of attn_prefill_t now run on the card's matrix cores. Q*K^T took the score tile two commits ago;
this takes P*V, which had become the bigger half: with the scores ported, removing the P*V step entirely was worth
pp 32k 1677 -> 2674 tok/s, i.e. 37-44% of the prefill time at that depth.

A = P comes from the half staging tile the Volta path already had (ps, unused on HIP until now): the softmax's
registers already hold adjacent key pairs of one row, so the tile is one 32-bit store a pair. B = V^T needs its
operand's 16 rows to be head dimensions with the 16 k-values being keys, which no row of the V tile is, so
strata_ld_wmma_t reads it down a column (one half a key apart) instead of through a 16-byte vector load. The
results land in AMD's layout again (rows 8*(lane>>4)+i, column lane & 15), so each 16x16 tile is staged in f32 --
in the same warp-private `st` tile the scores use, which is free by then -- and read back into the two m16n8k16 dim
tiles the rescale and the epilogue are written for. Reusing `st` is why the shared-memory request does not change.

Measured on Qwen3.6-35B-A3B UD-Q4_K_XL, --mtp 0 --fixed-experts, same placement, same build:

  pp 8192    2556 / 2558 -> 2647 / 2666 tok/s   (Vulkan 2148 / 2152)
  pp 32768   1677 / 1502 -> 2029 / 2026 tok/s   (Vulkan 1661)
  pp 131072            660 ->  872 tok/s        (Vulkan 731)

The depth slope of the per-token cost is now 4.7 ns per position over 8k -> 32k against Vulkan's 5.6 (6.3 against
7.3 over 8k -> 128k), down from 20-21 with the attention on the CUDA cores: 3.4x on prefill at depth, and HIP is
ahead of Vulkan at every depth tried. Decode is unmoved (68-73 / 64 / 48). The run-to-run spread also collapsed
from 10% to under 1% at 32k, which says the P*V instruction count was what the CPU-side expert copies used to
hide behind.

hip::tests::attn_prefill_matches_cpu grew to head_dim 128 with 130 queries (three query tiles, five key tiles) and
head_dim 256 with 70, and both are 1.5e-4 against the CPU reference (f16 rounding of q, k and the softmax weights),
so the layout staging is pinned on both products; STRATA_HIP_WMMA=0 covers the CUDA-core path with the same test.
Greedy parity with Vulkan (--fixed-experts --mtp 0) holds on 4 of 5 long prose prompts and 2 of 2 on the dense 9B;
the fifth prompt flips at a near-tie after ten tokens, where all 5 agreed with P*V left on the CUDA cores -- the
hardware sums a 16-deep dot product in another order than the emulation does. docs/HIP.md carries that, the new
numbers and the refreshed short-prompt table (pp 4096 2993 against Vulkan's 2325; dense 27B pp 1024 784 against
508).
The gated delta-rule scan behind Qwen3.6/3.8's linear-attention layers is 12% of a long-prompt prefill (the second
largest kernel after the prefill GEMM), and the obvious guess -- "it is a sequential scan with redundant loads, so
give it more parallelism or fewer loads" -- is wrong in every direction. Measured with a new probe,
tools/hip/deltanet.cpp, which times the scan alone at the 35B's shape (dk 128, nk 16, nv 32, dv 128, T 4096, 128
blocks) at 3.11 ms a layer, ~1750 cycles a token. A model-level prefill A/B cannot resolve this: two runs of the
same build differ by more than any of the variants gain.

  base (16 floats a lane, `tok * stride` in the loop)   3.11 ms  1.00x
  32 floats a lane (half the blocks, one wave on 60 CUs) 3.84 ms  0.81x
  loop address math hoisted into pointer increments      3.26 ms  0.93x
  dot-product accumulators split in two                  3.22 ms  0.96x
  every token re-reading token 0's q/k/v (L1-resident)   3.13 ms  0.99x
  no per-token expf(g) for the decay                     2.76 ms  1.12x
  no warp reductions (wrong results)                     2.33 ms  1.33x

So the kernel is latency, not bandwidth (the reads are free, with all of the redundancy), and the only parts with
headroom are the two dependent warp-reduction rounds and the per-token exp -- both properties of the sequential
recurrence, removable only by the chunked WY/UT-transform form (a small triangular inverse plus matmuls over a
chunk). That form wants f32 for the state, so it would not use the tensor cores, and 12% of prefill is the whole
prize: ~4%. Not done, deliberately, and now with the numbers to back that up instead of a hand-wave.

docs/HIP.md gains a "What is left, measured" section: the kernel-time profile of a prefill and of a decode step
(~90% of decode is the CPU expert worker's latency, not GPU), and this table. tools/hip/README.md lists the probe.
Cross-checked this backend's work against the reference engine (same card, same models, MIT) and recorded the
comparison rather than leaving it implicit:

- Strata's prompt attention has had the same two instructions (gfx11 `v_wmma_f32_16x16x16_f16_w32`, gfx12 the
  `_gfx12` form) since its 0.1.32, with the fragment layout this backend probed: `A` lane l holds
  `A[l % 16][(l / 16) * 8 + i]` on gfx12, `D[2i + l / 16][l % 16]` on gfx11. It is default on gfx12 Linux, tied to an
  int8 KV cache (q and p as FP16 hi+lo parts), and worth 7.2-7.5x their portable kernel / +31% prompt throughput at
  8.8K tokens. Ours works on an f16 KV cache and stays inside the CUDA-era m16n8k16 code by staging the scores; the
  two land in the same place, ~2x the attention and +22-35% prefill at depth.
- They did write the chunked gated delta-rule scan this backend measured and declined (`gdn_chunk.cu` FP32,
  `gdn_tc.cuh` gfx11, `gdn_wmma12.inc` gfx12), and their own numbers are the argument: recurrence 1.6x, whole prompt
  +1.4-2.1% on an RDNA3 iGPU, 0.73-0.87x (slower) on CUDA, off by default because the rounding differs.
- The int8-WMMA verdict needed a scope: it holds for GGUF K-quants dequantized on the fly. Strata gets +19.1% at 4K
  (8-8.5% at 16K/32K) from int8 matrix cores on gfx12 for prompt experts, because it repacks the weights into a
  format laid out for the fragment (A = 16 weight rows, so a lane's eight results share one token's activation
  scale). That is the class of evidence that would reopen GEMM_TC here, and it costs a repack pass.
# Conflicts:
#	README.md
#	src/cuda/mod.rs
…, KV_MODE)

Adds rope_pairs and dflash2_conv; --kv q4/q2 is refused on HIP instead of running f16.
@aletheore

aletheore Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/backend.rs"]
    n1["src/cuda/mod.rs"]
    n2["lib.rs"]
    n3["cpu_worker.rs"]
    n4["src/deepseek/chat.rs"]
    n5["mat.rs"]
    n6["expert_cache.rs"]
    n7["src/gemma4/mod.rs"]
    n8["gguf.rs"]
    n9["forward.rs"]
    n10["src/glm/mod.rs"]
    n11["src/gpu_model.rs"]
    n12["prefill.rs"]
    n13["src/hy4/chat.rs"]
    n14["src/hy4/mod.rs"]
    n15["src/inkling2/chat.rs"]
    n16["device.rs"]
    n17["src/inkling2/mod.rs"]
    n18["model.rs"]
    n19["ngram.rs"]
    n20["serve.rs"]
    n21["src/vulkan/mod.rs"]
    n22["preflight.rs"]
    n23["weights.rs"]
    n24["tests/backend.rs"]
    n25["tests/common/mod.rs"]
    n26["tests/gpu_model.rs"]
    n27["kernels.rs"]
    n28["kv_q8.rs"]
    n29["llama_numerics.rs"]
    n0 --> n3
    n0 --> n5
    n0 --> n6
    n0 --> n11
    n0 --> n12
    n0 --> n16
    n0 --> n18
    n0 --> n21
    n0 --> n24
    n0 --> n25
    n0 --> n26
    n0 --> n27
    n0 --> n28
    n0 --> n29
    n1 --> n16
    n1 --> n21
    n1 --> n22
    n1 --> n25
    n1 --> n26
    n1 --> n28
    n1 --> n29
    n2 --> n4
    n2 --> n5
    n2 --> n6
    n2 --> n7
    n2 --> n8
    n2 --> n9
    n2 --> n10
    n2 --> n11
    n2 --> n12
    n2 --> n13
    n2 --> n14
    n2 --> n15
    n2 --> n17
    n2 --> n18
    n2 --> n19
    n2 --> n20
    n2 --> n22
    n2 --> n23
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 changed
    class n2 changed
    class n3 dependent
    class n4 dependent
    class n5 dependent
    class n6 dependent
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
    class n14 dependent
    class n15 dependent
    class n16 dependent
    class n17 dependent
    class n18 dependent
    class n19 dependent
    class n20 dependent
    class n21 dependent
    class n22 dependent
    class n23 dependent
    class n24 dependent
    class n25 dependent
    class n26 dependent
    class n27 dependent
    class n28 dependent
    class n29 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • README.md · modified · +4/-1
  • THANKS.md · modified · +5/-0
  • docs/HIP.md · added · +207/-0
  • docs/USAGE.md · modified · +2/-1
  • src/backend.rs · modified · +28/-4 · +3 functions · 14 other dependents
  • src/cuda/kernels.cu · modified · +161/-7
  • src/cuda/mod.rs · modified · +13/-13 · 7 other dependents
  • src/hip/compat.h · +159/-0 · new file, 14 symbols
  • src/hip/ffi.rs · +373/-0 · new file, 23 symbols
  • src/hip/mod.rs · +1152/-0 · new file, 111 symbols
  • src/lib.rs · modified · +1/-0 · 18 other dependents
  • src/main.rs · modified · +4/-3
  • tools/hip/README.md · added · +22/-0
  • tools/hip/deltanet.cpp · +246/-0 · new file, 17 symbols
  • tools/hip/wmma_rate.cpp · +42/-0 · new file, 4 symbols
  • tools/hip/wmma_rescale.cpp · +166/-0 · new file, 6 symbols

Aggregate deltas

  • Modules: +6
  • Dependency graph edges: +7
  • Commits: 28

Comment thread src/hip/compat.h Resolved
Comment thread src/cuda/kernels.cu Resolved
Comment thread src/hip/ffi.rs Resolved
Comment thread src/hip/ffi.rs Resolved
Comment thread src/hip/compat.h Resolved
Comment thread src/cuda/kernels.cu Resolved
Comment thread src/hip/ffi.rs Resolved
Comment thread src/cuda/kernels.cu Resolved
Comment thread src/hip/ffi.rs Resolved
Comment thread src/hip/compat.h Resolved
@aletheore

aletheore Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This pull request adds a ROCm/HIP backend that runs the existing CUDA kernels through hiprtc, and it adds a test checking that argmax_rows breaks ties at the first index. It also makes calibrate validate the requested devices before opening the model file. The people affected are users with AMD GPUs who want to run the project on ROCm, and anyone running calibration who would otherwise wait for a GGUF load before hitting a bad --device value.

Merge confidence Review effort Merge risk
2 / 5 1 / 5 Medium
Area Files Lines
src 1 +1 −0
src/hip 1 +24 −0

1 finding(s) posted as inline review comment(s). 13 earlier finding(s) from previous pushes still open.

# Severity Category Where
1 🔵 Low Maintainability main.rs:2095 Device validation added only to calibrate, not to the other commands that take --device. A bad --device…
- 🟠 High Correctness compat.h:67 Earlier finding, still open
- 🟠 High Correctness kernels.cu:3224 Earlier finding, still open
- 🟠 High Correctness ffi.rs:186 Earlier finding, still open
- 🟡 Medium Correctness ffi.rs:190 Earlier finding, still open
- 🟡 Medium Correctness compat.h:60 Earlier finding, still open
- 🟡 Medium Correctness kernels.cu:1206 Earlier finding, still open
- 🟡 Medium Correctness ffi.rs:290 Earlier finding, still open
- 🔵 Low Correctness kernels.cu:3325 Earlier finding, still open
- 🔵 Low Performance kernels.cu:3114 Earlier finding, still open
- 🔵 Low Maintainability mod.rs:983 Earlier finding, still open
- 🔵 Low Maintainability mod.rs:942 Earlier finding, still open
- 🟠 High Correctness main.rs:2102 Earlier finding, still open
- 🔵 Low Maintainability mod.rs:925 Earlier finding, still open
Review details

Reviewed 2 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 1 of 2 proposed finding(s).

Fix all with your agent
File: src/main.rs
Line: 2095
Symbol: calibrate
Issue: Device validation added only to calibrate, not to the other commands that take --device. A bad --device passed to another subcommand that also reads the GGUF before validating devices still fails only after the expensive load. The new early check is not shared through a common entry point, so it can drift between commands. Move the check into the shared device-parsing path if one exists.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Blast radius: 51 other file(s) depend on what this PR changes (2 directly, 49 indirectly)

Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.

  • src/hip/mod.rs is imported by src/backend.rs, src/lib.rs

Indirectly affected: examples/gguf_dump.rs, src/chat.rs, src/config.rs, src/cpu_moe.rs, src/cpu_worker.rs, src/cuda/mod.rs (+43 more)

The graph is large; this list is capped and not exhaustive.

Hannes Klas added 4 commits November 24, 2026 07:28
Rtc::get returns the reasons like Hip::open does; it returned None with no reason.
RDNA3 interleaves the D rows (2i + lane/16), RDNA4 keeps them in blocks (8*(lane/16) + i);
the epilogues assumed the gfx12 layout. gfx11 numerics are not checked on a card; a test compiles the gfx11 branch.
… scan it in bounds

The 1472-byte buffer was ROCm 7's struct size, and the gfx scan could slice past its end.
…e warps, prefill matrix cores)

moe_prefetch on HIP is one #if around the body instead of a loop that breaks at once.
Comment thread src/cuda/kernels.cu Resolved
Comment thread src/cuda/kernels.cu Resolved
Hannes Klas added 2 commits November 24, 2026 13:29
act & !SAME_X let BATCHED (8) reach the kernel, which ran it as an add to y; the activation is act & 3, as on Vulkan.
Comment thread src/hip/mod.rs
let got: Vec<f32> = g.get(&gy, 0, n * rows).unwrap();
// A batch step's flag picks no other kernel here, so it gives the same bits (it reached the kernel as an add,
// which y filled with ones shows).
g.put(&vec![1f32; n * rows], &gy, 0).unwrap();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability

The test comment says BATCHED reaches the kernel as an add, but act & 3 masks it to 0, which is an overwrite, so the ones-prefill check proves nothing about the flag. A later change makes the flag bit reach the kernel again. Readers trust the comment that the ones-prefill would reveal it, but with act 0 the ones are simply overwritten, so the test gives a false sense of coverage for the flag path.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 983
Issue: The test comment says BATCHED reaches the kernel as an add, but `act & 3` masks it to 0, which is an overwrite, so the ones-prefill check proves nothing about the flag. A later change makes the flag bit reach the kernel again. Readers trust the comment that the ones-prefill would reveal it, but with act 0 the ones are simply overwritten, so the test gives a false sense of coverage for the flag path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The mask is real: act & 3 turns BATCHED (8) into a store, so the ones are overwritten. But that is the point of the check. If the flag ever reached the kernel as act 8, the kernel would take the add branch (act == 0 ? v : act == 1 ? ... : yr + v), the result would be 1 + v, and the bit comparison would fail. The ones make a leak visible. I have reworded the comment at src/hip/mod.rs:982 to say this. No behaviour change.

The host strips the flag with act & 3, so the ones-prefill is overwritten.
A leaked flag would reach the kernel as act 8 and fail the bit comparison.
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Hi, ty for the PR, a ROCm backend is a great thing to have. I have no AMD card with ROCm here, so I could only read the code, nothing was run. Two things must be fixed before merge:

In src/hip/mod.rs line 209 the argmax buffer is allocated as 64 x AMAX_PARTS bytes, but CUDA allocates that many pairs of i32 (8 bytes each). The check at line 663 compares with bytes too. So argmax with more than 8 rows writes outside the buffer. It needs x 8 in both places.

Line 351 does act & !SAME_X. main has a new BATCHED bit in act now, so after a rebase it must be act & 3 like in the CUDA backend.

It also conflicts with main in src/cuda/mod.rs at kernel_names (keep the doc comment of main with your pub(crate)).

Smaller things that can come later: docs/USAGE.md and the --backend help do not mention hip, the tests never open hip, and I am not sure --device 0,1 works bc hipSetDevice is called only once. Maybe just refuse a split on hip for now.

Hannes Klas added 2 commits November 24, 2026 14:59
Each int2 partial is 8 bytes; the buffer was 64 * AMAX_PARTS bytes and the check counted rows, not bytes.
A test runs argmax on 64 rows against a CPU argmax and opens the backend through backend::open.
hip runs one device per process, so a split would put every layer on the first card.
The --backend help and docs/USAGE.md name hip.
Comment thread src/hip/mod.rs Outdated
let g: &dyn Backend = &gpu;
let (rows, n) = (64usize, 1000usize);
let mut st = 5u32;
let x: Vec<f32> = (0..rows * n).map(|_| { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 8) as f32 }).collect();

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of e4baa037e792.


🔵 Low · Maintainability · 1 of 3

argmax test expects first-index tie-breaking on random floats, so an equal maximum can make it fail intermittently The inputs are random u32-derived floats in a 2^24 range with 1000 values per row. In some rows the maximum is shared by two indices, and the GPU reduction may return the other index than the strict '>' reference, so assert_eq! fails on some runs but not others.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 924
Issue: argmax test expects first-index tie-breaking on random floats, so an equal maximum can make it fail intermittently The inputs are random u32-derived floats in a 2^24 range with 1000 values per row. In some rows the maximum is shared by two indices, and the GPU reduction may return the other index than the strict '>' reference, so assert_eq! fails on some runs but not others.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 48e35b1: each row is now a permutation of 0..n, so its maximum is unique and the test no longer depends on the tie rule. The old random rows passed only because the seed is fixed.

Comment thread src/hip/mod.rs

/// `--backend hip` reaches this backend through `backend::open`, the path the CLI takes.
#[test]
fn opens_through_backend_open() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 2 of 3

opens_through_backend_open passes silently when no HIP device is present On a machine without a HIP device the test prints a skip message and returns, so CI reports it as passed even though the backend::open path was never exercised.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 942
Issue: opens_through_backend_open passes silently when no HIP device is present On a machine without a HIP device the test prints a skip message and returns, so CI reports it as passed even though the backend::open path was never exercised.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

/dismiss The other HIP tests (add_kernel_round_trips, norm_gate, the GEMM and attention checks) also print a skip and return when no device is present, and this test follows that rule. Without a device every HIP test is skipped, which is intended.

Comment thread src/main.rs Outdated
set_kv_env(&self.kv); // read by Gpu::new and Vk::new
let open = || self.device.iter().map(|&d| backend::open(self.backend.as_deref(), d)).collect::<anyhow::Result<Vec<_>>>();
let open = || {
backend::check_devices(self.backend.as_deref(), &self.device)?;

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of e4baa037e792.


🔵 Low · Maintainability · 3 of 3

the hip device-list check is repeated at each call site instead of living in the open path Any future caller of backend::open over a device list must remember to call check_devices first. Forgetting it in a new path silently runs a split on the first HIP card, the bug this check exists to prevent.

Prompt for your AI agent
File: src/main.rs
Line: 398
Symbol: runner
Issue: the hip device-list check is repeated at each call site instead of living in the open path Any future caller of backend::open over a device list must remember to call check_devices first. Forgetting it in a new path silently runs a split on the first HIP card, the bug this check exists to prevent.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in e4baa03: backend::open_all(kind, devices) runs check_devices and then opens each device. serve and calibrate both call it, so there is one check and no call site to forget.

Hannes Klas added 2 commits November 24, 2026 15:06
Each row is a permutation of 0..n, so the strict-greater reference needs no tie rule.
The old random rows passed only because the seed is fixed.
serve and calibrate opened a list with their own check; a new caller could skip it and split a hip run.
calibrate now fails when it opens its devices, after the model is loaded, not before.
Comment thread src/main.rs
@@ -2100,7 +2100,7 @@ fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kin
anyhow::ensure!(n_pf >= 512, "--ctx too small to calibrate");
let pf = prose(&tok, n_pf)?;
let load = |chunk: usize, split: Option<&[f64]>| -> anyhow::Result<GpuModel> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 1 of 2

calibrate() now validates the device list only inside the load closure, so a bad --device is reported after the GGUF is opened and re-checked on every load call. A user runs calibrate with an invalid --device. Before this change the error came before Gguf::open. Now Gguf::open runs first, and check_devices runs again on each load invocation (once per chunk), so the error arrives later and the validation is repeated.

Prompt for your AI agent
File: src/main.rs
Line: 2102
Symbol: calibrate
Issue: calibrate() now validates the device list only inside the load closure, so a bad --device is reported after the GGUF is opened and re-checked on every load call. A user runs calibrate with an invalid --device. Before this change the error came before Gguf::open. Now Gguf::open runs first, and check_devices runs again on each load invocation (once per chunk), so the error arrives later and the validation is repeated.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in aed841f: calibrate checks its --device list before it opens the GGUF, so a bad device fails at once. open_all still checks when the devices open.

Comment thread src/hip/mod.rs
let (rows, n) = (64usize, 1000usize);
// Each row is a permutation of 0..n, so its maximum is unique and the reference needs no tie rule.
let x: Vec<f32> = (0..rows * n).map(|k| { let (r, i) = (k / n, k % n); ((i * 7919 + r * 31) % n) as f32 }).collect();
let want: Vec<i32> = (0..rows).map(|r| {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 2 of 2

The new test input is a set of permutations, so each row has only one distinct value ordering and the argmax tie and random-value paths are no longer exercised. A regression in argmax handling of repeated or arbitrary-valued inputs passes this test, because every row is a permutation and never contains ties.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 925
Symbol: argmax_rows_takes_64_rows
Issue: The new test input is a set of permutations, so each row has only one distinct value ordering and the argmax tie and random-value paths are no longer exercised. A regression in argmax handling of repeated or arbitrary-valued inputs passes this test, because every row is a permutation and never contains ties.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in af3a8fc: the permutation test stays for the unique-maximum case, and a second test runs argmax_rows on values 0..16 so most rows tie. The CPU reference takes the first index on ties, and the test asserts that some row really has a tie.

@hun

hun commented Nov 24, 2026

Copy link
Copy Markdown
Author

Thanks for the careful read. Both blocking points are fixed and pushed, in 57299c0 and 6b58bac, with two follow-ups in 48e35b1 and e4baa03.

  • Argmax buffer: the HIP buffer was sized in bytes but counted in rows. Each partial is an int2, so it is now 64 * AMAX_PARTS * 8 bytes, and the check is rows * AMAX_PARTS * 8 <= len. A test runs argmax_rows on 64 rows against a CPU argmax. It passes on the RX 9070 XT. I haven't run it against the old code, so I can't say it failed there.
  • act & 3: this branch already masks with act & 3 (src/hip/mod.rs). The act & !SAME_X line you quoted isn't in the current branch, so I think it came from an earlier revision.
  • Merge with main: a git merge-tree of origin/main into this branch is clean for me, so I don't see the kernel_names conflict. If you still see one, tell me which main commit you're looking at.
  • Device split: --device with several indices is refused on --backend hip, with an error that says to use cuda or vulkan. backend::open_all runs that check and then opens the devices, and both serve and calibrate go through it.
  • Docs: --backend help and docs/USAGE.md now list hip, and the USAGE note says hip runs one device.

The full lib test suite passes (111 tests) on the card.

For scope: I have one card, an RX 9070 XT (gfx1201), and no multi-GPU setup. Everything above is tested on that card only. The device-split refusal and the open_all path are checked by unit tests and by reading the code; no multi-device run was done. The gfx11 WMMA layout is also untested on hardware, as noted in the earlier reply.

Hannes Klas added 2 commits November 24, 2026 15:15
A bad --device used to fail after the model was loaded, and the check ran again for every chunk.
It now fails before Gguf::open; open_all still checks when the devices open.
Values 0..16 give most rows a tied maximum; the CPU reference takes the first index, as the kernel does.
The permutation test keeps the unique-maximum case.
Comment thread src/main.rs
fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option<Vec<f64>>) -> anyhow::Result<()> {
backend::check_devices(kind, device)?; // before the GGUF is read: a bad --device fails here, not after the load
let g = Gguf::open(model)?;
let aux_g = open_mtp_gguf(aux)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 1 of 1

Device validation added only to calibrate, not to the other commands that take --device. A bad --device passed to another subcommand that also reads the GGUF before validating devices still fails only after the expensive load. The new early check is not shared through a common entry point, so it can drift between commands. Move the check into the shared device-parsing path if one exists.

Prompt for your AI agent
File: src/main.rs
Line: 2095
Symbol: calibrate
Issue: Device validation added only to calibrate, not to the other commands that take --device. A bad --device passed to another subcommand that also reads the GGUF before validating devices still fails only after the expensive load. The new early check is not shared through a common entry point, so it can drift between commands. Move the check into the shared device-parsing path if one exists.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

@Vasyl-Trefilov
Vasyl-Trefilov merged commit 6339050 into RustingStudio:main Nov 24, 2026
3 checks passed
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Hi, ty, I looked at the new commits. Both points are fixed, and you were right about the conflict, the merge with main is clean. It builds here and the CUDA tests still pass on my 3060, so I merged it.

I have no AMD card, so the hip path itself is tested only on your card. One small thing: the build now shows 9 dead code warnings in src/hip (unused fields and constants in ffi.rs and mod.rs). If you have time, please clean them in a small PR. Ty for the work!

Vasyl-Trefilov added a commit that referenced this pull request Nov 25, 2026
…the fields, methods, constants and library pointers that nothing read (the nine dead-code warnings of the build after #95); the staging ring keeps its pinned buffer as _pin, which frees it on drop
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.

2 participants