diff --git a/README.md b/README.md index 02465a2e..3b9e7f2f 100644 --- a/README.md +++ b/README.md @@ -44,8 +44,11 @@ A GPU run needs one of: under `%CUDA_PATH%\bin`); `STRATA_NVRTC` names another file. Without it the run falls back to Vulkan. - a Vulkan 1.3 driver with shaderFloat64, int8/16/64 and subgroup size 32 or a fixed 64 (tested on RTX 3060, Radeon VII and V100; Intel Arc lacks shaderFloat64). +- for `--backend hip`: a ROCm runtime with hiprtc (`libamdhip64.so`, `libhiprtc.so`), also loaded at run time; the + kernels are compiled for the card's `gfx` target on first use. Experimental — status, numbers and limits are in + [docs/HIP.md](docs/HIP.md). -`--gpu` picks CUDA when it loads, else Vulkan; `--backend` chooses. The first CUDA run compiles the kernels (~15 s) and +`--gpu` picks CUDA when it loads, else Vulkan; `--backend` chooses (`cuda`, `vulkan` or `hip`). The first CUDA run compiles the kernels (~15 s) and caches them. Every GPU tried so far is in [docs/SUPPORTED_GPUS.md](docs/SUPPORTED_GPUS.md). ## Quick start diff --git a/THANKS.md b/THANKS.md index 774f2cf7..6455110f 100644 --- a/THANKS.md +++ b/THANKS.md @@ -41,6 +41,11 @@ If you helped and your name is missing here, that is our mistake. Open an issue - [luckydevil13](https://github.com/luckydevil13): AMD benchmarks and a lot of talk about which models to support. - [ike287](https://github.com/ike287): feedback and feature requests. +## Code + +- [Niko1221](https://github.com/Niko1221/Strata): the HIP backend's device-side compatibility layer (`src/hip/compat.h`) + follows the structure and several implementations of Strata's `include/strata/hip_compat/intrinsics.hpp` (MIT). + ## Ideas - [FredWalter](https://github.com/FredWalter): asked for multi-GPU and Qwen3.8-Flash-Next (issue #1), and later diff --git a/docs/HIP.md b/docs/HIP.md new file mode 100644 index 00000000..594228cc --- /dev/null +++ b/docs/HIP.md @@ -0,0 +1,207 @@ +# HIP (ROCm) backend + +`--backend hip` runs the same `src/cuda/kernels.cu` on an AMD card through HIP, without `hipcc`, ROCm headers or a C++ +build step: the kernels are compiled at run time by hiprtc and launched through the HIP runtime, both loaded by name +(`libamdhip64.so`, `libhiprtc.so`), the way `src/cuda` loads NVRTC. `cargo build --release` is the whole build. + +**Status: experimental.** Brought up on an RX 9070 XT (gfx1201, ROCm 7.2.3). With `--fixed-experts --mtp 0` +(deterministic placement, no speculative verify) the greedy output is **bit-identical to the Vulkan backend** on the +four local models tried (Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense) for the decode +path, and on the batched prefill path 4 of 5 long prose prompts (64-79 tokens) agree token for token on the 35B +(head_dim 128), 2 of 2 on the dense 9B and 1 of 2 on the dense 27B: the fifth 35B prompt flips at a near-tie after +ten tokens, because the matrix cores sum a 16-deep dot product in a different order than Vulkan does (all 5 agree +with the P·V product left on the CUDA cores), and the 27B flips on its first token with either attention path — at +head_dim 256 it takes 16-key tiles where Vulkan goes deeper, so its softmax and P·V sum over more steps. With the +calibrated MTP drafts on (3 on this machine, 1 on Vulkan) the two backends verify different batch shapes, so 1 of +those 7 probes flips too. HIP's prefill attention is pinned to a CPU f32 reference to 2e-4 by +`hip::tests::attn_prefill_matches_cpu`. Not yet ported: the host-side pipeline details of the CUDA backend (pinned +ring staging for `htod`, side stream for `beside`). + +## What runs + +Everything the Vulkan backend runs, through the same kernels: + +| | HIP | Vulkan (same machine, same model) | +|---|---|---| +| Prefill, pp 1024 / 4096, calibrated | 1104 / 2993 tok/s | 1097 / 2325 tok/s | +| Decode, tg 48, calibrated | 209 / 219 tok/s | 199 / 163 tok/s | +| Qwen3.8-27B dense, pp 1024, prefill / decode | 784 / 39.1 tok/s | 508 / 35.3 tok/s | + +Qwen3.6-35B-A3B UD-Q4_K_XL (first rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`, one process each, +`calibrate` run for each backend (chunk 4096; HIP picks `--mtp 3`, Vulkan `--mtp 1`). Each cell is pp / the decode that +follows it, so the second value is throughput at that depth. The pp 1024 row runs first in the process, before expert +placement has settled, so it understates both backends (1577-2072 tok/s was measured for HIP there when it was not the +first row); pp 4096 is the honest short-prompt number and is 1.29x Vulkan's. Decode is within a few percent in either +direction — the spread over repeated runs is larger than the difference, because each backend finds its own expert +placement and that moves the MTP draft acceptance. A dense model's prefill is 1.5x ahead and its decode 11% ahead. + +`serve` works too, checked on Qwen3.5-9B: `GET /v1/models`, non-streaming and streaming (`stream: true`) chat +completions, and the prompt cache across turns (`prompt_tokens_details.cached_tokens` on a follow-up request). + +## Long prompts + +Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term), and the prefill +attention now runs both of its products on the card's matrix cores (below). Its per-position cost is now below +Vulkan's, which is where the depth-dependent deficit used to be. + +Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`, `--fixed-experts` (two runs where a +range is given, one process each): + +| pp | HIP | Vulkan | HIP, everything on the CUDA cores (`STRATA_HIP_WMMA=0`) | +|---|---|---|---| +| 8192 | 2647-2666 tok/s | 2148-2152 tok/s | 1303-1308 tok/s | +| 32768 | 2026-2029 tok/s | 1661 tok/s | 776-794 tok/s | +| 131072 | 872 tok/s | 731 tok/s | (not run) | +| decode at 8k / 32k / 128k | 68-73 / 64 / 48 tok/s | 71-72 / 68 / 44 tok/s | 74 / 64-65 / - | + +Fitting the per-token cost against depth gives a slope of 4.7 ns per position over 8k -> 32k (6.3 over 8k -> 128k) +for HIP against 5.6 (7.3) for Vulkan and 20-21 for HIP with the attention on the CUDA cores: **3.4x on prefill at +depth** (pp 32k 794 -> 2029 tok/s, pp 8k 1308 -> 2647, same placement in the same build), the score product worth 2x +of it (pp 32k 794 -> 1677) and the P·V product the rest (1677 -> 2029). HIP is now ahead of Vulkan at every depth +tried — 1.23x at 8k, 1.22x at 32k, 1.19x at 128k — and at parity or ahead on decode; the earlier numbers in this file +(pp 32k 720 tok/s, pp 128k 173, gen 80.8, slope 33 ns) were taken on the CUDA cores and are the ones to compare +against. `--chunk 0`-style token-by-token prefill is still not the answer, but a shorter `--ctx` and `--kv q8` both +buy expert slots back. + +Two caveats on the numbers: `--fixed-experts` only means "same residents, no re-placement during the run", so the +spread between two runs of the same build was up to 10% before the P·V port (1502 vs 1677 at 32k) — expert placement +and host page-cache state, not the kernel — and has been under 1% since (2029 vs 2026), which is itself a sign of how +much of the prefill used to wait on the CPU-side copies; and a prompt's depth cost is the fit over the two depths, +not either point. A 128k prompt costs more VRAM in +the KV cache than a 16 GB card has left over for experts, so the run above streams most of them from host memory. + +## How it works + +- `src/hip/compat.h` is prepended to `kernels.cu`: it supplies the CUDA intrinsics the source uses (`__shfl_*_sync`, + `__ballot_sync`, `__dp4a`, `__byte_perm`, `__vsub4`, `__vadd4`, `__nanosleep`, `__trap`, the f16 conversions) with + their AMD equivalents, and sets `__CUDA_ARCH__` to the pre-Volta level so the source takes its portable paths: + per-lane shared loads instead of `ldmatrix`, plain copies instead of `cp.async`, and the CUDA-core multiplicands + instead of `mma.sync`. +- The kernels compile as **wave32** (lane = `threadIdx.x & 31`), which is the default wavefront size on RDNA and the + assumption the CUDA source already makes about a warp. The backend refuses a device that reports a 64-wide wave. +- **Matrix cores**: the prefill GEMM (`gemm_q` in `kernels.cu`) 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 rows + of 16 halves, which is exactly how the kernel stages X (positions) and W (output rows) in shared memory — no + transpose, and the same tile loop and epilogue shape as the CUDA path. 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 the k dimension across the two half-waves) and holds 8 results, column `lane & 15`, rows `8*(lane>>4) + i`. + `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications: 737 -> 1684 tok/s prefill at pp 1024 on the RX 9070 + XT, and 5 of 6 prompts bit-identical between the two. +- **Matrix-core prefill attention** (`attn_prefill_t`): the same WMMA computes both products. Q·Kᵀ is one 16-query + x 16-key instruction against the 16-half `qs`/`ks` rows; P·V takes A = P from a half staging tile (the `ps` tile the + Volta path already had, unused on HIP until now, written from the softmax registers as half pairs) and B = Vᵀ read + down a column of the `vs` tile (`strata_ld_wmma_t`, one half a key apart, since that operand's rows are head + dimensions). + Both results land in AMD's layout — 8 a lane, rows `8*(lane>>4) + i`, column `lane & 15` — rather than the m16n8k16 + layout the softmax, the causal mask and the epilogue are written for, so each 16x16 result tile is staged in f32 + and read back as `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]` (scores) or `o[d][2r + e]` (P·V). One warp + staging tile serves both stages (`FA_BQ` x (`FA_BKL` + 8) floats, 6-10 KiB added to the block's dynamic shared + memory), and it is why head_dim 256 prefill takes 16 keys a step (`FA_BK_FOR`, as on Turing's 64 KB blocks): 32 + keys would need 78 KiB of a block's 64. `STRATA_HIP_WMMA=0` runs the same numerics on the CUDA cores; the + CPU-reference test covers both. +- The CUDA-core P·V path (`ldsm4t` + `mma16816`) is still there for `STRATA_HIP_WMMA=0` and for CUDA, and it is + worth knowing how it is shaped: on HIP it reads the two halves of a transposed register as *adjacent* keys, which is + what the `ldmatrix.trans` fragments mean. An emulation that read them two rows apart (every even key counted twice, + every odd one never) shipped with the first HIP commit: it moved no token on the short prompts the parity checks + used, and on the batched prefill it made every long prompt disagree with Vulkan. `hip::tests:: + attn_prefill_matches_cpu` pins it now. +- `src/cuda/kernels.cu` keeps one source for both backends: the few places that cannot be shared are behind + `#if STRATA_HIP` (f16 conversions, the per-lane fragment loads, `mma884`, the KV f16x2 math, the L2 prefetch hint), + so the CUDA build's preprocessed source is unchanged. +- The code object is cached in `$XDG_CACHE_HOME/rusting_strata/.amdgcn`, keyed by the source, the `gfx` target + and the hiprtc version. +- `calibrate --backend hip` measures chunk, MTP drafts and the short-prompt threshold on this machine and writes + `strata--hip.json`; later runs read it, as they do for the other backends. +- Large `htod`s go through a 64 MB pinned ring (the DMA reads it while the host fills the next region), so expert + streaming does not stop the CPU side; small copies are queued asynchronously on the same stream, and `memset` is + stream-ordered (the null-stream `hipMemset` could land after a copy queued for the same buffer). + +## Requirements + +- A ROCm runtime with hiprtc: `libamdhip64.so` and `libhiprtc.so` on the loader path, in `/opt/rocm/lib`, or named by + `STRATA_HIP` and `STRATA_HIPRTC`. The card must be RDNA (wave32, gfx10+); head_dim 256 prefill attention uses a + 16-key tile because a 32-key tile needs 72 KiB of shared memory and a block may use 64 KiB. +- The device's `gfx` target is read from the driver's device properties; `STRATA_HIP_ARCH=gfx1201` overrides it. + +## Switches + +- `STRATA_HIP_SYNC=1` waits after every launch, so a hardware exception names the kernel that raised it. +- `STRATA_HIP_TRACE=1` names every launch before it goes out (grid, block, shared memory). +- `STRATA_HIP_GRAPH=0` runs the forward every time instead of capturing it (capture is on by default, +5% decode). +- `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. +- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM and in both products of the prefill + attention instead of the matrix cores. + +## Why the prefill GEMM does not use int8 matrix cores + +The CUDA backend runs integer weight types as int8 `mma.sync` because NVIDIA's int8 tensor cores are 2-4x its f16 ones +and its layout puts each lane's 4 results over 2 rows and 2 columns, so the per-16-weight scale and min the K-quants +carry cost 2 multiplications a result. On RDNA4 both premises fail: + +- `v_wmma_i32_16x16x16_iu8` is only **2x** `v_wmma_f32_16x16x16_f16` (137 vs 57 TMAC/s on gfx1201, + `tools/hip/wmma_rate.cpp`). +- AMD's WMMA layout gives a lane 8 results in 8 *different rows*, so the scale of each result is different and the + rescale costs ~8 scalar operations per result — per 16-key group, not once per GEMM. + +Measured in the kernel's own inner-loop shape (`tools/hip/wmma_rescale.cpp`): int8 without its epilogue runs in 0.35x +the time of f16, with a vector-friendly rescale 6.6x *slower*, with the layout the source uses 13-16x slower. The +integer path cannot pay for itself here, so `GEMM_TC` stays 0 on HIP and the prefill GEMM dequantizes to f16 in shared +memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulkan backend. + +That verdict is about GGUF K-quants dequantized on the fly, and there is a known way out of it: **repack the weights**. +Strata runs int8 matrix cores for prompt experts on gfx12 (its `STRATA_PF_FUSED`, on by default for its own IQ3_S, +IQ3_XXS and Q2_0 packs) and measures a 4K prompt 1,612 -> 1,353 ms (+19.1%, 8-8.5% at 16K/32K), because a pack can be +laid out for the fragment (A = 16 weight rows, so a lane's eight results share one token's activation scale) instead +of the per-16-weight K-quant rescale that kills it here. Doing that in this engine would mean a repack pass and our own +pack format — a project, not a kernel — but it is the shape of the evidence that would reopen `GEMM_TC`. + +## What is left, measured + +Profiled on the same 35B prefill (`rocprofv3 --kernel-trace`, pp 4096): 54% of the kernel time is the quantized +prefill GEMM (already on the matrix cores), 12% the gated delta-rule scan `deltanet_seq`, 10% the prefill attention +(ported), and nothing else above 3%. Of a decode step's wall time, ~90% is not GPU at all — `moe_combine` spends most +of its time waiting on the CPU expert worker, which is an expert-tier question, not a kernel one. + +`deltanet_seq` is the one kernel left worth a look, and it has now been measured properly rather than guessed at +(`tools/hip/deltanet.cpp`, which times the scan alone at the 35B's shape): + +- its per-token latency (~1750 cycles) is **not** memory: a variant that re-reads token 0's q/k/v every step, so the + reads stay in L1, runs just as fast (1.00x), even though the scan as written re-reads them from 128 blocks. +- no rearrangement of the scan wins: 32 floats a lane instead of 16 (half the blocks, one wave on 60 CUs) is 0.81x, + hoisting the loop's `tok * stride` address math into pointer increments is 0.93x, splitting the dot-product + accumulators is 0.96x, combinations worse. +- the parts with headroom are the two dependent warp-reduction rounds (1.33x if both are removed, wrong results) and + the per-token `expf(g)` for the decay (1.12x). Both are properties of the *sequential* recurrence: they only go + away with the chunked WY/UT-transform form (a small triangular inverse plus a few matmuls over a chunk), which + wants f32 for the state and therefore does not get tensor cores. + +Since the whole kernel is 12% of prefill, that rewrite's ceiling is ~4% of prefill. Left alone deliberately — and +Strata, which did write it (chunked scans on the gfx11 matrix cores in `gdn_tc.cuh` and the gfx12 ones in +`gdn_wmma12.inc`, both MIT), measures exactly that: their recurrence is 1.6x faster on an RDNA3 iGPU for a **1.4-2.1%** +gain in whole-prompt time (docs/DETAILS.md), it is off by default because the rounding differs from the token-by-token +FP32 scan, and on CUDA it is 0.73-0.87x, i.e. slower. + +## Next + +1. A side stream for `beside`, so expert uploads overlap with compute in prefill (the run-to-run spread collapsing + from 10% to 1% with the faster attention says the copies now wait on the CPU less than they used to). +2. Decode on an MoE model: the expert residency policy, not a kernel. That is where the multi-x is (see the reference + numbers from Strata in the handoff). + +## Credits + +The compatibility shim follows the structure and several implementations of Strata's +`include/strata/hip_compat/intrinsics.hpp` (MIT, (c) 2025 Niko1221, https://github.com/Niko1221/Strata), which runs +CUDA-shaped kernels on the same wave32 targets. See `THANKS.md`. + +The two matrix-core ports in this backend were written independently and turned out to match work already in Strata, in +a different design: + +- **Prompt attention on the matrix cores**: their `src/kernels/cuda/qsa_prompt_attn.cu` has the same instruction for + gfx11 and gfx12 with the fragment layout noted here (`A` lane l holds `A[l % 16][(l / 16) * 8 + i]`, gfx11 + `D[2i + l / 16][l % 16]`), default on gfx12 Linux but tied to an int8 KV cache and to keeping q and p as FP16 + hi+lo parts; it is 7.2-7.5x their portable kernel and +31% prompt throughput at 8.8K tokens. This backend's version + works on an f16 KV cache and reuses the CUDA-era m16n8k16 softmax by staging the scores, at ~2x the prefill + attention and +22-35% prefill at depth. +- **A chunked gated delta-rule scan** (`gdn_chunk.cu`, `gdn_tc.cuh`, `gdn_wmma12.inc`): the rewrite this backend + measured and declined, with their own numbers agreeing with the estimate (see "What is left, measured"). diff --git a/docs/USAGE.md b/docs/USAGE.md index f22cff24..46c22b8d 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -71,6 +71,7 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def ## Flags +- `--backend NAME` GPU backend: `cuda`, `vulkan` or `hip` (AMD cards through ROCm, one device per run, see [HIP.md](HIP.md)). Without it CUDA is used when it loads, else Vulkan. - `--ctx` KV cache size in tokens (default 4096). For Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 it is the prompt plus reply limit instead, and the default is the context the model was trained on; their caches grow with the text. - `--mtp [N]` speculative decoding with the model's draft head. Greedy tokens stay the same; sampling keeps its distribution. Needs a GGUF with an MTP head (for example the Qwen3.6-35B-A3B MTP files). @@ -225,7 +226,7 @@ OpenCode and other agents use the OpenAI address. `--device 0,1` splits the layers over the cards in proportion to their free VRAM, so more experts stay resident. The cards run one after the other, so one request gets more memory, not twice the speed of one card. MTP drafting is off on -a split model. +a split model. The HIP backend runs one device, so `--device 0,1` is refused with `--backend hip`. An index is the same card on both backends. NVIDIA cards are counted as CUDA counts them (by default the fastest card first, which is not the order of `nvidia-smi`), on Vulkan too; the other Vulkan devices follow, dedicated cards before diff --git a/src/backend.rs b/src/backend.rs index d9013e61..12489b2d 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -58,12 +58,28 @@ unsafe impl Plain for u64 {} /// Device memory, recorded graphs and kernel ops. Host copies are synchronous; device work runs in queue order. /// Pointer arguments are device addresses; strides are in floats unless named otherwise. -/// The backend `kind` ("cuda" or "vulkan") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. +/// The backend `kind` ("cuda", "vulkan" or "hip") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. +/// Refuses a `--device` list with several indices on the HIP backend: `hip::Gpu` opens one device per process +/// (hipSetDevice runs once, in `Gpu::new`), so a split over two cards would run both layers on the first one. +pub fn check_devices(kind: Option<&str>, devices: &[usize]) -> anyhow::Result<()> { + if kind == Some("hip") && devices.len() > 1 { + anyhow::bail!("the hip backend runs one device: --device {} needs cuda or vulkan", devices.iter().map(|d| d.to_string()).collect::>().join(",")); + } + Ok(()) +} + +/// Opens every device of a `--device` list, after the check above. Callers open a list through this, not one device at a time. +pub fn open_all(kind: Option<&str>, devices: &[usize]) -> anyhow::Result>> { + check_devices(kind, devices)?; + devices.iter().map(|&d| open(kind, d)).collect() +} + pub fn open(kind: Option<&str>, device: usize) -> anyhow::Result> { match kind { Some("cuda") => Ok(Box::new(crate::cuda::Gpu::new(device)?)), Some("vulkan") => Ok(Box::new(crate::vulkan::Vk::new(device)?)), - Some(k) => anyhow::bail!("unknown backend {k:?} (cuda or vulkan)"), + Some("hip") => Ok(Box::new(crate::hip::Gpu::new(device)?)), + Some(k) => anyhow::bail!("unknown backend {k:?} (cuda, vulkan or hip)"), None => match crate::cuda::Gpu::new(device) { Ok(g) => Ok(Box::new(g)), Err(c) if format!("{c}") == "CUDA init" => { @@ -101,7 +117,7 @@ pub const BATCHED: i32 = 8; pub fn upload_type(ty: GgmlType) -> GgmlType { if ty == GgmlType::F16 { GgmlType::F32 } else { ty } } pub trait Backend: Send { - /// "cuda" or "vulkan". + /// "cuda", "vulkan" or "hip". fn name(&self) -> &'static str; /// The GPU's name as the driver reports it. fn device(&self) -> String; @@ -533,7 +549,15 @@ impl<'a> dyn Backend + 'a { #[cfg(test)] mod tests { - use super::device_order; + use super::{check_devices, device_order}; + + #[test] + fn hip_refuses_a_device_split_and_nothing_else() { + assert!(check_devices(Some("hip"), &[0, 1]).is_err()); + assert!(check_devices(Some("hip"), &[0]).is_ok()); + assert!(check_devices(Some("cuda"), &[0, 1]).is_ok()); + assert!(check_devices(None, &[0, 1]).is_ok()); + } /// Identifiers are letters here. Two cards of one model have one name and two identifiers, so names play no part. #[test] diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 41f1f30e..21f37af1 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6,8 +6,14 @@ typedef unsigned short u16; typedef unsigned int u32; typedef unsigned long long u64; +#if STRATA_HIP +// AMD: the ISA converts f16 in one instruction, the compiler emits it for these. +__device__ __forceinline__ float h2f(u16 h) { return (float)*(const _Float16*)&h; } +__device__ __forceinline__ u16 f2h(float f) { _Float16 x = (_Float16)f; return *(const u16*)&x; } +#else __device__ __forceinline__ float h2f(u16 h) { float f; asm("cvt.f32.f16 %0, %1;" : "=f"(f) : "h"(h)); return f; } __device__ __forceinline__ u16 f2h(float f) { u16 h; asm("cvt.rn.f16.f32 %0, %1;" : "=h"(h) : "f"(f)); return h; } +#endif __device__ __forceinline__ u32 ld16(const u8* p) { return *(const u16*)p; } // 2-aligned only (every quant field is) __device__ __forceinline__ u32 ld32(const u8* p) { return p[0] | (p[1] << 8) | (p[2] << 16) | ((u32)p[3] << 24); } __device__ __forceinline__ float ldh(const u8* p) { return h2f((u16)ld16(p)); } @@ -1022,8 +1028,12 @@ __device__ __forceinline__ void ldsm4(u32* r, const u16* p) { #pragma unroll for (int m = 0; m < 4; m++) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; +#if STRATA_HIP + r[m] = *(const u32*)(p + (m_row + row) * PQ + m_col + col); +#else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); asm("ld.shared.b32 %0, [%1];" : "=r"(r[m]) : "r"(a)); +#endif } #else unsigned a = (unsigned)__cvta_generic_to_shared(p); @@ -1040,11 +1050,16 @@ __device__ __forceinline__ void ldsm4t(u32* r, const u16* p) { #pragma unroll for (int m = 0; m < 4; m++) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; +#if STRATA_HIP + const u16* a = p + (m_row + row) * PQ + m_col + col; + r[m] = (u32)a[0] | ((u32)a[PQ] << 16); +#else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); unsigned short lo, hi; asm("ld.shared.u16 %0, [%1];" : "=h"(lo) : "r"(a)); asm("ld.shared.u16 %0, [%1];" : "=h"(hi) : "r"(a + 2 * PQ)); r[m] = (u32)lo | ((u32)hi << 16); +#endif } #else unsigned a = (unsigned)__cvta_generic_to_shared(p); @@ -1101,7 +1116,7 @@ __device__ __forceinline__ void mma16816(float* c, u32 a0, u32 a1, u32 a2, u32 a : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); #endif } -#if __CUDA_ARCH__ < 800 +#if __CUDA_ARCH__ < 800 && !STRATA_HIP // D[8,8] += A[8,4] * B[4,8] with the four independent computations of mma.m8n8k4 (Volta, SASS HMMA.884) selected // by g & 3. PTX ISA 8.5 §9.7.13.4.1: lane l = 4*g + t owns A row t + 4*(g >= 4) at k 0..3 and D elements by the // column/row formulas implemented in gemm_q's sm_70 path. mma.m16n8k16 is sm_80+, so this helper only exists for @@ -1140,6 +1155,10 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int #if __CUDA_ARCH__ < 800 && GEMM_TC // Same 32 f32 storage as acc, seen as 4 m8 tiles x 8 D registers: accv[j][i] == &acc[0][0][0][j*8+i]. float (&accv)[4][8] = reinterpret_cast(acc); +#endif +#if GEMM_WMMA + // The same 32 f32 as 4 WMMA tiles of 8 results: accw[t][i] is tile t, result i of this lane. + float (&accw)[4][8] = reinterpret_cast(acc); #endif // W step kb is decoded into registers (as halves) during step kb - 1's mma and stored after it. constexpr int WQ = 64 * SUBS / NT; @@ -1182,7 +1201,30 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int if (wm < tl.cnt) #pragma unroll for (int kk = 0; kk < BK; kk += 16) { -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // AMD matrix cores: the tile in xs (positions, rows = m) and ws (rows = n) is fed straight in as A and B + // of D[16x16] += A * B^T. A warp owns MT x NT 16x16 tiles: (32 positions, 32 rows) for the big kernel and + // one (16 positions, 16 rows) for the small-tile one, whose 8 warps cover 32 positions x 64 rows. Each lane holds 8 results of every tile. + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); + constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; + strata_hip::strata_hk wa[MT], wb[NTW]; +#pragma unroll + for (int mt = 0; mt < MT; mt++) wa[mt] = strata_hip::strata_ld_wmma(xs + (wm + mt * 16 + l16) * P + kk + w0); +#pragma unroll + for (int nt = 0; nt < NTW; nt++) wb[nt] = strata_hip::strata_ld_wmma(ws + (wn + nt * 16 + l16) * P + kk + w0); +#pragma unroll + for (int mt = 0; mt < MT; mt++) +#pragma unroll + for (int nt = 0; nt < NTW; nt++) { + float* t = accw[mt * NTW + nt]; + strata_hip::strata_f8 c, r; +#pragma unroll + for (int i = 0; i < 8; i++) c[i] = t[i]; + r = strata_hip::strata_wmma(wa[mt], wb[nt], c); +#pragma unroll + for (int i = 0; i < 8; i++) t[i] = r[i]; + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // Volta: eight m8n8k4 ops replace one m16n8k16 for the same 16-deep k step. The four computations of // each instruction are selected by c = g & 3: SM == false maps them to the four n8 tiles (m8 = j, n8 = // c, 32 f32 per lane in accv[0..3]); SM == true maps them to the four 8x8 quadrants of the 16x16 warp @@ -1222,7 +1264,28 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int __syncthreads(); if (kb + 1 < nk) stw(); } -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // D layout of the AMD WMMA: the lane keeps column lane & 15 and rows STRATA_WMMA_ROW(lane, 0..7) of each tile. + { + const int l16 = lane & 15; + constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; +#pragma unroll + for (int mt = 0; mt < MT; mt++) +#pragma unroll + for (int nt = 0; nt < NTW; nt++) { + int n = n0 + wn + nt * 16 + l16; + if (n >= rows) continue; +#pragma unroll + for (int i = 0; i < 8; i++) { + int r = wm + mt * 16 + STRATA_WMMA_ROW(lane, i); + if (r >= tl.cnt) continue; + float* yr = y + (size_t)(tl.m0 + r) * y_stride; + float v = accw[mt * NTW + nt][i]; + yr[n] = act == 0 ? v : act == 1 ? silu(yr[n]) * v : yr[n] + v; + } + } + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // m8n8k4 D layout (PTX ISA 8.5 §9.7.13.4.1): register i = 4*p4 + 2*p2 + e sits at row (t & 1) + 2*p2 + 4*hi // and column (t & 2) + 4*p4 + e of the 8x8 tile. For each fixed c, lanes {4c..4c+3} and {16+4c..19+4c} cover // that tile exactly once; the tile itself is picked by c (n8 = c) and j (m8 = j), or by c alone for SM. @@ -2615,8 +2678,18 @@ template __device__ __forceinline__ void ldkv(const u16* c, size_t off // q * d rounded once to f16 equals f2h((float)q * d). auto deq = [&](unsigned x, unsigned sel) { unsigned h = __byte_perm(x ^ 0x80808080u, 0x64646464u, sel), r; +#if STRATA_HIP + // Same two f16 lanes without : a 2-element _Float16 vector (the ISA's packed f16 sub/mul). + typedef _Float16 f16x2 __attribute__((ext_vector_type(2))); + unsigned c64 = 0x64806480u; + f16x2 hh = *(f16x2*)&h, cc = *(f16x2*)&c64, dd = *(f16x2*)&d, rr; + rr[0] = (hh[0] - cc[0]) * dd[0]; + rr[1] = (hh[1] - cc[1]) * dd[1]; + r = *(unsigned*)&rr; +#else asm("sub.rn.f16x2 %0, %1, %2;" : "=r"(h) : "r"(h), "r"(0x64806480u)); asm("mul.rn.f16x2 %0, %1, %2;" : "=r"(r) : "r"(h), "r"(d)); +#endif return r; }; if (PER % 8 == 0 && hd % 128 == 0) { // rows 8-byte aligned @@ -3246,6 +3319,10 @@ extern "C" __global__ void moe_route(const float* p, int n, int k, float extra_s // One block per expert (grid.y) and line range (grid.x). STRATA_MOE_PREFETCH=1 only; a hint, never a correctness // dependency. Volta: prefetch.global.L2 exists since sm_20. extern "C" __global__ void moe_prefetch(const int* ids, int k, const int* table, const char* base, int stride, int bytes) { +#if STRATA_HIP + // AMD has no L2 prefetch instruction to give: on HIP this hint does nothing. + (void)ids; (void)k; (void)table; (void)base; (void)stride; (void)bytes; +#else int j = blockIdx.y; if (j >= k) return; int s = table[ids[j]]; @@ -3254,6 +3331,7 @@ extern "C" __global__ void moe_prefetch(const int* ids, int k, const int* table, int lines = bytes >> 7; for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) asm volatile("prefetch.global.L2 [%0];" ::"l"(p + ((size_t)i << 7))); +#endif } // x += sum_j w[j] ye[j] + sigmoid(sg) sh + cpu. If a slot missed, wait for the CPU worker's done flag first. @@ -3314,8 +3392,9 @@ extern "C" __global__ void moe_combine_seq(float* x, const float* ye, const floa #endif #define FA_BK_DEFAULT FA_BK // Turing's 64 KB shared memory cannot hold the HD = 256 tile at 32 keys either: 16 fit (the kernel keeps the same -// 64 queries a block and four warps). -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800 +// 64 queries a block and four warps). The HIP build has the same 64 KB a workgroup, and its score staging tile comes +// on top of the qs/ks/vs/ps sizes, so it takes the same 16-key tile. +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800) || STRATA_HIP #define FA_BK_FOR(HD) ((HD) == 256 ? 16 : FA_BK_DEFAULT) #else #define FA_BK_FOR(HD) FA_BK_DEFAULT @@ -3341,6 +3420,14 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co // Volta only: warp-private P tile for the PV A fragments (see the staging in the PV step below). Appended after // `vs` so the qs/ks/vs offsets above do not move; FA_BQ * (FA_BKL + 8) halves = 5120 B. u16* ps = vs + FA_BKL * PQ; +#endif +#if GEMM_WMMA + // HIP: the P staging tile in halves (the PV A fragments, as on Volta) and, after it, the f32 tile the matrix-core + // scores are staged through before they are read in the m16n8k16 layout the softmax below is written for. Both + // sit after `vs` so the qs/ks/vs offsets do not move; `hip::Gpu::attn_prefill_m` adds the f32 tile to the block's + // dynamic shared memory (FA_BQ * (FA_BKL + 8) floats: 10 KiB at 32 keys, 6 KiB at 16). + u16* ps = vs + FA_BKL * PQ; + float* st = (float*)(ps + FA_BQ * (FA_BKL + 8)); #endif // The last query tiles see the most keys: start them first so the short ones fill the tail. int pos0 = step[0], q0 = (gridDim.x - 1 - blockIdx.x) * FA_BQ, h = blockIdx.y, kvh = h / (nh / nkv), kvd = nkv * HD; @@ -3425,7 +3512,34 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co bool skip = qm && !__any_sync(0xffffffff, (vis[0] | vis[1]) != 0); #endif float s[FA_BKL / 8][4] = {}; -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // Q K^T on the matrix cores: one 16-query x 16-key tile per instruction against the 16-half qs/ks rows, then + // staged and read back so the softmax keeps its m16n8k16 lane layout (row g / g + 8, keys 2t / 2t + 1). The + // warp writes and reads only its own 16 rows of the tile, so a warp barrier publishes it. + if (!skip) { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane), PW = FA_BKL + 8; + float* sw = st + warp * 16 * PW; + const u16* qrow = qs + (warp * 16 + l16) * PQ + w0; +#pragma unroll + for (int kg = 0; kg < FA_BKL / 16; kg++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; + const u16* krow = ks + (kg * 16 + l16) * PQ + w0; +#pragma unroll + for (int kk = 0; kk < HD; kk += 16) + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(qrow + kk), strata_hip::strata_ld_wmma(krow + kk), acc); +#pragma unroll + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * PW + kg * 16 + l16] = acc[i]; + } + __syncwarp(); +#pragma unroll + for (int ng = 0; ng < FA_BKL / 8; ng++) +#pragma unroll + for (int i = 0; i < 4; i++) + s[ng][i] = sw[(g + 8 * (i >> 1)) * PW + ng * 8 + 2 * t4 + (i & 1)]; + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // Same 16 f32 storage as s, seen as m8n8k4 D registers: s2[ng][j][4*p4 + 2*p2 + e] is S[8*j + (t & 1) + // 2*p2 + 4*hi][8*(4*ng + c) + (t & 2) + 4*p4 + e] of the 16 x FA_BKL score tile. Every lane holds the four // computations its c selects, so the warp must stay in uniform control flow (`skip` is warp-uniform). @@ -3554,7 +3668,47 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co cp_async_wait<1>(); // sm_80+: this V tile, the next K tile may still be in flight; sm_70: already copied here __syncthreads(); #endif -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // P * V on the matrix cores, the way the scores are: A = P (this warp's 16 query rows x the tile's keys, in + // halves), B = V^T (16 head dimensions x the same keys, one half a tile row apart). The lane's 8 results land + // in AMD's layout again (query rows STRATA_WMMA_ROW(lane, i), dim column lane & 15), so each 16 x 16 result tile is + // staged in f32 and read back as the two m16n8k16 dim tiles the rescale above, the epilogue below and the + // score stage all use (`st` is free again by now: it held the scores of this tile). + if (!skip) { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane), PW = FA_BKL + 8; +#pragma unroll + for (int ng = 0; ng < FA_BKL / 8; ng++) { + // P in halves, one 32-bit store a half pair (keys 2t / 2t+1 are adjacent in this lane's registers) + *(u32*)(ps + (warp * 16 + g) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][0], s[ng][1]); + *(u32*)(ps + (warp * 16 + g + 8) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][2], s[ng][3]); + } + __syncwarp(); + float* sw = st + warp * 256; +#pragma unroll + for (int dt = 0; dt < HD / 16; dt++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; +#pragma unroll + for (int kg = 0; kg < FA_BKL / 16; kg++) { + const u16* pa = ps + (warp * 16 + l16) * PW + kg * 16 + w0; + const u16* pb = vs + (kg * 16 + w0) * PQ + dt * 16 + l16; + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(pa), strata_hip::strata_ld_wmma_t(pb, PQ), acc); + } +#pragma unroll + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * 16 + l16] = acc[i]; + __syncwarp(); +#pragma unroll + for (int r = 0; r < 2; r++) +#pragma unroll + for (int e = 0; e < 2; e++) { + o[2 * dt][2 * r + e] += sw[(g + 8 * r) * 16 + 2 * t4 + e]; + o[2 * dt + 1][2 * r + e] += sw[(g + 8 * r) * 16 + 8 + 2 * t4 + e]; + } + __syncwarp(); + } + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // P -> the warp-private staging tile: the m8n8k4 A fragment of the PV product wants row t + 4*hi and four // contiguous keys per lane, which the QK^T D layout does not give for free. One 32-bit store per half pair; // the __syncwarp() publishes the tile to the mma step below (the next tile's stores follow the loop's diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 85ad4d1f..e909a561 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -13,11 +13,11 @@ use std::sync::Arc; mod nvrtc; -const QTYPES: [GgmlType; 29] = { +pub(crate) const QTYPES: [GgmlType; 29] = { use GgmlType::*; [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -const KERNELS: [&str; 54] = [ +pub(crate) const KERNELS: [&str; 54] = [ "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", "kv_store", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", @@ -85,7 +85,7 @@ const GEMMD_SLOT: usize = GEMMD_SPLIT_ROWS / 128 * 4 + 2 * 64 * GEMMD_SPLIT_ROWS /// bound (cudarc leaves `CudaGraph` without `Send` only because it holds raw pointers). struct Graph(CudaGraph); -const AMAX_PARTS: usize = 64; +pub(crate) const AMAX_PARTS: usize = 64; unsafe impl Send for Graph {} /// `--llama-numerics`: quantize activations like llama.cpp's CPU q8_K (one scale per 256) for every integer matmul, @@ -115,11 +115,11 @@ pub fn gemm_fma() -> bool { std::env::var_os("STRATA_GEMM_FMA").is_some() } /// Prefill attention query / key tile sizes in positions. `FA_BQ` is one warp's 16 query rows times the four warps /// of the 128-thread block; `FA_BK` is the K/V tile depth and must stay a multiple of 32 for the sm_70 `m8n8k4` /// and sm_80+ `m16n8k16` fragment loops. Injected into kernels.cu by `source()`, never edited there. -const FA_BQ: usize = 64; -const FA_BK: usize = 32; +pub(crate) const FA_BQ: usize = 64; +pub(crate) const FA_BK: usize = 32; /// Prefill GEMM K tile in halves (default, candidate C3 overrides it with `STRATA_GEMM_BK=32`). `GEMM_BM` lives in /// `backend.rs` because the prefill tile-list builder shares it with Vulkan. -const GEMM_BK: usize = 64; +pub(crate) const GEMM_BK: usize = 64; /// Row padding of the attention shared-memory tiles (`PQ = HD + 8`, `FA_BK + 8` in `attn_prefill_t`). const ATTN_SMEM_PAD: usize = 8; @@ -153,13 +153,13 @@ impl Tune { } /// `default` unless `v` parses to a value accepted by `valid`. -fn tuned(v: Option<&str>, default: usize, valid: impl Fn(usize) -> bool) -> usize { +pub(crate) fn tuned(v: Option<&str>, default: usize, valid: impl Fn(usize) -> bool) -> usize { v.and_then(|s| s.trim().parse::().ok()).filter(|&x| valid(x)).unwrap_or(default) } /// Rows per warp: the family override (`STRATA_RPW_MOE`/`_DENSE`) first, then `STRATA_RPW`, then the shape default. /// 1..=64 keeps a block's row loop bounded; anything else falls back one level, as `tuned` does. -fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize { +pub(crate) fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize { let ok = |v: usize| (1..=64).contains(&v); family.and_then(|s| s.trim().parse().ok()).filter(|&v| ok(v)) .or_else(|| global.and_then(|s| s.trim().parse().ok()).filter(|&v| ok(v))) @@ -168,7 +168,7 @@ fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize /// Threads per block of the integer GEMV: the family override first, then the global value, then 256. Only the /// three warp counts the kernel's row mapping can tile are accepted (4/8/16 warps per block). -fn gemv_block_from(global: Option<&str>, family: Option<&str>) -> u32 { +pub(crate) fn gemv_block_from(global: Option<&str>, family: Option<&str>) -> u32 { let ok = |v: u32| matches!(v, 128 | 256 | 512); family.and_then(|s| s.trim().parse::().ok()).filter(|&v| ok(v)) .or_else(|| global.and_then(|s| s.trim().parse::().ok()).filter(|&v| ok(v))) @@ -220,7 +220,7 @@ fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { fn attn_prefill_smem(hd: usize) -> usize { attn_prefill_smem_bk(hd, FA_BK) } /// `attn_prefill_smem` for a K/V tile depth of `bk` keys (16 on Turing at head_dim 256, else `FA_BK`). -fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { +pub(crate) fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { let pq = hd + ATTN_SMEM_PAD; 2 * (FA_BQ + 2 * bk) * pq + 2 * FA_BQ * (bk + ATTN_SMEM_PAD) } @@ -268,7 +268,7 @@ fn int8_gemm_arch(cc: (i32, i32)) -> bool { cc.0 >= 8 } /// decode GQA kernels (8 query slices per head group plus the cp.async K/V chunks at head_dim 128/256, `attn`), /// `usize::MAX` for `gemvn_*` whose request depends on the tensor shape (`xq_smem * nt`, `gemv_cfg`), and `None` /// for every kernel that never asks for more than the 48 KiB default (`attn_decode_*`, `attn_merge`, the rest). -fn dyn_shmem_need(name: &str) -> Option<(&'static str, usize)> { +pub(crate) fn dyn_shmem_need(name: &str) -> Option<(&'static str, usize)> { let family = if name.starts_with("attn_prefill") { "attn_prefill_*" } else if name.starts_with("attn_decode_gqa") { "attn_decode_gqa*" } else if name.starts_with("gemvn") { "gemvn_*" } @@ -367,7 +367,7 @@ fn smem_log(family: &str, optin: usize, stat: usize, set: Option, carveou /// The kernel names to load from the cubin: the full list on sm_80+, without the int8 GEMM (`gemmi_*`, `gemmis_*` and /// `gemmd_*`, 23 non-float types x 3 fewer names) on a device where that code is not compiled in. Pure so a CPU test can pin /// both lists (393 / 324 names). -fn kernel_names(sm80: bool) -> Vec { +pub(crate) fn kernel_names(sm80: bool) -> Vec { let int8 = move |&&t: &&GgmlType| sm80 && !t.float_x(); KERNELS.iter().map(|s| s.to_string()) .chain(QTYPES.iter().flat_map(|&t| ["dequant", "gemv", "gemvn", "moe_gemv", "gemm", "gemms"].map(|p| kname(p, t)))) @@ -452,7 +452,7 @@ macro_rules! launch { }}; } -fn kname(prefix: &str, ty: GgmlType) -> String { format!("{prefix}_{}", ty.name().to_lowercase()) } +pub(crate) fn kname(prefix: &str, ty: GgmlType) -> String { format!("{prefix}_{}", ty.name().to_lowercase()) } /// The UUID of every CUDA device in CUDA's order, the order `Gpu::new` counts in: `None` for a device the driver /// gives none for, empty when CUDA does not load. No context is created. NVIDIA's Vulkan driver reports the same 16 diff --git a/src/hip/compat.h b/src/hip/compat.h new file mode 100644 index 00000000..936e4b93 --- /dev/null +++ b/src/hip/compat.h @@ -0,0 +1,159 @@ +// Device-side compatibility layer for the HIP backend. `src/hip/mod.rs` prepends this (and the quant tables) to +// `../cuda/kernels.cu`, which the CUDA backend hands to NVRTC unchanged: `kernels.cu` is one source with an explicit +// `STRATA_HIP` branch where the two architectures cannot share code, and this header supplies everything CUDA's +// headers give it for free (warp intrinsics, packed-byte helpers, the f16 SIMD ops) from HIP. +// +// The portable intrinsic implementations are adapted from Strata's include/strata/hip_compat/intrinsics.hpp +// (MIT, (c) 2025 Niko1221); see THANKS.md. They assume the wave32 model the kernels are written for (lane = +// threadIdx.x & 31), which is the default wavefront size on RDNA (gfx10+) — the same assumption the CUDA source +// makes about a warp. +// Prepended to a concatenated source string, so a plain include guard: `#pragma once` would warn in a main file. +#ifndef STRATA_HIP_COMPAT_H +#define STRATA_HIP_COMPAT_H +#include +#include + +// kernels.cu selects its code paths by the CUDA architecture level: ldmatrix from sm_75, cp.async/m16n8k16/int8-mma +// from sm_80, m8n8k4 (mma884) from sm_70. AMD has none of those instructions, so the build takes the portable +// pre-Volta level: per-lane shared loads instead of ldmatrix, plain typed copies instead of cp.async, and the +// CUDA-core (f16 FMA) multiplicands instead of mma.sync. On gfx11 and gfx12 the prefill GEMM and attention use the +// WMMA matrix cores instead (GEMM_WMMA, below); other targets and STRATA_HIP_WMMA=0 keep the f16 FMA path. Decode is +// unaffected (it has no tensor-core path). +#ifndef __CUDA_ARCH__ +#define __CUDA_ARCH__ 700 +#endif +#define STRATA_HIP 1 +#ifndef __forceinline__ +#define __forceinline__ inline __attribute__((always_inline)) +#endif +#ifndef __align__ +#define __align__(n) __attribute__((aligned(n))) +#endif +// The wave is 32 lanes wide here; a kernel that ever runs with a 64-wide wave would corrupt its reductions. +#if defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32 +#error "the HIP backend needs wave32 (RDNA); wave64 targets are not supported" +#endif + +namespace strata_hip { + +__device__ __forceinline__ int signed_byte(unsigned word, int lane) { + unsigned v = (word >> (lane * 8)) & 0xffu; + return v < 0x80u ? (int)v : (int)v - 0x100; +} + +// CUDA's signed __dp4a: four signed byte products accumulated modulo 2^32. +__device__ __forceinline__ int dp4a(int a, int b, int c) { +#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1200__) || defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4) + return __builtin_amdgcn_sudot4(true, a, true, b, c, false); +#elif (defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__)) && __has_builtin(__builtin_amdgcn_sdot4) + return __builtin_amdgcn_sdot4(a, b, c, false); +#else + unsigned ua = (unsigned)a, ub = (unsigned)b, sum = (unsigned)c; +#pragma unroll + for (int i = 0; i < 4; ++i) sum += (unsigned)(signed_byte(ua, i) * signed_byte(ub, i)); + return (int)sum; +#endif +} + +// CUDA's __byte_perm: result byte i is byte s.nibble[i] & 7 of {y:x}. One v_perm_b32 instead of HIP's byte array. +__device__ __forceinline__ unsigned byte_perm(unsigned x, unsigned y, unsigned s) { + unsigned sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12); + return __builtin_amdgcn_perm(y, x, sel); +} + +// Packed byte arithmetic, four lanes at once (SWAR, Hacker's Delight 2-18): gfx11/gfx12 have no packed 8-bit +// add/sub, and a per-lane loop costs the Q3_K/Q6_K dots several times the instructions. +constexpr unsigned kHigh = 0x80808080u; + +__device__ __forceinline__ int vsub4(int a, int b) { + unsigned ua = (unsigned)a, ub = (unsigned)b; + return (int)(((ua | kHigh) - (ub & ~kHigh)) ^ ((ua ^ ~ub) & kHigh)); +} +__device__ __forceinline__ int vadd4(int a, int b) { + unsigned ua = (unsigned)a, ub = (unsigned)b; + return (int)(((ua & ~kHigh) + (ub & ~kHigh)) ^ ((ua ^ ub) & kHigh)); +} + +// The mask is informational here: an AMD wave either takes part in the corresponding `ds_bpermute` or does not, so a +// lane that is not in the mask still receives whatever the exchange computes (CUDA leaves it undefined). That matches +// CUDA whenever the lanes a participating lane exchanges with are participating too, which is how kernels.cu uses it +// (`quant8` shuffles inside groups of four active lanes; the rest pass 0xffffffff). +template __device__ __forceinline__ T shfl_xor_sync(unsigned, T v, int lane_mask, int width = 32) { return __shfl_xor(v, lane_mask, width); } +template __device__ __forceinline__ T shfl_down_sync(unsigned, T v, unsigned d, int width = 32) { return __shfl_down(v, d, width); } +template __device__ __forceinline__ T shfl_up_sync(unsigned, T v, unsigned d, int width = 32) { return __shfl_up(v, d, width); } +template __device__ __forceinline__ T shfl_sync(unsigned, T v, int src, int width = 32) { return __shfl(v, src, width); } +__device__ __forceinline__ unsigned ballot_sync(unsigned, int predicate) { return (unsigned)__ballot(predicate); } +__device__ __forceinline__ int any_sync(unsigned, int predicate) { return (int)(__ballot(predicate) != 0); } + +// ---- matrix cores (gfx11/gfx12 WMMA) ---- +// D[16x16] += A[16x16] * B^T[16x16]: both operands are 16 rows of 16 halves, which is exactly how the prefill GEMM +// stages X (positions) and W (output rows) in shared memory, so no transpose is needed. Each lane supplies the +// k-values of its own row of both operands and holds 8 results of column lane & 15, in rows STRATA_WMMA_ROW(lane, i). +// gfx12 splits the k dimension across the two half-waves (each lane gives 8 halves, lanes 16-31 the upper half) and +// gives lanes 16-31 rows 8..15; gfx11 takes all 16 halves from every lane (lanes 16-31 repeat lanes 0-15) and +// interleaves the rows, even ones in lanes 0-15 and odd ones in lanes 16-31 (as llama.cpp's mma.cuh has it for RDNA3). +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1152__) +#define STRATA_WMMA 1 +#define STRATA_WMMA_K 16 +#define STRATA_WMMA_ROW(lane, i) (2 * (i) + ((lane) >> 4)) +#elif defined(__gfx1200__) || defined(__gfx1201__) +#define STRATA_WMMA 1 +#define STRATA_WMMA_K 8 +#define STRATA_WMMA_ROW(lane, i) (8 * ((lane) >> 4) + (i)) +#else +#define STRATA_WMMA 0 +#define STRATA_WMMA_K 0 +#endif +// First k half the lane supplies: gfx12 lanes 16-31 give k 8..15, every lane on gfx11 gives k 0..15. +#define STRATA_WMMA_K0(lane) (((lane) >> 4) * (16 - STRATA_WMMA_K)) + +#if STRATA_WMMA +typedef _Float16 strata_hk __attribute__((ext_vector_type(STRATA_WMMA_K))); +typedef float strata_f8 __attribute__((ext_vector_type(8))); + +__device__ __forceinline__ strata_f8 strata_wmma(strata_hk a, strata_hk b, strata_f8 c) { +#if defined(__gfx1200__) || defined(__gfx1201__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +#else + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#endif +} + +/// STRATA_WMMA_K halves at `p` (16-byte aligned); lanes 16-31 read their own upper half of the same row. +__device__ __forceinline__ strata_hk strata_ld_wmma(const unsigned short* p) { + union { uint4 u[STRATA_WMMA_K / 8]; strata_hk h; } c; +#pragma unroll + for (int i = 0; i < STRATA_WMMA_K / 8; i++) c.u[i] = *(const uint4*)(p + 8 * i); + return c.h; +} + +/// The same STRATA_WMMA_K halves one tile row apart from each other: the B operand when the operand's rows are the +/// transposed side (the prefill attention's V, whose rows are head dimensions and whose k are keys). One load a have +/// instead of a 16-byte vector load. +__device__ __forceinline__ strata_hk strata_ld_wmma_t(const unsigned short* p, int stride) { + strata_hk r; +#pragma unroll + for (int i = 0; i < STRATA_WMMA_K; i++) r[i] = *(const _Float16*)(p + i * stride); + return r; +} +#endif + +} // namespace strata_hip + +#define __dp4a(a, b, c) (strata_hip::dp4a((a), (b), (c))) +#define __byte_perm(x, y, s) (strata_hip::byte_perm((x), (y), (s))) +#define __vsub4(a, b) (strata_hip::vsub4((a), (b))) +#define __vadd4(a, b) (strata_hip::vadd4((a), (b))) +#define __shfl_xor_sync(...) (strata_hip::shfl_xor_sync(__VA_ARGS__)) +#define __shfl_down_sync(...) (strata_hip::shfl_down_sync(__VA_ARGS__)) +#define __shfl_up_sync(...) (strata_hip::shfl_up_sync(__VA_ARGS__)) +#define __shfl_sync(...) (strata_hip::shfl_sync(__VA_ARGS__)) +#define __ballot_sync(m, p) (strata_hip::ballot_sync((m), (p))) +#define __any_sync(m, p) (strata_hip::any_sync((m), (p))) +// The compiled-out sm_80+ paths still mention these; no CUDA-only helper may survive into a HIP build. +#define __trap() __builtin_trap() +#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1) + +#endif // STRATA_HIP_COMPAT_H diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs new file mode 100644 index 00000000..076fc186 --- /dev/null +++ b/src/hip/ffi.rs @@ -0,0 +1,373 @@ +//! HIP runtime and hiprtc, loaded by name like `cuda/nvrtc.rs` loads NVRTC: no ROCm headers, link flags or `hipcc` +//! at build time, and no C++ build step. Every entry point the backend uses is resolved once per process. + +use anyhow::{Context, bail}; +use libloading::Library; +use std::ffi::{CStr, c_char, c_int, c_void}; +use std::path::PathBuf; +use std::sync::OnceLock; + +pub type Stream = *mut c_void; +pub type Module = *mut c_void; +pub type Func = *mut c_void; +pub type Event = *mut c_void; +pub type Graph = *mut c_void; +pub type GraphExec = *mut c_void; +pub type RtcProgram = *mut c_void; + +// hipError_t / hiprtcResult +pub const HIP_SUCCESS: c_int = 0; + +// Values the ROCm 7 headers give these enums (probe-printed; see the module docs of `hip`). +pub const MEMCPY_H2D: c_int = 1; +pub const MEMCPY_D2H: c_int = 2; +pub const MEMCPY_D2D: c_int = 3; +pub const HOST_MALLOC_PORTABLE: u32 = 1; +pub const HOST_MALLOC_MAPPED: u32 = 2; +pub const EVENT_DISABLE_TIMING: u32 = 2; +pub const STREAM_NON_BLOCKING: u32 = 1; +pub const CAPTURE_MODE_THREAD_LOCAL: c_int = 1; +pub const ATTR_MAX_DYNAMIC_SHARED: c_int = 8; +pub const ATTR_SHARED_PER_BLOCK_OPTIN: c_int = 75; +pub const ATTR_SHARED_PER_BLOCK: c_int = 74; +pub const ATTR_WARP_SIZE: c_int = 87; +pub const ATTR_INTEGRATED: c_int = 16; +pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; +pub const ATTR_MAX_THREADS_PER_BLOCK: c_int = 56; + +/// Room for `hipDeviceProp_t`, which `hipGetDeviceProperties` writes whole. ROCm 7's `hipDeviceProp_tR0600` is 1472 +/// bytes; the size is not exported and changes between versions, so the buffer leaves ample room for a larger one. +/// The architecture name is found by shape (`find_gfx`), and `STRATA_HIP_ARCH` overrides it. +const PROP_BUF: usize = 16 << 10; + +/// The first `gfxNNNN`-looking string at a 4-byte offset in `bytes` (at least 6 characters, at most 16), read only +/// within `bytes`. +fn find_gfx(bytes: &[u8]) -> Option { + for i in (0..bytes.len()).step_by(4) { + let w = &bytes[i..(i + 16).min(bytes.len())]; + if !w.starts_with(b"gfx") { continue } + let end = w.iter().position(|&b| b == 0 || !b.is_ascii_alphanumeric()).unwrap_or(w.len()); + if end < 6 { continue } + return String::from_utf8(w[..end].to_vec()).ok(); + } + None +} + +type Fn = unsafe extern "C" fn(); + +/// Library names to try, in order. `STRATA_HIP` (a path or a name) replaces the whole list. +fn candidates(vars: Option, default_suffix: &[&str]) -> Vec { + if let Some(p) = vars { return vec![p]; } + let mut v: Vec = Vec::new(); + for s in default_suffix { v.push(PathBuf::from(s)); } + // A ROCm install that is not on the loader path (`/opt/rocm` may be a symlink chain). + for root in ["/opt/rocm/lib", "/opt/rocm/core-10.1/lib", "/usr/lib/x86_64-linux-gnu", "/usr/local/lib"] { + for s in default_suffix { v.push(PathBuf::from(root).join(s)); } + } + v +} + +pub struct Hip { + pub init: unsafe extern "C" fn(c_int) -> c_int, + pub device_count: unsafe extern "C" fn(*mut c_int) -> c_int, + pub set_device: unsafe extern "C" fn(c_int) -> c_int, + pub device_name: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int, + pub device_attribute: unsafe extern "C" fn(*mut c_int, c_int, c_int) -> c_int, + pub mem_get_info: unsafe extern "C" fn(*mut usize, *mut usize) -> c_int, + pub malloc: unsafe extern "C" fn(*mut *mut c_void, usize) -> c_int, + pub free: unsafe extern "C" fn(*mut c_void) -> c_int, + pub memset: unsafe extern "C" fn(*mut c_void, c_int, usize) -> c_int, + pub memset_async: unsafe extern "C" fn(*mut c_void, c_int, usize, Stream) -> c_int, + pub memcpy: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int) -> c_int, + pub memcpy_async: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int, Stream) -> c_int, + pub stream_create: unsafe extern "C" fn(*mut Stream, u32) -> c_int, + pub stream_destroy: unsafe extern "C" fn(Stream) -> c_int, + pub stream_sync: unsafe extern "C" fn(Stream) -> c_int, + pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> c_int, + pub stream_begin_capture: unsafe extern "C" fn(Stream, c_int) -> c_int, + pub stream_end_capture: unsafe extern "C" fn(Stream, *mut Graph) -> c_int, + pub stream_is_capturing: unsafe extern "C" fn(Stream, *mut c_int) -> c_int, + pub graph_instantiate: unsafe extern "C" fn(*mut GraphExec, Graph, u64) -> c_int, + pub graph_launch: unsafe extern "C" fn(GraphExec, Stream) -> c_int, + pub graph_exec_destroy: unsafe extern "C" fn(GraphExec) -> c_int, + pub graph_destroy: unsafe extern "C" fn(Graph) -> c_int, + pub event_create: unsafe extern "C" fn(*mut Event, u32) -> c_int, + pub event_record: unsafe extern "C" fn(Event, Stream) -> c_int, + pub event_sync: unsafe extern "C" fn(Event) -> c_int, + pub event_query: unsafe extern "C" fn(Event) -> c_int, + pub event_destroy: unsafe extern "C" fn(Event) -> c_int, + pub host_malloc: unsafe extern "C" fn(*mut *mut c_void, usize, u32) -> c_int, + pub host_free: unsafe extern "C" fn(*mut c_void) -> c_int, + pub host_device_ptr: unsafe extern "C" fn(*mut *mut c_void, *mut c_void, u32) -> c_int, + pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> c_int, + pub module_unload: unsafe extern "C" fn(Module) -> c_int, + pub function: unsafe extern "C" fn(*mut Func, Module, *const c_char) -> c_int, + pub launch: unsafe extern "C" fn(Func, u32, u32, u32, u32, u32, u32, u32, Stream, *mut *mut c_void, *mut *mut c_void) -> c_int, + pub func_set_attribute: unsafe extern "C" fn(*const c_void, c_int, c_int) -> c_int, + pub error_string: unsafe extern "C" fn(c_int) -> *const c_char, + pub last_error: unsafe extern "C" fn() -> c_int, + _lib: Library, +} + +impl Hip { + /// The runtime, or an error naming what was missing. "HIP init" lets `backend::open` fall back to Vulkan. + pub fn open() -> anyhow::Result { + let want = candidates(std::env::var_os("STRATA_HIP").map(Into::into), + &["libamdhip64.so", "libamdhip64.so.7", "libamdhip64.so.6"]); + let mut tried = Vec::new(); + for path in &want { + if let Ok(lib) = unsafe { Library::new(path) } { + if let Some(h) = unsafe { Self::bind(lib) } { return Ok(h); } + tried.push(format!("{}: missing symbols", path.display())); + } else { + tried.push(format!("{}: not loadable", path.display())); + } + } + Err(anyhow::anyhow!("no HIP runtime: {}", tried.join(", "))).context("HIP init") + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } + + unsafe fn bind(lib: Library) -> Option { + macro_rules! g { ($n:literal) => { unsafe { Self::sym(&lib, $n)? } } } + Some(Hip { + init: g!("hipInit"), + device_count: g!("hipGetDeviceCount"), + set_device: g!("hipSetDevice"), + device_name: g!("hipDeviceGetName"), + device_attribute: g!("hipDeviceGetAttribute"), + mem_get_info: g!("hipMemGetInfo"), + malloc: g!("hipMalloc"), + free: g!("hipFree"), + memset: g!("hipMemset"), + memset_async: g!("hipMemsetAsync"), + memcpy: g!("hipMemcpy"), + memcpy_async: g!("hipMemcpyAsync"), + stream_create: g!("hipStreamCreateWithFlags"), + stream_destroy: g!("hipStreamDestroy"), + stream_sync: g!("hipStreamSynchronize"), + stream_wait_event: g!("hipStreamWaitEvent"), + stream_begin_capture: g!("hipStreamBeginCapture"), + stream_end_capture: g!("hipStreamEndCapture"), + stream_is_capturing: g!("hipStreamIsCapturing"), + graph_instantiate: g!("hipGraphInstantiateWithFlags"), + graph_launch: g!("hipGraphLaunch"), + graph_exec_destroy: g!("hipGraphExecDestroy"), + graph_destroy: g!("hipGraphDestroy"), + event_create: g!("hipEventCreateWithFlags"), + event_record: g!("hipEventRecord"), + event_sync: g!("hipEventSynchronize"), + event_query: g!("hipEventQuery"), + event_destroy: g!("hipEventDestroy"), + host_malloc: g!("hipHostMalloc"), + host_free: g!("hipHostFree"), + host_device_ptr: g!("hipHostGetDevicePointer"), + module_load: g!("hipModuleLoadData"), + module_unload: g!("hipModuleUnload"), + function: g!("hipModuleGetFunction"), + launch: g!("hipModuleLaunchKernel"), + func_set_attribute: g!("hipFuncSetAttribute"), + error_string: g!("hipGetErrorString"), + last_error: g!("hipGetLastError"), + _lib: lib, + }) + } + + pub fn err(&self, code: c_int) -> String { + let s = unsafe { (self.error_string)(code) }; + if s.is_null() { return format!("hip error {code}") } + unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned() + } + + pub fn check(&self, code: c_int, what: &str) -> anyhow::Result<()> { + if code == HIP_SUCCESS { return Ok(()) } + bail!("{what}: {}", self.err(code)) + } + + /// The device's `gfxNNNN` target, from `hipDeviceProp_t`'s `gcnArchName`. `STRATA_HIP_ARCH` overrides it. + /// ROCm 7 dropped the `hipDeviceAttributeArch`/`GcnArchName` attributes, so the property struct is the only + /// source; it is version-specific, hence the field-length and shape check before the value is trusted. + pub fn arch(&self, device: c_int) -> anyhow::Result { + if let Ok(a) = std::env::var("STRATA_HIP_ARCH") { return Ok(a) } + if let Some(a) = self.prop_arch(device) { return Ok(a) } + bail!("cannot read the device's gfx architecture; set STRATA_HIP_ARCH (e.g. gfx1201)") + } + + /// The device property struct is version-specific (`hipDeviceProp_t` and `hipDeviceProp_tR0600` differ, and ROCm 7 + /// resolves `hipGetDeviceProperties` to the latter), so the target name is found by shape inside the struct + /// instead of at a fixed offset: the first `gfxNNNN`-looking string, validated. + fn prop_arch(&self, device: c_int) -> Option { + // Resolved here and not in `bind`: this is the only use, and a missing symbol must not fail the backend. + let f: unsafe extern "C" fn(*mut c_void, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipGetDeviceProperties") }?; + let mut buf = vec![0u64; PROP_BUF / 8]; + let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; + if r != HIP_SUCCESS { return None } + find_gfx(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_BUF) }) + } + + pub fn device_name(&self, device: c_int) -> String { + let mut buf = [0 as c_char; 256]; + let r = unsafe { (self.device_name)(buf.as_mut_ptr(), 256, device) }; + if r != HIP_SUCCESS { return "AMD GPU".into() } + unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().into_owned() + } + + pub fn attribute(&self, attr: c_int, device: c_int) -> anyhow::Result { + let mut v = 0; + self.check(unsafe { (self.device_attribute)(&mut v, attr, device) }, "hipDeviceGetAttribute")?; + Ok(v) + } +} + +pub struct Rtc { + version: unsafe extern "C" fn(*mut c_int, *mut c_int) -> c_int, + create: unsafe extern "C" fn(*mut RtcProgram, *const c_char, *const c_char, c_int, *const *const c_char, *const *const c_char) -> c_int, + compile: unsafe extern "C" fn(RtcProgram, c_int, *const *const c_char) -> c_int, + log_size: unsafe extern "C" fn(RtcProgram, *mut usize) -> c_int, + log: unsafe extern "C" fn(RtcProgram, *mut c_char) -> c_int, + code_size: unsafe extern "C" fn(RtcProgram, *mut usize) -> c_int, + code: unsafe extern "C" fn(RtcProgram, *mut c_char) -> c_int, + destroy: unsafe extern "C" fn(*mut RtcProgram) -> c_int, + error_string: unsafe extern "C" fn(c_int) -> *const c_char, + lib_path: PathBuf, + _lib: Library, +} + +static RTC: OnceLock> = OnceLock::new(); + +impl Rtc { + /// The library, or which paths were tried and why each failed. + pub fn get() -> Result<&'static Rtc, &'static str> { RTC.get_or_init(Self::open).as_ref().map_err(|e| e.as_str()) } + + fn open() -> Result { + let want = candidates(std::env::var_os("STRATA_HIPRTC").map(Into::into), + &["libhiprtc.so", "libhiprtc.so.7", "libhiprtc.so.6"]); + let mut tried = Vec::new(); + for path in &want { + let lib = match unsafe { Library::new(path) } { + Ok(l) => l, + Err(e) => { tried.push(format!("{}: not loadable ({e})", path.display())); continue } + }; + unsafe { + macro_rules! g { ($n:literal) => { match Self::sym(&lib, $n) { Some(f) => f, None => { tried.push(format!("{}: no {}", path.display(), $n)); continue } } } } + return Ok(Rtc { + version: g!("hiprtcVersion"), + create: g!("hiprtcCreateProgram"), + compile: g!("hiprtcCompileProgram"), + log_size: g!("hiprtcGetProgramLogSize"), + log: g!("hiprtcGetProgramLog"), + code_size: g!("hiprtcGetCodeSize"), + code: g!("hiprtcGetCode"), + destroy: g!("hiprtcDestroyProgram"), + error_string: g!("hiprtcGetErrorString"), + lib_path: path.clone(), + _lib: lib, + }); + } + } + Err(format!("no hiprtc: {}", tried.join(", "))) + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } + + pub fn version(&self) -> (i32, i32) { + let (mut maj, mut min) = (0, 0); + unsafe { (self.version)(&mut maj, &mut min) }; + (maj, min) + } + + fn err(&self, code: c_int) -> String { + let s = unsafe { (self.error_string)(code) }; + if s.is_null() { return format!("hiprtc error {code}") } + unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned() + } + + /// Directories holding `hip/hip_runtime.h`: hiprtc compiles a string in a scratch directory, so the ROCm headers + /// have to be named. Found next to the loaded `libhiprtc` and through the environment. + fn include_dirs(&self) -> Vec { + let mut v = Vec::new(); + for k in ["ROCM_PATH", "HIP_PATH"] { + if let Some(p) = std::env::var_os(k) { v.push(PathBuf::from(p).join("include")); } + } + if let Some(dir) = self.lib_path.parent() { + // libhiprtc.so -> /lib, headers in /include (also /include/hip). + v.push(dir.join("../include")); + } + for p in ["/opt/rocm/include", "/usr/include", "/usr/local/include"] { v.push(PathBuf::from(p)); } + v.retain(|p| p.join("hip/hip_runtime.h").exists()); + v + } + + /// Compile `src` to an AMDGPU code object for `arch` (`gfx1201`). `name` only labels diagnostics. + pub fn compile(&self, src: &str, name: &str, arch: &str, extra: &[&str]) -> anyhow::Result> { + let csrc = std::ffi::CString::new(src).context("kernel source contains a NUL byte")?; + let cname = std::ffi::CString::new(name)?; + let mut prog: RtcProgram = std::ptr::null_mut(); + let code = unsafe { (self.create)(&mut prog, csrc.as_ptr(), cname.as_ptr(), 0, std::ptr::null(), std::ptr::null()) }; + if code != HIP_SUCCESS { bail!("hiprtcCreateProgram: {}", self.err(code)) } + let guard = ProgGuard { prog, destroy: self.destroy }; + let mut opts: Vec = vec![ + std::ffi::CString::new(format!("--offload-arch={arch}"))?, + std::ffi::CString::new("-O3")?, + std::ffi::CString::new("--std=c++17")?, + ]; + for dir in self.include_dirs() { opts.push(std::ffi::CString::new(format!("-I{}", dir.display()))?); } + for e in extra { opts.push(std::ffi::CString::new(*e)?); } + let ptrs: Vec<*const c_char> = opts.iter().map(|o| o.as_ptr()).collect(); + let code = unsafe { (self.compile)(guard.prog, ptrs.len() as c_int, ptrs.as_ptr()) }; + let mut logsize = 0usize; + unsafe { (self.log_size)(guard.prog, &mut logsize) }; + if logsize > 1 { + let mut log = vec![0 as c_char; logsize]; + unsafe { (self.log)(guard.prog, log.as_mut_ptr()) }; + let text = unsafe { CStr::from_ptr(log.as_ptr()) }.to_string_lossy(); + if code != HIP_SUCCESS { bail!("hiprtc ({arch}): {}\n{}", self.err(code), text.trim_end()) } + let text = text.trim_end(); + if !text.is_empty() { eprintln!("hiprtc {name} ({arch}): {text}") } + } else if code != HIP_SUCCESS { + bail!("hiprtc ({arch}): {}", self.err(code)) + } + let mut n = 0usize; + unsafe { (self.code_size)(guard.prog, &mut n) }; + anyhow::ensure!(n > 0, "hiprtc produced no code for {arch}"); + let mut code_obj = vec![0u8; n]; + let r = unsafe { (self.code)(guard.prog, code_obj.as_mut_ptr().cast()) }; + if r != HIP_SUCCESS { bail!("hiprtcGetCode: {}", self.err(r)) } + Ok(code_obj) + } +} + +struct ProgGuard { + prog: RtcProgram, + destroy: unsafe extern "C" fn(*mut RtcProgram) -> c_int, +} + +impl Drop for ProgGuard { + fn drop(&mut self) { unsafe { (self.destroy)(&mut self.prog) }; } +} + +#[cfg(test)] +mod tests { + use super::find_gfx; + + /// The name is found at the end of the buffer without reading past it, a short `gfx` is passed over, and a + /// buffer without one gives None. + #[test] + fn find_gfx_reads_only_inside_the_buffer() { + let mut b = vec![0u8; 64]; + b[8..11].copy_from_slice(b"gfx"); + b[56..63].copy_from_slice(b"gfx1201"); + assert_eq!(find_gfx(&b).as_deref(), Some("gfx1201")); + assert_eq!(find_gfx(&b[..60]), None); + let mut tail = vec![0u8; 61]; + tail[52..61].copy_from_slice(b"gfx1100ab"); + assert_eq!(find_gfx(&tail).as_deref(), Some("gfx1100ab")); + assert_eq!(find_gfx(&[0u8; 32]), None); + } +} diff --git a/src/hip/mod.rs b/src/hip/mod.rs new file mode 100644 index 00000000..235e99d0 --- /dev/null +++ b/src/hip/mod.rs @@ -0,0 +1,1152 @@ +//! HIP (ROCm) backend: the same `kernels.cu` as `cuda`, with `STRATA_HIP` selecting its portable code paths, compiled +//! at run time by hiprtc for the device's `gfx` target and launched through the HIP runtime loaded by name (see +//! `ffi` and `compat.h`). No ROCm headers, no `hipcc`, no C++ build step: `cargo build --release` and `--backend hip`. +//! +//! The device side is one source: `kernels.cu` keeps its CUDA paths behind `#if !STRATA_HIP`, and `compat.h` supplies +//! what CUDA's headers give it for free. On RDNA the kernel is compiled as wave32 (lane = threadIdx.x & 31), which is +//! the assumption the source already makes about a warp. +//! +//! Status: the host layer and the wave32 device build are in place; ops are being wired up one family at a time +//! against the CPU reference (`cargo test --release hip`). Everything not yet ported returns an error naming the op, +//! so a run says exactly which kernel is missing instead of computing silently wrong numbers. + +use crate::backend::{ATT_SPLITS, ATT_SPLITS_1, Backend, Buf, GpuTensor, GEMM_BM, SAME_X}; +use crate::cuda::{AMAX_PARTS, FA_BK, attn_prefill_smem_bk, dyn_shmem_need, kname, rpw_from, gemv_block_from, tuned}; +use crate::quant::GgmlType; +use anyhow::{Context, bail}; +use std::any::Any; +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::{Arc, LazyLock, Mutex}; + +/// `STRATA_HIP_SYNC`: one sync per launch (see `Gpu::launch`). +static SYNC_EACH: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_SYNC").is_some()); +/// `STRATA_NO_GRAPH` / `STRATA_HIP_GRAPH=0`: run the forward every time instead of capturing it. +static NO_GRAPH: LazyLock = LazyLock::new(|| { + std::env::var_os("STRATA_NO_GRAPH").is_some() || std::env::var("STRATA_HIP_GRAPH").map(|v| v == "0").unwrap_or(false) +}); +/// `STRATA_HIP_TRACE`: name every launch before it goes out, so a fault that kills the process names the kernel. +static TRACE: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_TRACE").is_some()); + +mod ffi; + +pub struct Gpu { + /// The runtime, shared with every allocation and graph so none of them outlives the library that frees it. + hip: Arc, + device: usize, + stream: ffi::Stream, + module: ffi::Module, + fns: HashMap, + /// "gfx1201": the target hiprtc compiled for. + arch: String, + /// `--kv q8` (the kernels were compiled with `KV_MODE` 0 or 1; HIP has no q4/q2 cache rows). + pub kv_q8: bool, + /// Opt-in shared memory per block on this device (64 KiB on RDNA). + max_smem: usize, + /// `argmax_rows` partials. + am: Buf, + /// q8 rows of the last integer GEMM's X (see quant_q8 in kernels.cu) and which x they hold; `None` after a call + /// without `SAME_X` that did not quantize. + q8: Mutex<(Buf, Option<[u64; 4]>)>, + /// Recorded graphs by `Backend::graph` key. + graphs: Mutex>, + /// Recorded by `sync`, so a wait can poll it instead of spinning in the driver. + done: ffi::Event, + /// Rope frequency tables, `base` and `n_rot` to the device buffer that holds them. + fr: Mutex<(HashMap<(u32, usize), Buf>, Vec<(f32, usize)>)>, + /// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next + /// region while the card reads the previous one (expert streaming in prefill). + staging: Mutex, +} + +// The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` +// requires `Send`: transfers, launches and synchronization may come from any thread. +unsafe impl Send for Gpu {} + +struct Graph { + exec: ffi::GraphExec, + graph: ffi::Graph, + hip: Arc, +} + +impl Drop for Graph { + fn drop(&mut self) { + unsafe { + (self.hip.graph_exec_destroy)(self.exec); + (self.hip.graph_destroy)(self.graph); + } + } +} + +/// One launch: grid and block dimensions and the dynamic shared memory the kernel asks for. +#[derive(Clone, Copy)] +pub struct LaunchConfig { + pub grid_dim: (u32, u32, u32), + pub block_dim: (u32, u32, u32), + pub shared_mem_bytes: u32, +} + +pub fn cfg(grid: (u32, u32), block: u32, smem: u32) -> LaunchConfig { + LaunchConfig { grid_dim: (grid.0, grid.1, 1), block_dim: (block, 1, 1), shared_mem_bytes: smem } +} + +/// Launch kernel `$name` with `cfg`. Every argument is evaluated into a local, so `hipModuleLaunchKernel` reads it +/// from a live address; the type of the expression gives the parameter width, as the kernel's signature expects. +macro_rules! launch { + ($g:expr, $name:expr, $cfg:expr, $($a:expr),* $(,)?) => {{ + let c = $cfg; + $g.launch(&$name, c, &mut [ $(&mut { $a } as &mut dyn Any),* ]) + .with_context(|| format!("launch {}", $name))?; + }}; +} + +/// `kernels.cu` assembled for hiprtc: the compatibility layer, the quant tables, the compile-time switches, the file. +fn source(kv_q8: bool) -> String { + use crate::quant::tables::*; + let join = |v: Vec| v.join(","); + format!( + "{}\n\ + __device__ const unsigned long long iq2xs_grid[512] = {{{}}};\n\ + __device__ const unsigned long long iq2xxs_grid[256] = {{{}}};\n\ + __device__ const unsigned long long iq2s_grid[1024] = {{{}}};\n\ + __device__ const unsigned long long iq1s_grid[2048] = {{{}}};\n\ + __device__ const unsigned int iq3xxs_grid[256] = {{{}}};\n\ + __device__ const unsigned int iq3s_grid[512] = {{{}}};\n\ + __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ + __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ + __device__ const float tq_lut[4096] = {{{}}};\n\ + #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define GEMM_TC 0\n#define GEMM_WMMA (STRATA_WMMA && {})\n\ + #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS 1\n#define GEMV_LOADW {}\n\ + #define FA_BQ {}\n#define FA_BK {}\n{}", + include_str!("compat.h"), + join(IQ2XS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ2XXS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ2S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ1S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ3XXS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ3S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(KSIGNS_IQ2XS.iter().map(|v| v.to_string()).collect()), + join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), + join(crate::quant::TQ_LUT.iter().flatten().map(|v| format!("{v:e}f")).collect()), + crate::cuda::llama_numerics() as u8, + kv_q8 as u8, + // `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications (A/B comparison, and a workaround if a + // card's matrix cores misbehave). + (std::env::var("STRATA_HIP_WMMA").map(|v| v != "0").unwrap_or(true)) as u8, + GEMM_BM, + crate::cuda::GEMM_BK, + tuned(std::env::var("STRATA_GEMV_LOADW").ok().as_deref(), 0, |v| v <= 1), + crate::cuda::FA_BQ, + crate::cuda::FA_BK, + include_str!("../cuda/kernels.cu"), + ) +} + +/// Cache key for a compiled code object: the source, the target and the hiprtc version. +fn cache_key(src: &str, arch: &str, rtc: &str) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (src, arch, rtc).hash(&mut h); + h.finish() +} + +impl Gpu { + pub fn new(device: usize) -> anyhow::Result { + let hip = Arc::new(ffi::Hip::open()?); + hip.check(unsafe { (hip.init)(0) }, "hipInit")?; + let n = { + let mut n = 0; + hip.check(unsafe { (hip.device_count)(&mut n) }, "hipGetDeviceCount")?; + n as usize + }; + anyhow::ensure!(device < n, "HIP device {device}: {n} device(s) present"); + hip.check(unsafe { (hip.set_device)(device as i32) }, "hipSetDevice")?; + let arch = hip.arch(device as i32)?; + let warp = hip.attribute(ffi::ATTR_WARP_SIZE, device as i32)?; + anyhow::ensure!(warp == 32, "H100 HIP backend needs wave32; {arch} reports warp size {warp}"); + // Opt-in (75) is what a kernel may ask for; fall back to the plain per-block limit (74) if a runtime does not + // know the attribute, and never trust a figure below the smallest tile the prefill attention needs. + let mut max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK_OPTIN, device as i32).unwrap_or(0) as usize; + if max_smem < (16 << 10) { + max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK, device as i32).unwrap_or(16 << 10) as usize; + } + anyhow::ensure!(max_smem >= (16 << 10), "HIP device reports {max_smem} B of shared memory a block"); + // The HIP kernels hold an f16 or q8 cache (KV_MODE 0 or 1): refuse q4 and q2 rather than run f16 unasked. + anyhow::ensure!(crate::cuda::kv_mode() <= 1, "--kv q4 and q2 are not available on the HIP backend (f16 or q8)"); + let kv_q8 = crate::cuda::kv_q8(); + let rtc = ffi::Rtc::get().map_err(|e| anyhow::anyhow!("{e}")).context("HIP init").context("hiprtc is required to compile the kernels")?; + let (maj, min) = rtc.version(); + let tag = format!("{maj}.{min}"); + eprintln!("hip: {} ({arch}, wave{warp}, {} B shared memory a block)", + hip.device_name(device as i32), max_smem); + let src = source(kv_q8); + let obj = compile_cached(rtc, &src, &arch, &tag)?; + let mut stream: ffi::Stream = std::ptr::null_mut(); + hip.check(unsafe { (hip.stream_create)(&mut stream, ffi::STREAM_NON_BLOCKING) }, "hipStreamCreate")?; + let mut module: ffi::Module = std::ptr::null_mut(); + hip.check(unsafe { (hip.module_load)(&mut module, obj.as_ptr().cast()) }, "hipModuleLoadData")?; + let mut fns = HashMap::new(); + for name in kernel_names() { + let c = std::ffi::CString::new(name.clone())?; + let mut f: ffi::Func = std::ptr::null_mut(); + hip.check(unsafe { (hip.function)(&mut f, module, c.as_ptr()) }, &format!("hipModuleGetFunction({name})"))?; + // The kernels ask for up to 49 KiB of dynamic shared memory, more than HIP allows by default. The ceiling + // is the device's opt-in minus what the kernel already uses statically, which the runtime only checks + // here, so an over-ask is halved instead of failing the backend. + if let Some((_, need)) = dyn_shmem_need(&name) { + let mut want = need.min(max_smem); + loop { + let r = unsafe { (hip.func_set_attribute)(f, ffi::ATTR_MAX_DYNAMIC_SHARED, want as i32) }; + if r == ffi::HIP_SUCCESS { break } + if want < 8192 { + bail!("hipFuncSetAttribute({name}, {want}): {}", hip.err(r)); + } + want /= 2; + } + } + fns.insert(name, f); + } + // argmax_part writes an int2 (8 bytes) per partial: AMAX_PARTS per row, up to 64 rows. + let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS * 8)?; + let q8_buf = alloc_raw(&hip, 1)?; + // Pinned ring for large host-to-device copies. + let mut host: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.host_malloc)(&mut host, RING, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc(ring)")?; + let mut dev: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer(ring)")?; + let staging = Staging { pin: Buf::new(dev as u64, RING, PinnedHost { hip: hip.clone(), p: host }), host: host.cast(), head: 0, busy: VecDeque::new() }; + let mut done: ffi::Event = std::ptr::null_mut(); + hip.check(unsafe { (hip.event_create)(&mut done, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; + Ok(Gpu { hip, device, stream, module, fns, arch, kv_q8, max_smem, am: am_buf, q8: Mutex::new((q8_buf, None)), + graphs: Mutex::new(HashMap::new()), done, fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) + } + + fn h(&self) -> &ffi::Hip { &self.hip } + + pub fn arch(&self) -> &str { &self.arch } + + /// Launch kernel `name` with `cfg`; `args` are the kernel parameters, in order, read from the given addresses. + pub fn launch(&self, name: &str, c: LaunchConfig, args: &mut [&mut dyn Any]) -> anyhow::Result<()> { + let f = *self.fns.get(name).ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded"))?; + if *TRACE { eprintln!("hip launch {name} grid {:?} block {:?} smem {}", c.grid_dim, c.block_dim, c.shared_mem_bytes); } + let mut params: Vec<*mut c_void> = args.iter_mut().map(|a| (*a as *mut dyn Any).cast::()).collect(); + let r = unsafe { + (self.hip.launch)(f, c.grid_dim.0, c.grid_dim.1, c.grid_dim.2, c.block_dim.0, c.block_dim.1, c.block_dim.2, + c.shared_mem_bytes, self.stream, params.as_mut_ptr(), std::ptr::null_mut()) + }; + if r != ffi::HIP_SUCCESS { bail!("{}: {}", name, self.hip.err(r)) } + // `STRATA_HIP_SYNC`: wait after every launch, so a hardware exception or bad argument names the kernel that + // raised it instead of the sync at the end of the pass. Debugging only: no overlap and no graphs. + if *SYNC_EACH { + self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, &format!("kernel {name} failed"))?; + } + Ok(()) + } + + fn wait(&self) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, "hipStreamSynchronize") + } + + fn ptr(&self, b: &Buf) -> u64 { b.addr() } + + fn f(&self, name: &str) -> anyhow::Result { + self.fns.get(name).copied().ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded")) + } + + /// qwen35moe and the other models this backend targets dequantize in the kernel, so the ops below are the + /// generic ones. + fn float_ty(ty: GgmlType) -> bool { matches!(ty, GgmlType::F32 | GgmlType::BF16) } + + fn gemv_cols(prefix: &str, ty: GgmlType, cols: usize) -> anyhow::Result<(i32, String)> { + let b = ty.block_elems().max(32); + if cols % b != 0 { bail!("{} tensor with {cols} columns: GEMV needs a multiple of {b}", ty.name()); } + Ok((cols as i32, kname(prefix, ty) + if cols % 256 != 0 { "_p" } else { "" })) + } + + fn rpw(rows: usize, cols: usize, k: usize) -> usize { + let d = if k > 1 { if cols <= 512 { 4 } else { (2048 / cols).max(1) } } else if rows >= 65536 { 8 } else if rows >= 8192 || rows == 2048 { 2 } else { 1 }; + let fam = if k > 1 { "STRATA_RPW_MOE" } else { "STRATA_RPW_DENSE" }; + let family = std::env::var(fam).ok(); + rpw_from(std::env::var("STRATA_RPW").ok().as_deref(), family.as_deref(), d) + } + + fn gemv_block(k: usize) -> u32 { + let fam = if k > 1 { "STRATA_GEMV_BLOCK_MOE" } else { "STRATA_GEMV_BLOCK_DENSE" }; + let family = std::env::var(fam).ok(); + gemv_block_from(std::env::var("STRATA_GEMV_BLOCK").ok().as_deref(), family.as_deref()) + } + + fn xq_smem(ty: GgmlType, cols: usize) -> u32 { + if Self::float_ty(ty) { 0 } else { (cols + cols / 8) as u32 } + } + + fn gemv_cfg(ty: GgmlType, rows: usize, cols: usize, k: usize) -> (LaunchConfig, i32) { + if Self::float_ty(ty) { + let wpb = if rows >= 4096 { 8 } else { 1 }; + return (cfg((rows.div_ceil(wpb) as u32, k as u32), 32 * wpb as u32, 0), 1); + } + let (rpw, wpb) = (Self::rpw(rows, cols, k), Self::gemv_block(k) as usize / 32); + (cfg((rows.div_ceil(wpb * rpw) as u32, k as u32), (32 * wpb) as u32, Self::xq_smem(ty, cols)), rpw as i32) + } + + /// Whether the stream is capturing a graph: no allocation and no synchronous copy may be issued inside one. + fn capturing(&self) -> bool { + let mut status = 0; + unsafe { (self.hip.stream_is_capturing)(self.stream, &mut status) }; + status != 0 + } + + /// The rope frequencies base^(-2i / n_rot) as `rms_norm_rope` computes them in f64, made once by `rope_freq`. + /// While a graph is captured a missing table gives 0 (the kernel computes the frequencies itself) and is made + /// after the capture, which `graph` then repeats. + fn rope_fr(&self, base: f32, n_rot: usize) -> anyhow::Result { + let mut fr = self.fr.lock().unwrap(); + if let Some(b) = fr.0.get(&(base.to_bits(), n_rot)) { return Ok(b.addr()) } + if self.capturing() { + fr.1.push((base, n_rot)); + return Ok(0); + } + let buf = alloc_raw(&self.hip, 8 * (n_rot / 2).max(1))?; + let p = buf.addr(); + let (bs, nr) = (base, n_rot as i32); + launch!(self, "rope_freq", cfg((1, 1), 256, 0), p, bs, nr); + self.wait()?; + fr.0.insert((base.to_bits(), n_rot), buf); + Ok(p) + } + + /// `gemvq`; with z = 2 also the matrix of `pair.2` rows at byte offset `pair.0` into the output at byte offset + /// `pair.1` (token stride `pair.2`). + fn gemvq_pair(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize, + pair: (i64, i64, i32, f32), z: u32) -> anyhow::Result<()> { + if !(1..=4).contains(&nt) { bail!("gemvn: {nt} inputs (1 to 4)"); } + let (ncols, k1) = Self::gemv_cols("gemv", w.ty, w.cols)?; + let (mut c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); + let per = c.shared_mem_bytes; + c.shared_mem_bytes = if xq == 0 { per * nt as u32 } else { 0 }; + c.grid_dim.2 = z; + // gemvn caches one x row per token in shared memory; when that exceeds the block's limit, run a token at a time. + if xq == 0 && c.shared_mem_bytes as usize > self.max_smem { + c.shared_mem_bytes = per; + for t in 0..nt { + let (xt, yt) = (x + 4 * t as u64 * x_stride as u64, y + 4 * t as u64 * y_stride as u64); + launch!(self, &k1, c, w.ptr, xt, yt, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2, w.scale, pair.3); + } + return Ok(()); + } + if nt == 1 { + launch!(self, &k1, c, w.ptr, x, y, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2, w.scale, pair.3); + return Ok(()); + } + let kn = k1.replacen("gemv", "gemvn", 1); + launch!(self, &kn, c, w.ptr, x, x_stride as i32, y, y_stride as i32, w.rows as i32, ncols, rpw, nt as i32, xq, pair.0, pair.1, pair.2, w.scale, pair.3); + Ok(()) + } + + /// Prefill GEMM over a tile list (or one dense matrix when `tiles` is 0). Without int8 tensor cores the f16 + /// `gemm_*`/`gemms_*` kernels run; `gemm_tc` is compiled out of this build (`GEMM_TC 0`). + fn gemm_raw(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, wd: u64, nd: usize, + x: u64, x_stride: usize, _n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32, w_scale: f32) -> anyhow::Result<()> { + if cols % 64 != 0 { bail!("{} matrix with {cols} columns: GEMM needs a multiple of 64", ty.name()); } + if n_tiles == 0 { return Ok(()) } + // Only the activation reaches the kernel: SAME_X and BATCHED (the same kernels here) are flags for the host. + let (same, act) = (act & SAME_X != 0, act & 3); + let _ = same; + let grid = (rows.div_ceil(64) as u32, n_tiles as u32); + let sm = tiles == 0 && (grid.0 * grid.1 < 112 || nd <= 32); + let grid = if sm { (grid.0, nd.div_ceil(32) as u32) } else { grid }; + launch!(self, &kname(if sm { "gemms" } else { "gemm" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); + // Tile lists: gemm_* skips the tiles of at most 32 positions, which gemms_* takes. + if tiles != 0 { + launch!(self, &kname("gemms", ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); + } + Ok(()) + } + + /// Decode attention: `attn_decode_gq` plus `attn_merge`, which also writes `out` quantized into xq. + fn attn(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, + scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize, kvt: u64, ns1: usize) -> anyhow::Result<()> { + if ![64, 128, 256, 512].contains(&hd) { bail!("attention head_dim {hd} unsupported (64, 128, 256 or 512)"); } + let group = nh / nkv; + let g = [8, 4, 2, 1].into_iter().find(|&g| group % g == 0 && g * hd <= 2048).unwrap(); + let ns = if kvt != 0 { ns1 } else { ATT_SPLITS }; + let pz = (nh * ns * (hd + 2)) as i32; + if gq_min != 0 { + launch!(self, &format!("attn_decode_{hd}"), cfg(((nh * nt) as u32, ns1 as u32), 256, (8 * hd * 4) as u32), + q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); + } + // No cp.async double buffering here: that path is the sm_80+ one (`ATT_RUN_CP`), so the K/V tile comes + // through registers and the kernel needs no extra shared memory. + let g4 = false; + let (name, cp) = if g4 { ("attn_decode_gqa4_128".to_string(), 0) } else { (format!("attn_decode_gqa_{hd}"), 0) }; + if gq_min != i32::MAX { + launch!(self, &name, cfg(((nh / g * nt) as u32, ns as u32), 256, (8 * hd * 4 + cp) as u32), + q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); + } + launch!(self, "attn_merge", LaunchConfig { grid_dim: (nh as u32, 1, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }, + part, qg, out, hd as i32, ns as i32, step, ns1 as i32, gq_min, xq, sink); + Ok(()) + } + + fn grid(n: usize) -> LaunchConfig { cfg((n.div_ceil(256) as u32, 1), 256, 0) } +} + +/// Pinned host allocation freed with the runtime that made it. +struct PinnedHost { hip: Arc, p: *mut c_void } + +unsafe impl Send for PinnedHost {} +unsafe impl Sync for PinnedHost {} + +impl Drop for PinnedHost { + fn drop(&mut self) { unsafe { (self.hip.host_free)(self.p) }; } +} + +/// Pinned host memory used as a ring for `htod`: a region is free again once the copy that read it has completed. +struct Staging { + pin: Buf, + host: *mut u8, + head: usize, + busy: VecDeque<(usize, usize, Event)>, +} + +/// A `hipEvent_t` that destroys itself; `query` reports completion. +struct Event { hip: Arc, ev: ffi::Event } + +impl Event { + fn new(hip: &Arc) -> anyhow::Result { + let mut ev: ffi::Event = std::ptr::null_mut(); + hip.check(unsafe { (hip.event_create)(&mut ev, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; + Ok(Event { hip: hip.clone(), ev }) + } + fn record(&self, stream: ffi::Stream) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.event_record)(self.ev, stream) }, "hipEventRecord") + } + fn done(&self) -> bool { unsafe { (self.hip.event_query)(self.ev) == ffi::HIP_SUCCESS } } +} + +impl Drop for Event { + fn drop(&mut self) { unsafe { (self.hip.event_destroy)(self.ev) }; } +} + +/// Recorded graphs kept before a forward runs uncaptured (CUDA's cap, same reason). +const GRAPHS_MAX: usize = 32; + +const RING: usize = 64 << 20; +const RING_MIN: usize = 256 << 10; + +fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { + let mut p: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.malloc)(&mut p, bytes.max(1)) }, "hipMalloc")?; + // The Buf owns the allocation through its address; the free happens when the owner (the backend or the tensor) + // drops, so the owner is a small RAII handle. + struct DevAlloc { hip: Arc, p: *mut c_void } + unsafe impl Send for DevAlloc {} + unsafe impl Sync for DevAlloc {} + impl Drop for DevAlloc { + fn drop(&mut self) { unsafe { (self.hip.free)(self.p) }; } + } + Ok(Buf::new(p as u64, bytes.max(1), DevAlloc { hip: hip.clone(), p })) +} + +fn compile_cached(rtc: &ffi::Rtc, src: &str, arch: &str, tag: &str) -> anyhow::Result> { + let dir = std::env::var_os("XDG_CACHE_HOME").map(Into::into) + .unwrap_or_else(|| std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".cache")) + .join("rusting_strata"); + let path = dir.join(format!("{:016x}.amdgcn", cache_key(src, arch, tag))); + if let Ok(b) = std::fs::read(&path) { return Ok(b) } + eprintln!("compiling HIP kernels for {arch} with hiprtc {tag} (first run only)"); + let b = rtc.compile(src, "kernels.cu", arch, &[])?; + let _ = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&path, &b)); + Ok(b) +} + +/// The kernel names to load: `cuda::kernel_names(false)` has no int8-mma GEMM, which needs no separate list here. +fn kernel_names() -> Vec { crate::cuda::kernel_names(false) } + +impl Backend for Gpu { + fn name(&self) -> &'static str { "hip" } + + fn device(&self) -> String { self.hip.device_name(self.device as i32) } + + fn alloc(&self, bytes: usize) -> anyhow::Result { + let b = alloc_raw(&self.hip, bytes)?; + self.memset(&b)?; + Ok(b) + } + + /// Queue a host-to-device copy on the stream and return once `src` may be reused: from pageable memory the + /// runtime stages the buffer inside the call, and large copies go through the pinned ring so the DMA does not + /// stop the host (expert streaming during prefill). + fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { + anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); + if src.len() < RING_MIN { + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), + ffi::MEMCPY_H2D, self.stream) }; + return self.hip.check(r, "hipMemcpyAsync(htod)"); + } + let mut g = self.staging.lock().unwrap(); + for (i, c) in src.chunks(RING).enumerate() { + if g.head + c.len() > RING { g.head = 0; } + let (a, b) = (g.head, g.head + c.len()); + // Regions still being read by an earlier copy have to complete before the host overwrites them. + while g.busy.iter().any(|&(s, e, _)| s < b && a < e) { + let (_, _, ev) = g.busy.pop_front().unwrap(); + self.hip.check(unsafe { (self.hip.event_sync)(ev.ev) }, "hipEventSynchronize")?; + } + unsafe { std::ptr::copy_nonoverlapping(c.as_ptr(), g.host.add(a), c.len()) }; + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + (off + i * RING) as u64) as *mut c_void, + g.host.add(a) as *const c_void, c.len(), ffi::MEMCPY_H2D, self.stream) }; + self.hip.check(r, "hipMemcpyAsync(htod ring)")?; + let ev = Event::new(&self.hip)?; + ev.record(self.stream)?; + g.busy.push_back((a, b, ev)); + g.head = b; + } + Ok(()) + } + + fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()> { + anyhow::ensure!(off + dst.len() <= src.len(), "dtoh: {} bytes at {off} from {}", dst.len(), src.len()); + self.wait()?; + let r = unsafe { (self.hip.memcpy)(dst.as_mut_ptr().cast(), (src.addr() + off as u64) as *const c_void, dst.len(), + ffi::MEMCPY_D2H) }; + self.hip.check(r, "hipMemcpyAsync(dtoh)") + } + + fn dtod(&self, src: &Buf, src_off: usize, dst: &Buf, dst_off: usize, bytes: usize) -> anyhow::Result<()> { + anyhow::ensure!(src_off + bytes <= src.len() && dst_off + bytes <= dst.len(), "dtod: {bytes} bytes out of range"); + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + dst_off as u64) as *mut c_void, + (src.addr() + src_off as u64) as *const c_void, bytes, ffi::MEMCPY_D2D, self.stream) }; + self.hip.check(r, "hipMemcpyAsync(dtod)") + } + + /// On the stream, so it is ordered against the copies and launches around it (the plain `hipMemset` goes to the + /// null stream and can land after a copy that was queued for the same buffer). + fn memset(&self, dst: &Buf) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.memset_async)(dst.addr() as *mut c_void, 0, dst.len(), self.stream) }, "hipMemsetAsync") + } + + fn mem_info(&self) -> anyhow::Result<(usize, usize)> { + let (mut free, mut total) = (0usize, 0usize); + self.hip.check(unsafe { (self.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo")?; + Ok((free, total)) + } + + fn sync(&self) -> anyhow::Result<()> { self.wait() } + + /// Recorded with `hipStreamBeginCapture`: the same launches, replayed by the driver with no host work. + /// HIP refuses an allocation on a capturing stream ("operation not permitted when stream is capturing"), where + /// CUDA's stream-ordered allocator allows it, so anything a step allocates has to be made before the capture (the + /// rope table defers itself, see `rope_fr`). `STRATA_HIP_GRAPH=0` turns capture off. + fn graph(&self, key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { + if *NO_GRAPH { return f() } + if let Some(g) = self.graphs.lock().unwrap().get(&key) { + let r = unsafe { (self.hip.graph_launch)(g.exec, self.stream) }; + return self.hip.check(r, "hipGraphLaunch"); + } + // Each graph holds device memory and `step_rows` keys one per combination of sequence slots: past the cap a + // forward runs uncaptured (the CUDA backend caps for the same reason). + if self.graphs.lock().unwrap().len() >= GRAPHS_MAX { return f() } + if self.capturing() { return f() } // never nest captures + self.hip.check(unsafe { (self.hip.stream_begin_capture)(self.stream, ffi::CAPTURE_MODE_THREAD_LOCAL) }, "hipStreamBeginCapture")?; + let r = f(); + let mut graph: ffi::Graph = std::ptr::null_mut(); + let end = unsafe { (self.hip.stream_end_capture)(self.stream, &mut graph) }; + r?; + self.hip.check(end, "hipStreamEndCapture")?; + anyhow::ensure!(!graph.is_null(), "empty HIP graph"); + let mut exec: ffi::GraphExec = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.graph_instantiate)(&mut exec, graph, 0) }, "hipGraphInstantiate")?; + self.hip.check(unsafe { (self.hip.graph_launch)(exec, self.stream) }, "hipGraphLaunch")?; + // A rope table the capture lacked: make it, and capture again next time (this graph computes it per call). + let want = std::mem::take(&mut self.fr.lock().unwrap().1); + if !want.is_empty() { + for (base, n_rot) in want { self.rope_fr(base, n_rot)?; } + return Ok(()); + } + self.graphs.lock().unwrap().insert(key, Graph { exec, graph, hip: self.hip.clone() }); + Ok(()) + } + + /// Pinned host memory mapped into the device address space (the CPU expert worker's mailbox). + fn host_mailbox(&self, words: usize) -> anyhow::Result<(Buf, *mut u32)> { + let n = words.max(1); + let mut host: *mut c_void = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.host_malloc)(&mut host, 4 * n, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc")?; + let mut dev: *mut c_void = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer")?; + unsafe { std::ptr::write_bytes(host as *mut u8, 0, 4 * n) }; + let owner = PinnedHost { hip: self.hip.clone(), p: host }; + Ok((Buf::new(dev as u64, 4 * n, owner), host.cast())) + } + + fn kv_words(&self, n: usize) -> usize { if self.kv_q8 { n * 17 / 32 } else { n } } + + // ---- kernels ------------------------------------------------------------------------------------------------- + + fn gemm(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, x: u64, x_stride: usize, n_x: usize, + xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + self.gemm_raw(ty, rows, cols, tiles, n_tiles, 0, 0, x, x_stride, n_x, xrow, y, y_stride, act, 1.0f32) + } + + fn gemm_dense(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + self.gemm_raw(w.ty, w.rows, w.cols, 0, n.div_ceil(GEMM_BM), w.ptr, n, x, x_stride, n, 0, y, y_stride, act, w.scale) + } + + fn int8_gemm(&self, _ty: GgmlType) -> bool { false } + + fn gemv(&self, w: &GpuTensor, x: u64, y: u64) -> anyhow::Result<()> { + let (ncols, kn) = Self::gemv_cols("gemv", w.ty, w.cols)?; + let (c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); + launch!(self, &kn, c, w.ptr, x, y, w.rows as i32, ncols, rpw, 0u64, 0i64, 0i64, 0i32, w.scale, 1.0f32); + Ok(()) + } + + fn gemvn(&self, w: &GpuTensor, x: u64, x_stride: usize, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { + self.gemvq(w, x, x_stride, 0, y, y_stride, nt) + } + + fn gemvq(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { + self.gemvq_pair(w, x, x_stride, xq, y, y_stride, nt, (0, 0, 0, 1.0f32), 1) + } + + fn gemvq2(&self, a: &GpuTensor, b: &GpuTensor, x: u64, x_stride: usize, xq: u64, ya: u64, yb: u64, nt: usize) -> anyhow::Result<()> { + if a.ty != b.ty || a.cols != b.cols { + self.gemvq(a, x, x_stride, xq, ya, a.rows, nt)?; + return self.gemvq(b, x, x_stride, xq, yb, b.rows, nt); + } + let ((a, ya), (b, yb)) = if a.rows >= b.rows { ((a, ya), (b, yb)) } else { ((b, yb), (a, ya)) }; + self.gemvq_pair(a, x, x_stride, xq, ya, a.rows, nt, (b.ptr as i64 - a.ptr as i64, yb as i64 - ya as i64, b.rows as i32, b.scale), 2) + } + + fn moe_gemv(&self, ty: GgmlType, rows: usize, cols: usize, w: u64, stride: usize, ids: u64, k: usize, x: u64, x_stride: usize, + xg: usize, y: u64, pair: Option<(i64, i64)>, xq: u64) -> anyhow::Result<()> { + let (ncols, kn) = Self::gemv_cols("moe_gemv", ty, cols)?; + let (mut c, mut rpw) = Self::gemv_cfg(ty, rows, cols, k); + if rpw == 1 && !Self::float_ty(ty) { + rpw = 2; + c.grid_dim.0 = rows.div_ceil(2 * (Self::gemv_block(k) as usize / 32)) as u32; + } + let (w2, y2) = pair.unwrap_or((0, 0)); + c.grid_dim.2 = if pair.is_some() { 2 } else { 1 }; + if xq != 0 { c.shared_mem_bytes = 0; } + launch!(self, &kn, c, w, ids, stride as i64, x, x_stride as i32, xg as i32, y, rows as i32, ncols, rpw, w2, y2, xq); + Ok(()) + } + + fn dequant(&self, w: &GpuTensor, rows: usize, out: u64) -> anyhow::Result<()> { + launch!(self, &kname("dequant", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, out, Self::gemv_cols("dequant", w.ty, w.cols)?.0, w.scale); + Ok(()) + } + + fn quant_xq(&self, x: u64, x_stride: usize, n: usize, nt: usize, out: u64) -> anyhow::Result<()> { + launch!(self, "quant_xq", cfg((nt as u32, 1), 256, 0), x, x_stride as i32, n as i32, out); + Ok(()) + } + + fn rms_norm(&self, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, n: usize, rows: usize, eps: f32) -> anyhow::Result<()> { + self.rms_norm_q(x, x_stride, w, out, out_stride, n, rows, eps, 0, 0) + } + + fn rms_norm_q(&self, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, n: usize, rows: usize, eps: f32, xq: u64, res: u64) -> anyhow::Result<()> { + launch!(self, "rms_norm", cfg((rows as u32, 1), 512, 0), x, x_stride as i32, w, out, out_stride as i32, n as i32, eps, xq, res, 1i32); + Ok(()) + } + + fn rms_norm_streams(&self, x: u64, w: u64, out: u64, n: usize, hc: usize, nt: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "rms_norm", cfg(((nt * hc) as u32, 1), 512, 0), x, n as i32, w, out, n as i32, n as i32, eps, 0u64, 0u64, hc as i32); + Ok(()) + } + + fn argmax_rows(&self, x: u64, n: usize, rows: usize, out: u64) -> anyhow::Result<()> { + let part = self.ptr(&self.am); + anyhow::ensure!(rows * AMAX_PARTS * 8 <= self.am.len(), "argmax_rows: {rows} rows"); // len is in bytes + launch!(self, "argmax_part", cfg((AMAX_PARTS as u32, rows as u32), 256, 0), x, n as i32, part); + launch!(self, "argmax_rows", cfg((rows as u32, 1), AMAX_PARTS as u32, 0), part, n as i32, out); + Ok(()) + } + + fn l2_norm(&self, x: u64, n: usize, per: usize, stride: usize, rows: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "l2_norm", cfg((rows as u32, 1), 128, 0), x, n as i32, per as i32, stride as i32, eps); + Ok(()) + } + + fn rope_neox(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { + self.rope_pairs(x, stride, heads, per, n_rot, step, base, 0, n_rot / 2) + } + + fn rope_pairs(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32, lo: usize, hi: usize) -> anyhow::Result<()> { + launch!(self, "rope_neox", cfg(((heads / per) as u32, 1), (n_rot / 2) as u32, 0), x, stride as i32, per as i32, n_rot as i32, step, base, lo as i32, hi as i32); + Ok(()) + } + + fn rms_norm_rope(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { + self.rms_norm_rope_kv(x, x_stride, w, out, n, rows, eps, per, n_rot, step, base, 0, 0, 0) + } + + fn rms_norm_rope_kv(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, + step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg((rows as u32, 1), 256, 0), x, x_stride as i32, w, out, n as i32, eps, per as i32, n_rot as i32, + step, base, v, kc, vc, 0i32, 0u64, 0i32, 0u64, 0u64, 0i32, fr, 0u64); + Ok(()) + } + + fn rms_norm_rope_qk(&self, q: u64, q_stride: usize, qw: u64, qo: u64, qrows: usize, qper: usize, k: u64, kw: u64, ko: u64, + krows: usize, kper: usize, n: usize, eps: f32, n_rot: usize, step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg(((qrows + krows) as u32, 1), 256, 0), k, n as i32, kw, ko, n as i32, eps, kper as i32, n_rot as i32, + step, base, v, kc, vc, qrows as i32, q, q_stride as i32, qw, qo, qper as i32, fr, 0u64); + Ok(()) + } + + fn kv_rows(&self) -> bool { true } + + fn rms_norm_rope_qk_rows(&self, q: u64, q_stride: usize, qw: u64, qo: u64, nh: usize, k: u64, kw: u64, ko: u64, nkv: usize, + hd: usize, eps: f32, n_rot: usize, step: u64, base: f32, v: u64, kvt: u64, nt: usize) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= hd.min(512) && hd % 32 == 0, "rms_norm_rope: head of {hd}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg(((nt * (nh + nkv)) as u32, 1), 256, 0), k, hd as i32, kw, ko, hd as i32, eps, nkv as i32, n_rot as i32, + step, base, v, 0u64, 0u64, (nt * nh) as i32, q, q_stride as i32, qw, qo, nh as i32, fr, kvt); + Ok(()) + } + + fn attn_rows(&self, q: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, nt: usize, + sink: u64, win: usize, kvt: u64, splits: usize) -> anyhow::Result<()> { + self.attn(q, 0, 0, qg, out, part, step, nh, nkv, hd, scale, 0, nt, 0, 0, 0, sink, win, kvt, splits) + } + + fn add(&self, x: u64, y: u64, n: usize) -> anyhow::Result<()> { + launch!(self, "add", Self::grid(n), x, y, n as i32); + Ok(()) + } + + fn swiglu(&self, g: u64, u: u64, n: usize) -> anyhow::Result<()> { + launch!(self, "swiglu", Self::grid(n), g, u, n as i32); + Ok(()) + } + + fn swiglu_q(&self, g: u64, u: u64, n: usize, rows: usize, xq: u64) -> anyhow::Result { + launch!(self, "swiglu_q", cfg((n.div_ceil(256) as u32, rows as u32), 32, 0), g, u, n as i32, xq); + Ok(xq) + } + + fn ssm_gates(&self, beta: u64, g: u64, dt_bias: u64, a: u64, n: usize, nv: usize) -> anyhow::Result<()> { + launch!(self, "ssm_gates", Self::grid(n), beta, g, dt_bias, a, n as i32, nv as i32); + Ok(()) + } + + fn conv_silu(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, nn: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "conv_silu", cfg((ch.div_ceil(128) as u32, 1), 128, 0), qkv, state, w, y, ch as i32, kw as i32, nn as i32, eps); + Ok(()) + } + + fn deltanet(&self, y: u64, s: u64, beta: u64, g: u64, dt_bias: u64, a: u64, o: u64, nk: usize, nv: usize, interleave: bool, + dk: usize, dv: usize, scale: f32, t: usize, ych: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { + let rows = 512 / dk.max(1); + anyhow::ensure!(matches!(dk, 32 | 64 | 128 | 256) && dv % rows == 0, "deltanet: head dims {dk}/{dv} unsupported"); + launch!(self, "deltanet_seq", cfg((nv as u32, dv.div_ceil(8 * rows) as u32), 256, 0), + y, s, beta, g, o, nk as i32, nv as i32, interleave as i32, dk as i32, dv as i32, scale, t as i32, ych as i32, + snap, nsnap as i32, dt_bias, a); + Ok(()) + } + + fn conv_seq(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, t: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { + launch!(self, "conv_seq", Self::grid(t * ch), qkv, state, w, y, ch as i32, kw as i32, t as i32); + launch!(self, "conv_state", Self::grid(ch), qkv, state, ch as i32, kw as i32, t as i32, snap, nsnap as i32); + Ok(()) + } + + fn dflash2_conv(&self, x: u64, dyn_w: u64, base: u64, out: u64, h: usize, gs: usize, k: usize, t: usize, part: usize) -> anyhow::Result<()> { + launch!(self, "dflash2_conv", cfg((h.div_ceil(256) as u32, t as u32), 256, 0), x, dyn_w, base, out, h as i32, gs as i32, k as i32, t as i32, part as i32); + Ok(()) + } + + fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, + scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { + if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } + // The tile depth has to be the one the kernel picks for itself (`FA_BK_FOR(HD)`, which takes 16 keys rather than + // 32 at head_dim 256): 32 keys plus the score staging tile need 78 KiB, more than a 64 KiB workgroup may use, + // while 16 keys need 58 KiB. A smaller depth here would under-allocate what the kernel addresses. + let bk = if hd == 256 { 16 } else { FA_BK }; + // The HIP kernel stages its matrix-core scores through an extra FA_BQ x (bk + 8) f32 tile (see attn_prefill_t); + // the qs/ks/vs/ps sizes the shared helper computes are the same as CUDA's. + let smem = (attn_prefill_smem_bk(hd, bk) + 4 * crate::cuda::FA_BQ * (bk + 8)) as u32; + anyhow::ensure!(smem as usize <= self.max_smem, "attn_prefill_{hd}: {smem} B of shared memory, {} allowed", self.max_smem); + launch!(self, &format!("attn_prefill_{hd}"), cfg((t.div_ceil(64) as u32, nh as u32), 128, smem), + q, kc, vc, qg, out, step, t as i32, nh as i32, nkv as i32, scale, qm, mw as i32, sink, win as i32); + Ok(()) + } + + fn qsa_pool(&self, ik: u64, ring: u64, pool: u64, w: u64, step: u64, t: usize, n_rot: usize, base: f32, eps: f32) -> anyhow::Result<()> { + launch!(self, "qsa_pool", cfg(((t / 4 + 1) as u32, 1), 128, 0), ik, ring, pool, w, step, t as i32, n_rot as i32, base, eps); + Ok(()) + } + + fn qsa_select(&self, q: u64, pool: u64, score: u64, sel: u64, mask: u64, step: u64, r0: usize, rows: usize, nbs: usize, top: usize, sst: usize, mw: usize) -> anyhow::Result<()> { + launch!(self, "qsa_score", cfg((64, rows.div_ceil(8) as u32), 256, 0), q, pool, score, step, r0 as i32, rows as i32, nbs as i32, top as i32); + launch!(self, "qsa_select", cfg((rows as u32, 1), 1024, 0), score, sel, mask, step, r0 as i32, nbs as i32, top as i32, sst as i32, mw as i32); + Ok(()) + } + + fn moe_combine_seq(&self, x: u64, ye: u64, wts: u64, inv: u64, k: usize, sh: u64, sg: u64, n: usize, t: usize) -> anyhow::Result<()> { + launch!(self, "moe_combine_seq", Self::grid(n * t), x, ye, wts, inv, k as i32, sh, sg, n as i32, t as i32); + Ok(()) + } + + fn norm_gate(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32) -> anyhow::Result<()> { + self.norm_gate_q(o, w, z, n, heads, eps, 0).map(|_| ()) + } + + fn norm_gate_q(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32, xq: u64) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() || n % 32 != 0 { 0 } else { xq }; + launch!(self, "norm_gate", cfg((heads as u32, 1), 128, 0), o, w, z, n as i32, eps, xq, 0i32); + Ok(xq) + } + + fn norm_gate_sig(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32, xq: u64) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() || n % 32 != 0 { 0 } else { xq }; + launch!(self, "norm_gate", cfg((heads as u32, 1), 128, 0), o, w, z, n as i32, eps, xq, 1i32); + Ok(xq) + } + + fn hc_silu(&self, x: u64, sc: f32, n: usize) -> anyhow::Result<()> { + launch!(self, "hc_silu", Self::grid(n), x, sc, n as i32); + Ok(()) + } + + fn hc_mix(&self, xn: u64, g: u64, out: u64, n: usize, hc: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "hc_mix", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), xn, g, out, n as i32, hc as i32); + Ok(()) + } + + fn hc_write(&self, r: u64, out: u64, inj: u64, n: usize, hc: usize, nt: usize, clear: bool) -> anyhow::Result<()> { + launch!(self, "hc_write", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), r, out, inj, n as i32, hc as i32, clear as i32); + Ok(()) + } + + fn ple_gate(&self, key: u64, query: u64, value: u64, gated: u64, n: usize, hc: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ple_gate", cfg((hc as u32, nt as u32), 256, 0), key, query, value, gated, n as i32); + Ok(()) + } + + fn ple_conv(&self, r: u64, gated: u64, norm: u64, kw: u64, ring: u64, step: u64, d: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ple_conv", Self::grid(d), r, gated, norm, kw, ring, step, d as i32, nt as i32); + Ok(()) + } + + fn kv_store(&self, k: u64, v: u64, kc: u64, vc: u64, n: usize, t: usize, step: u64, hd: usize) -> anyhow::Result<()> { + anyhow::ensure!(!self.kv_q8 || (hd % 32 == 0 && n % hd == 0), "q8 KV cache: head_dim {hd} is not a multiple of 32"); + launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + Ok(()) + } + + fn attn_decode_gq(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, + scale: f32, gq_min: i32, nt: usize, sink: u64, win: usize) -> anyhow::Result<()> { + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, 0, 0, 0, sink, win, 0, ATT_SPLITS_1) + } + + fn attn_decode_q(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, + scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() { 0 } else { xq }; + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, xq, sel, sst, sink, win, 0, ATT_SPLITS_1)?; + Ok(xq) + } + + fn router_topk(&self, p: u64, n: usize, k: usize, extra_scale: f32, ids: u64, wts: u64, t: usize, sigmoid: bool) -> anyhow::Result<()> { + anyhow::ensure!(n <= 512 && k <= 32, "router_topk: {n} experts, top {k}"); + launch!(self, "router_topk", cfg((t as u32, 1), 32, 0), p, n as i32, k as i32, extra_scale, ids, wts, sigmoid as i32); + Ok(()) + } + + fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, + mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool) -> anyhow::Result<()> { + anyhow::ensure!(n <= 512 && k <= 32, "moe_route: {n} experts, top {k}"); + launch!(self, "moe_route", cfg((1, 1), 256, 0), p, n as i32, k as i32, extra_scale, table, ids, wts, slots, wh, h, mb, + nh as i32, h_off as i32, step, t as i32, pid, sigmoid as i32); + Ok(()) + } + + fn moe_mailbox_optional(&self) -> bool { true } + fn moe_prefetch_supported(&self) -> bool { false } + + fn moe_combine(&self, x: u64, ye: u64, w: u64, k: usize, sh: u64, sg: u64, mb: u64, y_off: usize, step: u64, slots: u64, n: usize, t: usize) -> anyhow::Result<()> { + let mut c = Self::grid(n); + c.grid_dim.1 = t as u32; + launch!(self, "moe_combine", c, x, ye, w, k as i32, sh, sg, mb, y_off as i32, step, slots, n as i32); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The whole plumbing on the device: allocate, upload, launch a real kernel, read it back. `add` is the + /// simplest kernel in the file, so a failure here is the backend, not the math. + #[test] + fn add_kernel_round_trips() { + let g = match Gpu::new(0) { + Ok(g) => g, + Err(e) => { + eprintln!("skipping: HIP unavailable: {e:#}"); + return; + } + }; + let n = 1024; + let x: Vec = (0..n).map(|i| i as f32).collect(); + let y: Vec = (0..n).map(|i| 0.5 * i as f32).collect(); + let want: Vec = (0..n).map(|i| 1.5 * i as f32).collect(); + let g: &dyn Backend = &g; + let bx = g.alloc(4 * n).unwrap(); + let by = g.alloc(4 * n).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.put(&y, &by, 0).unwrap(); + // `Backend::add` is x += y, so the result lands in x. + g.add(bx.addr(), by.addr(), n).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bx, 0, n).unwrap(); + assert!(got.iter().zip(&want).all(|(a, b)| a == b), "first mismatch at {:?}", got.iter().zip(&want).position(|(a, b)| a != b)); + } + + /// `argmax_rows` on 64 rows, the most a batch step has. The partials are 8 bytes each, AMAX_PARTS per row; the + /// buffer used to be sized as if they were one byte, so rows past 8 wrote past its end. + #[test] + fn argmax_rows_takes_64_rows() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + 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 = (0..rows * n).map(|k| { let (r, i) = (k / n, k % n); ((i * 7919 + r * 31) % n) as f32 }).collect(); + let want: Vec = (0..rows).map(|r| { + let row = &x[r * n..(r + 1) * n]; + let mut best = 0; + for i in 1..n { if row[i] > row[best] { best = i; } } + best as i32 + }).collect(); + let bx = g.alloc(4 * rows * n).unwrap(); + let bo = g.alloc(4 * rows).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.argmax_rows(bx.addr(), n, rows, bo.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bo, 0, rows).unwrap(); + assert_eq!(got, want); + } + + /// `argmax_rows` on values 0..16, so most rows tie for the maximum: the first index wins, as in the CPU reference. + #[test] + fn argmax_rows_breaks_ties_at_the_first_index() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (rows, n) = (64usize, 1000usize); + let mut st = 77u32; + let x: Vec = (0..rows * n).map(|_| { st = st.wrapping_mul(1664525).wrapping_add(1013904223); ((st >> 16) % 16) as f32 }).collect(); + let want: Vec = (0..rows).map(|r| { + let row = &x[r * n..(r + 1) * n]; + let mut best = 0; + for i in 1..n { if row[i] > row[best] { best = i; } } + best as i32 + }).collect(); + assert!(want.iter().enumerate().any(|(r, &b)| x[r * n..(r + 1) * n].iter().filter(|&&v| v == x[r * n + b as usize]).count() > 1), "no row has a tie"); + let bx = g.alloc(4 * rows * n).unwrap(); + let bo = g.alloc(4 * rows).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.argmax_rows(bx.addr(), n, rows, bo.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bo, 0, rows).unwrap(); + assert_eq!(got, want); + } + + /// `--backend hip` reaches this backend through `backend::open`, the path the CLI takes. + #[test] + fn opens_through_backend_open() { + let Ok(b) = crate::backend::open(Some("hip"), 0) else { eprintln!("skipping: no HIP device"); return }; + assert_eq!(b.name(), "hip"); + } + + /// `norm_gate` with the quantize-to-int8 epilogue: the first kernel of the qwen35 attention layer, and the one + /// that faulted first on the card, so it gets its own comparison against the reference math. + #[test] + fn norm_gate_matches_the_reference() { + let g = match Gpu::new(0) { Ok(g) => g, Err(e) => { eprintln!("skipping: HIP unavailable: {e:#}"); return } }; + let (heads, n) = (4usize, 128usize); + let mut st = 12345u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 8) as f32 / 16777216.0 - 0.5 }; + let o: Vec = (0..heads * n).map(|_| rnd()).collect(); + let w: Vec = (0..n).map(|_| rnd() + 1.0).collect(); + let z: Vec = (0..heads * n).map(|_| rnd()).collect(); + let want: Vec = (0..heads).flat_map(|h| { + let row = &o[h * n..(h + 1) * n]; + let ss: f32 = row.iter().map(|v| v * v).sum(); + let sc = 1.0 / (ss / n as f32 + 1e-6).sqrt(); + let silu = |v: f32| v / (1.0 + (-v).exp()); + (0..n).map(|i| row[i] * sc * w[i] * silu(z[h * n + i])).collect::>() + }).collect(); + let gx = g.alloc(4 * heads * n).unwrap(); + let gw = g.alloc(4 * n).unwrap(); + let gz = g.alloc(4 * heads * n).unwrap(); + let xq_bytes = heads * n + heads * n / 32 * 4; + let gxq = g.alloc(xq_bytes).unwrap(); + let g: &dyn Backend = &g; + g.put(&o, &gx, 0).unwrap(); + g.put(&w, &gw, 0).unwrap(); + g.put(&z, &gz, 0).unwrap(); + g.norm_gate(gx.addr(), gw.addr(), gz.addr(), n, heads, 1e-6).unwrap(); + g.sync().unwrap(); + eprintln!("plain norm_gate ok: {:?}", &g.get::(&gx, 0, 2).unwrap()); + g.put(&o, &gx, 0).unwrap(); + g.norm_gate_q(gx.addr(), gw.addr(), gz.addr(), n, heads, 1e-6, gxq.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&gx, 0, heads * n).unwrap(); + let worst = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst < 2e-5, "max |diff| = {worst}"); + } + + /// `gemm_dense` against a CPU product, both tile regimes: the 16-position warp tile (`SM`) the small shapes take + /// and the 32-position one, which is what the matrix-core path in `gemm_q` computes. + #[test] + fn gemm_dense_matches_cpu_in_both_tile_regimes() { + let Ok(g) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + for (rows, n, cols) in [(128usize, 64usize, 64usize), (8192, 128, 64)] { + let mut st = 7u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let w: Vec = (0..rows * cols).map(|_| rnd()).collect(); + let x: Vec = (0..n * cols).map(|_| rnd()).collect(); + let mut want = vec![0f32; n * rows]; + for m in 0..n { + for r in 0..rows { + let mut a = 0f32; + for k in 0..cols { a += x[m * cols + k] * w[r * cols + k]; } + want[m * rows + r] = a; + } + } + let gw = g.alloc(4 * rows * cols).unwrap(); + let gx = g.alloc(4 * n * cols).unwrap(); + let gy = g.alloc(4 * n * rows).unwrap(); + let g: &dyn Backend = &g; + g.put(&w, &gw, 0).unwrap(); + g.put(&x, &gx, 0).unwrap(); + let t = GpuTensor::new(GgmlType::F32, rows, cols, gw); + g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, 0).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&gy, 0, n * rows).unwrap(); + // A batch step's flag picks no other kernel here, so it gives the same bits. The host masks the flag off + // (`act & 3`), so this call stores over y. If the flag ever reached the kernel as `act` 8, the kernel would add + // to the ones and the bit comparison below would fail. + g.put(&vec![1f32; n * rows], &gy, 0).unwrap(); + g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, crate::backend::BATCHED).unwrap(); + g.sync().unwrap(); + let batched: Vec = g.get(&gy, 0, n * rows).unwrap(); + assert!(got.iter().zip(&batched).all(|(a, b)| a.to_bits() == b.to_bits()), "rows {rows}: BATCHED changed the result"); + let mut worst = 0f32; + let mut at = 0; + for i in 0..n * rows { + let d = (got[i] - want[i]).abs(); + if d > worst { worst = d; at = i; } + } + // f32 products summed over 64 terms: a few ulps either way, and f16 inputs quantize harder, so compare by + // relative error against the magnitude of the row's terms. + assert!(worst < 1e-2 * cols as f32, "rows {rows}: max |diff| = {worst} at {at} (got {}, want {})", got[at], want[at]); + } + } + + /// `attn_prefill_t` end to end (score product, causal softmax, P·V, the epilogue) against a CPU reference, at + /// head_dim 128 with three query tiles and five key tiles and at head_dim 256 (the HIP build's 16-key tiles). + /// A wrong lane/lane-staging mapping, a lost half of a fragment or a missing key shows up as a large per-element + /// difference on a specific query or head — which is how the transposed-V bug below was found — rather than as + /// the near-tie token flip a parity run sees. + #[test] + fn attn_prefill_matches_cpu() { + use half::f16; + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (nh, nkv) = (4usize, 2usize); + for (hd, t) in [(128usize, 130usize), (256, 70)] { + let scale = 1.0 / (hd as f32).sqrt(); + let mut st = 99u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let q: Vec = (0..t * nh * hd).map(|_| rnd()).collect(); + let kh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let vh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let half = |h: u16| f16::from_bits(h).to_f32(); + // Reference: the kernel scales Q before rounding it to f16, sums in f32, rounds the weights to f16 to + // feed P·V, and divides by the row sum at the end (`out = o * inv` with `inv = sc / den`). + let mut want = vec![0f32; t * nh * hd]; + for h in 0..nh { + let kvh = h / (nh / nkv); + for ti in 0..t { + let mut sc = vec![0f32; ti + 1]; + for (j, s) in sc.iter_mut().enumerate() { + let mut a = 0f32; + for d in 0..hd { + a += half(f16::from_f32(q[ti * nh * hd + h * hd + d] * scale).to_bits()) + * half(kh[(j * nkv + kvh) * hd + d]); + } + *s = a; + } + let mx = sc.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let e: Vec = sc.iter().map(|s| (s - mx).exp()).collect(); + let den: f32 = e.iter().sum(); + for d in 0..hd { + let mut a = 0f32; + for (j, w) in e.iter().enumerate() { + a += half(f16::from_f32(w / den).to_bits()) * half(vh[(j * nkv + kvh) * hd + d]); + } + want[ti * nh * hd + h * hd + d] = a; + } + } + } + let gq = g.alloc(4 * q.len()).unwrap(); + let gk = g.alloc(2 * kh.len()).unwrap(); + let gv = g.alloc(2 * vh.len()).unwrap(); + let go = g.alloc(4 * q.len()).unwrap(); + let gs = g.alloc(4).unwrap(); + g.put(&q, &gq, 0).unwrap(); + g.put(&kh, &gk, 0).unwrap(); + g.put(&vh, &gv, 0).unwrap(); + g.put(&[0i32], &gs, 0).unwrap(); + g.attn_prefill_m(gq.addr(), gk.addr(), gv.addr(), 0, go.addr(), gs.addr(), t, nh, nkv, hd, scale, 0, 0, 0, 0).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&go, 0, q.len()).unwrap(); + let mut worst = 0f32; + let (mut at, mut gv_) = (0, 0f32); + for i in 0..q.len() { + let d = (got[i] - want[i]).abs(); + if d > worst { worst = d; at = i; gv_ = got[i]; } + } + eprintln!("hd {hd} T {t}: max |diff| = {worst:e} at {at} (row {}, head {}, d {}): got {gv_} want {}", + at / (nh * hd), (at / hd) % nh, at % hd, want[at]); + assert!(worst < 5e-3, "hd {hd}: max |diff| = {worst} at {at}"); + } + } + + /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). + #[test] + fn hiprtc_compiles_the_kernels() { + let Ok(rtc) = ffi::Rtc::get() else { + eprintln!("skipping: no hiprtc"); + return; + }; + let Ok(hip) = ffi::Hip::open() else { + eprintln!("skipping: no HIP runtime"); + return; + }; + let arch = hip.arch(0).unwrap(); + rtc.compile(&source(false), "kernels.cu", &arch, &[]).expect("hiprtc compiles kernels.cu for the device"); + } + + /// The gfx11 (RDNA3) WMMA branch compiles, whatever card is present: its intrinsics, operand width and + /// `STRATA_WMMA_ROW` layout differ from gfx12's. Numerics on gfx11 need an RDNA3 card to check. + #[test] + fn hiprtc_compiles_the_kernels_for_gfx11() { + let Ok(rtc) = ffi::Rtc::get() else { + eprintln!("skipping: no hiprtc"); + return; + }; + rtc.compile(&source(false), "kernels.cu", "gfx1100", &[]).expect("hiprtc compiles kernels.cu for gfx1100"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 54f6a169..2af3bcb9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ pub mod model; pub mod backend; pub mod cuda; pub mod vulkan; +pub mod hip; pub mod gpu_model; pub mod cpu_moe; pub mod expert_cache; diff --git a/src/main.rs b/src/main.rs index 30f8ee18..00314b51 100644 --- a/src/main.rs +++ b/src/main.rs @@ -146,7 +146,7 @@ struct Engine { /// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16). #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2"])] kv: String, - /// GPU backend: cuda or vulkan [default: cuda if it loads, else vulkan]. + /// GPU backend: cuda, vulkan or hip [default: cuda if it loads, else vulkan]. #[arg(long)] backend: Option, /// GPU index, or several separated by commas (such as 0,1) to split the layers over those GPUs in proportion to @@ -394,7 +394,7 @@ impl Engine { } if self.llama_numerics { unsafe { std::env::set_var("STRATA_LLAMA_NUMERICS", "1") } } // read by Gpu::new 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::>>(); + let open = || backend::open_all(self.backend.as_deref(), &self.device); let bk = match self.gpu.then(open).transpose() { Err(e) if self.cpu_fallback => { say!("no GPU backend ({e:#}), running on the CPU"); None } r => r?, @@ -2090,6 +2090,7 @@ fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { /// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use /// the measured draft count. fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> 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)?; let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; @@ -2100,7 +2101,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 { - let bk = device.iter().map(|&d| backend::open(kind, d)).collect::>>()?; + let bk = backend::open_all(kind, device)?; let mut gm = GpuModel::load_split_margins(&m, bk, ctx, chunk, margin, split, kload, 1).context(LOAD_HINT)?; gm.adapt_every = 0; // fixed placement: steadier timings Ok(gm) diff --git a/tools/hip/README.md b/tools/hip/README.md new file mode 100644 index 00000000..4ddd5b3a --- /dev/null +++ b/tools/hip/README.md @@ -0,0 +1,22 @@ +# HIP micro-benchmarks + +Device-side probes behind the decisions in `docs/HIP.md`. Build and run with the ROCm compiler; they need no model and +no RustingStrata binary: + +```sh +hipcc --offload-arch=gfx1201 -O3 wmma_rate.cpp -o wmma_rate && ./wmma_rate +hipcc --offload-arch=gfx1201 -O3 wmma_rescale.cpp -o wmma_rescale && ./wmma_rescale +``` + +- `deltanet.cpp`: the gated delta-rule scan (`deltanet_seq`) alone, at the 35B model's shape, with the variants that + were tried against it: fewer, fatter lanes, two accumulators a dot sum, the loop's address math hoisted into + pointer increments, and two ablations (the per-token `expf`, the two warp reductions). All of them are neutral or + slower; the reads are free (a variant that re-reads token 0 every step is as fast), and the reductions plus the + exp are the only parts with headroom — which is the chunked WY form's job, not a rearrangement of the scan. The + file's header carries the numbers. +- `wmma_rate.cpp`: the matrix-core instruction rate of the two operand types, operands in registers, so the numbers + are the instruction rate and not memory bandwidth. On RX 9070 XT (gfx1201): f16 57 TMAC/s, int8 137 TMAC/s. +- `wmma_rescale.cpp`: the inner-loop shape of the prefill GEMM (`gemm_q`: 2x2 tiles of 16x16, four 16-deep k-steps per + BK = 64, fragments from shared memory), as f16 and as int8 with the epilogue the integer weight formats need. The + int8 instruction is twice as fast on its own (0.35x the time) but the per-16-weight rescale takes it to 6.6x the f16 + time even written SoA with 8 rows contiguous per lane, which is why the HIP backend keeps the f16 matrix-core path. diff --git a/tools/hip/deltanet.cpp b/tools/hip/deltanet.cpp new file mode 100644 index 00000000..febc8bdd --- /dev/null +++ b/tools/hip/deltanet.cpp @@ -0,0 +1,246 @@ +// deltanet_seq (the gated delta-rule scan that Qwen3.6/3.8's linear-attention layers run in prefill) in isolation. +// Answering "can this kernel be made faster without changing the algorithm", with numbers instead of guesses: a +// model-level prefill A/B cannot resolve a 5% change (two runs of the same build differ by more), so the variants are +// timed here. Fixed shape of the 35B model: dk 128, nk 16, nv 32, dv 128, T 4096, i.e. 128 blocks of 256 threads. +// +// hipcc --offload-arch=gfx1201 -O3 deltanet.cpp -o deltanet && ./deltanet +// +// Measured on RX 9070 XT (3.11 ms for one layer's scan over 4096 tokens, ~1750 cycles a token; the ratios move by +// +-4% between runs, so treat anything under 5% as noise): +// +// base 3.11 ms 1.00x deltanet_seq as committed +// dn16 (running pointers) 3.26 ms 0.93x the loop's `tok * stride` products hoisted into pointer increments +// dn16s (+ 2 accumulators) 3.22 ms 0.96x one chain of 16 dependent adds split in two +// dn32 (32 floats a lane) 3.84 ms 0.81x half the blocks (one wave on 60 CUs), twice the work a lane +// dn32s 3.73 ms 0.83x +// no expf(g) per token 2.76 ms 1.12x the per-token decay, which only half the calls need as an exp +// no warp reductions 2.33 ms 1.33x both dependent shuffle rounds removed (wrong results, timing only) +// same q/k/v every step 3.13 ms 0.99x per-token reads held in L1: the strided, 128-block-redundant reads +// cost nothing, so this kernel is latency, not bandwidth +// +// So: no rearrangement of the scan wins (several lose), the reads are free, and the 33% inside reach is the two +// dependent shuffle rounds plus the per-token exp -- both of which only disappear if the per-token recurrence +// becomes a chunked one (the WY/UT-transform form: a triangular inverse and matmuls over a chunk, and with f16 +// tensor cores it would lose state precision). 12% of a 4096-token prefill is in this kernel, so the whole +// theoretical prize is ~4% prefill for that rewrite. Left alone deliberately. +#include +#include +#include +#include +#include +typedef unsigned short u16; +__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } +__device__ __forceinline__ float softplus(float x) { return x > 20.0f ? x : log1pf(expf(x)); } +// kernels.cu's HIP shim routes the mask-less form here; the HIP builtin itself wants a 64-bit mask. +template __device__ __forceinline__ T shflx(T v, int off) { return __shfl_xor(v, off, 32); } +__global__ void dn_base(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + int L = dk >> 4, R = 32 / L, lane = threadIdx.x & 31, s = lane % L, vh = blockIdx.x, kh = ilv ? vh / (nv / nk) : vh % nk; + int j0 = (blockIdx.y * 8 + (threadIdx.x >> 5)) * R, j = j0 + lane / L; + if (j0 >= dv) return; // whole warp past the end (R divides dv) + float4* row = (float4*)(S + ((size_t)vh * dv + j) * dk); + float r[16]; +#pragma unroll + for (int i = 0; i < 4; i++) { float4 v = row[s + L * i]; r[4 * i] = v.x; r[4 * i + 1] = v.y; r[4 * i + 2] = v.z; r[4 * i + 3] = v.w; } + // Token inputs do not depend on the state: token tok + 1's are loaded while token tok computes. + float nk_[16], nq[16], ng, nb, nvv; + auto ld = [&](int tok) { + const float* yt = y + (size_t)tok * ych; + const float4* q4 = (const float4*)(yt + kh * dk); + const float4* k4 = (const float4*)(yt + nk * dk + kh * dk); +#pragma unroll + for (int i = 0; i < 4; i++) { + float4 v = k4[s + L * i]; nk_[4 * i] = v.x; nk_[4 * i + 1] = v.y; nk_[4 * i + 2] = v.z; nk_[4 * i + 3] = v.w; + v = q4[s + L * i]; nq[4 * i] = v.x; nq[4 * i + 1] = v.y; nq[4 * i + 2] = v.z; nq[4 * i + 3] = v.w; + } + ng = g[tok * nv + vh]; nb = beta[tok * nv + vh]; nvv = yt[2 * nk * dk + vh * dv + j]; + if (dtb) { ng = softplus(ng + dtb[vh]) * ga[vh]; nb = sigmoid(nb); } + }; + ld(0); + for (int tok = 0; tok < T; tok++) { + float kk[16], qv[16], decay = expf(ng), bt = nb, vt = nvv, sk = 0.0f, oq = 0.0f; +#pragma unroll + for (int e = 0; e < 16; e++) { kk[e] = nk_[e]; qv[e] = nq[e]; } + if (tok + 1 < T) ld(tok + 1); +#pragma unroll + for (int e = 0; e < 16; e++) { r[e] *= decay; sk += r[e] * kk[e]; } + for (int off = L >> 1; off; off >>= 1) sk += shflx(sk, off); + float d = bt * (vt - sk); +#pragma unroll + for (int e = 0; e < 16; e++) { r[e] += d * kk[e]; oq += r[e] * qv[e]; } + for (int off = L >> 1; off; off >>= 1) oq += shflx(oq, off); + if (s == 0) o[(size_t)tok * nv * dv + vh * dv + j] = oq * scale; + if (tok < min(nsnap, T - 1)) { + float4* sr = (float4*)(snap + (size_t)tok * nv * dv * dk + ((size_t)vh * dv + j) * dk); +#pragma unroll + for (int i = 0; i < 4; i++) sr[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + } + } +#pragma unroll + for (int i = 0; i < 4; i++) row[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); +} + +template +__device__ __forceinline__ void dn_opt(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + int L = dk / DNP, R = 32 / L, lane = threadIdx.x & 31, s = lane % L, vh = blockIdx.x, kh = ilv ? vh / (nv / nk) : vh % nk; + int j0 = (blockIdx.y * (int)(blockDim.x >> 5) + (threadIdx.x >> 5)) * R, j = j0 + lane / L; + if (j0 >= dv) return; // whole warp past the end (R divides dv) + float4* row = (float4*)(S + ((size_t)vh * dv + j) * dk); + float r[DNP]; +#pragma unroll + for (int i = 0; i < DNP / 4; i++) { float4 v = row[s + L * i]; r[4 * i] = v.x; r[4 * i + 1] = v.y; r[4 * i + 2] = v.z; r[4 * i + 3] = v.w; } + // Running pointers, one step per token: the loop body used to recompute `tok * stride` (and the 64-bit + // multiplies and divides that drag in) for every operand, which was most of its instruction count. + const float4* kp = (const float4*)(y + (size_t)kh * dk); // chunk s + L*i of this lane's row + const float4* qp = (const float4*)(y + (size_t)(nk + kh) * dk); + const float* vp = y + (size_t)2 * nk * dk + (size_t)vh * dv + j; // token's v[j] + const float* gp = g + vh, *bp = beta + vh; // this head's decay gate and beta + float* op = o + (size_t)vh * dv + j; // token's output element + float* sp = snap + (size_t)((size_t)vh * dv + j) * dk; // snapshot of this lane's chunks + const int kstep = ych / 4, snapstep = nv * dv * dk; + const int ns = min(nsnap, T - 1); + // Token inputs do not depend on the state: token tok + 1's are loaded while token tok computes. + float nk_[DNP], nq[DNP], ng, nb, nvv; + auto ld = [&]() { +#pragma unroll + for (int i = 0; i < DNP / 4; i++) { + float4 v = kp[s + L * i]; nk_[4 * i] = v.x; nk_[4 * i + 1] = v.y; nk_[4 * i + 2] = v.z; nk_[4 * i + 3] = v.w; + v = qp[s + L * i]; nq[4 * i] = v.x; nq[4 * i + 1] = v.y; nq[4 * i + 2] = v.z; nq[4 * i + 3] = v.w; + } + ng = *gp; nb = *bp; nvv = *vp; + if constexpr (false) { ng = softplus(ng + dtb[vh]) * ga[vh]; nb = sigmoid(nb); } + kp += kstep; qp += kstep; gp += nv; bp += nv; vp += ych; + }; + ld(); + for (int tok = 0; tok < T; tok++) { + float kk[DNP], qv[DNP], decay = PROBE == 1 ? 0.99f : expf(ng), bt = nb, vt = nvv, sk = 0.0f, oq = 0.0f; +#pragma unroll + for (int e = 0; e < DNP; e++) { kk[e] = nk_[e]; qv[e] = nq[e]; } + if (tok + 1 < T) ld(); + float sk1 = 0.0f, oq1 = 0.0f; + if constexpr (SPLIT) { +#pragma unroll + for (int e = 0; e < DNP; e += 2) { r[e] *= decay; r[e + 1] *= decay; sk += r[e] * kk[e]; sk1 += r[e + 1] * kk[e + 1]; } + sk += sk1; + } else { +#pragma unroll + for (int e = 0; e < DNP; e++) { r[e] *= decay; sk += r[e] * kk[e]; } + } + if (PROBE != 2) for (int off = L >> 1; off; off >>= 1) sk += shflx(sk, off); + float d = bt * (vt - sk); + if constexpr (SPLIT) { +#pragma unroll + for (int e = 0; e < DNP; e += 2) { r[e] += d * kk[e]; r[e + 1] += d * kk[e + 1]; oq += r[e] * qv[e]; oq1 += r[e + 1] * qv[e + 1]; } + oq += oq1; + } else { +#pragma unroll + for (int e = 0; e < DNP; e++) { r[e] += d * kk[e]; oq += r[e] * qv[e]; } + } + if (PROBE != 2) for (int off = L >> 1; off; off >>= 1) oq += shflx(oq, off); + if (s == 0) *op = oq * scale; + if (tok < ns) { + float4* sr = (float4*)sp; +#pragma unroll + for (int i = 0; i < DNP / 4; i++) sr[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + } + op += nv * dv; sp += snapstep; + } +#pragma unroll + for (int i = 0; i < DNP / 4; i++) row[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); +} + +__global__ void dn16(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, false>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn32(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<32, false>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn16s(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, true>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn32s(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<32, true>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} + +__global__ void dn16x(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, false, 1>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn16r(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, false, 2>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +// --------------------------------------------------------------------------------------------------------------- +constexpr int DKN = 128, NKN = 16, NVN = 32, DVN = 128, TN = 4096, YCH = NVN * DVN + 2 * NKN * DKN; +struct Args { + std::vector y, S, beta, g, o; + float *dy, *dS, *dbeta, *dg, *dout, *dsnap; +}; +static void init(Args& a) { + size_t ny = (size_t)TN * YCH; + a.y.assign(ny, 0.f); a.S.assign((size_t)NVN * DVN * DKN, 0.f); + a.beta.assign(TN * NVN, 0.f); a.g.assign(TN * NVN, 0.f); a.o.assign((size_t)TN * NVN * DVN, 0.f); + srand(1234); + auto rnd = [] { return (float)rand() / 2147483647.f - 0.5f; }; + for (auto& v : a.y) v = rnd(); + for (auto& v : a.S) v = rnd() * 0.1f; + for (auto& v : a.beta) v = rnd(); + for (auto& v : a.g) v = -0.01f - fabsf(rnd()) * 0.02f; // decay < 1: a real gated delta rule + hipMalloc(&a.dy, ny * 4); hipMalloc(&a.dS, a.S.size() * 4); hipMalloc(&a.dbeta, a.beta.size() * 4); + hipMalloc(&a.dg, a.g.size() * 4); hipMalloc(&a.dout, a.o.size() * 4); hipMalloc(&a.dsnap, 4); + hipMemcpy(a.dy, a.y.data(), ny * 4, hipMemcpyHostToDevice); + hipMemcpy(a.dbeta, a.beta.data(), a.beta.size() * 4, hipMemcpyHostToDevice); + hipMemcpy(a.dg, a.g.data(), a.g.size() * 4, hipMemcpyHostToDevice); +} +struct Res { float ms; std::vector out; }; +template static Res run(K k, Args& a, int dnp, int ych = YCH) { + int rows = 32 * dnp / DKN, gy = DVN / (8 * rows); + dim3 grid(NVN, gy), block(256); + auto launch = [&] { k<<>>(a.dy, a.dS, a.dbeta, a.dg, a.dout, NKN, NVN, 0, DKN, DVN, 1.0f / sqrtf(DKN), TN, ych, a.dsnap, 0, nullptr, nullptr); }; + hipMemcpy(a.dS, a.S.data(), a.S.size() * 4, hipMemcpyHostToDevice); + hipMemset(a.dout, 0, a.o.size() * 4); + launch(); hipDeviceSynchronize(); + hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1); + const int reps = 10; + hipEventRecord(e0); + for (int i = 0; i < reps; i++) launch(); + hipEventRecord(e1); hipEventSynchronize(e1); + float ms = 0; hipEventElapsedTime(&ms, e0, e1); + hipMemcpy(a.o.data(), a.dout, a.o.size() * 4, hipMemcpyDeviceToHost); + return {ms / reps, a.o}; +} +int main() { + Args a; init(a); + Res ref = run(dn_base, a, 16); + printf("%-10s %8.3f ms %5.2fx max |reldiff| vs base\n", "base", ref.ms, 1.0); + struct V { const char* name; void (*k)(const float*, float*, const float*, const float*, float*, int, int, int, int, int, float, int, int, float*, int, const float*, const float*); int dnp; }; + V vs[] = {{"dn16", dn16, 16}, {"dn16s", dn16s, 16}, {"dn32", dn32, 32}, {"dn32s", dn32s, 32}, + {"no expf(g)", dn16x, 16}, {"no reductions", dn16r, 16}}; + for (auto& v : vs) { + Res r = run(v.k, a, v.dnp); + double worst = 0; + for (size_t i = 0; i < ref.out.size(); i++) { + double d = ref.out[i] != 0 ? fabs((ref.out[i] - r.out[i]) / ref.out[i]) : fabs(ref.out[i] - r.out[i]); + if (d > worst) worst = d; + } + printf("%-13s %8.3f ms %5.2fx %.2e\n", v.name, r.ms, ref.ms / r.ms, worst); + } + // The same scan with every token reading token 0's q/k/v (ych = 0): the per-token reads then stay in L1, which + // separates "cost of the data" from "cost of the strided, 128-blocks-redundant reads". + Res l1 = run(dn16, a, 16, 0); + printf("%-10s %8.3f ms %5.2fx (same token's q/k/v every step)\n", "dn16-l1", l1.ms, ref.ms / l1.ms); + return 0; +} diff --git a/tools/hip/wmma_rate.cpp b/tools/hip/wmma_rate.cpp new file mode 100644 index 00000000..9cd2561e --- /dev/null +++ b/tools/hip/wmma_rate.cpp @@ -0,0 +1,42 @@ +// Isolated matrix-core rate: f16 WMMA vs int8 WMMA, same 16x16x16 shape, operands in registers so the number is the +// instruction rate, not memory bandwidth. +#include +#include +using h8 = _Float16 __attribute__((ext_vector_type(8))); +using f8 = float __attribute__((ext_vector_type(8))); +using i8v = int __attribute__((ext_vector_type(8))); +using b8 = int __attribute__((ext_vector_type(2))); // 8 int8 values + +__global__ void f16_loop(float* out, int iters) { + h8 a, b; f8 c; + for (int i = 0; i < 8; i++) { a[i] = (_Float16)i * 0.001f; b[i] = (_Float16)i * 0.002f; c[i] = 0.f; } + for (int t = 0; t < iters; t++) { c = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); a[0] += 1e-7f; } + float s = 0; for (int i = 0; i < 8; i++) s += c[i]; + if (threadIdx.x == 0) out[blockIdx.x] = s; +} +__global__ void i8_loop(float* out, int iters) { + b8 a = {0x01020304, 0x05060708}; + b8 b = {0x11121314, 0x15161718}; + i8v c; for (int i = 0; i < 8; i++) c[i] = 0; + for (int t = 0; t < iters; t++) { c = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, true, b, c, false); a[0] ^= 1; } + int s = 0; for (int i = 0; i < 8; i++) s += c[i]; + if (threadIdx.x == 0) out[blockIdx.x] = (float)s; +} +template static float run(K k, int blocks, int iters) { + float* out; hipMalloc(&out, blocks * 4); + hipEvent_t a, b; hipEventCreate(&a); hipEventCreate(&b); + k<<>>(out, 16); // warm up + hipDeviceSynchronize(); + hipEventRecord(a); k<<>>(out, iters); hipEventRecord(b); hipEventSynchronize(b); + float ms = 0; hipEventElapsedTime(&ms, a, b); + hipFree(out); + double macs = (double)blocks * 2.0 * 4096.0 * iters; // 2 warps a block, 16x16x16 + return (float)(macs / (ms * 1e-3) / 1e12); +} +int main() { + int iters = 20000; + for (int blocks : {256, 1024}) { + printf("blocks %4d: f16 %.3f TMAC/s | i8 %.3f TMAC/s\n", blocks, run(f16_loop, blocks, iters), run(i8_loop, blocks, iters)); + } + return 0; +} diff --git a/tools/hip/wmma_rescale.cpp b/tools/hip/wmma_rescale.cpp new file mode 100644 index 00000000..6b85583a --- /dev/null +++ b/tools/hip/wmma_rescale.cpp @@ -0,0 +1,166 @@ +// Inner-loop shapes of the prefill GEMM: f16 WMMA vs int8 WMMA with the per-16 rescale fold that int8 needs. +// Both read their fragments from the same shared-memory tiles and run 16 WMMA per k-step (2x2 tiles of 16x16, 4 +// k-groups), which is one GEMM_TC step of the 128-thread warp tile. +#include +#include +using h8 = _Float16 __attribute__((ext_vector_type(8))); +using f8 = float __attribute__((ext_vector_type(8))); +using b8 = int __attribute__((ext_vector_type(2))); +using i8v = int __attribute__((ext_vector_type(8))); + +#define P 72 +__global__ void f16_loop(float* out, int iters) { + __shared__ __align__(16) _Float16 xs[128 * P], ws[64 * P]; + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xs[i] = (_Float16)(i & 7) * 0.01f; + for (int i = tid; i < 64 * P; i += blockDim.x) ws[i] = (_Float16)(i & 7) * 0.01f; + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, w0 = (lane >> 4) * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + f8 acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0.f; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int kk = 0; kk < 64; kk += 16) { + h8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint4*)&a[mt] = *(const uint4*)(xs + (wm + mt * 16 + l16) * P + kk + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint4*)&b[nt] = *(const uint4*)(ws + (wn + nt * 16 + l16) * P + kk + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) for (int nt = 0; nt < 2; nt++) + acc[mt * 2 + nt] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a[mt], b[nt], acc[mt * 2 + nt]); + } + } + float s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = s; +} +__global__ void i8_loop(float* out, int iters) { + __shared__ __align__(16) signed char xq[128 * P], wq[64 * P]; + __shared__ float xd[128][2], xs2[128][4]; // X scale per 32 keys, X sums per 16 keys + __shared__ float2 wdm[4][64]; // W scale and min per 16 weights + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xq[i] = (signed char)(i & 31); + for (int i = tid; i < 64 * P; i += blockDim.x) wq[i] = (signed char)(i & 31); + for (int i = tid; i < 128; i += blockDim.x) { xd[i][0] = 0.01f; xd[i][1] = 0.02f; for (int j = 0; j < 4; j++) xs2[i][j] = 0.5f; } + for (int i = tid; i < 64; i += blockDim.x) for (int g = 0; g < 4; g++) wdm[g][i] = make_float2(0.01f, 0.3f); + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4, w0 = hi * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + f8 acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0.f; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int g = 0; g < 4; g++) { // 16-key groups = one weight scale + b8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint2*)&a[mt] = *(const uint2*)(xq + (wm + mt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint2*)&b[nt] = *(const uint2*)(wq + (wn + nt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) + #pragma unroll + for (int nt = 0; nt < 2; nt++) { + i8v c = {0,0,0,0,0,0,0,0}; + i8v r = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a[mt], true, b[nt], c, false); + float2 wq2 = wdm[g][wn + nt * 16 + l16]; + int base = wm + mt * 16 + 8 * hi; + f8 a4 = acc[mt * 2 + nt]; + #pragma unroll + for (int i = 0; i < 8; i++) { + float dx = xd[base + i][g >> 1]; + float sx = xs2[base + i][g]; + a4[i] += (float)r[i] * dx * wq2.x - sx * wq2.y; + acc[mt * 2 + nt] = a4; + } + } + } + } + float s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = s; +} + +__global__ void i8_nofold(float* out, int iters) { + __shared__ __align__(16) signed char xq[128 * P], wq[64 * P]; + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xq[i] = (signed char)(i & 31); + for (int i = tid; i < 64 * P; i += blockDim.x) wq[i] = (signed char)(i & 31); + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4, w0 = hi * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + i8v acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int g = 0; g < 4; g++) { + b8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint2*)&a[mt] = *(const uint2*)(xq + (wm + mt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint2*)&b[nt] = *(const uint2*)(wq + (wn + nt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) for (int nt = 0; nt < 2; nt++) + acc[mt * 2 + nt] = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a[mt], true, b[nt], acc[mt * 2 + nt], false); + } + } + int s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = (float)s; +} +// SoA fold: 8 rows of the lane are consecutive, so a scale is one 8-wide vector of separate arrays. +__global__ void i8_soa(float* out, int iters) { + __shared__ __align__(16) signed char xq[128 * P], wq[64 * P]; + __shared__ float dx0[128], sx0[128]; // X scale (one per 32 keys) and X sum (one per 16 keys) + __shared__ float2 wdm[4][64]; + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xq[i] = (signed char)(i & 31); + for (int i = tid; i < 64 * P; i += blockDim.x) wq[i] = (signed char)(i & 31); + for (int i = tid; i < 128; i += blockDim.x) { dx0[i] = 0.01f; sx0[i] = 0.5f; } + for (int i = tid; i < 64; i += blockDim.x) for (int g = 0; g < 4; g++) wdm[g][i] = make_float2(0.01f, 0.3f); + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4, w0 = hi * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + f8 acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0.f; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int g = 0; g < 4; g++) { + b8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint2*)&a[mt] = *(const uint2*)(xq + (wm + mt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint2*)&b[nt] = *(const uint2*)(wq + (wn + nt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) + #pragma unroll + for (int nt = 0; nt < 2; nt++) { + i8v c = {0,0,0,0,0,0,0,0}; + i8v r = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a[mt], true, b[nt], c, false); + float2 wq2 = wdm[g][wn + nt * 16 + l16]; + int base = wm + mt * 16 + 8 * hi; + const float* dx = dx0 + base; + const float* sx = sx0 + base; + f8 a4 = acc[mt * 2 + nt]; + #pragma unroll + for (int i = 0; i < 8; i++) a4[i] += (float)r[i] * dx[i] * wq2.x - sx[i] * wq2.y; + acc[mt * 2 + nt] = a4; + } + } + } + float s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = s; +} + +template static float run(K k, int blocks, int iters) { + float* out; hipMalloc(&out, blocks * 4); + hipEvent_t a, b; hipEventCreate(&a); hipEventCreate(&b); + k<<>>(out, 16); hipDeviceSynchronize(); + hipEventRecord(a); k<<>>(out, iters); hipEventRecord(b); hipEventSynchronize(b); + float ms = 0; hipEventElapsedTime(&ms, a, b); hipFree(out); + return (float)ms; +} +int main() { + int iters = 200000; + for (int blocks : {256, 1024}) { + float f = run(f16_loop, blocks, iters), i = run(i8_loop, blocks, iters); + float n = run(i8_nofold, blocks, iters), so = run(i8_soa, blocks, iters); + printf("blocks %4d: f16 %.2f | i8 nofold %.2f (%.2fx) | i8 SoA fold %.2f (%.2fx) | i8 scalar fold %.2f (%.2fx)\n", + blocks, f, n, n / f, so, so / f, i, i / f); + } + return 0; +}