diff --git a/CMakeLists.txt b/CMakeLists.txt index e0c61046..4c422bb3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -297,6 +297,14 @@ add_subdirectory(libquant) if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt) add_subdirectory(libr4d) endif() +# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP +# toolchain. It declares itself for `^gfx11` and returns without a target when the build's +# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it (and a card +# with no kernel library of its own keeps refusing device-only ops, which is the rule, not a +# regression: docs/PLUGIN.md §10). +if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt) + add_subdirectory(libr3d) +endif() # libavx: the production host kernels (x86 SIMD, dispatched by CPU feature), built on every x86-64. # Not optional: host-placed ops need a kernel other than the oracle (rad_gate_reference_kernels # refuses libref), and a table too large for the card, such as the n-gram embedding's gather, runs diff --git a/data/kbench_rows/kbench_rows_kernels_libr3d.txt b/data/kbench_rows/kbench_rows_kernels_libr3d.txt new file mode 100644 index 00000000..2dd4e49b --- /dev/null +++ b/data/kbench_rows/kbench_rows_kernels_libr3d.txt @@ -0,0 +1,36 @@ +# Kernel rows a replay of this fixture reaches (rad-kbench --coverage). +# A row listed here and not reached fails the replay; regenerate with +# --coverage-write when a row is added or deliberately retired. +add_bf16 +attn_paged_fp8_decode +cast_bf16_bf16 +dflash_select_bf16 +gated_quant_fp8_bf16 +gather_rows_bf16 +gemm_nt_bf16_m16 +gemm_nt_bf16_tiled +gemm_nt_q_fp8a8_m16 +gemm_nt_q_fp8a8_tiled +gemm_nt_q_gated_fp8a8 +kv_store_fp8 +layernorm_bf16 +quant_act_fp8_bf16 +quant_act_i8_bf16 +rmsnorm_bf16 +rmsnorm_quant_fp8_bf16 +rope_bf16 +row_topk_bf16 +sample_argmax_f32 +sample_dry_f32 +sample_logprobs_f32 +sample_mask_f32 +sample_minp_f32 +sample_penalties_f32 +sample_pick_f32 +sample_temp_f32 +sample_topk_f32 +sample_topp_f32 +sample_typical_f32 +sample_xtc_f32 +scatter_rows_bf16 +silu_mul_bf16 diff --git a/libr3d/CMakeLists.txt b/libr3d/CMakeLists.txt new file mode 100644 index 00000000..2a198858 --- /dev/null +++ b/libr3d/CMakeLists.txt @@ -0,0 +1,149 @@ +# libr3d serves RDNA3 only, declared here and nowhere else. Its kernels rely on wave32 and on +# instructions RDNA3 has: v_dot2acc_f32_f16 for the matrix work, v_cvt_pkrtz_f16_f32, DPP16 and +# v_permlanex16. They do not use the gfx12 WMMA fragment layouts or gfx12-only instructions such as +# global_load_tr_b128, and they decode every quantised weight in software, because RDNA3 has no +# fp8 conversion instruction and this ROCm declares no WMMA builtin for any gfx11 target. +# +# A build targeting other cards skips libr3d. The engine then has no device kernel library for that +# card and refuses ops only a reference library implements, unless +# --debug-accept-reference-kernels is passed (spec §17). The supported fix is a kernel library for +# that card; libr4d is that library for gfx12 and libr3d is it for gfx11. +# +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S libr3d -B build -DCMAKE_PREFIX_PATH=`, naming the HIP compiler as for +# the tree); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(libr3d LANGUAGES CXX HIP) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +# `^gfx11` is the family, not a chip: gfx1100, gfx1101, gfx1102, gfx1103, gfx1150, gfx1151 and the +# family target `gfx11-generic` all take these kernels, exactly as `^gfx12` covers RDNA4 for libr4d. +# The RDNA3 cards differ in CU count and clock, never in the instructions these kernels issue, so +# one code object per family serves the lot; a build that lists both a chip and the family gets +# both, and the engine picks the chip's object first (docs/PLUGIN.md §10). +rad_plugin_gpu_targets(R3D_GPU_TARGETS "^gfx11") +if(NOT R3D_GPU_TARGETS) + message(STATUS + "libr3d: RDNA3 (gfx11xx) only, and this build targets ${RAD_GPU_TARGETS} -- not built") + return() +endif() + +# R3D_UNITS is the definitive list of libr3d's device translation units, as "unit|extra flags". +# +# Every unit is compiled -ffp-contract=off, which rad_hipify puts on all HIP sources. It is not a +# style preference: libref accumulates in f32 with no FMA and no reassociation (ref_common.h), and +# a contracted device kernel disagrees with the oracle it is checked against. It also keeps the +# instruction counts quoted in kernel comments true. + +# Kernels and libr3d's declaration (row table, operand descriptions) share one directory. There is +# no launch adapter: every entry point takes `(const RadArgs*, RadStream)` and sits beside its +# kernel. The plugin links rad_abi only, like one written out of tree. + +set(R3D_UNITS + # The model's small ops, one workgroup per row: rmsnorm, layernorm, the binary and unary element + # ops, the activations, cast, softmax, embed_lookup, gather_rows and scatter_rows, rope and + # kv_store. This is the set the engine refuses on a card with no device kernel library. + "r3d_model_bf16|" + # The sampler's pre-filters: penalties, DRY, the n-gram ban, the bitmask, and the logprobs + # summary, which reads the logits plane once where the reference reads it three. + "r3d_sample_pre_f32|" + # The speculative decoder's accept step: a walk over the draft block's candidate lattice, which is + # a gather out of two codebooks rather than arithmetic. + "r3d_dflash_f32|" + # The gated MLP band: GEMM, gate and output quantiser in one launch, so the [M,N] intermediate the + # unfused chain writes and re-reads never exists. + "r3d_gemm_fp8a8_gated|" + # The vocab projection at decode: U2 codes, int8 activations, a joined scale+zero operand. + "r3d_gemm_nt_q_w2a8|" + # The vocabulary projection at both heights: the head streamed for M <= 16, tiled above it. + "r3d_vocab_bf16|" + # The quantised GEMM at prefill heights: the 176 bands a forward pass ran on the CPU. + "r3d_gemm_fp8a8_tiled|" + # The OCP-MXFP4 weight against the fp8 activation, both heights: e2m1 codes with one e8m0 scale + # per 32 of K, the block's partials scaled at the block boundary. + "r3d_gemm_mxfp4a8|" + "r3d_gemm_inta8|" + # Paged attention at head_dim 128: the decode leg (one head group a workgroup, 16-token tiles, + # split-KV) and the prefill leg (a 16-token query tile staged in LDS), over a bf16 or an E4M3 + # cache. The walk is shared; the tile is what a workgroup stages once and every wave consumes. + "r3d_attn_paged_h128|" + # The sampler's spine: the row's top-R in one scan, and the stages that turn the candidate plane + # the top-R produces into one token -- argmax, temp, top-k, the draw, and the four narrowings. + "r3d_sample_f32|" + # Activation quantisation: per-(row, group) symmetric E4M3 and int8, the gated form that + # quantises a silu-gated pair, and the dequantise that reads a container's own quantised weights. + "r3d_quant_fp8|" + # The skinny bf16 GEMM, M <= 16: one output element a lane, k ascending, so the accumulation order + # is libref's. The decode GEMM -- the op a token is made of. + "r3d_gemm_bf16_nt_m16|" + # The same shape over a block-scaled fp8 weight, decoded to f16 exactly (E4M3's four exponent bits + # and three mantissa bits are a subset of f16's), and over int8 codes. + "r3d_gemm_fp8a16_nt_m1|" + # Landing next, in the same shape as libr4d's: the prefill GEMM (an 8x8 tile a wave over LDS, the + # same dot2 inner product), paged causal attention (the decode leg split-KV, the prefill leg a + # query tile a workgroup, bf16 or fp8 KV), the vocab (logits as a GEMM over the embedding, the row + # top-k, the cross-rank top-1) and the sampler's stages. Their rows are not in r3d_rows.cpp yet, + # because a row naming an entry point that is not in the library is an undefined symbol and the + # plugin would fail to load, taking every other row with it. +) + +set(R3D_SRC "") +foreach(u ${R3D_UNITS}) + string(REPLACE "|" ";" parts "${u}") + list(GET parts 0 unit) + list(LENGTH parts n) + set(extra "") + if(n GREATER 1) + list(GET parts 1 extra) + endif() + set(src "${CMAKE_CURRENT_SOURCE_DIR}/${unit}.hip") + if(NOT EXISTS "${src}") + message(FATAL_ERROR "libr3d unit ${unit}.hip is missing from ${CMAKE_CURRENT_SOURCE_DIR}") + endif() + if(extra) + set_source_files_properties("${src}" PROPERTIES COMPILE_OPTIONS "${extra}") + endif() + list(APPEND R3D_SRC "${src}") +endforeach() + +# The host sources are declaration only: the row table, the operand descriptions and the fusion +# claims. They are pure host C++ that includes neither r3d.h nor hip_runtime.h, so these tables +# compile and can be inspected without ROCm. libr3d has no layout source: nothing it serves is +# repacked, because a dot2 GEMM reads a weight in the order it is stored (see r3d_rows.cpp). +# r3d_fuse.cpp joins the list with the first fused row: a `replaces` chain with no row naming it +# would be dead code, and the fused rmsnorm-then-quant kernel is the first one worth its bytes. +set(R3D_DECLARATION r3d_rows.cpp r3d_shapes.cpp) + +rad_add_plugin(libr3d kernels + SOURCES ${R3D_DECLARATION} + HIP_SOURCES ${R3D_SRC} + GPU_TARGETS ${R3D_GPU_TARGETS} + INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}) + +# rad_plugin_info's build_target is this build's own target list, spelled as the device reports its +# arch, because the loader warns when a plugin claims a card the running device is not +# (core/plugin/loader.cpp, target_covers). A library built for two archs says two. +string(REPLACE ";" " " R3D_BUILD_TARGET "${R3D_GPU_TARGETS}") +target_compile_definitions(libr3d PRIVATE R3D_BUILD_TARGET="${R3D_BUILD_TARGET}") + +# Catalogue dump: prints every row and, on a card, calls each launch with a minimal valid input, to +# catch transcription errors in the constraint table. It dlopens the plugin so an undefined symbol +# in the .so is caught too. +add_executable(r3d_selftest ${CMAKE_CURRENT_SOURCE_DIR}/r3d_selftest.cpp) +# Links the HIP runtime to allocate the device buffers it feeds the kernels. +target_link_libraries(r3d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME}) +target_include_directories(r3d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +# The device phase of the selftest -- the per-row launch -- is built only when the HIP runtime is +# there, which in this plugin's build it always is. +target_compile_definitions(r3d_selftest PRIVATE RAD_HAVE_HIP) +set_target_properties(r3d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +# Installed beside the tools, so the image can run the rows' own card checks without a build tree: +# r3d_selftest /kernels/libr3d.so [--case ] +install(TARGETS r3d_selftest RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) + +# C++17, the standard every radiance plugin builds device code at: it is what the tree's kernels are +# written against and what the cost figures assume. +set_target_properties(libr3d PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON) diff --git a/libr3d/README.md b/libr3d/README.md new file mode 100644 index 00000000..b437806d --- /dev/null +++ b/libr3d/README.md @@ -0,0 +1,1193 @@ +# libr3d + +libr3d is radiance's kernel library for RDNA3 and RDNA3.5 — the gfx11xx family: +`gfx1100`, `gfx1101`, `gfx1102`, `gfx1103`, `gfx1150`, `gfx1151`, and `gfx11-generic`, +the code object for a gfx11 card a build did not name. HIP kernels behind a plain C +ABI ([`r3d.h`](r3d.h)) plus the kernel-plugin rows the engine selects from +(`r3d_rows.cpp`); `libr3d/CMakeLists.txt` names every unit and its flags. + +It claims `^gfx11` where [`libr4d`](../libr4d/README.md) claims `^gfx12`: a card gets +one device library, picked by the rows and never by the name. The kernels are not +libr4d's ported — RDNA3 has no matrix instruction a compiler will emit, no fp8 +conversion, no bf16 pack, no VOPD — so every arithmetic path is its own: +`v_dot2acc_f32_f16` for products, software codecs for every format, a weight read in +the order the container stores it. The contract is shared: the same op schemas (copied +slot for slot from libref, as the loader requires), the same numerics rules, the same +geometry in constraints. Family parts differ in CU count and clock, never in these +instructions, so one code object per family suffices — and every number here is quoted +with its geometry, and with the class of part where the part's size is part of the +fact. + +## Naming + +An entry point is `r3d__[_]`: +`gemm_nt_bf16_m16` serves `gemm_nt` at bf16 for M ≤ 16 and refuses a larger M; +`r3d_rope_bf16` serves bf16 QKV in place and refuses anything else. A dimension named +in a name is a compile-time constant, and the entry point rejects a mismatch instead +of running. Shared dimensions stay out of the names: wave32, the attention rows' head +size (128), and the target architecture, reported by `rad_plugin_info`'s +`build_target` — spelled as a device reports its arch, because the loader warns when a +plugin claims a card the running device is not. + +Rows are `RadKernelInfo` entries in a table the engine reads from a dlopened `.so`; +the plugin links the ABI headers and nothing of the engine's. + +**Schema equality at load:** the first library to declare an op fixes its schema, and +a second declaring it with a different schema is refused by name with every row it +carries — arguments are positional, so a mistyped operand role is not a bad row, it is +no library. + +**The tail order is the ABI's:** `init, fini, launch, scratch, layout, relayout, +opd_shape, unrelayout, replaces` — `replaces` last on purpose, because kernel tables +are positional aggregate initialisers: a field inserted mid-struct shifts every later +one, and `nullptr` converts to any function pointer, so part of the shift would +compile. + +There is no launch adapter: every entry point *is* the row's `launch`, `(const +RadArgs*, RadStream)`, spelled `r3d_rad_` in [`r3d_plugin.h`](r3d_plugin.h). + +Behind it, two layers per unit: the **launcher** (`r3d_(...)` in `r3d.h`) takes +pointers as longs, checks what a `__global__` cannot, computes the grid, issues one +kernel on the stream it was handed; the **shim**, named by the row, reads operands +with [`r3d_args.h`](r3d_args.h), takes dtype from the tensor and the row count from +the operand, checks strides, returns a RAD status. Neither allocates, neither +synchronises. The table lists a selection; `r3d_rows.cpp` and `r3d.h` hold the full +set. + +| family | rows | +| --- | --- | +| `norm` | `rmsnorm_bf16` (optional residual add and multiplier), `rmsnorm_f32`, `layernorm_bf16` | +| `elem` | `add` (with `div`, and the broadcast band) · `mul` · `silu` · `gelu` · `sigmoid` · `act_mul_{silu,gelu,sigmoid}` · `softmax` · `scale` · `fill` (bf16/f32/i32/i64) · `gather_rows` · `scatter_rows`, bf16 and f32 where the op has both, plus seven `cast` pairs and `silu_mul_bf16` | +| `attn` | `rope_bf16` (neox and gptj, in place over packed QKV), `kv_store_{bf16,f16,fp8}`, `attn_paged_{bf16,fp8}_{decode,prefill}` — head_dim 128, split-KV combined in the same launch | +| `gemm` | `embed_lookup_bf16`, `gemm_nt_bf16_{m16,tiled}`, `gemm_nt_q_fp8a16_m16`, `gemm_nt_q_fp8a8_{m16,tiled}`, `gemm_nt_q_mxfp4a8_{m16,tiled}` (OCP-MXFP4 weight: e2m1 codes, an e8m0 scale per 32 of K), `gemm_nt_q_w2a8_{m16,tiled}` (2-bit and 4-bit grids on the 128×128 tile), `gemm_nt_q_w4a8_m16` (signed int4 weight, decode band), `gemm_nt_q_w8a8_m16` (signed int8 weight, decode band), `gemm_nt_q_gated_fp8a8` | +| `vocab` | `logits_gemm_bf16` — the head read once a token, bf16 codes, or E4M3 codes with a bf16 scale per 128×128 block | +| `quant` | `quant_act_fp8_bf16`, `quant_act_i8_bf16`, `quant_act_i8g_bf16`, `gated_quant_fp8_bf16`, `rmsnorm_quant_fp8_bf16` (norm and quantiser in one pass), `dequant_fp8` `dequant_e5m2` `dequant_i8` | +| `sample` | pre-filters `sample_{penalties,dry,ngram_ban,mask,logprobs}_f32`; spine `sample_{argmax,temp,topk,pick,topp,minp,typical,xtc}_f32` | +| `moe` | `row_topk_{bf16,f32}` — the op's stage in the reference is `moe`, so the row's is too | +| `draft` | `dflash_select_bf16` — the drafter's accept step, a walk over the draft block's candidate lattice | + +Seventy-eight rows, 44 schemas, every schema checked against the `libref.so` beside the +plugin, slot for slot, by `r3d_selftest`. GEMM rows carry tunables (`sk`, `wv`, `nt`); +the rest have none. + +Two int8 activation rows, because the reference has two ops and they are not +interchangeable: `quant_act_i8` is one scale per row, codes in the order an int8 +matrix operand is read (`i8_step_pos`, bits 2 and 3 of the column swapped) — what +`w8a8`/`w4a8`/`w2a8` producers mean; `quant_act_i8g` is one scale per (row, group), +row-major codes — what this library's `i8a8` GEMM reads and `dequant` inverts. The +step order is the op's, not a kernel's convenience: the plane is what the oracle +compares element by element, the one place in libr3d where a store address carries a +permutation. + +## Constraints as data + +Constraints are data in the rows the engine reads — a third copy of a geometry in each +caller drifts — and `r3d_selftest` checks every constraint key against the op's +declared parameters: a key renamed in one place only is a row that matches nothing. +Three rules decide what goes in a table, all three the engine's. + +* **A constraint on a key the band does not carry does not hold.** A band carries the + parameters its graph set and nothing else, so a row constraining an optional + parameter serves only graphs that spell it out: `rotary_dim` is optional on `rope`, + and binding it resolved a row to nothing for every graph that rotates a whole head; + `pb1`/`pb2` on the quantised GEMMs did the same to a whole model's bands, which fell + to the host. The selftest's reachability phase names every row that narrows itself + this way. +* **A band's `dtype` is the activation's.** A row whose dtype lives in the weight does + not constrain it: `logits_gemm` carries no `dtype` constraint, because the head's + dtype is a property of the operand and the row answers dtype with a check on the + tensor. `gemm_nt_q` is the opposite case — there `dtype` *is* the operand scheme, so + `C_IN` filters — stated at each table. +* **A row's floor is its sibling's declared ceiling + 1.** The tiled rows begin at `M + >= 17` because `gemm_nt_bf16_m16` declares `C_LE("M", 16)`, read from the constraint + and not from the name. A floor reasoned from prose ("the decode heights") left + 17..64 unserved and 209 batched-decode bands on the host: the shape a serving card + spends most of its life in. + +What the kernel cannot read goes in the constraints, not only in the launch: `n_vocab +>= 4` is the store's granularity (rows are written in 16-byte runs); `n_cand <= 1024` +is the candidate kernels' LDS budget (five f32 arrays of `n_cand` = 20 KiB of the 64 +KiB); `K % 32` / `K % 128` are the tile's k-chunk and the container's scale block. + +## Building + +Out of tree, against an installed radiance, as a third-party plugin is built: + +``` +cmake -S libr3d -B build -G Ninja \ + -DCMAKE_PREFIX_PATH="$RADIANCE_PREFIX" \ + -DCMAKE_HIP_COMPILER=/opt/rocm/lib/llvm/bin/clang++ \ + -DRAD_GPU_TARGETS="gfx1100;gfx11-generic" +cmake --build build +``` + +`rad_plugin_gpu_targets(R3D_GPU_TARGETS "^gfx11")` filters requested targets to the +family, and the project returns without a target when the filter is empty: a build for +gfx12 machines does not produce this library, on any path. `gfx11-generic` is the +object for a gfx11 card the build did not name — why one `.so` serves the family. In +tree, `add_subdirectory(libr3d)` sits beside libr4d's under the same `RAD_HIP_FOUND` +guard. + +`R3D_UNITS` lists units as `"file|extra flags"`, each named after the entry point it +provides; the shared headers (`r3d_common.h`, `r3d_codecs.h`, `r3d_args.h`, +`r3d_launch.h`, `r3d_tiling.h`, `r3d_fp8_dequant.h`) provide no kernel. Every unit is +`-ffp-contract=off`, which `rad_hipify` puts on all HIP sources — not a style +preference (Numerics). `r3d_rows.cpp` and `r3d_shapes.cpp` include neither `r3d.h` nor +the runtime, so the tables compile without ROCm. Occupancy is per kernel: +`__launch_bounds__` and `amdgpu_waves_per_eu` (`R3D_WAVES`) are written against this +family's register file, not RDNA4's. + +## Adding a kernel + +1. Write the `.hip`, named after the entry point it provides, geometry included. +2. Declare the launcher in [`r3d.h`](r3d.h) and the shim in + [`r3d_plugin.h`](r3d_plugin.h). +3. Add the unit to `R3D_UNITS` in `libr3d/CMakeLists.txt`, with any per-unit flags. +4. Add a `RadKernelInfo` row in `r3d_rows.cpp` with its constraint table. If its + `op` is one libref declares, copy libref's schema slot for slot — names and doc + strings are free, roles are not; if the op is new, declare the schema in the + same file. +5. Add the operand description to `r3d_shapes.cpp` if the row's operands are not + the schema's plain reading, and a geometry to the selftest's list. +6. Give the row a case: the selftest walks the table, so a row is run by adding no + test code — geometry comes from its constraints. +7. Measure it: `r3d_selftest /kernels/libr3d.so --case `, then + `rad-kbench --home "$RADIANCE_HOME" --kernels libref:libr3d --op `. + +A row naming an entry point that does not exist is an undefined symbol at `dlopen`, +which refuses the library and takes every row with it: a row lands in the same change +as its kernel, and a constraint array whose kernel has not landed stays out of the +table. + +## What the family gives, and what it takes + +Measured by reading emitted assembly for the gfx11 targets (`__has_builtin` off +`--offload-device-only`, `llvm-mc -show-encoding` per target) against the ROCm this +tree builds against; where a claim was taken on one chip it says which. Nothing here +changes between gfx110x and gfx115x — which is what makes the family one code object. + +**No matrix instructions a compiler will emit.** Every `v_wmma_*` mnemonic is rejected +by the assembler on gfx1100, gfx1102 and gfx1151 (and on gfx12, where libr4d does +carry a WMMA path: the feature is the target's, not the assembler's); inline asm +clears the frontend and dies in `amdgcn-link`. The tile builtin that *does* compile +for gfx1100/1102/1151 measured 1.99 against the dot path's 1.97 TFLOP/s at four +occupancies, so the tile buys a fragment layout and a block-alignment requirement and +no throughput. Products go through `__builtin_amdgcn_fdot2` → `v_dot2acc_f32_f16` on +every gfx11 target, paired as `v_dual_dot2acc_f32_f16` where the scheduler can — about +a quarter of RDNA4's matrix rate. No fragment layouts, so no repacked weights, so no +layout hook except the container's own planes force. + +**No int8 dot.** `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a`, +`__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are all undeclared for gfx1102, and all +four were tested. Codes widen to f16 and the dot runs on `dot2_f16x4`, paid for with a +trick: the f16 bits of `128 + x` are `0x5800 + 8x` for `0 <= x < 8`, so a 2-bit code +becomes an f16 with a mask, two shifts and an add, and the dot's answer comes back +carrying `128 · Σa` — the plane the op already has for the zero point, so de-bias is +one exact f32 subtraction per (row, group). + +**`v_fdot2_f32_f16` carries a little under 24 bits on integers — call it 22.** +"Products and partials are integers below 2^24, so the dot is exact" is true of f32 +and false of this instruction. Instrument: `probe_dot_kernel`, in the unit that uses +it — 32 lanes a block, one 64-code dot per lane, its f32 beside the exact integer. +Bias 1024: **71027 of 262144 dots inexact, worst |err| 0.125**, every one a dot whose +magnitude had reached 2^20; bias 128: 70115 of 262144, worst 0.015625. Worst error +over magnitude is ~2^-22, so shrinking the bias shrinks the tail and does not remove +it. The same work as four `__fmaf_rn` per quad in f32: 262144 samples, **0 inexact, +worst error exactly 0**. `gemm_nt_q` at `w2a8` ships a documented tail, not a claim. + +**`v_cvt_pk_f16_fp8` is listed by the compiler and absent from the silicon:** on +gfx1102 the ISA of a build calling it contains zero `v_cvt_pk_f16_fp8`, counted by +grep — it expands to software, ~100 instructions per 8 codes against the four that +widen bf16. `v_cvt_pk_fp8_f32` / `v_cvt_pk_f32_fp8` need `fp8-conversion-insts`, which +no gfx11 target has; their builtins are *declared* for gfx11 — the trap a +`__has_builtin` guard falls into — and die at instruction selection. Both directions +of e4m3 are bit maths in [`r3d_codecs.h`](r3d_codecs.h), mirroring `rad_plugin.h` line +for line, checked over every code. + +**No fp8 instruction means the decode is arithmetic, so the arithmetic gets a table.** +Ten VALU a code, and a weight-stationary row decodes every code it multiplies — twice +over where a lane owns two chains — which at M=1 is every code in the operand. A +256-entry f16 table in LDS, 512 bytes, built once a block by the arithmetic path +itself and therefore exact by construction, costs two `ds_read_u16` and a pack a pair +at zero register cost: the gated row's tall arm is 109 registers a lane, four waves a +SIMD, zero spills, and the table alone moves M=64 from 8395.3 us to 2786.5 us (its +band: N=12288 K=2048 group=128, codes resident, best of nine) — two thirds of that +arm's gain is the decoder. Two landmines in it, both load-bearing. The table's +argument is a **PAIR**, low code in the low byte, not an index: feeding it the index +fills the even entries and decodes code 0 into every odd one, and the code-enumeration +case names that as `rel_l2` 9.6e-01, not a NaN. And the decoded pairs +go from the table into the dot **inline**: materialising the round's eight pairs into +an array on the way — the shape this loop had, and the shape the arithmetic decoder +feeds — put the plane about a third away from the reference at every tall height (M=7 +`rel_l2` 6.6e-01; M=64 `-nan`) with the table itself proven exact on the device, entry +by entry and pair by pair. The array form is the one that miscomputes; do not restore +it as a tidy-up. + +**`f16x2_pack` is `v_cvt_pkrtz_f16_f32`: rounds toward zero, flushes subnormal f16.** +Only values f16 represents exactly may go through it — bf16 widened (7 mantissa bits +into 10), E4M3 widened (3 into 3) — never a code times a scale. Folding `code * scale` +through the pack biased every product toward zero: `rel_l2` 2.8e-4 against the fold's +law, 0.53 of outputs within 2 ulps. Folding with `v_mul_f16` (round to nearest, +subnormals kept) is one rounding in the right direction and one instruction: 4.5e-06, +1.000 within 2 ulps, nothing beyond six. Every scale fold here goes through +`v_mul_f16`. + +**`v_cvt_pk_bf16_f32` does not exist** on gfx1100, gfx1102, gfx1151: a bf16 pair is +rounded by hand and packed with `v_perm_b32`. **The dot's bf16 selector is a lie** — +`__builtin_amdgcn_fdot2` takes a `sel` operand for the bf16 form, the compiler accepts +`sel = true`, emits the f16 instruction, and bf16 operands are read as f16s: nonsense +products, silently. `dot2_f16x2` passes `false`, always. f16 is the compute type: bf16 +and E4M3 widen to it exactly, with the edges in the codecs — above 65504 a widening +saturates, below 2^-14 the f16 subnormal grid is coarser than the source's and +truncates. + +**Wave32, smaller register file than RDNA4:** 1024 VGPR entries a SIMD for a wave32, +granules of 8, against RDNA4's 1536; 64 KiB of LDS a workgroup on both. Occupancy +constants do not cross the generation, so `R3D_WAVES` is per kernel. A CU is 4 SIMDs × +16 wave32s = 64 wave slots, and `multiProcessorCount` reports CUs on gfx11 (WGPs on +gfx12), so a row-per-block kernel with one wave a block passes 64 waves a CU at +exactly the row count where tail waves start waiting. A wave64 build is refused at +compile time: it computes garbage rather than running slower. + +**No vector f64:** consumer RDNA3 is 1:64 on doubles, in practice soft-float, which +sets the transcendental policy per unit — the sampler keeps the reference's +`(float)exp((double)x)` (drawing a different token than the recording is wrong at any +speed), attention cannot pay it and ships a polynomial, the gated MLP uses `expf` into +a bf16 narrowing. + +**The lane ops are libr4d's** — `update_dpp` (xor and shr controls), `permlanex16`, +`readlane`, `readfirstlane`, `ballot`, `ds_bpermute`, `v_perm_b32`, `exp2f`, `rcpf`, +`s_barrier`, `sched_group_barrier`; DPP16 and `v_permlanex16` are RDNA1 onward, and +the encodings in [`r3d_common.h`](r3d_common.h) are the ones libr4d proved on +hardware. **No transposed loads, no VOPD:** neither `global_load_tr_b128` (RDNA4) nor +`ds_read_b64_tr_b16` (rejected by this assembler), so a transpose is done in +registers; VOPD is RDNA4, and the tree's `-mllvm=-amdgpu-enable-vopd=false` comes from +the LLVM version, not from here. LLVM single-buffers LDS and drains before a dependent +read unless told, and with no matrix unit there is nothing to overlap a load with, so +the barrier needed is the plain one. + +## Weights are stored once: the hook, and the writer that goes with it + +Four rows declare a `layout` — `gemm_nt_q_w2a8_m16`, `gemm_nt_q_w2a8_tiled`, +`gemm_nt_q_fp8a8_tiled`, `logits_gemm_bf16` — and each declares the `relayout` that +produces the form it names; `r3d_selftest.cpp` enforces the pair by name (a `layout` +without a `relayout` fails the table, a `relayout` without a `layout` fails it, any +`unrelayout` fails it). + +The starting rule — *no layout hooks in this library* — came from the dot path: a dot2 +GEMM reads a weight in the order it is stored, so there is nothing to repack. It +stands in every part that carries weight: **no plugin-private dtype, no repack into a +format of this plugin's invention, no container format changed from inside a kernel +library.** + +What it got wrong is that the container's quantiser already stores weights where a +kernel cannot read them in place — codes and per-block scales as separate planes, +`fp8_e4m3 * bf16[128x128]` for a head — and the engine's answer is its own canonical +form: planes joined behind one operand, `rad.planes`, sized by `rad_planes_plan`, +written by `rad_planes_relayout`. A row that reads such a weight *describes* that form +and *produces* it; the engine does the work at load, in the loader's pool behind the +container read. Three laws came out of it. + +* **A hook that answers is a promise** — the ABI says so: *RAD_OK: out describes the + stored form, and `relayout` will produce it*. With `relayout = nullptr` the model + does not load: `could not produce '…' (rad.planes) from fp8_e4m3*bf16[128x128]: + unsupported`. +* **A weight is stored once, so the row that got there first owns its plan.** The + engine arbitrates across every row of every band reading the weight, at declare: *is + wanted in two stored forms: 'rad.planes' by row A and '(as it is)' by row B. A + weight is stored once.* A second row gets the same answer by *calling the first + row's hook*, and its kernel reads the container the builder settled — by role, not + by the arrangement it declared. +* **`RAD_E_UNSUPPORTED` means stored as is**, the only kind of weight the mapped tier + can read where it lies — the lever the placement ladder runs on. A joined weight is + a resident weight, and a band that resolves to the host drags its whole layer group + onto the tier that reads the container in place, where a norm weight needing + conversion at load refuses to live. Hence the quantised GEMM at prefill heights as a + startup failure and not a slow band: no device row for `gemm_nt_q` above the decode + band → bands resolve to host kernels → the layer's weights stay in the container's + mapping → its norms group with them → the mapped tier is asked for a widening it + cannot perform. +* **A container arrives as a tensor of `rank = 1`, `shape[0] = bytes`.** That is the + joined form's stored shape — a byte count, from `rad_planes_layout` — and not a + plane. A consumer that reads it as a plane measures a scale plane's rows against + `ceil(N/group)` and refuses with a message about a geometry the operand never had: + the fp8a8 tiled row refused the sibling decode row's settled spelling (codes plain + on `b`, scale joined behind `b_scale`) with `E_SHAPE` from a tensor geometry test on + every case of one probe and at `n_b = 0`, and with `E_STRIDE` at one band — two + codes, one expression, both naming rows and columns of a thing that was never a + plane. Decode by role, on the host, where the header lives: the tag, the entry table + and the stored dtype (the first plane's) are host-readable, so the shim reads them + once per call and hands the kernel three device pointers. In that form the row + computed the reference's answer on **192 cases, 192 agreements, worst `rel_l2` + 1.362e-03** — and the same fix carried the m16/tiled crossing to 1018 cases with no + numeric divergence, where before it the crossing never reached the joined spelling. +* **A `zero` plane is refused as `E_DTYPE`, not folded.** `w2a8` is the only scheme + here with an activation zero point, and its producer is a row of this library. + `fp8a8`'s quantiser is symmetric, so the reference's fp8a8 arm refuses `a_sum` + outright (`ref_gemm.cpp:395`, `RAD_E_UNSUPPORTED` — that arm has no grid to sum a + zero over), the shape hook skips the operand, and every served band omits it. A row + that folded a zero point would be inventing a number the oracle has no law for, so + the refusal names its own fix instead: the row that computes zeros is + `r3d_gemm_nt_q_w2a8`. + +Same law, gains: read them in the dtype the checkpoint stores (a 2048-element norm +gain in f32 is 8.00 KiB), because the row's `dtype` band names the activation, never +the weight — the fused norm's kernel grew the plain norm's `WDT` leg, a dtype +parameter on the gain, rather than ask the checkpoint to be rewritten. + +## The request: a plan's vocabulary is not its contents + +A clean graph dump means every band has a row; it does not mean a request runs. At +request time the engine hands the shim the *contents* — descriptors, strides, an +arena, a step's shape — and the refusals between a clean dump and a first generated +token were one mistake: code that read the band's vocabulary as if it were the plan's +contents. Laws of the ABI, not of any one model. + +**A band's `dtype` is the activation's; a weight's dtype comes off the operand.** The +key names the step's activations, and the head of a `dtype=bf16` band can be E4M3 +codes with a bf16 scale per 128×128 block. A shim that trusts the key refuses the +request the plan is making. + +**An optional operand with no bytes is absent.** Optional operands arrive as +descriptors with a null `data` when the graph bound none, so the test is `r3d_has(t)` +— `t && t->data`; a bare `if (t)` is the bug: dtype-checking a descriptor with no +bytes answers `E_DTYPE` to a band whose dtype was fine, which is what +`rmsnorm_quant_fp8` did at M=5 with an unbound `out_bf16`. + +**A sizing hook runs at declare, where a descriptor has a shape and no bytes** (`data` +is null for every tensor in the plan). A scratch hook opening `if (!a->t[0].data) +return 0` answers 0 for the whole run, the engine allocates an arena of 0 bytes, the +split pass finds nowhere to write — a request-time `scratch buffer absent or too +small` from a hook that looked healthy. Size off the shape (`rad_tensor_numel`) or the +parameters, as the GEMM hook does. Absence at launch means the plan asked for nothing; +absence at declare means the bytes come later. + +**A band key is a bound, not the step's value.** A plan's geometry line reads `at M=30 +[band M<=2048] geometry {N=2560 K=2048 group=128 M=2048}`: the geometry's `M` is the +**ceiling the band was built for**; the height of *this* step is what the operands +say. A GEMM asking a 30-row activation for 2048 rows, and a sampler computing `rows = +(M_hint > 0) ? *M_hint : cirows` before asking the plane to be that tall, refuse every +request that asks for logprobs. Geometry comes off the operand — `nel / N`, `qnel / +n`, `r3d_rows_pitch(y, N, &M)` — and the key stays the ceiling promised not to be +exceeded. **Exceeding it is a refusal, and it prints both numbers.** + +**The engine sizes vector operands to the step, so their geometry comes from the +tensor.** The attention shim required `numel(BT) >= n_seq * max_blocks` with +`max_blocks` from the band's `max_ctx` — a table as wide as the cache — while a +five-token prompt with nothing behind it carries `[n_seq, 1]`: one block, because one +block is what the sequence has. The reference takes geometry from the tensor +(`max_blocks` from `bt->shape[last]`, row pitch from `stride[rank-2]`, column stride +from `stride[rank-1]`, `jend = min(ctx, max_blocks * block_size)`), so a context +longer than the table has columns is truncated — by the oracle as much as by us, which +makes it truncation, not corruption. The shim derives all three from the operand and +checks the one thing required: that the last reachable index `(n_seq-1)*bt_rs + +(bt_cols-1)*bt_cs + 1` is inside the plane. Two conflated counts are named apart: +`cache_blocks` bounds a slot's byte offset, `bt_cols` bounds the walk. + +**Serve the unoptimised form when the optimisation has no room.** Split-KV's halving +loop said "down to 1, which needs none" in its comment and returned `RAD_E_SCRATCH` at +1. One slice is the whole walk in one block, the same keys in the same order: not a +degraded answer, the answer without the split. Refusing a band because an optimisation +has no arena tells the user to go away. + +**A refusal carries a code, names its own fix, and prints the descriptor it saw.** +`R3D_NO(code)` prints the site under `RAD_R3D_TRACE=1`; `R3D_STR` prints the two +numbers a stride test compared; `r3d_trace_desc` prints dtype, rank, shape and strides +— in **elements**, what the engine binds and what a reader reproducing a refusal +needs. + +**The ragged query batch is a descriptor, not a second kernel.** `cu_seqlens`, when +present, is `[n_seq + 1]` of i32, and `cu[0] == 0`, monotonicity, and `cu[n_seq] ==` +the plane's row count are the *description's* promises — the served engine keeps them, +and no row may rely on them. `seq_of` walks `while (s + 1 < n && cu[s+1] <= row) ++s`, +so rows below `cu[0]` are not excluded: they land in sequence 0 with a negative index +into its query, and the reference computes them at `pos = ctx - qlen + i`, pushed +`cu[0]` keys into the past. Nothing in the oracle says the plane starts where the +descriptor starts. So `q_len` is *per-sequence* (`q_len = cus ? 0 : rows / n_seq`), the +total row count is the plane's, and a ragged batch has no `q_len` at all. One grid +covers it because the clamp a tile needs is per sequence; the rectangular case is the +descriptor's absence (`len_s = q_len`, `start_s = s * q_len`). One mapping, one mask, +one walk, one store, both forms. + +**A descriptor carries two row counts, and the store is bounded by the second.** +`len = cu[s+1] - cu[s]` is what the positions count from; `span = cu[s+1] - start`, +with `start = (s == 0 && cu[0] > 0) ? 0 : cu[s]`, is how many rows the sequence's tiles +carry, because the grid covers the plane from 0. The tile count comes from the length; +the store bound comes from the span. Bounding the store by the length drops the last +`cu[0]` rows of an in-bounds plane, silently, with status 0 from both rows: 20 rows, +`cu = [3, 17]`, one sequence, ctx 24 left 6144 items — 3 rows × 2048 — at the `0x7fc0` +pre-fill while the 17 rows it wrote agreed to bf16 rounding (max abs 1.22e-04), and the +engine read its own `out` buffer back as attention output. The plane's `rel_l2` is +`nan` in that case only because the untouched slots are bf16 NaN, which is exactly why +a finite-output check passes it and a whole-plane read-back does not. Every other +served shape agreed — 233 cases — which is what makes `cu[0] > 0` the descriptor's own +law and not a geometry note: the reference reads the descriptor, the fixture never +draws one, and the ragged oracle builds its prefix sum from 0, so the shape +that broke the agreement is a shape no oracle upstream could generate. + +## Numerics + +f32 accumulation, IEEE round-to-nearest-even narrowing, subnormals kept, no +reassociation; the oracle is `libref`. + +**`-ffp-contract=off` on every HIP source** (`rad_hipify`, library-wide): a fused +product-sum rounds once where the reference rounds twice, and a kernel diverging by a +rounding the reference does not make will not match it; the flag also keeps the +instruction counts quoted in kernel comments true. + +**Accumulation order is part of the contract:** `v_dot2acc_f32_f16` folds two products +into the accumulator and rounds once, so the match is not bit-exact and cannot be — +under an ulp a pair, a random walk of ~`sqrt(K/2)` ulps over a K-long dot, a +thousandth of the bf16 a store narrows to and inside what `rad-kbench` measures. The +*order* must be the reference's: k ascending, one accumulator per output, no +reassociation across lanes, with lane maps built so no lane ever has to break it (a +group spanning two lanes folds in one `shfl_xor`, in integers, before any float work). + +**Reductions are the reference's tree:** a wave butterfly (`dpp_xor` at 16, 8, 4, 2, +1; the halves of a 64-lane row read through `permlanex16` first where the reference +sums a whole row), then wave partials in wave order — the same bracketing at any +thread count. Activations, rope and quantisation are the reference's formulas in its +order (`1/(1+exp(-x))`, `0.5*x*(1+erf(x*0.70710678118654752))`, amax/127 with ties to +even), from `libref/ref_common.h`. + +**The accepted divergences, and the family reason for each** — where a row is checked +against a law it implements rather than against libref's bytes, each named in the unit +that ships it. + +| divergence | why, and what it costs | +| --- | --- | +| an index at or past an operand's row count takes the padding path (zero row, no store); `kv_store` drops a slot past the cache's span | the reference validates index arrays on the host and refuses, and `kv_store` refuses such a slot with `E_SHAPE` before it starts; a kernel cannot, so the bound travels as an argument (`slot_max`). A slot lost, not a step lost. A negative index is padding too and is not clamped to zero, which would duplicate row 0 across every padding row | +| rope divides the position by `scale` and evaluates the frequency ladder in double | `scale` is the position scale (the multiplier on a rotated pair is YaRN's magnitude, and the shims refuse YaRN, so it is 1). `powf` puts the reciprocal a ulp off, and at position 262144 a ulp of a frequency is a hundredth of a radian — the one place in that kernel where f32 is not enough | +| `block_sum`'s tree | wave butterfly, then partials in wave order: the reference's bracketing at any thread count, and why kernel and reference agree at 256 threads and at 64 | +| `sample_logprobs` keeps a NaN out of the max and into the sum; `sample_mask` skips a row whose `mask_row` is negative | maxima are a strict `>`, `std::max`'s law, so a NaN is never adopted; the sum propagates it, because the reference's `exp(NaN - mx)` is NaN and is added. The k-list is per lane in the reference's order (descending by value, ties to the lower column), merged in the same butterfly; the pool is 64 deep and a bigger k is refused, not truncated. The mask bound is the reference's own test (`mask_row` is `-1` for no mask), read off the operand, not off M | +| the sampler's `exp` and `log` are `double` calls narrowed once | the draws must reproduce: the device's `(float)exp((double)x)` is bit-identical to the host's over 2^20 points in [-100, 100] (0 differ) where `expf` differs by 1 ulp in 5.7% of them. Consumer RDNA3 is 1:64 on doubles, so this is the slow path by law: at the band, one read of the logits plane is 3.6 ms, a read that also sums double exponentials 30.4 ms, this kernel 38.9 ms. The candidate set is where it is affordable (1024 exponentials a row); attention is not | +| attention's `exp` is a degree-8 polynomial; the gated MLP's sigmoid is `expf` | no vector f64, and prefill is tens of millions of exponentials a layer. Against `(float)exp((double)x)` over 1.31M points of [-100, 0]: every point within one f32 ulp, 76.1% bit-identical (the device `expf` is 94.0% identical and no better in ulps), `exp(0)` exactly 1 — the only place an explicit `__fmaf_rn` is allowed, because what must be reproduced is a *function*. The MLP feeds a bf16 narrowing whose ulp is 2^-8 against the transcendental's ~1e-7, so the narrowing lands the same bf16 everywhere but on a tie | +| `w2a8` lands with a one-ulp tail | the pair-dot carries ~22 bits on integers: 0.1–0.2% of outputs one bf16 ulp off, `rel_l2` 5.0e-3 at the band, nothing further. The row's prose says so, because the law it transcribes is exact integers and the row reads like a bit-exact one | +| the fp8 folds land in f16, not f32 | the tile is f16, so a scale enters as a f16 multiply at staging — one rounding per staged value, through `v_mul_f16`. Against the reference's exact dequantise law: `rel_l2` 2.77e-04, half an f16 ulp, 250× finer than an E4M3 code's quantum (2^-4); against a model of the fold itself: 4.5e-06, the dot's fused rounding. At a bf16 output the store's ulp (3.9e-3) binds, not the fold's: 83% of outputs bit-exact, 99.93% within fold plus one store ulp | +| the bf16 GEMM's long-K tail | the pair is folded into the accumulator by one rounding, so ~0.3% of a long-K output lands one bf16 store ulp from the reference's and none is further: 99.93% bit-exact at the 512-column twin, 100% within two ulps | + +**How a plane is proved to have been written.** Every output plane in the comparison +runs is pre-filled with the dtype's NaN (`0x7fc0` for bf16 and f16) and read back whole: a +kernel returning `RAD_OK` without launching leaves the caller's bytes behind, and the +caller's zeros are finite, so only a NaN fill says the row ran. A clean case prints +`untouched 0`, `nonfinite 0`, no output beyond six ulps of the law the kernel +implements, and a whole-plane `rel_l2` inside what the fusion costs — `2 · sqrt(K/2)` +output ulps, with room for the fixture's spread. + +Two named planes (an int8 row-sum padded to a 16-row grid, a quantiser's per-group +statistics) keep the fill in their padding legitimately, because the row writes only +the rows it was given: the report says *pad NaN of N, the reference's grid, not the +row's work*, and a NaN anywhere else is the silent no-op the fill exists to find. + +Infinities are contract, not corruption, in the sampler and row top-k: a dropped +candidate, a narrowing stage's drop, and an unfilled `row_topk` slot are all `-inf`. + +## Testing + +[`r3d_selftest.cpp`](r3d_selftest.cpp) dlopens the `.so` — so an undefined symbol is +its failure, not a link failure — and runs five gates. + +**Codecs** against the ABI's host versions in `rad_plugin.h`: bf16 and f16 over all +65536 patterns both directions; e4m3 over all 256 codes plus the encoder's saturating, +subnormal, signed-zero and NaN cases; int8 against `rad_round_even_sat` over every +tie; the widenings over the range they are exact in; the bf16 pair packer against +`rad_f32_to_bf16`. The codecs are this library's own arithmetic, so they belong to the +tests: kbench compares whole ops, where a codec's disagreement is a diffuse +percentage. + +**The table:** unique names, a launch on every row, an `init` with a `fini`, the +device domain, prose on every row, a schema for every `op`, every constraint key a +declared parameter, a tunable's default among its ascending values, the layout pair +rule. + +**Band reachability:** every constraint a row puts on an optional parameter, named — +not an error, it is how a row says *I serve the form that states the parameter*, but a +decision, and a row whose author did not make it silently will not serve. + +**The schemas against `libref.so` beside the plugin**, with the loader's own +comparison (parameter count, keys, types, requiredness; operand count, roles, +optionality): one role mistyped and the loader refuses the whole library, every row +with it, one line in a log. + +**Every row, run** on a card — buffers from the row's own `opd_shape`, filled per its +fill code, outputs checked whole, one child process per row so a GPU page fault names +its row and the run continues. No card is not a failure: the static phase is a third +of what it checks, and a build machine runs it without one. + +The numerical authority is `rad-kbench`, replaying a recorded fixture against libref: + +``` +rad-kbench --home "$RADIANCE_HOME" --kernels libref:libr3d +``` + +`--all-rows` runs every row whose constraints hold, not only the one selection picks — +how a tunable arm the tuned defaults never reach gets measured. `--coverage DIR +--coverage-write` records the rows a fixture reaches, so a row that stops being +reachable fails the run; the census is +[`kbench_rows_kernels_libr3d.txt`](../data/kbench_rows/kbench_rows_kernels_libr3d.txt), +written by the same run, so census and numbers cannot disagree. + +**A fixture covers a checkpoint, not the library.** A fixture is generated from the +bands a recorded checkpoint issues, so a row can be shipped, correct, and absent from +its census: the packed 2-bit grid serves the head bands of the checkpoint it is served +on, and the base fixture has no `w2a8` band above M=16. Its gate: clean cases on both +stored arrangements, every refusal refused as stated, the writer's codes, scale and +zero regions byte-identical to the fixture's including a 73,113,920-byte head operand — +plus the fp8a8 row against the same file, 36 of 36 clean. + +A row should say which of the two vouches for it. + +The rule has a tool: `rad-kbench` records a fixture **from a model**, reading only the +tables, then widens every case into the constraints of every row under test. + +``` +rad-kbench -m /path/to/served.rad --record "$RADIANCE_HOME/kb-served.rkb" +rad-kbench --fixture "$RADIANCE_HOME/kb-served.rkb" --record-rows "$RADIANCE_HOME/kbrows.rkb" \ + --kernels libr3d,libref +rad-kbench --fixture "$RADIANCE_HOME/kbrows.rkb" --kernels libref:libr3d --all-rows \ + --no-cache --max-cases 2 --max-bytes 1024 --seed 42 +``` + +Line 1 answers the served checkpoint's own bands against the reference on the +container's real weight bytes: **975 checked, 975 passed, 0 diverged, worst `rel_l2` +1.605e-03** — the sentence worth keeping in a log is *every resolved kernel agrees +with libref on this container's bytes*. + +Lines 2–3 take each case into the M and `q_len` no container selects, the edges of a +row's constraints where its floors and ceilings get exercised: 45 cases reach 45 rows, +90 checked, 90 passed, 0 diverged, worst 9.684e-04. Rows a checkpoint's +graph never uses report `no recorded case of its op`. **Record one fixture per +checkpoint you serve:** a row green on a 27B fp8 fixture and untested at the shape +your served model walks is covered by a checkpoint, not by you. + +Against that base fixture, on a 16-CU RDNA3 part with 8 GiB, built out of tree as +above: **1153 checked, 1153 passed, 0 failed, 24 skipped for the case's own memory +budget, 0 diverged, 0 capped, worst `rel_l2` 1.362e-03** against a tolerance of 8e-03 +— the GEMMs' long-K accumulations and the fused norm-quantiser's E4M3 step. 436 cases +ran inside guarded allocations and 0 wrote outside one: the whole-plane write law, +tested on the fixture and in the hand-rolled comparisons. + +**Two proofs a tolerance cannot give.** A refactor is proved by the recorded decision +lines **bit-identical**: the same run against the build of HEAD and the build of the new +file, diffed with the timing column blanked (`6143/6144`, `2047/2048`, +`3667126/3670016`, +`4193353/4194304`). A change to an index, a scale plane or a row mapping is proved +**bit-for-bit against the same fixture**, in a mode whose whole job is that pair test: +feeding a per-row scale plane as the first M floats of the `[M][groups]` array +*passed*, because those floats are row 0's slots, so row *m* read row *m/groups*' +scale, and on data drawn from one distribution the answer is a few percent off — +inside a `rel_l2` tolerance, outside the truth. A fixture whose scales are +statistically alike cannot tell a row-indexing error from rounding; the pair test can. + +A test that cannot fail is not a test, so the comparison harness carries the control +that says so: a `selfcheck` run hands the scorer a plane rebuilt under a +known misreading and requires a DIVERGENT verdict naming it. + +The first full fixture run found three bugs a finite-output check cannot find: a cast +and a gather advancing the row base by the pitch in *bytes* where it is in *elements*; +raw bf16 patterns fed to `v_dot2acc_f32_f16` (0x3F80 is bf16 1.0 and f16 1.875); a +staging loop striding by the compile-time block size, correct at eight waves a block +and silently reading unwritten LDS at one. All three are in rows a fixture selects at +M > 1, none in a row the tuned defaults select. + +The gates prove a binary, not a tree. The box builds a *synced* tree, so a file that +never went to the box can reach the repo unmeasured, and one commit did exactly that: +it carried 567 lines of a unit's redesign where the built and measured file is 483, +and the added staged-arm and window paths use a constant — `kWin` — that is declared +nowhere, so the tree at tip did not compile while every gate above kept passing, +because not one of them builds from the commit. The check that catches it costs one +clean export: archive HEAD, build the archive on the target, and `build=0` is the only +answer. Two rules follow. A file enters the tree in the bytes that were measured — the +file an agent measured in its own snapshot is the file that lands, and its md5 is +quoted with its numbers. And unfinished work stays in a scratch directory, never in a +path a commit will sweep: the 567-line file is outside the repo now, with the constant +declared, for whoever finishes and measures it. + +## The fp8x8 GEMM by row count + +The band this family exists for is 42 layers plus a drafter at `group=128 +dtype=fp8a8` with a band ceiling of M=2048: N=12288 K=2048 ×44 (the gated MLP, two +halves of 6144), N=2560 K=2048 ×44 (qkv), N=2048 K=6144 ×44 (o-proj), N=2048 K=2048 +×44, and N=2048 K=10240 ×3 (the drafter). Three rows cover it by row count and the +boundary is read off the constraint tables, not off names: `gemm_nt_q_fp8a8_m16` +declares `C_LE("M", 16)`, so `gemm_nt_q_fp8a8_tiled` opens at `C_GE("M", 17)`, and +`gemm_nt_q_gated_fp8a8` runs M=1..64 with N even and K % 128. A floor reasoned from +prose, not from the sibling's *declared* ceiling, left 17..64 unserved and 209 +batched-decode bands on the host. The census in [Naming](#naming) is the index; the +measured floors and the placement law that prices them are in +[Measuring](#measuring). + +**The m16 row is a wave a run of columns.** One output element a lane, the weight +streamed past an activation kept in registers, no wave reduction — so a lane's chain is +the reference's chain and the row is bit-comparable at the store. Above 16 rows the same +operands want a 128×128 tile through LDS with 8×8 f32 accumulators a lane. The two +ranges are complements by construction, so neither row competes for the other's band, +and the m16 row is run against the tiled row on the same bytes, which is where a +boundary that moved would be seen. + +**The tiled row folds the scales at staging, and the fold is the arithmetic.** The tile +is f16, so both scale streams enter as f16 multiplies where the codes are staged: the +activation's `a_scale[m][g]` per staged row, the weight's `b_scale[nb][g]` once a chunk +— TN 128 is the scale plane's row extent, so a tile is one scale-row, and kKC 32 divides +128, so a chunk sits inside one k-block. The products are separable, +`(a*sa)*(b*sb) = (a*b)*sa*sb`, so folding each side is the same sum formed a different +way and the accumulator stays one f32 register. The reference's law is the group sub-sum +accumulated from the raw codes and scaled once per group (`ref_gemm.h`'s `quant_dot`, the +same body the m16 and gated rows carry); the fold answers to it at 2.77e-04 `rel_l2` +against a store that costs 3.9e-3, so it is invisible under the bf16 output: 1.71e-03 +overall, 83% of outputs bit-exact, 99.93% within the fold floor plus one store rounding, +nothing beyond eight fold floors and two store ulps. `|y|` is not the denominator — a sum +of 2048 random products is as often near zero as not — the scale is +`S = sqrt(sum (a_k b_k)^2)`, and the fold's measured floor is 9.8e-4 of it. + +**At the band's ceiling.** M=2048, container resident, every number on a +placement line: N=12288 K=2048 28.171 ms and 3659 GFLOP/s; N=2560 K=2048 5.911 ms and +3633; N=2048 K=6144 14.699 ms and 3506; N=2048 K=2048 4.381 ms and 3922; N=2048 K=10240 +29.798 ms and 2883, the drafter. 2883 to 3922 GFLOP/s is 27 to 36% of a part's dense f16 +rate; the bytes floor at the 163 GB/s this class streams is 0.051 to 0.257 ms a band, and +2MNK/(K+N) is ~1900 flops a byte at M=2048. Prefill is compute-bound here, as it should +be, so these numbers describe the loop and not the wire. + +**The cliff is recorded with its numbers, because it is not arithmetic.** The tiled +kernels run one block a CU at 18.4 to 18.5 us a block on every column-tile count the +graphs issue (16 and 20 measured, 4.72 and 5.911 ms over the grid); 19 tiles costs 211 us +a block, 11.4×, and 21 tiles 385 us, 20.9× — deterministic to 0.1% in two isolated +processes, clean at both. Every column-tile count the served graphs issue is even, +so no band walks into it; first try the block-index swizzle these cliffs usually answer +to, then the `nt` streaming loads. + +**What proved the crossing, and what would not have.** One `RadArgs`, the device row and +libref's host row on the same bytes, the whole `y` plane compared — pre-filled `0x7fc0` +so an unwritten element is visible, every other plane poisoned, 256-byte guards checked +after the launch. In every form the served plan hands the row (rank-1 `a_scale` of `[M]`, +the codes as a rank-3 `[M][ceil(K/128)][128]` plane, the weight as the container the +layout hook writes) at the four served bands and at M = 17, 21, 30, 45, 64, 65, 128, 258: +**832 of 1600 cases computed by both sides, 0 numeric divergences, worst `rel_l2` +1.440e-03** against a 5e-3 tolerance, 86.8% of elements bit-identical. The container form +above is what let the crossing reach the joined spelling at all: in it, 192 cases, 192 +agreements, worst 1.362e-03, and the full crossing comes to 1018 cases with 0 numeric +divergences; the same band with `b_scale=[scale,zero]` is 192 cases refused `E_DTYPE`. + +**A fixture whose scales are alike cannot tell an indexing error from rounding.** The +paired run spreads its activation by orders of magnitude a group at a time, because with +uniform random data the amax of 128 samples is statistically concentrated, every block's +scale comes out equal to bf16, and a scale-*index* bug — reading group 0's scale for +group 7 — changes nothing. The unit's own selfcheck said so: two of its eight sabotages +scored 0.00. So the crossing is proved by the paired run and not by the selftest, and +the +planted bug is the proof of the instrument: one line in the shim's launch call — the row +pitch handed to the kernel for a rank-1 activation scale becomes `kb`, a row plane read +at a group plane's pitch, checks and geometry untouched. Against the paired run, 300 +cases: +**240 divergent, worst `rel_l2` 1.389e+00**, and all 180 cases whose `a_scale` is the +served rank-1 binding diverge (9.669e-01, 43 507 of 43 520 elements differing, max abs +6.75e+01: rows 0 and 1 read real scales, every row from 2 reads the bytes past the plane +and produces zeros) while the 60 rank-2 cases are untouched and agree. In `served`, the +fixed scorer names 8 of 8 as `a_scale[m*kb+g]` — the read law, which is what the sabotage +*is*. The same bug is invisible to the row's own geometry test, which sees a rank-1 scale +of `M` rows at a stride of `groups`: a gate that cannot see a wrong scale is not a gate. + +**The gated row couples column *i* to column *n + i*,** so a lane owns both products of +its column: the partner is 192 waves away at the band's n = 6144, no lane-to-lane +exchange reaches it, and staging a whole row through LDS to get it is a round trip of the +[M, N] tensor the row exists to avoid. A lane walks k ascending with two accumulators +over two weight rows, `i` and `n + i` — exactly the traffic the unfused GEMM spent on the +two columns, so the coupling is free — and a block is one group of columns by +`256/group` rows, which closes the group's amax inside the block: a wave max folded over +the group's waves in LDS, one scale store, one code a lane. Product, gate and quantiser +in one launch with no scratch, which is why the row is concurrent +(`rad_kernel_concurrent(i)` is `scratch == nullptr`) and why the bf16 row of the +intermediate is not written, read, or allocated. Both halves are narrowed to bf16 before +the gate because the pair it replaces stored them and re-read them; the activation itself +is not — `gt * sg` is f32 from the narrowed gate and the product with `up` rounds once, at +the store. The law is `ref_quant.cpp:700` and its order is the point. + +**The gated band, both arms, best/median of nine launches, codes resident:** + +``` +M = 1 987.4 / 1154.9 -> 171.3 / 181.6 us (147 GB/s of codes; the floor for +M = 2 1120.6 / 1196.5 -> 166.2 / 177.1 us 24 MiB at 163 GB/s is 154 us, and +M = 4 1417.3 / 1581.2 -> 221.0 / 229.6 us the same sixteen loads with no +M = 8 1874.0 / 2318.0 -> 403.4 / 412.3 us decode and no dot run in 139 us) +M = 16 2949.3 / 3226.1 -> 1055.0 / 1160.6 us +M = 32 5123.4 / 5405.1 -> 1660.6 / 1705.0 us +M = 64 8395.3 / 9051.0 -> 2786.5 / 2877.3 us +``` + +**The arm is chosen by row count, in the launcher, from the same band key.** M ≤ 8 with +fp8a8 reads the activation and both weight rows straight from memory, 16 bytes at a +time, decodes them out of the block's table and multiplies: no shared memory between a +load and a dot, no barrier in the k-loop, six loads in flight. M ≥ 9, and every fp8a16 +case, stages — at those heights the grid is 48 × M/2 blocks and occupancy, not the +window, feeds the stream, and the stage pays for itself. The two numbers that chose the +shape came from the band's own stream (24 MiB of codes, resident, this loop with the +epilogue off): staged through LDS and decoded arithmetically 497 us; read straight and +decoded from the table 187 us; the read alone 139 us. The crossover and its gap live in +the launcher's comment, beside the `M <= 8` it selects on: with the table decoder in +**both** arms, N=12288 K=2048 group=128, codes resident, skinny 402 against staged 754 at +M=8 and skinny 955 against staged 1030 at M=16 — so the crossover is above 16 and +M=9..15 has never been measured. Decode lives at M=1 and a draft's verify at M ≤ 8, which +is what the shipped threshold is chosen for; a prefill at 9..16 rows would take the skinny +arm on the M=16 numbers, for about 7%. The window is a skinny-arm fix only: at M=64 it +buys its loads per lane at 32 registers, which is a fifth of a wave a SIMD given up on the +47 bands at the ceiling, and there it costs more than it saves. + +**No relayout on the gated row, and that is a claim.** libref reads the gated +`[N, K]` weight row-major; libr4d stores fp8a8 weights in WMMA fragment order. The two +readings are ~1.35 apart — a relative error, not noise — so this row carries no +relayout and says so in its prose: a row that inherits the fp8 GEMM's `unrelayout` +scores 1.35. The launcher refuses M > 64 (past the bands' ceiling the weight stream is +the wall, and that is a tiled kernel's problem), N odd, a group that is not a power of +two in [32, 256], `group > n` (the reference then defaults the *quantiser's* group to +n and leaves the weight's K block at the stated width: two grids this kernel reads as +one), `K % group != 0` (a ragged K block reads past the scale plane), `sk > 1` (no K +slab closes an epilogue that needs the whole row), and an absent `act`. + +**The instrument** is a paired run with two plugins dlopened, both row tables resolved +the way the engine's loader resolves them, one `RadArgs`, and a plane scored against +nine index laws with a hash beside it. It runs every stored form × the bands × the +crossing heights, the served geometry with the rank-1 activation scales the plan binds, +and the collapsed mapped and managed tier arrangements (the mirror layout, the default, +is the served one). Its numbers are the ones quoted above. + +## The paged attention, decode and prefill + +Two rows, chosen by `q_len`: the decode entry, which takes `splits`, and the prefill +entry. The served plan is n_head 16 over n_head_kv 2 at head_dim 128 — gqa 8 — with +`block_size 16` and a 4096 context, the cache `fp8_e4m3` with its descales attached. The +layout is the reference's: `kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim]`, +K then V inside a slot, so a key's row is a 512-byte pair and both halves are 16-byte +aligned at every slot; `block_table[seq, j / block_size]` names the block holding key +j; a negative entry is an unmapped block and hides its key, which the allocator uses to +free a sequence by writing −1, so the kernel keeps that test even though the fixture +never sets it; `seqused[s]` is the sequence's **total** key count, this step's query +rows included, so query row *i* of a `len_s`-row step sits at the absolute position +`seqused[s] - len_s + i`. One kernel serves decode (q_len 1), a speculative verify +(q_len 7) and a prefill chunk (q_len 2048). + +**A lane owns one output row and a wave is the GQA heads of one KV head:** +`h = kh * GQA + (lane & (GQA-1))`, `tok = base + (lane >> lg GQA)` — 8 heads over 4 rows +at gqa 8 — so every lane of a wave reads the same cache row at the same moment. Every +cache read is then an LDS broadcast, one `ds_read_b128` serving the wave, and the paged +walk is a per-wave event rather than a per-lane one. 32 rows per cache read is also the +register file's ceiling, not a preference: a second output row a lane needs 2 × 64 +VGPRs of widened query plus 2 × 128 of f32 accumulator, 384, over the 256 that four +waves a SIMD allows. + +**The walk happens twice, on purpose.** The reference keeps its scores; 32 keys × 128 +dims of f32 is 512 KiB a wave against 64 KiB of LDS, so pass two recomputes them. The +recomputation is the same order over the same operands, so it is bit-identical the +second time, and the op costs half again what keeping them would. A masked key is +skipped, never scored to −inf, so the denominator gets exactly the terms the reference +has, and a row with no visible key stores zeros — the reference's `mx == -INFINITY` +case, as in every other kernel here. P·V stays f32: folding the softmax weight into V +reads every weight to 11 bits, a ~1e-4 change that survives the bf16 store on a few +percent of outputs, for a third of the instructions. `exp` is a degree-8 polynomial +because there is no vector f64: over 1.31M points of [-100, 0] every point lands within +one f32 ulp of `(float)exp((double)x)` and 76.1% land bit-identical, where the device's +`expf` is 94.0% bit-identical — neither is the reference, and `exp(0)` is exactly 1, +which is the term the row is normalised by. + +**The width of a workgroup is the only lever this op has ever given.** A row slot past +a sequence's length computes a clamped duplicate: the walk, the tile and the store all +run for it. `pick_waves` picks the narrowest workgroup that carries the step's `q_len` +(one wave to 32/GQA rows, two to 64/GQA, four above); prefill keeps four. Medians of 15 +per-launch event times, two binaries in one session so the clocks drift together — the +same session's prefill reads 44.9 for both, which is how an earlier session's 40.0 was +explained: 294.7 → 158.4 ms at 256 sequences × 7 rows over 4096 keys, 268.0 → 128.4 ms +with 4 splits, 4.33 → 2.06 ms at 8 sequences over 2048, 4.27 → 3.97 ms at one sequence +over 4096, prefill 44.95 → 44.78. The kernel issues ~15% of the SIMD's slots at the +band and 3.7% at eight sequences, so halving arithmetic on a stalling kernel "should +not" buy 46%, and it did: two waves arriving at a barrier is not twice as cheap as +four, it is four times cheaper. A measurement, not an explanation, which is why the +width is a run-time choice. + +**Measured, and not the answer.** `s_setprio` around the consume leg of the walk: |Δ| ≤ +0.7% everywhere, and the one −6.4% in a session's first pair is clock ramp — the same +band run second gives +0.26%. `R3D_WAVES(2)` to lift the scalar-register ceiling: +`sgpr_count` 107 and `sgpr_spill_count` ~98 at *both* 4 and 2 waves a SIMD, timings +unmoved — the compute-shader scalar budget is not set by waves/SIMD the way the VGPR one +is. `__noinline__` on the staging leg: spills 98 → 72, a 160-byte private frame, timings +unchanged. A two-stage pipeline: +7% prefill, +7% decode, −5% split-KV. + +**Split-KV is a rescale, and the row says which splits are bit-identical.** A slice +accumulates its own `(acc[128], sum, max)` into scratch and the reducer combines before +the single narrowing, rescaling each partial by `exp(m_s - M)`; every term then arrives +as `exp(s - m_s) * exp(m_s - M)` where the reference has `exp(s - M)` — last-bit at f32 +(~2 ulp a term, ~1 ulp on the sum), and it vanishes under the bf16 store except on +outputs sitting on a rounding boundary. The row's prose states the contract: `splits = 1` +is bit-identical to the reference, `splits > 1` is not. `splits` is a **maximum**, +resolved per sequence from its own `seqused`: `nslice = ceil(nblk / ceil(nblk / splits))` +with `nblk` the sequence's block count, so a short sequence uses fewer slices and there +is no per-sequence legality check to fail, and the reducer recomputes `nslice` from the +same two numbers, so a partial needs no header. The arena is a bound, not an error: the +launcher lowers `splits` to what the arena holds, down to 1, which needs none. + +**The split curve on the served shape** — 64 sequences, 8 KV heads, fp8 cache, 15 +launches, ms a launch, at splits 1/2/4/8/16/32/64: at ctx 1024, 8.17 / 5.51 / 9.29 / +1.50 / 2.54 / 0.39 / 0.23; at ctx 4096, 35.71 / 20.92 / 11.41 / 5.79 / 2.67 / 1.44 / +2.60. Each workgroup walks `ceil(nblk / splits)` blocks with `nblk = ceil(jcap/16)`, so +the total keys read are `jcap` at **every** split count: the cost is slices × per-slice +work plus the reduce, it falls to 32 and then rises. The clamp `splits ≤ +ceil(jcap/block_size)` is a no-op at the served shape — `ceil(1024/16)` is 64 — and +bites only where splits exceed `nblk`, where a grid built from the requested number +leaves slices with no blocks: 12 of 12 such cases agree, so the extra waves cost, they +do not corrupt. The curve declines the lever with its numbers; the launcher does not +refuse it. + +**Two counts bound the walk, and the descriptor's two counts bound the store.** +`jcap = min(max_ctx, cols * block_size)`: the block table is the window the kernel is +allowed to read, so a context longer than the table has columns is truncated — by the +oracle as much as by us, which makes it truncation, not corruption. `cache_blocks` +bounds a slot's byte offset, `bt_cols` bounds the walk, and the shim checks the one +thing required: that the last reachable index `(n_seq-1)*bt_rs + (bt_cols-1)*bt_cs + 1` +is inside the plane. In the tile walk, the descriptor's length gives the tile count and +its span gives the store bound, so a sequence whose `cu[0]` is above 0 stores every row +the grid covers: see the descriptor's two counts in +[The request](#the-request-a-plans-vocabulary-is-not-its-contents). + +**A padding row must not write a partial.** A padding row's `row` clamps to a REAL row, +so the split path needs the row-validity test *before* the partial store. Unguarded, +two lanes write the same `(row, h, slice)` — inside the declared arena, so no bounds +check sees it — and their 132-float records interleave, leaving a slot with one lane's +accumulator and the other lane's `(sum, max)`. The reducer then rescales a full slice by +the wrong maximum, the combined sum comes out thousands of times too small, and `1/sum` +hands back a power of two where a logit belongs. Measured at the sliding-window band +(one sequence, 32 heads over 8 KV heads, window 2048, fp8 cache, splits 4): q_len 4 at +ctx 8192 gives `rel_l2` 1.65e-01 with a worst item of +32.0 against a reference ++1.2e-05, and q_len 6 at the same context gives 1.23e-03 where splits 1 gives 1.09e-03. +The mechanism needs `q_len < 32/gqa`, which is why the decode band (q_len 7 at gqa 8 +fills a wave, so there are no padding rows) and a run of that geometry never +saw it, and why the failing fixture cases fail identically at three seeds: a schedule, +not a sample. The slots a padding row leaves unwritten are exactly the slots the reduce +does not read; its index runs over real rows only. + +**The instrument** is a paired run with libref and libr3d dlopened in one process, both +called with the *same* `RadArgs`, absent optional operands passed as a descriptor with +null `data` and never as a shorter `n_t`, with the fp8 cache form in the same run: 233 +served-shape cases with no divergence, the rectangular matrix, the deep contexts +512..4096, the narrow block tables (`bt cols` 1/2/3/4/8, so `jcap` 16/32/48/64/128 +under a ctx of 512), empty sequences (`cu = [0,0,5,5,17]`), split counts 1 and 4, +windows 1/3/17/64/512, causal and non-causal. It is where the descriptor law above +was found. On the fixture the row scores 87 of 87 with worst `rel_l2` 7.558e-05, the +same numbers in the base build and the work build — the pair a change has to keep. + +**The unit's own launch counts itself.** A served decode step is *played* — the recorded +pass re-issues queue packets and never calls the plugin's shim — so a print that lives in +the shim has never seen the played steps. The kernel does. Under +`RAD_R3D_TRACE` only, `attn_kernel` writes one record per launch — its launch ordinal, +the row's `ctx` off `seqused`, the whole block-id row of the table, the six operand +addresses, and FNV-1a folds of the query row and of the first and last block it walks — +into a plugin-owned `__device__` ring of 256 fixed 216-byte slots, and the shim drains +the ring to stderr on a traced call. Budget is a device global the shim writes; the +decrement is `atomicSub`, the counter `atomicAdd`, and with the flag unset the kernel +pays one scalar load and a not-taken branch on one thread. The record's emission is one +step late for played steps, and the record's own `L` and `ctx` restore the order. + +**The served channel is a buffer, not a global.** In a served process the plugin is +dlopened, and the runtime's symbol stub for a plugin-owned `__device__` global is not the +address the kernel's module writes: the shim's arm and the kernel's read are two +different memories, so the ring's budget cannot be armed and the ring drains zero. The +served channel is therefore a plain `hipMalloc`'d record slot passed as a kernel +argument — no symbol table between writer and reader, one record per launch, drained at +the launch, armed by the same flag. The ring stays the board's channel, where the two +memories are one. + +**The flag's price, stated.** A launch function serves the step and is not a place to +allocate or to synchronize. With the flag *unset* both hold: the attention launch pays +one cached flag read and nothing else. With it *set*, the traced call pays one device +synchronize (the descriptor probe reads the table on the host) and the launch one stream +synchronize (the record drain), and the first traced call allocates the record slot. +Those are the instruments working, and they are the reason the flag is a tracing +switch, not a mode. + +**The law that made it a ring:** a kernel that calls device `printf` takes an extra +implicit argument — `hidden_hostcall_buffer` — and the AQL backend does not provide it, +so such a kernel is *undispatchable by the engine* (the fixture refuses the row with +`refused a geometry its constraints accept: device error`) while the same kernel, +hipLaunched by a hand-rolled board, prints every line. A board is therefore blind to +dispatch-side problems of its own kernels: only a gate that dispatches through the +engine can see them, and for this unit that gate is the recorded fixture. + +## The sampler spine + +Thirteen rows: five pre-filters, `sample_topk` feeding `sample_pick`, and the narrowing +stages that run between them. `abi/rad_sample.h` is the wire format and it is the point +of the design: every scalar — `temp`, `top_k`, `top_p`, `min_p`, `typical_p`, the +`xtc_*` pair, `seed`, `pos`, the flags, the history window — is **data**, one 96-byte +row per sampled position, because a parameter is geometry and geometry is frozen at +declare, and two rows of one batch with different `top_p` must resolve to one kernel. +`param_rows` is that check, and it is the dtype check libref states: the plane is +32-bit words, and a 16-bit view passes a byte-count test and then misreads every row. + +**The draws must reproduce, so the summation order is transcription and not +performance.** Every max here is a strict `>`, and that is also how NaN is kept out: +libref's `if (v > mx) mx = v` over −infinity never adopts a NaN, and the butterfly +merges with the same strict comparison, so a NaN in a row of logits cannot become the +max anywhere. A sum of f32 is not order-free: the reference's sums run over the +candidates in **index order** and its CDF scan accumulates in index order, so the exps +are computed in parallel — each a separate value, order-free — and the accumulation is +serial on one lane, in index order, exactly as written. Parallel values, serial sums: +the whole design of the candidate kernels in one line. + +**The draw is a function of the ABI, not of a library, and the transcendentals are the +reference's.** splitmix64 over `seed * 0x9E3779B97F4A7C15 + pos`, the top 24 bits over +2^24, integer arithmetic so it is the same number on the device as on the host, +independent streams per purpose (the pick XORs `RAD_SAMPLE_KEY_PICK`, XTC's coin +`RAD_SAMPLE_KEY_XTC`). `ref_exp`/`ref_log` are `(float)std::exp((double)x)` and +`(float)std::log((double)x)`, transcribed as double calls rounded once to f32: the +device's are bit-identical to the host's over 2^20 points in [-100, 100] — 0 differ — +where `expf` differs from the host's by 1 ulp in 5.7% of them, and a `u < cum` +comparison sitting on an ulp boundary changes the drawn token, which is a fixture +failure even when the distribution is right. This is where the 1:64 fp64 rate is +affordable: the widest softmax here is the candidate set, 1024 exponentials a row at +half a millisecond a step, so the switch stays off and attention, at 17M exponentials a +layer, ships the polynomial instead. + +**The top-R is one scan because the reference's R scans are a sort.** `topk_next` takes, +on each of R scans, the largest value strictly below the last pick, ties to the LOWER +column; read as a whole that is a sort by (−value, +column), and the rule +`v == *pv && i <= *pi` is exactly "the next one within a run of equal values". So one +pass keeping the best R by that order produces the same R pairs, in the same order, with +the same tie-breaks. At the band's row — M=1792, N=130560, R=16, bf16 — the reference +scans the row sixteen times, 7.0 GB; this scans it once, 468 MB. Measured 22.0 ms bf16 +and 22.4 ms f32, 21 GB/s and 42 GB/s: the same time for half the bytes, which is the +finding. The pass is bound by the accepted inserts — ~55 sifts a lane at 510 elements a +lane — not by the plane, and a lane filtering against a block-wide threshold instead of +its own tail would take ~5 sifts a lane and land near the 2 ms the bandwidth floor +allows; 22 ms is not the memory system's answer, and it is written here so nobody reads +it as one. One pass needs a per-lane list, so the list is 64 deep and a merge keeps the +best 64 of two: a lane's test against its 64th best is one comparison for almost every +element (~12% of a row clears it at 510 elements a lane), and the deep comparisons +happen only for elements that enter. Sixty-four covers R=16, the selftest's 64-wide set, +and every `top_k` a request asks for in practice; past it `r3d_sample_topk` and +`r3d_row_topk` take `ceil(k/64)` passes — the reference's own chain, so the answer is +the same at any k and only the time is the reference's. + +**The candidate plane is the contract, its width is the BUFFER's, and it carries +LOGITS.** A row's set is its `top_k` largest logits, descending, ties to the lower +token id, with `cand_idx` −1 and `cand_val` −infinity for a hole. The width is the +declare-time bound — 1024 candidates is the engine's declared buffer width, and two f32 +arrays of it is 8 KiB of the 64 KiB a workgroup gets — and the row's `top_k` only +narrows *within* it: `top_k` 40 in a 1024-wide buffer is 40 candidates and 984 holes, +and the whole buffer is written every step because a hole is a value the later stages +test for. A greedy row takes none: its token is `sample_argmax`'s and the pick must not +overwrite it. `cand_val` carries LOGITS, not probabilities — every narrowing stage takes +its own softmax over the set, which is what lets the stages compose in any order and is +why a pre-filter can be moved rather than re-derived. + +**The band key is a ceiling and the plane is the step, and reading one as the other +killed every logprobs request.** The step's rows are the operand's row count. Preferring +the key's `M` over the plane asked one row of candidates to be 256 of them — `refused op +sample_topp at M=1 [band M<=256] geometry {n_cand=1024 M=256}` — so every request that +asked for logprobs died with `shape this kernel does not serve`. It was the third unit +in one night to read a band's bound as the step's value, after the tiled GEMM at M=30 +and the block table sized to the cache, which is the reason the rule is stated as a law +and not a fix. The key keeps its job as the ceiling the plan promised not to exceed, and +the refusal that fires on a plane over it prints the descriptor it saw. + +**The spine's instrument is the fixture, not a paired run.** No comparison harness pairs +these rows with libref: the selftest builds each row's buffers from its own `opd_shape`, +fills per the fill code, runs the row, and checks the plane whole in a child process, +and kbench +drives the `sample_*` bands against libref on the served checkpoint's fixture (975 of +975 across every op the run resolves, worst 1.605e-03, in the +[Testing](#testing) tally). What a paired run would add is the part the fixture cannot +check: the seeded draw compared against a *recording*, over the parameter rows a request +actually sends. That gap is in +[What is not here yet](#what-is-not-here-yet). + +## Measuring + +**Measure the floor first and name it in the verdict.** 66.8 MB of codes at a part's +22 GB/s is a 3.0 ms floor; 255 MiB at 163 GB/s is 1.64 ms; a 73.1 MB operand is a +0.449 ms read. Against those, "13.6 ms a token" and "24.151 ms at M=64" are statements +about the loop, not the wire. A number with no floor beside it is a feeling. + +**Name the placement of every operand on every timing line.** On a part whose memory +cannot hold the head this is worth an order of magnitude, and it is a property of the +class: at M=1, one kernel, the same head in VRAM is 13.6 ms a token; on the mapped +tier (pinned host bytes read over the host link by 8-byte strided loads) 643 ms; +managed and left alone 2071 ms at 122 MB/s, because managed pages do not migrate for a +read-mostly device access and the kernel faults page by page. A layout hook makes the +mapped placement *legal*, not fast. Boards state which placement produced which +number, time after a prefetch, and note that a container operand must be host-readable +at all (the shim reads its header on the host) — hence pinned or managed, never plain +`malloc`, which faults. + +A number belongs to whoever placed the bytes: the same shape in the same binary +measured 5.911 ms as the first case of a process and 85.7 ms as the second case of a +sequence that had allocated and freed a 24 MiB managed container first — 14.5×, +deterministic, clean run both ways, and at 0.2 GB/s the slow run is reading its +weight over the host link. The row's number is 5.911 ms, because the engine ships +weights to VRAM at load and reads them 44 times. + +**`vgpr_spill_count` is a gate, not a note:** 44 kernels, all zero, both builds of an +A/B. Per-group partials scaled into the accumulator cost 64 more accumulators on an +arm already at 237 VGPRs, and a runtime index into a register array of candidates +spills the array to private memory; both are rewrites, not tunables. A scalar spill in +a compute-shader wavefront is a slow path, not a stall — the ablations below say so +with numbers — so VGPR spills gate and SGPR spills get reported. + +**Number before verdict.** Four things that look like they should work on the +attention unit were measured to not work, and the one width that did move it is +recorded with them +[in the attention section](#the-paged-attention-decode-and-prefill); the tiled rows' +grid-shape cliff is recorded +[in the GEMM section](#the-fp8x8-gemm-by-row-count). A negative result carrying its +numbers is the cheapest documentation in a library: it is the only thing that stops +the next session re-measuring it. + +**Profiled per-op times sum to more than the token, and that is the tool working.** +On the served 2B plan, 61 + 24 + 12.7 + 4.2 = 102 ms of per-op device time against a +measured 87.6 ms token: the engine overlaps its ops, and `--profile-ops` restores the +synchronisations that serialise them — the caveat the served engine prints in its own +startup diagnostics ([`core/diag/checks.cpp`](../core/diag/checks.cpp): *times every op, +which restores synchronisations … drop `--profile-ops` for anything measured*). A per-op +table taken under that flag ranks the work and does not price it, and the token rate is +the price. The pair that proves the reading: the gated row's profiled saving on that plan +was ~44 ms of the 87.6 ms token, and the token got 11.4 ms faster. Quote a served run's +shape with its served numbers — the context length it was taken at, the prompt lengths it +walked — because a ranking is a property of the shape, not of the model. + +## Notes on the kernels + +Three properties are assumed throughout and not restated per kernel: **wave32 with a +1024-entry VGPR file a SIMD**, so every lane map has a lane owning whole dwords and +every budget is computed against 1024; **64 KiB of LDS a workgroup**, which sets the +candidate kernels' `n_cand <= 1024` and the tile sizes; **no matrix instruction**, +which is why the tile is a dot loop over LDS with an 8-element XOR swizzle, shared by +every tiled row in [`r3d_tiling.h`](r3d_tiling.h) and proven byte-identical between +them. + +**A staged chunk of 8 bytes against a row pitch of 512 is the 2-bit grid moving 8× the +bytes it uses** at `kKC` 32: 24.151 ms at M=64, N=130560, K=2048 against a 0.449 ms +read floor, 3.7 GB/s useful. The lever is a wider k-chunk (64 codes = 16 bytes, paid +for in LDS), not more loads in flight: leading the codes measured 0.6%, bit-identical, +and was reverted. + +**The head is the largest read in a decode step**, and the sampler reads f32 — why the +store is typed, not narrowed, and why a prefill band writes 1.07 GB. bf16 codes: 3.29 +ms a token at M=1 (163 GB/s), 0.507 ms at M=16 (the head read once for sixteen rows), +269 ms at 2048 rows (4067 GFLOP/s). E4M3 codes with a bf16 scale per 128×128 block, +read as the two container planes they are: 13.6 ms a token at M=1, 8× above the 1.64 +ms floor, cause named — the E4M3 decoder, ~100 instructions an eight-code group. The +decoder-as-a-table pass (256-entry f16 table in LDS, 512 bytes, eight reads a group, +exact by construction) is 2.70× where the decoder binds (M=8: 2.500 → 0.924 ms a +token), flat at prefill, and a **named non-result at M=1**: removing ~100 ALU +instructions did not move it. The suspect at M=1 is load width — eight codes a lane +through an 8-byte load, where the bf16 arm takes sixteen bytes a lane at 163 GB/s — so +the next experiment is a 16-byte code load, not more ALU. `rel_l2` between the two +binaries is bit-identical: the check that the swap moved work, not arithmetic. + +**A launch check that does not clear the flag first refuses a healthy step.** +`hipGetLastError()` reports the first error raised *since it was last cleared*, so a +check that does not clear attributes to this launch whatever the process raised before +it: in a served process, the op that ran last; in a comparison run, its own setup. Both +were +seen. The symptom to recognise is a whole timing mode returning the device code on +every geometry of every row, all of it vanishing under `HIP_LAUNCH_BLOCKING=1` — which +is what a synchronous launch does to a pending asynchronous error, it clears it before +the check — and a shim's own text rendering it as something about strides, because the +launcher printed a raw code and the caller appended its own sentence. Two lines fix +it: clear the flag after the arguments are staged and before the chevron, then read it +straight back; and on a refusal, name the error and print the grid, the block, the +waves, the splits and the width the launcher chose. A refusal that does not say what +it saw cost two hours, and the failure mode is a healthy step refused for a symptom a +neighbour caused — the launch is not the suspect. + +**No collective rows, and no chained forms.** The parts this family ships in are +single-GPU, and an all-reduce over the host link most of them sit on is slower than +sending the bytes through the host. Nothing here is built as a chained form, so both +optional symbols are left out — the ABI's own answer, with one less thing to keep in +step. + +## What is not here yet + +Stated as library work, so nobody looks for it in a row table. + +**The 2-bit grid's staging width.** The packed-code tile at prefill heights moves 8× +the bytes it uses at `kKC` 32; the fix is a 64-code chunk (16 bytes a lane) paid for +in LDS — the whole distance between 24.151 ms and a 0.449 ms floor at M=64, N=130560, +K=2048. + +**The skinny-load path for a one-row head.** The E4M3 decode arm loads eight codes a +lane through an 8-byte load and runs 8× above its floor at M=1; the 16-byte load (16 +codes, eight pairs, half the wavefronts) is the experiment, and the decoder table has +been shown not to be the lever. + +**The gated MLP's rows-by-column-groups pass.** The table decoder moved M=64 from +8395.3 to 2786.5 us (best of nine), which is most of the row's story at the ceiling +and none of its floor: the weight read is the wall there, and 47 of the 48 bands +declare the ceiling. Past 64 the fused row refuses and the work is four ops over a +bf16 `[M, N]` tensor — two GEMMs, the gate, the quantiser — so the pass that +amortises the weight read across rows *and* column groups is what stands between the +fused form and the pair it replaces, priced at M=64. + +**The gated row's arm threshold is a tunable.** The crossover between the skinny and +staged arms is above 16 rows and M=9..15 has never been measured; the shipped M ≤ 8 is +chosen for the decode's M=1 and a draft's verify, and the launcher's comment says so +beside the number it selects on. Nine launches a band would move the threshold, not the +kernel, and a band that lives in 9..15 is paying the staged arm for about 7%. + +**`gemm_nt_q_bias` has no row, and the gap is silent.** `gemm_nt_q` has no bias +operand: bias is its own op in the registry (`ref_registry.cpp:1361`, "gemm_nt_q with +a per-column bias"), and this library declares no row for it. So every band carrying a +bias resolves to the reference's host row — correct, slow, and invisible: no `E` line +in the coverage, because nothing refused, and no entry in the profile, because the op +never reaches a device. A model with bias'd projections runs them on the host while +the census reports a clean tree. The row is a bias load in the epilogue of the tiled +rows plus a declared schema; the gap is that nobody has to notice it. + +It is a *model-shaped* gap, not a served one, and the container says so: the checkpoint +measured here declares `draft.attention_bias` and `draft.mlp_bias` with **count 0** — +no planes, no bytes — so by the law that an optional operand with no bytes is absent, +this model carries no bias band and nothing falls. `rad-info -v | grep -i bias` +is the one-line census: a model whose bias tensors have planes is the model this row is +for, and on that model the fall is real and silent. + +**The sliding window over a partially-filled last tile diverges.** The shape is +`window` between 2 and 16, exclusive of 1 and 16, over a query plane whose last tile is +not full: 10 of 60 cases in the row's window matrix, base and work producing +byte-identical planes for all 60 — 10 divergent each, same hashes — so it is in the +shipped row, not in a session's change. The scan: rows 17 at ctx 33 agree at w = 1 and 16 and diverge at w = 2, 3 and +15; ctx 32 at w = 3 agrees where ctx 34 diverges; rows 32 at ctx 48 — two full tiles — +agree where rows 33 at ctx 49 diverge, tile 3 holding one row; rows 18..24 at ctx + 16 +diverge by two rows each. Five runs of rows 17 at ctx 33, w = 3, give the identical plane +hash (`223c70af1e9e5276`): one row of 17, 2044 of 2048 items differing, `rel_l2` +1.196e+00, status 0 from both rows, no non-finite. Served bands are full attention — all +471 `window = 0` cases agree — and the plan's windowed layers use a 2048 window over +16-wide blocks, so no served band walks into it. It is a bounded, named, reproducible +divergence in a row the plan declares, and the fix belongs in the last tile's mask, not in +the window's clamp. A dedicated comparison run reproduces it. + +**`sample_merge_topk`**, the cross-rank candidate merge: under a split vocabulary it +holds `world_size * n_cand` gathered pairs, and there is no row for it here. + +**A seeded-draw comparison for the spine.** kbench grades the `sample_*` bands against +the reference on the fixture, which covers the arithmetic and not the recording: no run +compares the *drawn token* against a captured sequence, over the parameter rows a +request actually sends. The draws are the part of this library a `rel_l2` cannot grade. + +**int8 × int8.** The constraint table is written (`i8a8`, group 128, M ≤ 16, K % 128) +and `quant_act_i8g` already produces the row-major activation it wants; the kernel is +not landed, so the row is not in the table, because a row naming an entry point that +is not in the library is an undefined symbol at `dlopen` and takes every other row +with it. + +**Chunked logits.** The head's f32 plane is written whole (1.07 GB at a 2048-row +prefill band); nothing yet emits it in chunks the sampler consumes in passes. + +**A sub-byte zero plane.** `w2a8` reads a zero point a byte at a time and refuses a +zero stored U2/U4/U5 by name; the bit-extract path is the ten lines `rad_load_bits` +already is for the codes. Written for the codes and not for the zero, and the refusal +is not an approximation. + +**Speculation that pays.** The draft head is served end to end — its bands by the +2-bit grid, its accept step by `dflash_select` — and the accepted text is identical. +The target's head read amortises over the draft block (5× cheaper per token at 8 rows +than at 1 on the same kernel), so what has to pay is the drafter's own steps, and on +the 16-CU part that measured it they did not: 87.6 → 94.4 ms/token on a 5-token +prompt, 91.6 → 187.1 on a 16-token chat band with 7 drafts. The engine's own rule +switches the drafter off for a plugin whose rows measured a gain without them, so the +work left is a draft path that costs less than the head read it saves, not a flag. diff --git a/libr3d/r3d.h b/libr3d/r3d.h new file mode 100644 index 00000000..e4dae930 --- /dev/null +++ b/libr3d/r3d.h @@ -0,0 +1,387 @@ +/* r3d.h -- the entry points libr3d exports, and the launchers behind them. + * + * Two layers, in every unit, as in libr4d: + * + * The launcher (`r3d_(...)`, this header) takes pointers as longs, a geometry as ints and a + * stream as a long, checks what a `__global__` cannot (nulls, non-positive extents, a pitch that + * does not describe the operand), computes the grid, and issues one kernel with + * hipLaunchKernelGGL on the stream it was handed. It returns 0, or a negative launcher code: + * -1 a null pointer, -2 a bad extent, -3 a bad pitch, -4 the HIP launch failed. It allocates + * nothing and synchronises on nothing. + * + * The shim (`r3d_rad_(const RadArgs*, RadStream)`, declared in the unit) is the RadLaunchFn + * the row table names. It reads the operands with r3d_args.h, takes the dtype from the tensor and + * not from the `dtype` parameter, takes the row count from the operand and not from `M` (which is + * the band's upper bound), checks strides, translates the ABI dtypes to the codes below, and + * returns a RAD status. + * + * A launcher is declared here and defined beside its kernel, in the same translation unit as the + * shim that calls it: there is no adapter, and an out-of-tree author reading one unit sees the whole + * path from RadArgs to the grid. + * + * Streams: a RadStream is the engine's queue, usable with hipLaunchKernel (and so <<<>>>), + * hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync and with nothing else in HIP + * (docs/PLUGIN.md §5). libr3d passes it to the launch and nowhere else. + */ +#ifndef RAD_R3D_H +#define RAD_R3D_H + +#include "r3d_plugin.h" + +extern "C" { + +/* ================================================================== r3d_model_bf16.hip + * + * One workgroup per row. Every launcher takes a row pitch in elements for each operand that can be + * a slice (a column slice of a fused projection is the usual case), 0 meaning "dense, so n". + */ + +/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. `wdt` is R3D_DT_BF16 or R3D_DT_F32 for a + * gain, R3D_DT_N for none (the gain is then 1, and wadd is refused by the shim, as libref does). */ +int r3d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, float mult, + int x_ld, int y_ld, int wdt, long stream); + +/* The same at f32 activations, for an f32 checkpoint's residual stream: the row is the op's, the + * store narrows nothing. `wdt` is the gain's dtype code, R3D_DT_N for none. */ +int r3d_rmsnorm_f32(long x, long w, long y, int M, int n, float eps, float wadd, float mult, + int x_ld, int y_ld, int wdt, long stream); + +/* y = (x - mean) / sqrt(var + eps) * w + b, the mean and variance both taken in the reference's + * two passes. `b` may be 0 (no bias). */ +int r3d_layernorm_bf16(long x, long w, long b, long y, int M, int n, float eps, + int x_ld, int y_ld, long stream); + +/* y = a + b, and y = a * b. `bcast` says b carries n elements and rides every row. `div` is the + * `add` op's optional divisor, 0 meaning none: with it, y = rd(rd(a + b) / div). */ +int r3d_add_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, float div, + int bcast, long stream); +int r3d_add_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, float div, + int bcast, long stream); +int r3d_mul_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, int bcast, + long stream); +int r3d_mul_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, int bcast, + long stream); + +/* y = x, one dtype to another, over M rows of n at the given pitches. The dtypes are R3D_DT_*; + * an integer pair goes straight through (ids above 2^24 survive an i64 -> i32 copy), everything + * else widens to f32 and narrows once on the way out. */ +int r3d_cast(long x, long y, int M, int n, int x_ld, int y_ld, int from_dt, int to_dt, long stream); + +/* The unary activations, f32 in, narrowed once by the store: y = x*sigmoid(x), 0.5x(1+erf(x/sqrt2)) + * and 1/(1+exp(-x)) respectively. */ +int r3d_silu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream); +int r3d_gelu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream); +int r3d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream); +int r3d_silu_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream); + +/* y = act(gate) * up, `act` R3D_ACT_SILU, R3D_ACT_GELU (the exact erf form) or R3D_ACT_SIGMOID. + * The two inputs are the halves of a fused [M, 2n] projection, so their pitches are separate. */ +int r3d_act_mul_bf16(long gate, long up, long y, int M, int n, int g_ld, int u_ld, int y_ld, + int act, long stream); + +/* y[i] = silu(gate_up[i]) * gate_up[n + i]: the llama MLP's gated product over one fused plane, + * the gate the FIRST half, which is the order rad-convert fuses gate and up in. The activation is + * not narrowed before the product: that is `act_mul`'s order, over two operands, and it stands for + * the unfused pair that stored the activation. `gu_ld` is the FUSED row's pitch (>= 2n), `y_ld` the + * output's; 0 takes each one's dense width. 0, -1, -2, -3, -4. */ +int r3d_silu_mul_bf16(long gate_up, long y, int M, int n, int gu_ld, int y_ld, long stream); + +/* Row-wise softmax over f32, maximum subtracted, the denominator summed in ascending order. */ +int r3d_softmax_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream); + +/* y = x * s, where `s` is the op's [1] weight plane, in device memory, of dtype `s_dt` + * (R3D_DT_BF16 or R3D_DT_F32). The scalar is read by the kernel, not by the launcher: a launch may + * not copy device memory to the host, and the reference reads the same one value on the host because + * its operands are host planes. Every lane loads the same address, which is one uniform load per + * block; `s` is 0 only for a call the shim has already refused. + * + * y = v (fill) is the other scalar-carried op, and its value is a parameter, so it is by value. */ +int r3d_scale_bf16(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, long stream); +int r3d_scale_f32(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, long stream); +int r3d_fill(long y, int M, int n, int y_ld, int dt, float v, long stream); + +/* In-place rotary on a fused qkv row: q, then k, then v untouched. `mode` is R3D_ROPE_NEOX or + * R3D_ROPE_GPTJ; `rot` the rotary width (<= head_dim, even). `scale` is the position divisor: the + * angle of pair i is (pos / scale) * theta^-i, which is libref's proportional ladder at a factor + * other than 1 (ref_rope's `scale` divides the position, and YaRN's magnitude is carried by + * `yarn_factor`, which this kernel does not implement). `pos` is M i32 positions, one a row. */ +int r3d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_head, int n_head_kv, float theta, + float scale, int mode, int rot, int qkv_ld, long stream); + +/* K and V into a paged cache, at slot_mapping's slots. The cache is [blocks, kv_heads, block_size, + * 2*head_dim] with the strides the shim read off the operand and passes as sb/sh/so/sd; a negative + * slot is skipped, and so is one at or past `slot_max` = n_blocks * block_size, which the launcher + * computes from M and block_size exactly as `r3d_shape_kv_store` sizes the cache. The reference + * *refuses* such a slot on the host, where it can see the block count; a launch cannot refuse a + * slot it has not read, and writing past the cache is the one failure mode worse than a value + * dropped, so the bound is the kernel's and the divergence is a slot lost rather than a step lost. `kv_dt` R3D_DT_BF16 stores the values, R3D_DT_U8 encodes them as E4M3 with the + * reciprocal of k_scale / v_scale, R3D_DT_F16 as f16. */ +int r3d_kv_store(long k, long v, long sm, long kv, int M, int head_dim, int n_head_kv, + int block_size, int kv_dt, float k_scale, float v_scale, int k_ld, int v_ld, + long long slot_max, long sb, long sh, long so, long sd, long stream); + +/* x[r] = wte[ids[r] - vocab_offset] * wscale, narrowed once. A row whose id is out of the table's + * range is zeroed, as libref does. */ +int r3d_embed_lookup(long ids, long wte, long x, int M, int n_embd, int n_vocab, int vocab_offset, + float wscale, float mult, int x_ld, int w_ld, int dt, long stream); + +/* y[r] = x[idx[r]] and x[idx[r]] = v[r], rows of n elements. + * + * `src_rows` and `dst_rows` are the plane's own row count. Only the shim can supply it -- it has the + * operand's numel, the launcher has a pointer -- and the kernel needs it, because the reference + * reads the index plane on the host and refuses an index outside the row count, while a launch + * cannot refuse an index it has not read. So the bound travels to the kernel and the kernel acts on + * it: a gather at idx >= src_rows takes the padding path (the zero row libref's padding form + * writes), a scatter at idx >= dst_rows drops the row, which is the same refusal seen from inside a + * launch. The worst failure here is a read or a write past the plane, and a dropped row is what + * stands between this card and it. 0 means unchecked: the shim's bug to avoid, not a caller's to + * supply. */ +int r3d_gather_rows(long x, long idx, long y, int M, int n, int x_ld, int y_ld, int dt, + long long src_rows, long stream); +int r3d_scatter_rows(long v, long idx, long x, int M, int n, int v_ld, int x_ld, int dt, + long long dst_rows, long stream); + +/* ================================================================== r3d_quant_fp8.hip + * + * All three quantisers write a plain row-major code plane and one f32 scale per (row, group); no + * fragment permutation, because a dot2 GEMM reads codes in order. + */ + +/* Per-(row, group) symmetric quantisation. scale = amax * (1/top) with top 448 for E4M3 and 127 + * for int8, the codes v * (1/scale) clamped to +-top and rounded by the codec. An all-zero group + * gets scale 1. */ +int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld, int s_ld, + long stream); +int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n, int group, int x_ld, int s_ld, + long stream); + +/* quant_act_i8g: the same code at `group` granularity -- amax / 127 per (row, group), 1 for an + * all-zero group -- stored row-major. This is the plane libr3d's i8a8 GEMM reads; `quant_act_i8` + * above is the per-row plane the WMMA-ordered ops read, and the two are not interchangeable. + * 0, -1, -2, -3, -4. */ +int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group, + long long x_ld, long long s_ld, long stream); + +/* The gated form: gate_up is [M, 2n] (gate in the first n, up in the second), and what is + * quantised is act(gate) * up. `q`/`s` carry that product's codes and scales; `out_bf16`, when + * present, also receives the product in bf16. */ +int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16, int M, int n, int group, + int act, long stream); + +/* The residual add, the RMS norm and the E4M3 quantiser in one pass, so the normalised row never + * goes back to VRAM. `res` is the residual plane, INOUT, and 0 when the op has no residual: with it + * the sum is STORED, narrowed to bf16, BEFORE the variance reads it, so the norm is over the bf16 + * sum -- the `add` + `rmsnorm` pair, not `rmsnorm_add`, which normalises the unrounded sum. `ob`, + * when present, receives exactly the bf16 values the codes were taken over. Pitches are in elements + * of their own operand, `s_ld` in scales, so a dense scale plane is n/group. `group` must divide n: + * a partial group is the standalone quantiser's zero-padded store, which this pass does not have. + * 0, -1, -2, -3, -4. */ +int r3d_rmsnorm_quant_fp8(long x, long res, long w, long q, long s, long ob, int M, int n, + int group, float eps, float wadd, int x_ld, int res_ld, int ob_ld, + int q_ld, int s_ld, int wdt, long stream); + +/* y = code * scale, the read of a container's own quantised weight: group-wide f32 scales, E4M3 or + * int8 codes. */ +int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s_ld, int y_ld, + long stream); + +/* ================================================================== r3d_gemm_*.hip + * + * y[M,N] = a[M,K] @ b[N,K]^T. One output element a lane, k ascending, f32 accumulate, the sum + * narrowed once by the store. Split-K (sk > 0) writes partials to `scratch` and reduces them in a + * second kernel on the same stream; the row's scratch hook sizes the arena for the largest sk the + * band allows. + */ + +/* bf16 (and f16) operands. `nt` 1 streams the weight with non-temporal loads. */ +int r3d_gemm_nt_bf16_m16(long a, long b, long y, int M, int N, int K, int a_ld, int y_ld, int sk, + int wv, int nt, long scratch, long stream); +int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int K, int a_ld, int y_ld, int sk, + int kb, int nt, long scratch, long stream); + +/* A block-scaled fp8 weight: b is E4M3 codes, b_scale one scale per (pb1 rows of N, pb2 of K) + * block, pb1/pb2 the block sizes the container states (absent, both default to `group`). The + * scale plane is **bf16** in the container's quantised family -- `gemm_q_shape` writes + * `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})` -- and f32 only under the separate dtype `fp8a8f32`. + * a is bf16 (fp8a16, no a_scale) or E4M3 codes with per-(row, group) f32 a_scale (fp8a8). */ +int r3d_gemm_nt_q_fp8(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K, + int group, int pb1, int pb2, int a_ld, int y_ld, int sk, int nt, + long scratch, long stream); + +/* The same kernel with the scale plane's dtype named, which the 17-argument entry above cannot + * state: it forwards RAD_F32, and the container's quantised weights carry bf16 block scales. Land + * new callers on this one; the older entry is kept for callers written against its RAD_F32 + * behaviour. bs_dt is the plane's RadDataType: RAD_BF16 reads bf16, anything else -- 0 included -- + * reads f32. */ +int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K, + int group, int pb1, int pb2, int a_ld, int y_ld, int sk, int nt, + long scratch, int bs_dt, long stream); + +/* The int8 weight twin, with the optional a_sum / b_ref row sums an int8 GEMM with a zero point + * needs (libquant's symmetric form leaves them null). */ +int r3d_gemm_nt_q_i8(long a, long a_scale, long b, long b_scale, long a_sum, long b_ref, long y, + int M, int N, int K, int group, int a_ld, int y_ld, int sk, int nt, + long scratch, long stream); + +/* ================================================================== r3d_attn_paged_h128.hip + * + * Paged causal attention. `kv` is the cache the shim read its strides from; `bt` a + * [num_seqs, blocks] block table; `seqused` per-sequence lengths; cu_seqlens, when present, the + * ragged query layout; k_descale / v_descale the per-(seq, head) fp8 cache descales. + */ +int r3d_attn_decode_h128(long q, long kv, long bt, long seqused, long k_desc, long v_desc, + long cu, long out, int num_seqs, int q_len, int head_dim, int gqa, + int n_head, int block_size, int bt_cols, int bt_rs, int bt_cs, + int max_ctx, int window, int causal, + float scale, int kv_dt, long q_ld, long out_ld, int splits, long scratch, + long stream); +int r3d_attn_prefill_h128(long q, long kv, long bt, long seqused, long k_desc, long v_desc, + long cu, long out, int num_seqs, int q_len, int head_dim, int gqa, + int n_head, int block_size, int bt_cols, int bt_rs, int bt_cs, + int max_ctx, int window, int causal, + float scale, int kv_dt, long q_ld, long out_ld, long scratch, + long stream); + +/* ================================================================== r3d_gemm_fp8a8_tiled.hip + * + * The quantised GEMM at prefill heights. b_row/bs_row are the container's row strides, 0 meaning + * dense; `group` is the scale block, 128 on every band this checkpoint declares. The scales arrive + * as the container's two planes behind one operand, which is what the row's layout hook presents; + * the plain two-tensor form is the same entry with bs_row dense. + */ +int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M, int N, + int K, int group, int a_ld, long long b_row, int as_ld, long long bs_row, + int y_ld, int nt, long stream); + +/* ================================================================== r3d_gemm_mxfp4a8.hip + * + * The quantised GEMM at dtype=mxfp4a8: an OCP-MXFP4 weight against the fp8 activation. `b` is the + * e2m1 codes, two per byte, [N, K/2] u8; `b_scale` the e8m0 scale, one per 32 of K, [N, K/32] u8; + * `a` E4M3 with `a_scale` f32 per (row, 128 of K); `y` bf16. b_row/e8_row are the row strides in + * bytes, 0 meaning dense. There is no zero point: the scale is symmetric, and a reserved e8 (0, + * 255) is refused. M <= 16 takes the m16 launcher, M >= 17 the tiled one. + */ +int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N, + int K, int group, int a_ld, int y_ld, long long e8_row, long stream); +int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M, + int N, int K, int group, int a_ld, long long b_row, int as_ld, + long long e8_row, int y_ld, int nt, long stream); + +/* ================================================================== r3d_gemm_inta8.hip + * + * The quantised GEMM at dtype=w4a8 and w8a8: the symmetric int4 and int8 weight grids at decode + * heights. `b` is the signed codes (I4, two a byte, or I8, one a byte), [N, K]; `b_scale` the f16 + * scale, one per (row, 128 of K), [N, K/128]; `a` int8 in the step order with `a_scale` f32 per + * row; `y` bf16. b_rb and sb_rb are the row strides (bytes / elements), 0 meaning dense. + * There is no zero point: + * the dequant is code times scale. M <= 16 only; the prefill band is the tiled rows' and the + * 8-bit grid at prefill heights is declared out of this unit. + */ +int r3d_gemm_nt_q_w4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N, + int K, int a_ld, int y_ld, long long b_rb, long long sb_rb, long stream); +int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N, + int K, int a_ld, int y_ld, long long b_rb, long long sb_rb, long stream); + +/* ================================================================== r3d_vocab_bf16.hip + * + * The vocab-sharded logits and the top-k that follows them. + */ + +/* logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T: the decode heights (M <= 16) on + * the decode arm, a prefill arm above them, over a vocabulary-wide N. */ +int r3d_logits_gemm_bf16(long x, long lm, long y, int M, int n_vocab, int n_embd, int x_ld, + int y_ld, int sk, int nt, long scratch, long stream); + +/* Per-row top-R of a [M, N] logits row: idx (i32) and val (f32), descending, ties to the lower + * index. `pairs`, when present, also receives the (index, value) dwords a cross-rank merge reads. */ +int r3d_row_topk_bf16(long x, long idx, long val, long pairs, int M, int N, int R, int vocab_off, + int x_ld, int rc, int nch, long scratch, long stream); + +/* The cross-rank top-1: one id and one value a row, out of [M, n] candidate pairs. */ +int r3d_pair_argmax(long pairs, long idx, long val, int M, int n, long stream); + +/* ================================================================== r3d_sample_f32.hip + * The sampler, and the vocabulary row it starts from. + * + * The shapes are libref's, operand for operand, and so is the `params` plane: + * one `RadSampleParams` a row, 96 bytes of f32 words, which every stage reads by field. `logits` is + * f32 and the candidate planes are word-typed -- `cand_idx` i32, `cand_val` f32, the pair planes + * i32 holding an id's bits beside a logit -- because that is what the reference writes. + * + * The stages over the full vocabulary (argmax, temp, topk, logprobs, penalties, dry, ngram_ban) are + * one block a row and are bound by the plane: at the band MiniCPM5-2B asks for, 2048 rows of 130560 + * f32, the logits are 1.02 GiB and one pass is the floor. The stages over the candidate set (the + * four narrowings and pick) are one block a row of `n_cand` and are bound by the arithmetic, which + * is why `pick` keeps the reference's double `exp`: the law is `(float)std::exp((double)x)`, and a + * hardware `v_exp_f32` two ulp away moves a draw whenever a true probability lands within an ulp of + * the `u < cum` boundary. + * + * M comes off the operand, never off the band: the band's `M` is a range's bound and a step's row + * count is what the planes hold. 0, -1 null pointer, -2 bad extent, -3 pitch, -4 launch failed. + */ +int r3d_row_topk(long x, long idx, long val, long pairs, int M, int N, int R, int x_dt, + long long x_ld, long long idx_ld, long long val_ld, long long pairs_ld, + int vocab_off, long stream); +int r3d_sample_argmax(long lg, long tok, int M, int n_vocab, long long lg_ld, long stream); +int r3d_sample_temp(long lg, long params, int M, int n_vocab, long long lg_ld, long stream); +int r3d_sample_topk(long lg, long params, long ci, long cv, long pairs, int M, int n_vocab, + int n_cand, long long lg_ld, long long ci_ld, long long cv_ld, + long long pairs_ld, int vocab_off, long stream); +int r3d_sample_pick(long ci, long cv, long params, long tok, int M, int n_cand, + long long ci_ld, long long cv_ld, long stream); + +/* The four narrowing stages: one shape, `cand_idx` and `cand_val` in place, one predicate each -- + * top-p a prefix rule in candidate order, min-p a floor under the best candidate's probability, + * typical the band around the set's entropy, XTC the exclusion-the-model-would-not-choose cut. */ +int r3d_sample_topp(long ci, long cv, long params, int M, int n_cand, long long ci_ld, + long long cv_ld, long stream); +int r3d_sample_minp(long ci, long cv, long params, int M, int n_cand, long long ci_ld, + long long cv_ld, long stream); +int r3d_sample_typical(long ci, long cv, long params, int M, int n_cand, long long ci_ld, + long long cv_ld, long stream); +int r3d_sample_xtc(long ci, long cv, long params, int M, int n_cand, long long ci_ld, + long long cv_ld, long stream); + +/* The pre-filters over the logits row. `hist` is the row's history of global token ids, i32 + * [M, max_hist]; its window, and the rule that a token is penalised at its first occurrence in the + * window, are libref's (`hist_window`), and the window is placed inside the params plane by the + * descriptor's `fill_chunk`. `vocab_off` shifts the ids a stage reports, for a split vocabulary. */ +int r3d_sample_penalties(long lg, long params, long hist, int M, int n_vocab, long long lg_ld, + long long hist_ld, int vocab_off, long stream); +int r3d_sample_dry(long lg, long params, long hist, long breakers, int M, int n_vocab, + long long lg_ld, long long hist_ld, int vocab_off, long stream); +int r3d_sample_ngram_ban(long lg, long params, long hist, long ngram, long whitelist, int M, + int n_vocab, long long lg_ld, long long hist_ld, int vocab_off, + long stream); +int r3d_sample_mask(long lg, long params, long bitmask, int M, int n_vocab, long long lg_ld, + int mask_rows, long stream); +/* The gated MLP band: b is E4M3 codes of N = 2n rows (gate rows [0,n), up rows [n,N)), b_scale one + * scale per (group, group) block, bf16 as the container writes it. The row is narrowed to bf16 as + * the unfused pair leaves it, gated (act: R3D_ACT_SILU | R3D_ACT_SIGMOID), narrowed again, and coded + * per group of `group` columns: q is the codes [M,n], scale the per-(row, group) amax scales, and + * out_bf16 the narrowed gated tensor when the caller wants it (y_ld is its row pitch, n when the + * plane is absent). M <= 64, sk == 1; no scratch, because the row never leaves the registers. */ +int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, long q, long scale, + long out_bf16, int M, int N, int K, int group, int act, + int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch, long stream); + +/* The same kernel naming the scale plane's dtype. The entry above forwards RAD_BF16, which is the + * container's form for this op; f32 is accepted and equal bit for bit. */ +int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale, long q, long scale, + long out_bf16, int M, int N, int K, int group, int act, + int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch, + int bs_dt, long stream); + +/* DFlash2's greedy walk over the candidate lattice. `hp` may be 0: the plane of ones the reference + * computes when the operand is absent. The rows of cand, unary and tokens are (sequence, step), + * M * steps of them; `anchor` is a row of M * anchor_stride ids. */ +int r3d_dflash_select(long cand, long unary, long hp, long anchor, long pred, long succ, + long tokens, int M, int steps, int top_k, int rank, int n_vocab, + int anchor_stride, long long cand_ld, long long un_ld, long long hp_ld, + long long pred_ld, long long succ_ld, long long tok_ld, long stream); +int r3d_sample_logprobs(long lg, long params, long stats, int M, int n_vocab, int k, + long long lg_ld, long long stats_ld, int vocab_off, long stream); + +} /* extern "C" */ + +#endif /* RAD_R3D_H */ diff --git a/libr3d/r3d_args.h b/libr3d/r3d_args.h new file mode 100644 index 00000000..4738edf6 --- /dev/null +++ b/libr3d/r3d_args.h @@ -0,0 +1,310 @@ +/* r3d_args.h -- how a libr3d entry point reads its arguments. + * + * There is no adapter layer. An entry point takes `(const RadArgs*, RadStream)` and returns a + * status, the same RadLaunchFn contract every other plugin implements; an out-of-tree author can + * write the same kernel without an adapter they could not reach. + * + * This header holds the shared helpers: reading a parameter, finding an operand, testing + * contiguity. Most are one line over rad_abi.h. + * + * Nothing here includes r3d.h or HIP: host translation units (the row table, the shape hooks) + * include it too, so those tables compile and can be checked without ROCm. + */ +#ifndef R3D_ARGS_H +#define R3D_ARGS_H + +#include "rad_abi.h" +#include "rad_plugin.h" + +#include +#include +#include +#include + +/* ================================================================== parameter access + * + * Forwards to rad_abi.h's static inline helpers, the ones a third-party plugin gets, keeping + * libr3d's spelling at its call sites. */ +static inline int r3d_geti(const RadArgs* a, const char* k, long long* out) { + return rad_args_geti(a, k, out); +} + +static inline long long r3d_geti_or(const RadArgs* a, const char* k, long long dflt) { + return rad_args_geti_or(a, k, dflt); +} + +static inline const char* r3d_gets(const RadArgs* a, const char* k) { + return rad_args_gets(a, k); +} + +/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so `dval` arrives + * and the step path runs no strtod. Deliberately laxer than rad_args_getf_or: string and integer + * spellings are still read, because a tool or selftest may call a launch directly with no declare + * to enforce the type. */ +static inline double r3d_getf(const RadArgs* a, const char* k, double dflt) { + if (!a || !k) return dflt; + for (int i = 0; i < a->n_p; ++i) { + if (!a->p[i].key || std::strcmp(a->p[i].key, k) != 0) continue; + if (a->p[i].kind == RAD_P_F64) return a->p[i].dval; + if (a->p[i].kind == RAD_P_INT) return (double)a->p[i].ival; + if (a->p[i].kind == RAD_P_STR && a->p[i].sval && a->p[i].sval[0]) { + char* end = nullptr; + const double v = std::strtod(a->p[i].sval, &end); + return (end && end != a->p[i].sval) ? v : dflt; + } + return dflt; + } + return dflt; +} + +/* An enumerated parameter: `act` is "silu" or "sigmoid", not 0 or 1, so a --debug-graph dump says + * what runs; the mapping to libr3d's integer lives in the shim. Returns -1 for an unknown name, + * which every caller turns into RAD_E_INVAL. `alt` is libr3d's own integer spelling of the same + * key, consulted only when the name is absent. */ +static inline int r3d_act_code(const RadArgs* a, const char* key, const char* alt, int dflt) { + if (const char* s = r3d_gets(a, key)) { + if (!std::strcmp(s, "silu") || !std::strcmp(s, "swish")) return 0; + if (!std::strcmp(s, "sigmoid")) return 1; + return -1; + } + long long v = 0; + if (alt && r3d_geti(a, alt, &v)) return (v == 0 || v == 1) ? (int)v : -1; + return dflt; +} + +/* Same, off a bare RadParam list (init() and the layout hooks); forwards to rad_plugin.h's + * rad_param_*. */ +static inline long long r3d_pgeti_or(const RadParam* p, int n_p, const char* k, long long dflt) { + return rad_param_geti(p, n_p, k, dflt); +} + +static inline const char* r3d_pgets(const RadParam* p, int n_p, const char* k) { + return rad_param_gets(p, n_p, k, nullptr); +} + +/* ================================================================== operand access + * + * An absent optional operand is a null RadTensor.data (rad_abi.h). r3d_opt() returns null both + * past the end and for a present-but-null operand, so an optional test is one pointer test. For a + * required operand the caller turns null into RAD_E_INVAL: it is a bug in the issue, not a shape + * the kernel declines. + */ +static inline const RadTensor* r3d_opt(const RadArgs* a, int i) { return rad_arg_in(a, i); } + +/* An optional operand the plan carries a slot for, with no bytes behind it, is ABSENT -- it is not a + * dtype problem. The engine hands the slots of an op's optional operands as descriptors with a null + * `data` when the graph did not bind one, and a shim that dtype-checks such a descriptor would refuse + * a band the op never reads -- `rmsnorm_quant_fp8` answering E_DTYPE to a band whose dtype is fine, + * for an empty `out_bf16` slot. Every test of an optional operand goes through here; a bare `if (t)` + * is the bug. */ +static inline bool r3d_has(const RadTensor* t) { return t && t->data; } + +static inline const void* r3d_p(const RadTensor* t) { return t ? t->data : nullptr; } + +/* The same for an operand a kernel writes, so an output cast reads as one rather than as a pointer + * laundered through `long`. */ +static inline void* r3d_wp(const RadTensor* t) { return t ? t->data : nullptr; } +static inline long r3d_addr(const RadTensor* t) { return t ? (long)(uintptr_t)t->data : 0L; } + +static inline long long r3d_dim(const RadTensor* t, int i) { + if (!t || i < 0 || (uint32_t)i >= t->rank) return 0; + return t->shape[i]; +} + +static inline long long r3d_stride(const RadTensor* t, int i) { + if (!t || i < 0 || (uint32_t)i >= t->rank) return 0; + return t->stride[i]; +} + +static inline long long r3d_numel(const RadTensor* t) { return rad_tensor_numel(t); } + +/* [rows..., K] flattened to (M, K). Every per-row kernel in libr3d owns whole rows (one workgroup + * per row), so the leading axes are only a row count. The GEMM makes the same fold explicitly. */ +static inline int r3d_rows_of(const RadTensor* t, long long* M, long long* K) { + if (!t || t->rank < 1) return RAD_E_SHAPE; + *K = t->shape[t->rank - 1]; + *M = 1; + for (uint32_t i = 0; i + 1 < t->rank; ++i) *M *= t->shape[i]; + return (*M >= 1 && *K >= 1) ? RAD_OK : RAD_E_SHAPE; +} + +/* Dense row-major over the whole tensor. libr3d's entry points take at most one pitch, so + * everything else must be tight, and the shim checks it. This is the "necessary condition only" + * boundary of spec §2.1: the constraint table settles geometry, contiguity is a property of the + * call. */ +static inline int r3d_contig(const RadTensor* t) { return rad_tensor_is_contiguous(t); } + +/* Contiguous in every axis but the leading one, whose stride is the row pitch libr3d takes as an + * explicit argument (`x_ld`, `a_stride`, ...). Returns the pitch in elements, or -1. */ +static inline long long r3d_row_pitch(const RadTensor* t) { + if (!t || t->rank == 0) return -1; + if (t->rank == 1) return 1; + long long acc = 1; + for (int i = (int)t->rank - 1; i >= 1; --i) { + if (t->shape[i] != 1 && t->stride[i] != acc) return -1; + acc *= t->shape[i]; + } + return t->stride[0]; +} + +/* [rows..., n] read as (rows, n): the leading axes are a row count and only the last is + * structural. Returns the pitch in elements, or -1. + * + * A column slice must refuse. k out of a fused [tok, 2*kv_dim] projection, read as + * [tok*n_head_kv, head_dim] for a per-head norm, has rows `n` apart within a token and a buffer row + * apart between tokens; no single pitch describes that, and the leading stride would make the + * consumer read most heads from garbage. So the trailing axes must cover the whole row. */ +static inline long long r3d_rows_pitch(const RadTensor* t, long long n, long long* rows) { + if (!t || t->rank < 1 || n <= 0) return -1; + const long long nel = rad_tensor_numel(t); + if (nel % n) return -1; + *rows = nel / n; + if (t->rank == 1) return n; + if (t->shape[t->rank - 1] == n) { + if (t->stride[t->rank - 1] != 1) return -1; + return t->rank >= 2 ? t->stride[t->rank - 2] : n; + } + if (rad_tensor_is_contiguous(t)) return n; + long long trail = 1; + for (int i = 1; i < (int)t->rank; ++i) trail *= t->shape[i]; + return trail == n ? r3d_row_pitch(t) : -1; +} + +/* An attention operand, [tokens, heads * head_dim] over its trailing axes: the token count, head + * count and row pitch in elements. False when the trailing axes are not whole heads or no single + * pitch describes the rows. */ +static inline bool r3d_head_rows(const RadTensor* t, long long head_dim, long long* n_tok, + long long* n_head, long long* ld) { + long long width = 1; + for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i]; + if (t->rank < 2 || width % head_dim) return false; + *n_head = width / head_dim; + *ld = r3d_rows_pitch(t, width, n_tok); + return *ld >= 0; +} + +/* 16-byte alignment, needed by every kernel that loads a dword pair per lane. The kernels do not + * check it, so the shim does. */ +static inline int r3d_aligned(const void* p, unsigned bytes) { + return p ? (((uintptr_t)p & (uintptr_t)(bytes - 1)) == 0) : 1; +} + +/* ================================================================== which check refused + * + * A shim refuses in many places with the same few codes, so the engine's report names the kernel + * and geometry but not the failing condition. R3D_NO() wraps a refusal and prints its own line when + * RAD_R3D_TRACE is set; otherwise it is the bare return plus one cached-flag load on a path that is + * failing anyway. */ +static inline int r3d_trace_on(void) { + static int on = -1; + if (on < 0) { const char* e = std::getenv("RAD_R3D_TRACE"); on = (e && *e && *e != '0'); } + return on; +} +static inline int r3d_refused(int code, const char* file, int line) { + if (r3d_trace_on()) std::fprintf(stderr, "[r3d] %s:%d refused -> %d\n", file, line, code); + return code; +} +#define R3D_NO(code) r3d_refused((code), __FILE__, __LINE__) + +/* The descriptor we were handed, printed when we decline one. A stride refusal that names no stride + * is a refusal the reader has to reproduce, and reproducing it costs a probe cycle: the engine binds + * rank, shape and strides in ELEMENTS, and the shape it binds is the step's, not the band's. */ +static inline void r3d_trace_desc(const char* what, const RadTensor* t) { + if (!r3d_trace_on()) return; + if (!t) { std::fprintf(stderr, "[r3d] %s: (absent)\n", what); return; } + std::fprintf(stderr, "[r3d] %s: dtype %u rank %u shape [", what, t->dtype, t->rank); + for (int i = 0; i < (int)t->rank; ++i) std::fprintf(stderr, "%s%lld", i ? "," : "", (long long)t->shape[i]); + std::fprintf(stderr, "] stride ["); + for (int i = 0; i < (int)t->rank; ++i) std::fprintf(stderr, "%s%lld", i ? "," : "", (long long)t->stride[i]); + std::fprintf(stderr, "] data %p\n", t->data); +} +#define R3D_STR(why, a1, v1, a2, v2) \ + do { \ + if (r3d_trace_on()) \ + std::fprintf(stderr, "[r3d] %s:%d stride refusal: %s, %s %lld, %s %lld\n",\ + __FILE__, __LINE__, (why), (a1), (long long)(v1), (a2), \ + (long long)(v2)); \ + return R3D_NO(RAD_E_STRIDE); \ + } while (0) + +/* ================================================================== dtype helpers + * + * A row's `dtype` constraint is a necessary condition on the geometry, not a promise about the + * tensors: the shim reads the dtype off the operand, and these are the tests it reads it with. */ +static inline int r3d_is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; } +static inline int r3d_is_f16(const RadTensor* t) { return t && t->dtype == RAD_F16; } +static inline int r3d_is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; } +static inline int r3d_is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; } +static inline int r3d_is_i64(const RadTensor* t) { return t && t->dtype == RAD_I64; } +static inline int r3d_is_fp8(const RadTensor* t) { + return t && (t->dtype == RAD_F8E4M3 || t->dtype == RAD_F8E5M2); +} +static inline int r3d_is_e4m3(const RadTensor* t) { return t && t->dtype == RAD_F8E4M3; } +static inline int r3d_is_i8(const RadTensor* t) { return t && t->dtype == RAD_I8; } +static inline int r3d_is_u8(const RadTensor* t) { return t && t->dtype == RAD_U8; } + +/* The dtype name a row's constraint table carries, for a shim that must match a string parameter + * against an operand. */ +static inline int r3d_dt_named(uint32_t dt, const char* name) { + if (!name) return 0; + if (!std::strcmp(name, "bf16")) return dt == RAD_BF16; + if (!std::strcmp(name, "f16") || !std::strcmp(name, "fp16")) return dt == RAD_F16; + if (!std::strcmp(name, "f32") || !std::strcmp(name, "fp32")) return dt == RAD_F32; + if (!std::strcmp(name, "fp8_e4m3") || !std::strcmp(name, "e4m3")) return dt == RAD_F8E4M3; + if (!std::strcmp(name, "fp8_e5m2") || !std::strcmp(name, "e5m2")) return dt == RAD_F8E5M2; + if (!std::strcmp(name, "i8") || !std::strcmp(name, "int8")) return dt == RAD_I8; + return 0; +} + +/* ================================================================== libr3d's constants + * + * Restated here because r3d_rows.cpp and r3d_shapes.cpp are host code built without ROCm and cannot + * include r3d.h, and because a .rad container records them in its layout tag. */ +enum { + R3D_WAVE = 32, + /* The activation quantiser's group: the width a scale covers along n. 128 is the WEIGHT + * scale's block width and therefore a property of the checkpoint, not a knob. */ + R3D_ACT_GROUP = 128, + /* Block-scaled fp8, on both axes: the checkpoint's `quantization_config.weight_block_size`, + * which the bytes on disk follow. The entry points reject a mismatch. */ + R3D_FP8_BLOCK = 128, + /* The int8 weight group, the same 128 the checkpoint's scales use. */ + R3D_W8_GROUP = 128, + /* The largest N a dot2 GEMM's per-lane accumulator grid spans in one wave. */ + R3D_NTILE = 16, + /* The operand count of `gemm_nt_q` (a, a_scale, b, b_scale, y, a_sum, b_ref). The shape hook + * builds the whole list at once and needs a name for its length; the schema in r3d_rows.cpp is + * the authority, and rad-kbench checks the two against each other. */ + R3D_GEMM_Q_NOPERAND = 7 +}; + +/* ================================================================== libr3d's tunables + * + * The knobs the row table declares, exposed so `rad-tune` can walk them and `--debug-graph` can + * name the pick (spec §15). The chosen point comes back appended to RadArgs::p, so a launch reads + * it with r3d_geti_or like any other parameter; these structs are how a launch reads several at + * once, with the row's defaults where a caller supplied none. + * + * sk == 0 means "choose the largest legal split count at issue". Split-K requires + * K % (sk * group) == 0, so no fixed default is legal at every shape, and an illegal default would + * make an untuned install fail rather than run slowly. The sentinel is resolved in one place, in + * the GEMM unit. + */ +struct R3dGemmCfg { int wv, sk, kb, nt; }; /* waves a block, split-K, K slab, non-temporal loads */ +struct R3dSplitCfg { int splits; }; /* split-KV segments; 0 is the kernel's own law */ +struct R3dTopkCfg { int rc, nch; }; /* candidates a chunk keeps, chunk width in columns */ + +extern "C" { +/* -- the tuned configuration (r3d_rows.cpp) -- + * + * The core picked a point in the space the row declared and appended it to RadArgs::p. These read + * it back, falling to the axis's default (defined once, in the RadTunable table) when a caller + * supplied none, so a checker with no tuned key runs what an untuned install runs. They cannot + * fail: the loader refuses a plugin whose default is not one of the axis's values. */ +void r3d_cfg_gemm (const RadArgs*, struct R3dGemmCfg*); +void r3d_cfg_split(const RadArgs*, struct R3dSplitCfg*); +void r3d_cfg_topk (const RadArgs*, struct R3dTopkCfg*); + +} /* extern "C" */ + +#endif /* R3D_ARGS_H */ diff --git a/libr3d/r3d_attn_paged_h128.hip b/libr3d/r3d_attn_paged_h128.hip new file mode 100644 index 00000000..3838d965 --- /dev/null +++ b/libr3d/r3d_attn_paged_h128.hip @@ -0,0 +1,1823 @@ +/* r3d_attn_paged_h128.hip -- paged attention at head_dim 128, the two bands MiniCPM5-2B declares. + * + * out[tok, h, :] = softmax_j( scale * q[tok, h, :] . K[j, h/gqa, :] ) . V[j, h/gqa, :] + * + * over a paged cache, in libref's order. The order is the point of the file: a + * tolerance on an attention output is not where a summation-order difference hides, so this kernel + * keeps the chain the reference writes, and says out loud where it cannot. + * + * ============================== the layout ============================== + * + * kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K then V inside a slot + * + * A slot's K is 128 elements and V the 128 after it, so a key's row is a 512-byte pair and both + * halves are 16-byte aligned at every slot. `block_table[seq, j / block_size]` names the block + * holding key j; the fixture *draws* its entries over [0, max_blocks), so ids repeat and one block + * serves several keys. A negative entry is an unmapped block and hides its key -- the engine's + * allocator frees a sequence by writing -1 into rows it is done with, so the kernel keeps the test + * even though the fixture never sets it. `seqused[seq]` is the sequence's TOTAL key count, this + * step's query rows included, so query row i of a len_s-row step sits at absolute position + * `seqused[s] - len_s + i`. One kernel serves decode (q_len 1), a speculative verify (q_len 7) and a + * prefill chunk (q_len 2048). + * + * ============================== the ragged batch ============================== + * + * A step's sequences do not have to contribute the same number of query rows. `cu_seqlens`, when + * the caller has it, is [n_seq + 1] of i32 with cu[0] == 0 and cu[n_seq] == the query plane's row + * count, and sequence s owns the rows [cu[s], cu[s+1]) -- `len_s = cu[s+1] - cu[s]` rows, whose + * positions run from `seqused[s] - len_s`. That is libref's reading and not a local invention: + * its shape hook (`cu[n_seq] == rows`, `q_len = cus ? 0 : rows / n_seq`) and its walk, where + * the row's sequence, its length and its index within the sequence come from the descriptor and the + * position from the sequence's own length. So `q_len` is a PER-SEQUENCE number in the reference and + * in this file; the total row count is the plane's, and a ragged batch has no q_len at all. + * + * One grid covers a ragged batch because the clamp the width section documents is per sequence: a + * tile is `ceil(len_s / rows_per_tile)` tiles for sequence s, and the slots of its last tile past + * `len_s` compute a duplicate that stores nothing. The rows are laid out by `map_seq`, which walks + * the descriptor once a workgroup -- a rectangular batch is the same walk with len_s = q_len and + * cu[s] = s * q_len, so there is one mapping, one mask, one walk and one store for both forms. + * The causal mask, the window, the block-table walk and the descales all key off the sequence the + * row belongs to, exactly as the reference's `s = seq_of(cus, n_seq, tok)` keys them. + * + * ============================== the mask ============================== + * + * causal = 1 key j visible when j <= pos + * causal = 0 key j visible when j < ctx + * window > 0 causal: additionally pos - j < window; non-causal: |pos - j| < window, the + * two-sided reading libref's prose and libr4d's window kernel both state. + * + * A masked key is skipped, never scored to -inf: the denominator gets exactly the terms the + * reference has, and a row with no visible key stores zeros, which is libref's `mx == -INFINITY` + * case and every other kernel in the project. + * + * ============================== the tile ============================== + * + * An output row is (query row, query head): 128 dims, one f32 chain per dim. A lane owns one output + * row, exactly as the skinny GEMM rows do, and for the same reason -- a lane's chain over keys is + * the reference's chain, and no cross-lane reduction touches the denominator. A wave32 is 32 output + * rows, and they must be 32 rows that read the same KV, which fixes the mapping: + * + * kh = blockIdx.y h = kh * GQA + (lane & (GQA-1)) tok = base + (lane >> lg GQA) + * + * so a wave is the GQA query heads of one KV head over 32/GQA query rows -- 8 heads x 4 rows at + * gqa = 8. Every lane of a wave then reads the same cache row at the same moment, which makes every + * cache read in this file an LDS broadcast (one `ds_read_b128` serves the wave) and makes the paged + * walk a per-wave event rather than a per-lane one. A workgroup is WAVES waves = WAVES x 32 threads + * = WAVES x (32/GQA) query rows of one sequence, one KV head: 16 rows at gqa 8 with four waves. + * WAVES is a template parameter and the launcher picks it -- see "the width of a workgroup" below. + * + * Rows per cache read is 32. It is also the ceiling the register file sets: a lane carrying a second + * output row needs 2 x 64 VGPRs of widened query and 2 x 128 of f32 accumulator, 384, over the 256 + * that four waves a SIMD allows. So the traffic is what gqa and the register file say it is. + * + * ============================== the width of a workgroup ============================== + * + * A row slot whose row is past its sequence's length computes a clamped duplicate: the walk, the + * tile and the store all run for it and the result is dropped. At the decode band's q_len = 7 with + * gqa = 8 a four-wave workgroup carries 16 row slots for 7 rows -- twice the walk for half the + * outputs. So the launcher picks the narrowest workgroup that carries the caller's q_len (pick_waves: + * one wave to 32/GQA rows, two to 64/GQA, four above), and prefill keeps four because its q_len is the + * whole chunk. At the decode band that is two waves: 512 workgroups of 64 threads, 7 of 8 slots used. + * A ragged batch has no one q_len to pick on: the launcher picks on the average sequence + * (`ceil(rows / n_seq)`), which is a performance choice and nothing else -- the tile width moves + * duplicate rows between tiles, never a result, and no host code reads the descriptor. + * + * Measured on the card: medians of 15 per-launch event times, both widths in one session, so the + * clock drifts together (both read the prefill band at 44.9): + * + * decode 256 x 7 @4096 294.7 ms -> 158.4 ms -46% + * decode 256 x 7 @4096 sp4 268.0 ms -> 128.4 ms -52% + * decode 8 x 7 @2048 sp8 4.33 -> 2.06 ms -53% + * decode 1 x 7 @4096 sp8 4.27 -> 3.97 ms -7% + * prefill 2048 x 2048 44.95 -> 44.78 ms the path is unchanged + * + * The tile is the same 8 KiB at every width, so nothing about the cache traffic changes; the win is + * the duplicated rows, and the reason it is this large is the one the counters show: the kernel + * issues 15% of the SIMD's slots at the band (SQ_INSTS_VALU 4.5G against 30G of capacity, + * SQ_INSTS_LDS 769M) and 3.7% at eight sequences. Halving the arithmetic on a kernel that is + * stalling is not supposed to buy 46%; it does, and that says the stall is a function of how many + * waves a workgroup has to bring to a barrier -- two arriving is not twice as cheap as four, it is + * four times cheaper. The width is a run-time choice because it is the only lever on this op that + * moves the band. + * + * ============================== measured, and not the answer ============================== + * + * Four things that look like they should work, each measured to not (medians of 15 per-launch + * hipEventElapsedTime, A/B in one process), so the next reader does not spend an hour on them: + * + * s_setprio 1 around the consume leg of the walk, 0 after: |delta| <= 0.7% on the bands. The + * knob is fine -- `s_setprio` takes an immediate, not an SGPR, so `s_setprio %0` will not link -- + * but priority does not move this op. + * + * R3D_WAVES(2) to lift the scalar-register ceiling: the bf16 arms report sgpr_count 107 and + * sgpr_spill_count ~98 at BOTH 4 and 2 waves a SIMD, and the timings do not move. The + * compute-shader scalar budget is not set by waves/SIMD the way the VGPR one is, so this is not + * a lever for the spills. + * + * __noinline__ on the stage leg: the spills drop (98 -> 72) and a 160-byte private frame + * appears, timings unchanged. The spills are a load-safety matter, not a time matter: while the + * bf16 arms spill SGPRs, a kernel in this TU that also needs a private segment fails to launch + * with "the operation cannot be performed in the present state". + * + * A two-stage pipeline -- two tiles, the next block's global loads issued before the current + * block is consumed, one barrier a block instead of two: a wash on the bands. The walk's + * per-block structure is the cost, and the two legs do not overlap at all -- the workgroup's + * width is the lever. + * + * ============================== the walk ============================== + * + * block_size = 16, so keys advance 16 at a time and one step stages a block of the KV head: 16 slots + * x 128 elements, K and V, widened to f16 pairs on the way in, 4 KiB each. The four waves of a + * workgroup share the stage, so a block of cache is one global read per workgroup per pass, and the + * walk costs 8 KiB of the 64 KiB of LDS. The second pass re-reads the same blocks; a sequence's + * cache for one KV head is ctx x 256 B, which at 4096 keys is 1 MiB, so the second pass is an L2 + * hit and the card's DRAM sees each byte once. + * + * The mask sits where the geometry puts it: a wave's query rows are consecutive, so at gqa 8 its + * four positions span 3 and its diagonals lie in one 16-key block, two at a block boundary. Blocks + * entirely below the wave's minimum position are walked with no mask code at all; the one or two + * diagonal blocks test `j <= pos` per lane; blocks past the wave's maximum position are not walked. + * In a 2048-token causal prefill that is one masked block in sixty-four. + * + * ============================== the two passes ============================== + * + * The reference is two-pass: pass one every visible key's score and the maximum; pass two, ascending + * keys, `w = exp(score - max)`, `sum += w`, `acc[d] += w * v[d]`, then `acc * (1/sum)` and one + * narrowing at the store. Online softmax -- the flash form, rescaling a running accumulator by + * `exp(m_old - m_new)` -- brackets the denominator and every acc[d] differently, so it is not in + * this file. Keeping the scores as the reference does costs a workspace of jcap floats a row: 32 + * rows x 4096 keys = 512 KiB a wave against 64 KiB of LDS. So the two passes are two walks, and + * pass two recomputes the scores it needs -- same order, same operands, bit-identical the second + * time. QK is paid twice and the op costs half again what keeping the scores would; that is the + * price of the reference's parentheses. + * + * QK is 64 `v_dot2acc_f32_f16` a key a lane over widened f16 pairs, ascending d. A dot2 folds a + * pair's two products into the accumulator in one rounding where the reference rounds per product, + * so a lane's score chain brackets the reference's: the same one-ulp departure the bf16 GEMM row + * documents, on a fraction of a percent of outputs, one bf16 store ulp each. + * + * P . V is 128 f32 multiply-accumulates a key a lane, `acc[d] += w * v[d]` with -ffp-contract=off, + * which is the reference's expression with vds already folded into the staged V. dot2 cannot do this + * leg in this layout: w is a per-lane scalar and the accumulation is per dim, so the only route to + * the matrix path is to fold w into V -- and w is f32, so every weight of the sum would be read to + * 11 bits, a ~1e-4 relative change on the output that survives the bf16 store as a few percent of + * outputs moved one ulp. It is a third of the instruction count, and it is not the default; the + * numbers this unit is measured with are the f32 leg's. + * + * ============================== exp ============================== + * + * `ref_exp` is `(float)std::exp((double)x)`: the reference's exponent is correctly rounded to f32 + * through a double. RDNA3 has no vector f64 -- double is soft-float, hundreds of cycles a call, and + * a call per key per lane is the whole kernel. The device libm's `expf` is a ~1-ulp polynomial and + * `__expf` is two orders of magnitude worse. `exp_ref` is a software expf: two-term range reduction + * against a split ln2, a degree-8 polynomial, and 2^k assembled in the integer domain (no libm call + * in the hot path). It is the only place in this library where an explicit `__fmaf_rn` is allowed, + * and the rule it is an exception to is the no-FMA rule: that rule exists because libref's + * expressions contain no FMA and a contracted multiply-add changes the order of rounding in + * arithmetic we are required to reproduce. Here the thing we must reproduce is a *function* libref + * computes in double precision on hardware that has f64 and this card does not. The polynomial's + * FMA is arithmetic we chose, scoped to this helper, to get the closest legal transcription of that + * function; it contracts no expression the reference wrote. + * + * `exp(0)` is exactly 1.0: k is 0, the reduction leaves r exactly 0, and the polynomial's constant + * term passes through untouched. The argument here is always <= 0 (the max is taken over the same + * set the exponentials are taken of), so the domain that matters is x <= 0. Below -103.98 the + * result is under f32's smallest subnormal and the helper returns 0; the reference's + * `(float)exp(-100)` is a denormal of order 3.7e-44, and a term that small added to a denominator + * of order 1 is not a change of any kind, let alone one that survives a bf16 store -- which is the + * reason the flush is legal and not an approximation to defend. Between -103.98 and -87.3 the + * result is subnormal, and the helper reaches it by one hardware multiply by 2^-126, so it is + * rounded the way the hardware rounds and not by hand. + * + * ============================== split-KV ============================== + * + * The decode entry takes `splits`: a sequence's blocks are cut into slices of a whole number of + * blocks, each slice accumulating its own (acc[128], sum, max) into scratch, and a second kernel + * combines the slices before the single narrowing. Combining needs the slices' maximum, so each + * slice's partial is rescaled by `exp(m_slice - M)`: the denominator becomes + * `sum = Σ_slices sum_s * exp(m_s - M)`, ascending in slice, and every term arrives as + * `exp(s - m_s) * exp(m_s - M)` where the reference has `exp(s - M)`. Both are last-bit at the f32 + * level -- ~2 ulp per term, ~1 ulp on the sum -- and both vanish under the bf16 store except on + * outputs sitting on a rounding boundary. The row's prose says `splits > 1` is not bit-identical to + * the reference and `splits = 1` is. + * + * `splits` is a maximum, resolved per sequence from its own `seqused`: `nslice = ceil(nblk / + * ceil(nblk / splits))` with nblk the sequence's block count, so a short sequence uses fewer slices + * and there is no per-sequence legality check to fail. `nslice` is recomputed by the reducer from + * the same two numbers, so the partials need no header beyond (acc, sum, max). + * + * ============================== what the shims refuse ============================== + * + * head_dim other than 128 (`RAD_E_SHAPE`; this file is named for it); a cache dtype other than bf16 + * and fp8_e4m3 -- an f32 cache has no dot2 path, and u8/u4/int8 codes are not this cache form + * (`RAD_E_DTYPE`); a query dtype other than bf16 or f16, and an out dtype that is not the query's + * (`RAD_E_DTYPE`); gqa outside {1,2,4,8} or not dividing n_head (the wave's head split is a shift); + * block_size other than 16 (the stage is sized for one); q_len < 1 in a rectangular batch, and a + * row count < 1 in a ragged one; a row count that does not fit the plane's 32-bit row indexing + * (num_seqs * q_len, or cu[n_seq], past 2^31); a q, kv or out stride that puts a slot's halves off + * a 16-byte boundary, or a row pitch that is not a multiple of 8; a `cu_seqlens` that is not i32 + * (`RAD_E_DTYPE` -- the kernel reads int, and the fix is an i32 plane, which is what the op + * describes), is not contiguous (`RAD_E_STRIDE`), is not [n_seq + 1] (`RAD_E_SHAPE`), or is not + * 4-byte aligned (`RAD_E_ALIGN`); descales attached to a bf16 cache, which the reference ignores + * and this kernel refuses rather than drops, and an fp8 cache missing them (`RAD_E_SHAPE`); an + * output shorter than rows * n_head * head_dim; and a scratch arena too small for the partials the + * requested `splits` needs, which the launcher answers by lowering `splits` to what the arena + * holds, down to 1, which needs none. + * + * What the descriptor carries that the host cannot see is clamped, not refused, because a launcher + * reads no device memory: cu[0] == 0, monotonicity and cu[n_seq] == the plane's row count are the + * description's promises (the reference's shape hook states all three), and the kernel's answer to each + * is the reference's own. Rows past the plane are dropped (`row_ok` tests the plane's row count, so + * a descriptor that runs long cannot write outside `out`); a segment with cu[s+1] <= cu[s] has no + * tiles and contributes no rows, which is the reference's `if (qlen <= 0) return;` + * (the reference's walk); and rows under cu[0] belong to sequence 0 with a negative index into its + * query, which is what `seq_of` gives them. + */ +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_args.h" +#include "r3d_launch.h" + +#include + +#include +#include /* size_t, in the arena indexing and the shim's scratch sizing */ +#include /* the device print, behind the budget; the shims already use std::fprintf */ +#include /* std::getenv / std::atoi, in the arming */ + +/* ================================================================== the device record ring + * + * THE LAW. A kernel that calls device `printf` is given an extra implicit argument -- + * `hidden_hostcall_buffer` -- and the engine's AQL dispatcher does not provide it, so a kernel that + * prints is UNDISPATCHABLE BY THE ENGINE: the instrument is not merely silent, the row is refused, + * and a gate that hipLaunches by hand cannot see it. The kernel therefore writes; it does not speak. + * The shim drains the ring to stderr, which is a host facility and costs the kernel nothing. + * + * Four plugin-owned device globals, and nothing else is added to the kernel: the launch parameters + * are fixed, `RadArgs` is the row's ABI and the plan builds it, so a field cannot join it (and `abi/` + * is untouched). The kernel owns these; the shim resolves them with `hipGetSymbolAddress` (once, + * cached) and, ONLY under `RAD_R3D_TRACE`, writes the budget with `hipMemcpyToSymbol`. + * + * r3d_dev_budget records left to write; 0 -- its initial value -- means record nothing + * r3d_dev_launches launches seen, incremented once per launch by the same thread that records + * r3d_dev_widx the ring's write index, bumped once per record written + * r3d_dev_ring kDevRing records, a fixed struct, 216 bytes each: 55 KiB, allocated once + * + * Why they exist: the engine's recorded pass plays a decode step by writing queue packets, and a + * play never reaches a plugin shim. The shim is not in the path of a played step. The kernel is. So + * the kernel writes down what it was handed: the step's `ctx` as the row reads it off `seqused`, the + * block ids as the walk reads them off the table, the operand addresses baked into the packet, and + * three content folds -- the query row, the K row of the FIRST block the row walks, the K row of the + * LAST one -- so a block whose BYTES move underneath a step is visible: the adopted prefix whose + * recycled block still holds the previous tenant's KV, and the address slip that serves fluent, + * plausible, wrong text. + * + * A played step's record is written on the device and printed at the NEXT shim call, so a served + * log's lines land one step behind the step they describe. The + * record's own `L` and `ctx` restore the order, and the shim's plan line quotes the same counter, so + * the gap between the two prints is the played pass, measured. + * + * Inert when the flag is unset: the budget is 0, so a launch pays one uniform scalar load of a + * global and one not-taken branch, on one thread of one workgroup, plus the atomic increment of the + * counter. The bound is decremented with `atomicSub` -- 16 CUs cannot record 16 copies of one launch + * -- and the counter is `atomicAdd` before it, so a launch counted is a launch that ran, played ones + * included. The ring is bounded (kDevRing slots): a harness that arms more than the ring holds loses + * records, never the count, and the shim says so on one line. + * + * The counter counts every `attn_kernel` launch, budget or not. It does NOT count the split-KV + * reduce: that kernel is a second launch of a step's work, not a step. */ +enum { kDevRing = 256, kDevIds = 8 }; + +/* One launch, as the launch saw it. A fixed plain-old struct: no pointers, no float, no padding the + * reader has to guess. The ids are the row's first kDevIds columns -- `block_size` 16 and a served + * ladder's 21 to 33 token contexts make that two columns, so the whole row fits -- and `idsum` folds + * every column, so a 4096-token context still has one comparable number for its row. */ +struct DevRec +{ + unsigned long long L; /* the launch's own ordinal */ + long long ctx, pos, slot0, slotL, idsum; /* the step as the row reads it, and where */ + unsigned long long qh, kh, khL; /* three content folds */ + unsigned long long kv, bt, su, cu, q, out; /* the six addresses baked into the packet */ + int dec, n_seq, rows, q_len, s, len, span, start; + int jcap, splits, waves, ncols, rowok, spare, spare2, spare3; + int b[kDevIds]; /* the row's ids; `ncols` of them are real */ +}; + +extern "C" __device__ int r3d_dev_budget = 0; +extern "C" __device__ unsigned long long r3d_dev_launches = 0ULL; +extern "C" __device__ unsigned r3d_dev_widx = 0u; +/* `= {}` is load-bearing: an uninitialised `__device__` variable emits no host-side symbol, and + * the engine's loader dlopens the plugin with the symbol live, so it stops with + * `undefined symbol: r3d_dev_ring` before a single row is declared. The zero fill is the device + * side's init, and it is what the flag-unset state is. */ +extern "C" __device__ DevRec r3d_dev_ring[kDevRing] = {}; + + +namespace { + +typedef float r3d_f32x4 __attribute__((ext_vector_type(4))); + +constexpr int kHeadDim = 128; +constexpr int kPairs = kHeadDim / 2; // f16 pairs a head: one dword is two dims +constexpr int kBlock = 16; // block_size: a step stages one of these +constexpr int kWaves = 4; // 128 threads +constexpr int kThreads = kWaves * 32; +constexpr int kPitch = kPairs; // dwords a staged row; rows are read as broadcasts +constexpr int kTileDw = kBlock * kPitch; // 1024 dwords = 4 KiB +constexpr int kPartStride = kHeadDim + 4; // acc[128], sum, max, pad -- 528 B, whole 16 B rows + +/* ------------------------------------------------------------------ exp */ + +/* exp(x) narrowed to f32, as close to `(float)std::exp((double)x)` as an ALU with no f64 gets. + * + * Measured against `(float)std::exp((double)x)` over 1.31M points of [-100, 0] and the boundary + * cases: every point is within one f32 ulp, 76.1% bit-identical (the device libm's expf is 94.0% + * identical and no better in ulps), exp(0) is exactly 1. The tail below 2^-126 -- x under about + * -87.3 -- comes out zero, not subnormal: the scaling multiply that assembles the subnormal is + * flushed by the hardware. That is invisible at the store, which is where the reference is + * compared: a weight of 1e-38 next to a maximum weight of exactly 1 cannot move an accumulator, and + * the bf16 store has no resolution at that ratio. + * + * Reduce by ln2 against a two-term constant: k = rn(x / ln2), r = x - k*LN_HI - k*LO with LN_HI the + * high 24 bits of ln2 and LO what is left. A single-term reduction is what makes the naive version + * 1.5 ulp -- k*ln2 is not representable, and the subtraction's cancellation is the whole error + * budget. |r| <= 0.35, where a degree-8 polynomial reaches ~0.55 ulp, then 2^k by exponent + * assembly. */ +__device__ __forceinline__ float exp_ref(float x) +{ + /* Above the overflow point the reference's own double path yields +inf, so this one must too; + * a NaN in, a NaN out. Both cases are outside the softmax's reach (the argument is a score + * minus the row's maximum, never positive), and are here so the function is an exp, not a + * softmax helper with an undefined edge. */ + if (!(x < 88.7228390525719f)) + return x == x ? __int_as_float(0x7f800000) : __int_as_float(0x7fc00000); + if (x < -103.9720770839916f) return 0.0f; /* under the subnormals: see header */ + const int k = (int)__float2int_rn(x * 1.4426950408889634f); + const float LN_HI = 0.693145751953125f; /* ln2, high bits, exactly a float */ + const float LN_LO = 1.42860681039557e-06f; /* ln2 - LN_HI */ + float r = x - (float)k * LN_HI; + r = r - (float)k * LN_LO; + /* e^r, |r| <= 0.35: 1 + r + r^2/2 + sum(r^i / i!), i = 3..8, Estrin over r^2. */ + const float c8 = 1.98412698412698e-04f, c7 = 1.38888888888889e-03f; + const float c6 = 8.33333333333333e-03f, c5 = 4.16666666666667e-02f; + const float c4 = 1.38888888888889e-01f, c3 = 1.66666666666667e-01f; + const float r2 = r * r; + const float p4 = __fmaf_rn(__fmaf_rn(__fmaf_rn(c8, r, c7), r, c6), r, c5); + const float p2 = __fmaf_rn(p4, r2, __fmaf_rn(c3, r, 5.0e-01f)); + const float e = __fmaf_rn(p2, r2, __fmaf_rn(r, 1.0f, 1.0f)); /* in [0.70, 1.42] */ + /* Scale by 2^k in the exponent field; x <= 0 here, so the normal case is the whole story and + * the subnormal one is a single hardware multiply. */ + const int be = __float_as_int(e); + const int field = ((be >> 23) & 0xff) + k; + if (field >= 1) return __int_as_float((be & 0x007fffff) | (field << 23)); + if (field <= -23) return 0.0f; + const float t = __int_as_float((be & 0x007fffff) | ((field + 126) << 23)); + return t * __int_as_float((127 - 126) << 23); /* one rounding, the hardware's */ +} + +/* ------------------------------------------------------------------ the kernel's view */ + +struct Args { + const uint16_t* q; /* bf16 or f16 (q16), rows x n_head x head_dim */ + const uint16_t* kv; /* bf16 cache */ + const uint8_t* kv8; /* E4M3 cache, when FP8 */ + const int* bt; /* block table, i32: the shim refuses i64 indices */ + const int* su; /* seqused, i32 */ + const int* cu; /* cu_seqlens, n_seq + 1, i32; null = q_len rows each */ + const float* kds; + const float* vds; + uint16_t* out; + float* part; /* split-KV partials */ + + /* Strides are elements, and 32-bit: a cache is blocks x kv_heads x 16 x 256 elements, a row + * pitch is n_head x head_dim, a block table pitch is max_blocks, and the launcher checks that + * each fits. Every address in this kernel is a 64-bit base plus a 32-bit product, and the + * register allocator is out of scalar registers long before it is out of vector ones -- the + * wavefront runs in compute-shader mode, where a scalar spill is not a slow path, it is a + * kernel the runtime refuses to load. */ + int sb, sh, so, sd; /* cache strides */ + int q_rs, o_rs; /* row pitches; the head stride is head_dim */ + int bt_rs; /* the block table row pitch, in entries: the tensor own stride */ + int bt_cs; /* its column stride: 1 for every dense table the engine builds */ /* block table pitch */ + int n_seq, q_len, rows, n_head, kv_heads, causal, window, jcap, splits, q16, waves; + float scale; + DevRec* trace_buf; /* one record slot, a plain hipMalloc buffer: the device + * globals are stubs in a dlopened plugin, the buffer is not */ +}; + +__device__ __forceinline__ long long ld_ix(const int* p, size_t i) { return p[i]; } + +/* ------------------------------------------------------------------ the row map + * + * One map for both batch forms. With a descriptor, sequence s owns the query rows [cu[s], cu[s+1]) + * -- `len_s` rows, the row's index within the sequence `i = row - cu[s]`, its absolute position + * `seqused[s] - len_s + i`. Without one, the same walk with len_s = q_len and cu[s] = s * q_len, + * which is the reference's own rectangular reading, not a parallel implementation + * of it. + * + * A grid row is resolved by subtracting each sequence's tile count from blockIdx.x until the + * remainder fits: n_seq int loads and n_seq subtractions, once per workgroup, against a walk of + * nblk blocks with two barriers each. The descriptor is device memory and a launcher reads none of + * it, so the grid is sized on the bound in `launch` and a grid row past the batch's last tile comes + * back with tile < 0 and leaves, having staged nothing. + * + * `start` is the sequence's first dense row and `i0` the row its positions count from. They differ + * only when cu[0] > 0: the reference's `seq_of` hands rows under cu[0] to sequence + * 0 with a negative index into its query, and that is transcribed rather than refused because a + * descriptor that does not start at 0 is a caller's arithmetic slip, not a geometry this kernel has + * to be wider than. Both are 32-bit: they index rows of a plane whose element offsets the launcher + * has already checked fit in 31 bits. */ +struct RowMap { int s, tile, start, i0, len, span; }; + +__device__ __forceinline__ RowMap map_seq(const Args& A, const int tpb, int g) +{ + const int n = A.n_seq; + for (int s = 0; s < n; ++s) { + const int c0 = A.cu ? (int)ld_ix(A.cu, (size_t)s) : s * A.q_len; + const int c1 = A.cu ? (int)ld_ix(A.cu, (size_t)(s + 1)) : c0 + A.q_len; + const int start = (s == 0 && c0 > 0) ? 0 : c0; + const int nr = c1 - start; + const int nt = nr > 0 ? (nr + tpb - 1) / tpb : 0; /* tpb is a template constant */ + /* TWO counts that are easy to conflate. `len` is the sequence's query length, + * cu[s+1] - cu[s], and it is what the positions count from (the reference: qlen, and + * pos = ctx - qlen + i). `span` is the number of rows this sequence's TILES carry, + * cu[s+1] - start, and the two differ by exactly cu[0] on sequence 0 of a descriptor that + * does not start at row 0: `start` reaches below cu[0] because seq_of hands those rows to + * sequence 0 with a negative index, so the tiles must cover `span` rows, and only `len` of + * them are inside the sequence. The store below is checked against the span and the + * positions against the length: bounding the tile slots by `len` drops the last cu[0] + * rows of the QUERY PLANE -- a silent, partial, in-bounds shortfall. */ + if (g < nt) return RowMap{ s, g, start, c0, c1 - c0, nr }; + if (s + 1 >= n) return RowMap{ s, -1, start, c0, c1 - c0, nr }; /* past the batch's tiles */ + g -= nt; + } + return RowMap{ n - 1, -1, 0, 0, 0, 0 }; +} + +/* The same walk for a row, not a tile: which sequence owns dense query row `r`. The reducer needs + * it because a partial is indexed by (row, head) and its slice count is the SEQUENCE's block count. */ +__device__ __forceinline__ int seq_of_row(const Args& A, int r) +{ + const int n = A.n_seq; + for (int s = 0; s < n; ++s) { + const int c1 = A.cu ? (int)ld_ix(A.cu, (size_t)(s + 1)) : (s + 1) * A.q_len; + if (r < c1 || s + 1 >= n) return s; + } + return n - 1; +} + +/* ------------------------------------------------------------------ staging */ + +/* Sixteen E4M3 codes -- one 16-byte load, the aligned unit a slot's 128-byte half divides into -- as + * eight f16 pairs, descaled on the way. A code is exact in f16, so a power-of-two descale (every real + * cache scale) costs a multiply and no rounding at all; a general descale is rounded once, toward + * zero by the packing instruction, where the reference keeps it in f32. The bf16 path has no descale, + * so it has no rounding to report. */ +__device__ __forceinline__ void codes16_to_f16x8(const uint8_t* p, float s, uint32_t* w) +{ + const r3d_u32x4 c = *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)p; + const uint32_t d[4] = { c.x, c.y, c.z, c.w }; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float a0 = e4m3_to_f32((uint8_t)(d[j] & 0xffu)) * s; + const float a1 = e4m3_to_f32((uint8_t)((d[j] >> 8) & 0xffu)) * s; + const float a2 = e4m3_to_f32((uint8_t)((d[j] >> 16) & 0xffu)) * s; + const float a3 = e4m3_to_f32((uint8_t)(d[j] >> 24)) * s; + w[j * 2] = f16x2_pack(a0, a1); + w[j * 2 + 1] = f16x2_pack(a2, a3); + } +} + +/* Stage one block of one KV head: 16 slots x 128 elements, K and V, widened to f16 pairs. + * + * A slot's halves are 512 bytes apart and each 256 of them, so a bf16 chunk of 8 elements is 16 + * bytes and lands on a 16-byte boundary; an E4M3 chunk of 16 codes is 16 bytes and lands there too. + * A chunk of 8 codes is 8 bytes and does not -- a misaligned 16-byte load on this hardware returns + * garbage, which is the whole difference between the two chunk sizes below. 128 threads, one chunk of + * K and one of V each for the cache, two each for the bf16: 256 chunks of 16 bytes a half, 8 KiB of + * tile, two loads and two stores a thread. + * + * Every offset is 32-bit and the launcher has checked that the whole cache fits in 2^31 elements: + * the wavefront runs in compute-shader mode, where a scalar spill is not a slow path but a kernel the + * runtime refuses to load, and 64-bit index arithmetic across a loop like this one is what fills the + * scalar bank. */ +template +__device__ __forceinline__ void stage(Args const& A, uint32_t* sK, uint32_t* sV, int blk, int kh, + float kds, float vds, int tid) +{ + constexpr int kC = FP8 ? 16 : 8; /* elements a 16-byte chunk */ + constexpr int kCPH = kHeadDim / kC; /* chunks a half, a slot */ + constexpr int kChunks = kBlock * kCPH; /* 128 code chunks, 256 bf16 */ + constexpr int kIter = kChunks / NTH; /* bf16: 8, 4, 2 at a wave, two, four */ + static_assert(kIter * NTH == kChunks, "the stage must divide into whole per-thread trips: " + "a bounds check inside the unrolled loop keeps the " + "loop from unrolling, and the loop-invariant operands " + "then get hoisted into scalar registers"); + const int base = blk * A.sb + kh * A.sh; /* this head's block, elements */ + +#pragma unroll + for (int u = 0; u < kIter; ++u) { + const int t = tid + u * NTH; + const int slot = t / kCPH; + const int c = (t % kCPH) * kC; /* element offset in the half */ + const int k0 = base + slot * A.so + c; + const int v0 = k0 + kHeadDim; + uint32_t* dk = sK + slot * kPitch + c / 2; + uint32_t* dv = sV + slot * kPitch + c / 2; + if constexpr (FP8) { /* codes: element and byte agree */ + codes16_to_f16x8(A.kv8 + k0, kds, dk); + codes16_to_f16x8(A.kv8 + v0, vds, dv); + } else { + const r3d_u32x4 ka = + *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)(A.kv + k0); + const r3d_u32x4 va = + *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)(A.kv + v0); + const uint32_t kd[4] = { ka.x, ka.y, ka.z, ka.w }; + const uint32_t vd[4] = { va.x, va.y, va.z, va.w }; +#pragma unroll + for (int j = 0; j < 4; ++j) { + dk[j] = bf16x2_to_f16x2(kd[j]); + dv[j] = bf16x2_to_f16x2(vd[j]); + } + } + } +} + +/* ------------------------------------------------------------------ the walks */ + +/* The keys a lane may see: j is a candidate for the wave, the predicate is per lane. */ +__device__ __forceinline__ bool visible(int j, long long pos, int causal, int window) +{ + if (causal && (long long)j > pos) return false; + if (window > 0) { + const long long d = pos - j; + if (causal ? (d >= window) : (d >= window || d <= -window)) return false; + } + return true; +} + +__device__ __forceinline__ float score_of(const uint32_t* qf, const uint32_t* kp, float scale) +{ + float dot = 0.0f; +#pragma unroll + for (int p = 0; p < kPairs; ++p) dot = dot2_f16x2(qf[p], kp[p], dot); + return dot * scale; +} + +/* ------------------------------------------------------------------ the launch's own voice + * + * Two content folds and one line, printed from ONE thread of ONE workgroup of a launch. + * + * `fold64` is FNV-1a over 64-bit words -- multiply, xor, per word; no float arithmetic, no + * reduction that a compiler could contract. The spelling is exact and the board's host-side fold + * copies it byte for byte, because a hash the driver cannot recompute is a number nobody can check. + * It is order-sensitive by construction (a permuted row is a different hash), which is the property + * that makes the layer-major addressing slip visible: the same 128 elements read at a layer-major + * offset fold to something else. + * + * The words are the row's OWN bytes, read as the walk reads them: the query row at + * `q + row * q_rs` for head 0 -- head 0 is the first head of kv-head 0, and 128 bf16 elements are + * the 32 words -- and the K row of the block the walk names FIRST, at `blk * sb + kh * sh + + * slot * so`, the same arithmetic `stage()` uses (this file has no `slot_of` helper; `slot_k_off` + * spells it out here so the print prints it). 128 elements are 16 words of E4M3 codes and 32 of + * bf16. Both rows are 16-byte aligned: the shim checks a 16-aligned cache, query and output base + * and a row pitch that is a multiple of 8 elements, and the header's layout note puts a slot's K on + * a 16-byte boundary at every slot. + */ +__device__ __forceinline__ unsigned long long fold64(const void* p, int words) +{ + const unsigned long long* w = (const unsigned long long*)p; + unsigned long long h = 14695981039346656037ULL; /* FNV-1a 64 offset basis */ + for (int i = 0; i < words; ++i) h = (h * 1099511628211ULL) ^ w[i]; + return h; +} + +__device__ __forceinline__ long long slot_k_off(const Args& A, int blk, int kh, int slot) +{ + return (long long)blk * A.sb + (long long)kh * A.sh + (long long)slot * A.so; +} + +/* One record per launch, from block (0,0,0), thread 0, into the ring. `noinline` on purpose: the + * walk's register budget is the scarcest thing in this file (see the stride note on Args -- a scalar + * spill is a kernel the runtime refuses to load), and a writer that a traced run runs once a launch + * must not be inlined into the middle of the mapping code that every launch runs. + * + * This function reads memory, so its bounds are the subject. THREE reads, three bounds: + * + * the query row bound: the PLANE's row count `A.rows`, the same bound the kernel checks + * before it stores (`M.start + tok < A.rows`, in the caller). `row` is the + * caller's clamped row index: the grid is sized on a bound, so a tile can name + * rows the plane does not have, and `row_ok` says whether this one is real. A + * band key (`q_len`) and the sequence's length are bounds on the SHAPE the shim + * accepted, not on the plane, and the clamp exists because the grid exceeds + * them; reading through a band key is the out-of-bounds this guard kills. A tile + * the batch has no rows for records `qh=0, rowok=0` -- the record says it did + * not read, and `L` still counts the launch. + * the table's row bound: the columns the WALK can name, ceil(jcap / block_size), where + * jcap = min(ctx, bt_cols * block_size), so a column under it is a column the + * shim proved when it sized the table from the tensor (row pitch plus bt_cols + * columns fit, at the table's own pitches), and the row is `M.s * bt_rs` with + * `M.s` a sequence index the mapping clamped. + * the cache bound: a block id is one the table names, and the shim insists every index + * the walk can reach is inside the cache's plane (`0 <= id < num_blocks`, plus + * the dense-stride requirement). The fold reads the slot-0 K row of kv-head 0 at + * the offset `stage()` computes, kHeadDim elements: 256 bytes of bf16, 128 of + * fp8, both inside a slot's 2*kHeadDim. A negative id -- an unmapped slot prints + * -1 -- folds to 0 and is not dereferenced. */ +template +__device__ __noinline__ void dev_record(const Args& A, const RowMap& M, long long row, bool row_ok, + long long ctx, int jend_all, long long pos) +{ + /* A launch that runs is a launch that is counted, budget or not: this is the number that stops + * the decode steps of a request being inferred from shim lines. */ + const unsigned long long n = atomicAdd(&r3d_dev_launches, 1ULL) + 1ULL; + /* The bound, decremented atomically, so 16 CUs cannot record 16 copies of one launch. A caller + * that armed 3 gets 3 records, wherever in the run they fall. The buffer channel bypasses the + * bound: it is one slot per launch, drained at the launch, and the budget is a device global + * that the engine process cannot arm. */ + if (!A.trace_buf && atomicSub(&r3d_dev_budget, 1) <= 0) return; + + DevRec r; + r.L = n; + r.dec = A.rows == 1 ? 1 : 0; + r.n_seq = A.n_seq; r.rows = A.rows; r.q_len = A.q_len; + r.s = M.s; r.len = M.len; r.span = M.span; r.start = M.start; + r.ctx = ctx; r.pos = pos; r.jcap = jend_all; r.splits = A.splits; r.waves = A.waves; + r.kv = (unsigned long long)(uintptr_t)(FP8 ? (const void*)A.kv8 : (const void*)A.kv); + r.bt = (unsigned long long)(uintptr_t)A.bt; + r.su = (unsigned long long)(uintptr_t)A.su; + r.cu = (unsigned long long)(uintptr_t)A.cu; + r.q = (unsigned long long)(uintptr_t)A.q; + r.out = (unsigned long long)(uintptr_t)A.out; + + const int cols = (A.jcap + kBlock - 1) / kBlock; /* <= bt_cols, by jcap's bound */ + const long long r0 = (long long)M.s * A.bt_rs; + r.ncols = cols; + unsigned long long is = 14695981039346656037ULL; /* the fold64 basis, so a sum of ids is a + * fold of them, spelled the same way */ + for (int c = 0; c < cols; ++c) { + const int b = (int)ld_ix(A.bt, (size_t)r0 + (size_t)c * (size_t)A.bt_cs); + is = (is * 1099511628211ULL) ^ (unsigned long long)(unsigned int)b; + if (c < kDevIds) r.b[c] = b; + } + for (int c = cols; c < kDevIds; ++c) r.b[c] = -2; /* a column the row does not have. -2 is + * not -1, which is an unmapped block */ + r.idsum = (long long)is; + + /* The query row, under the plane's bound, named above. */ + const bool q_ok = row_ok && row >= 0 && row < A.rows; + r.rowok = q_ok ? 1 : 0; + r.qh = q_ok ? fold64(A.q + row * (long long)A.q_rs, kHeadDim / 4) : 0ULL; + + /* The head K row of the first block the row WALKS, and of the last block it walks. The walk's + * extent is `jend_all = min(ctx, A.jcap)` keys, so the blocks it visits are `ceil(jend_all / + * kBlock)` — NOT the table's `cols`: the table row is the plane's full capacity (64 columns at + * a 4096 cap) and its far columns are `-1` for a short context, a fold of which is a fold of + * nothing. `ncols` and `idsum` keep the whole table row — that is the census — while `kh`, + * `khL`, `slot0`, `slotL` and `bL` are the walk's two ends: the head of an adopted prefix and + * the tail the step is writing, where a recycled block shows up. */ + const int walk_cols = (jend_all + kBlock - 1) / kBlock; + const int b0 = walk_cols > 0 ? r.b[0] : -2; + const int blast = walk_cols > 0 + ? (int)ld_ix(A.bt, (size_t)r0 + (size_t)(walk_cols - 1) * (size_t)A.bt_cs) + : -2; + const long long k0 = b0 >= 0 ? slot_k_off(A, b0, 0, 0) : 0; + const long long kL = blast >= 0 ? slot_k_off(A, blast, 0, 0) : 0; + r.slot0 = k0; r.slotL = kL; + r.kh = b0 < 0 ? 0ULL : (FP8 ? fold64(A.kv8 + k0, kHeadDim / 8) : fold64(A.kv + k0, kHeadDim / 4)); + r.khL = (kL == 0) ? 0ULL + : (FP8 ? fold64(A.kv8 + kL, kHeadDim / 8) : fold64(A.kv + kL, kHeadDim / 4)); + r.spare = blast; /* the id the last fold is of, printed */ + r.spare2 = cols; r.spare3 = 0; + + /* One slot, claimed by one atomic. Past the ring's end a record is counted and dropped: the + * counter keeps the truth, and the shim prints one line saying how many were lost. The struct is + * filled in a local and copied in one statement so the writer is one block of stores; a drain + * runs at a shim call, after the engine has synced the step, so it reads slots that are written + * whole. */ + const unsigned w = atomicAdd(&r3d_dev_widx, 1u); + if (w < (unsigned)kDevRing) r3d_dev_ring[w] = r; + if (A.trace_buf) A.trace_buf[0] = r; /* the engine-process channel: no symbol between us */ +} + +/* One wave's work: GQA heads x 32/GQA rows, over its slice of one sequence's blocks, for one KV + * head. CAUSAL and SPLIT are template parameters because both change the loop, not just a flag. */ +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(4) +void attn_kernel(const Args A) +{ + __shared__ uint32_t sK[kTileDw]; + __shared__ uint32_t sV[kTileDw]; + + constexpr int TOKS = 32 / GQA; /* query rows a wave carries */ + constexpr int kNThr = WAVES * 32; /* 32, 64, 128 threads */ + constexpr int ROWSB = WAVES * TOKS; /* rows a workgroup carries */ + constexpr int LG = (GQA == 1) ? 0 : (GQA == 2) ? 1 : (GQA == 4) ? 2 : 3; + + const int tid = (int)threadIdx.x; + const int wave = tid >> 5, lane = tid & 31; + const RowMap M = map_seq(A, ROWSB, (int)blockIdx.x); + /* A grid row the batch has no tiles for (the grid is sized on a bound), and a sequence with no + * rows (cu[s+1] <= cu[s], the reference's `qlen <= 0`), stage nothing and store nothing. A + * sequence that starts past the query plane -- a descriptor running beyond the operand -- is + * nobody's rows: the plane's row count is the bound the store is checked against below. */ + if (M.tile < 0 || M.len <= 0 || M.start >= A.rows) return; + const int s = M.s; + const int tile = M.tile; + const int kh = (int)blockIdx.y; + const int slice = SPLIT ? (int)blockIdx.z : 0; + + const int h = kh * GQA + (lane & (GQA - 1)); + const int tb = tile * ROWSB + wave * TOKS; /* the wave's first row of the sequence */ + const int tok = tb + (lane >> LG); /* this lane's, counted inside the sequence */ + /* A row the operands do not have: past the rows this sequence's tiles carry (the last tile of + * any sequence, and every tile of a short one in a ragged step), or past the query plane (a + * descriptor that runs long). Both are the clamp the width section documents. The bound is the + * SPAN, not the length: with cu[0] > 0 the span reaches below cu[0], and the rows there are + * the reference's rows too (seq_of gives them to sequence 0), so they are stored. */ + const bool row_ok = tok < M.span && M.start + tok < A.rows; + /* The clamp target is a row that EXISTS: the wave's first row if the sequence has one, else its + * last, and never past the plane. An idle lane loads a real query row so the walk stays + * branch-free; it never stores. */ + int tclamp = tb < M.span ? tb : M.span - 1; + if (M.start + tclamp >= A.rows) tclamp = A.rows - 1 - M.start; + const long long row = (long long)M.start + (row_ok ? tok : tclamp); + + const long long ctx = ld_ix(A.su, (size_t)s); + const int jend_all = (int)(ctx < A.jcap ? ctx : A.jcap); + /* `ib` is 0 for every descriptor the description allows (cu[0] == 0); it is the negative index + * into sequence 0's query that libref's seq_of gives rows under cu[0]. */ + const long long ib = (long long)M.start - M.i0; + const long long pos = ctx - M.len + tok + ib; + + /* THE LAUNCH WRITES. The shim is not in the path of a played step -- a play writes queue + * packets and never calls `rad_arch_step` (the recorded pass's packet path) -- and this kernel + * is, so the row writes down what the row was + * handed: `ctx` off `seqused`, the block ids off the table at the table's own pitches, the six + * operand addresses baked into the packet, and three content folds. ONE thread of ONE workgroup + * (`blockIdx.z` is the split-KV slice: one launch, not `splits` of them), gated on a global the + * shim writes only under `RAD_R3D_TRACE`. With the flag unset the gate is one load of a zero + * global and a not-taken branch, and the launch records nothing. It does not printf: a kernel + * that does takes the implicit `hidden_hostcall_buffer`, which the AQL backend does not supply, + * and the row stops being dispatchable at all (see the ring's header). + * + * Placed HERE, before the query is widened and long before the walk, so the record covers the + * launch even when the walk's rows are all clamped -- which is why the writer's own read of the + * query row is bounded by the PLANE's rows and not by the band key, and why a clamped tile + * records `qh=0 rowok=0` -- and so the writer's registers are live over the fewest live values + * in the kernel. */ + if (blockIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0 && threadIdx.x == 0) + dev_record(A, M, row, row_ok, ctx, jend_all, pos); + + /* The WORKGROUP's bounds, not the wave's. The stage is one tile shared by the four waves, so + * every wave of a workgroup must walk exactly the same blocks: a range narrowed to a wave's own + * four positions makes the waves stage different blocks over the same LDS, and the last writer + * per 16-byte chunk wins -- a corrupted tile that looks like a numerical error. The positions of + * a workgroup's 4 x TOKS consecutive rows span 4 x TOKS - 1, and keys past the last are nobody's; + * a window cuts the front off as well. The mask that this widens past is per lane and free. */ + const int gb = tile * ROWSB; + const long long wmin = ctx - M.len + gb + ib; + const long long wmax = wmin + ROWSB - 1; + int jlo = 0, jhi = jend_all; + if (CAUSAL) { + if (wmax + 1 < jhi) jhi = (int)(wmax + 1); + } + if (A.window > 0) { + const long long lo = wmin - A.window + 1; + if (lo > jlo) jlo = (int)(lo > 0 ? lo : 0); + if (!CAUSAL) { + const long long hi = wmax + A.window; + if (hi < jhi) jhi = (int)(hi > 0 ? hi : 0); + } + } + const int nblk = (jend_all + kBlock - 1) / kBlock; + int b0 = jlo / kBlock, b1 = (jhi + kBlock - 1) / kBlock; + if (SPLIT) { + const int tps = (nblk + A.splits - 1) / A.splits; + const int s0 = slice * tps; + const int s1 = s0 + tps < nblk ? s0 + tps : nblk; + if (b0 < s0) b0 = s0; + if (b1 > s1) b1 = s1; + } + + const float kds = A.kds ? A.kds[(size_t)s * A.kv_heads + kh] : 1.0f; + const float vds = A.vds ? A.vds[(size_t)s * A.kv_heads + kh] : 1.0f; + + /* The query row, widened once and kept for both walks: 64 dwords, the lane's own 256 bytes, the + * eight heads of a token contiguous in memory. An idle lane loads its wave's first row so the + * registers hold something and the walk stays branch-free; it never stores. */ + uint32_t qf[kPairs]; + { + const uint16_t* qp = A.q + row * (long long)A.q_rs + h * kHeadDim; +#pragma unroll + for (int u = 0; u < kPairs / 4; ++u) { /* eight elements a 16-byte load */ + const r3d_u32x4 raw = + *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)(qp + u * 8); + const uint32_t d[4] = { raw.x, raw.y, raw.z, raw.w }; +#pragma unroll + for (int j = 0; j < 4; ++j) qf[u * 4 + j] = A.q16 ? d[j] : bf16x2_to_f16x2(d[j]); + } + } + + float acc[kHeadDim]; +#pragma unroll + for (int d = 0; d < kHeadDim; ++d) acc[d] = 0.0f; + float sum = 0.0f, mx = -INFINITY; + + /* Walk one: the scores' maximum. Blocks entirely behind every row of the workgroup need no + * mask, and the ones straddling a row's position mask per lane. */ + for (int b = b0; b < b1; ++b) { + const int blk = (int)ld_ix(A.bt, (size_t)s * (size_t)A.bt_rs + (size_t)b * (size_t)A.bt_cs); + group_barrier(); + if (blk >= 0) stage(A, sK, sV, blk, kh, kds, vds, tid); + group_barrier(); + if (blk < 0) continue; + const int j0 = b * kBlock; + const int nu = j0 + kBlock <= jhi ? kBlock : (jhi > j0 ? jhi - j0 : 0); + const bool nomask = !CAUSAL && A.window <= 0; + if (nomask) { + for (int u = 0; u < nu; ++u) { + const float sc = score_of(qf, sK + u * kPitch, A.scale); + if (sc > mx) mx = sc; + } + } else { + for (int u = 0; u < nu; ++u) { + if (!visible(j0 + u, pos, CAUSAL, A.window)) continue; + const float sc = score_of(qf, sK + u * kPitch, A.scale); + if (sc > mx) mx = sc; + } + } + } + + /* Walk two: the same scores, exponentiated against the maximum, accumulated ascending. */ + if (mx > -INFINITY) { + for (int b = b0; b < b1; ++b) { + const int blk = (int)ld_ix(A.bt, (size_t)s * (size_t)A.bt_rs + (size_t)b * (size_t)A.bt_cs); + group_barrier(); + if (blk >= 0) stage(A, sK, sV, blk, kh, kds, vds, tid); + group_barrier(); + if (blk < 0) continue; + const int j0 = b * kBlock; + const int nu = j0 + kBlock <= jhi ? kBlock : (jhi > j0 ? jhi - j0 : 0); + const bool nomask = !CAUSAL && A.window <= 0; + for (int u = 0; u < nu; ++u) { + if (!nomask && !visible(j0 + u, pos, CAUSAL, A.window)) continue; + const float w = exp_ref(score_of(qf, sK + u * kPitch, A.scale) - mx); + sum += w; + const uint32_t* vp = sV + u * kPitch; +#pragma unroll + for (int p = 0; p < kPairs; ++p) { + const uint32_t q2 = vp[p]; + const int d = 2 * p; + acc[d] = acc[d] + w * f16_to_f32((uint16_t)(q2 & 0xffffu)); + acc[d + 1] = acc[d + 1] + w * f16_to_f32((uint16_t)(q2 >> 16)); + } + } + } + } + + /* A row slot past its sequence's length, or past the query plane, is a clamped duplicate: it + * computed a walk, and it stores nothing -- the partial store included, which needs the same + * test BEFORE it. A padding row's `row` clamps to a REAL row, so an unguarded partial store + * puts a second writer into (row, h, slice) -- inside the declared arena, so no bounds check + * sees it -- and the two writers' 132-float records interleave: a slot can end with one lane's + * acc and another lane's (sum, max). The reduce then rescales a full slice's accumulator by + * the other lane's maximum, the combined sum comes out thousands of times too small, and + * `1/sum` hands back a power of two where a logit belongs. The mechanism needs a padding row + * -- q_len < 32/gqa -- so a band that fills its waves (q_len 7 at gqa 8) has none. The slots a + * padding row leaves unwritten are exactly the slots the reduce does not read: its index runs + * to `nrows * n_head`, over real rows only. */ + if (!row_ok) return; + + if (SPLIT) { + float* pp = A.part + ((size_t)row * A.n_head + h) * ((size_t)A.splits * kPartStride) + + (size_t)slice * kPartStride; +#pragma unroll + for (int u = 0; u < kHeadDim / 8; ++u) { + const r3d_f32x4 v = { acc[8 * u], acc[8 * u + 1], acc[8 * u + 2], acc[8 * u + 3] }; + const r3d_f32x4 w = { acc[8 * u + 4], acc[8 * u + 5], acc[8 * u + 6], acc[8 * u + 7] }; + *(r3d_f32x4*)(pp + 8 * u) = v; + *(r3d_f32x4*)(pp + 8 * u + 4) = w; + } + pp[kHeadDim] = sum; + pp[kHeadDim + 1] = mx; + return; + } + + uint16_t* op = A.out + row * (long long)A.o_rs + h * kHeadDim; + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; /* no visible key: a zero row */ +#pragma unroll + for (int u = 0; u < kHeadDim / 8; ++u) { + uint32_t q4[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int d = 8 * u + 2 * j; + q4[j] = bf16x2_rne(acc[d] * inv, acc[d + 1] * inv); + } + *(r3d_u32x4*)(void*)(op + 8 * u) = r3d_u32x4{ q4[0], q4[1], q4[2], q4[3] }; + } +} + +/* ------------------------------------------------------------------ split-KV reduce + * + * A wave per (query row, head): 32 lanes x 4 dims. The slices combine ascending, each rescaled by + * exp(m_slice - M) with M the slices' maximum, which is where split-KV leaves the reference's + * parentheses; see the header. */ +__global__ __launch_bounds__(128) R3D_WAVES(4) +void attn_reduce(const Args A, long long nrows) +{ + const int w = (int)threadIdx.x >> 5, lane = (int)threadIdx.x & 31; + const long long idx = (long long)blockIdx.x * 4 + w; + const long long total = nrows * A.n_head; + if (idx >= total) return; + const long long row = idx / A.n_head, h = idx - row * A.n_head; + const int s = seq_of_row(A, (int)row); /* row / q_len with a null descriptor */ + const long long ctx = ld_ix(A.su, (size_t)s); + const int jend_all = (int)(ctx < A.jcap ? ctx : A.jcap); + const int nblk = (jend_all + kBlock - 1) / kBlock; + const int tps = (nblk + A.splits - 1) / A.splits; + const int nslice = tps > 0 ? (nblk + tps - 1) / tps : 0; + + float* pp = A.part + (size_t)idx * ((size_t)A.splits * kPartStride); + float M = -INFINITY; + for (int u = 0; u < nslice; ++u) { + const float m = pp[(size_t)u * kPartStride + kHeadDim + 1]; + if (m > M) M = m; + } + uint16_t* o = A.out + row * (long long)A.o_rs + h * kHeadDim; + const int d0 = lane * 4; + float a[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + float sum = 0.0f; + if (M > -INFINITY) { + for (int sl = 0; sl < nslice; ++sl) { + const float* q = pp + (size_t)sl * kPartStride; + const float f = exp_ref(q[kHeadDim + 1] - M); + sum += q[kHeadDim] * f; + a[0] += q[d0 + 0] * f; + a[1] += q[d0 + 1] * f; + a[2] += q[d0 + 2] * f; + a[3] += q[d0 + 3] * f; + } + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + *(r3d_u32x2*)(void*)(o + d0) = r3d_u32x2{ bf16x2_rne(a[0] * inv, a[1] * inv), + bf16x2_rne(a[2] * inv, a[3] * inv) }; +} + +} // namespace + +/* ================================================================== launchers + * + * Both entries take raw addresses and extents, in the library's style, and both assume the dense + * layouts the shim has just checked: the cache at [blocks, kv_heads, 16, 256], a block table whose + * row pitch is exactly ceil(max_ctx / block_size), seqused one i32 a sequence. That is what the + * signatures carry, so the shims refuse anything they cannot describe with it -- a strided cache, a + * wider block table, an i64 index plane. + * + * `cu` is the ragged query descriptor, and with it `q_len` changes meaning: it is the query PLANE's + * row count, the total, which the descriptor's cu[num_seqs] states and libref reads off the tensor + * (`rows = numel(q) / (q_heads * head_dim)`, `cu[n_seq] == rows`). Absent, it + * keeps its per-sequence meaning and the total is num_seqs * q_len. No entry reads the plane: the + * grid is sized on a bound, and the kernel does the walking. + */ +#define R3D_NEED(cond) do { if (!(cond)) return R3D_NO(RAD_E_SHAPE); } while (0) + +namespace { + +int fill(Args& A, long q, long kv, long bt, long seqused, long k_desc, long v_desc, long cu, + long rows, int num_seqs, int q_len, int head_dim, int gqa, int n_head, int block_size, + int bt_cols, int bt_rs, int bt_cs, int max_ctx, int window, int causal, float scale, + int kv_dt, long q_ld, long out_ld, int splits, long scratch, int waves) +{ + A = Args{}; + if (head_dim != kHeadDim) return -2; /* RAD_E_SHAPE */ + if (num_seqs <= 0 || n_head <= 0) return -2; + /* A rectangular batch is counted per sequence; a ragged one has no per-sequence length, and its + * `rows` is the query plane's row count. Both have to be at least one row. */ + if (cu) { if (rows < 1 || rows > 2147483000LL) return -2; } + else if (q_len < 1 || (long long)num_seqs * q_len > 2147483000LL) return -2; + if (block_size != kBlock) return -2; + if (gqa != 1 && gqa != 2 && gqa != 4 && gqa != 8) return -2; /* the wave split is a shift */ + if (n_head % gqa) return -2; + if (window < 0 || max_ctx < 1) return -2; + if (kv_dt != RAD_BF16 && kv_dt != RAD_F8E4M3) return -1; /* RAD_E_DTYPE */ + if (!q || !kv || !bt || !seqused) return -1; + + const int kv_heads = n_head / gqa; + /* Two counts that must not be conflated. The CACHE holds + * ceil(max_ctx / block_size) blocks, which bounds the byte offset of a slot address. The TABLE + * has `bt_cols` columns, and the engine sizes it to the step: a five-token prompt with nothing + * behind it is one block, a table of [n_seq, 1]. The walk is bounded by the TABLE -- + * the reference takes max_blocks from `bt->shape[last]`, the row pitch from + * `stride[rank-2]` and the column stride from `stride[rank-1]`, and jend = min(ctx, max_blocks * + * block_size) -- so a context longer than the table has columns is truncated by the reference, + * which is the oracle, and by us, to the same keys. */ + const int cache_blocks = (max_ctx + block_size - 1) / block_size; + if (bt_cols < 1 || bt_rs < 1 || bt_cs < 1) return -2; /* RAD_E_STRIDE, said where the shim sees it */ + + A.q = (const uint16_t*)(uintptr_t)q; + A.kv = kv_dt == RAD_BF16 ? (const uint16_t*)(uintptr_t)kv : nullptr; + A.kv8 = kv_dt == RAD_F8E4M3 ? (const uint8_t*)(uintptr_t)kv : nullptr; + A.bt = (const int*)(uintptr_t)bt; + A.su = (const int*)(uintptr_t)seqused; + A.cu = (const int*)(uintptr_t)cu; + A.kds = (const float*)(uintptr_t)k_desc; + A.vds = (const float*)(uintptr_t)v_desc; + /* The dense cache: a slot's K is 128 elements, V the 128 after it. Every stride has to fit the + * 32-bit form the kernel's addressing uses. */ + A.so = 2 * kHeadDim; + A.sh = block_size * A.so; + A.sb = kv_heads * A.sh; + A.sd = 1; + if ((long long)A.sb * cache_blocks > 2147483000LL) return -2; + if (q_ld > 2147483000LL || out_ld > 2147483000LL) return -2; + A.q_rs = (int)q_ld; + A.o_rs = (int)out_ld; + A.bt_rs = bt_rs; + A.bt_cs = bt_cs; + A.n_seq = num_seqs; A.q_len = cu ? 0 : q_len; + A.rows = cu ? (int)rows : num_seqs * q_len; + A.n_head = n_head; A.kv_heads = kv_heads; + A.causal = causal ? 1 : 0; A.window = window; + A.jcap = max_ctx; + if ((long long)bt_cols * block_size < max_ctx) A.jcap = bt_cols * block_size; + if (r3d_trace_on()) /* the walk's reach is a number the shim can print: a context that + * comes back short is a table narrower than the sequence, and + * that is a plan fact, not a kernel fact */ + std::fprintf(stderr, "[r3d] attn: q_len %d rows %ld n_seq %d bs %d bt cols %d pitch %d " + "cstride %d max_ctx %d -> jcap %d\n", q_len, rows, num_seqs, + block_size, bt_cols, bt_rs, bt_cs, max_ctx, A.jcap); + { /* the record's slot, for the engine process: a plain buffer the kernel can write and the + * shim can read back, no symbol table between them. Inert when the flag is unset. */ + static void* g_trace_buf = nullptr; + A.trace_buf = nullptr; + if (r3d_trace_on() && !g_trace_buf) + (void)hipMalloc(&g_trace_buf, sizeof(DevRec)); + if (g_trace_buf) A.trace_buf = (DevRec*)g_trace_buf; + } + if (r3d_trace_on()) /* the device's own view, at the launch: the table row, the + * seqused, the KV base, and the first block's bytes -- the + * four things a wrong answer can come from, spoken together. + * The sync is the price: the staging may ride the engine's + * stream, and a read on the default stream is unordered to it. */ + { + (void)hipDeviceSynchronize(); + const char* kvb = A.kv8 ? (const char*)A.kv8 : (const char*)A.kv; + for (int s = 0; s < (int)num_seqs && s < 4; ++s) { + int row[16]; + if (hipMemcpy(row, (const char*)A.bt + (size_t)s * (size_t)bt_rs * sizeof(int), + 16 * sizeof(int), hipMemcpyDeviceToHost) == hipSuccess) { + std::fprintf(stderr, "[r3d] devstate s=%d bt=", s); + for (int c = 0; c < 16; ++c) std::fprintf(stderr, "%s%d", c ? " " : "", row[c]); + std::fprintf(stderr, "\n"); + } + int su = -1; + if (A.su && + hipMemcpy(&su, (const char*)A.su + (size_t)s * sizeof(int), sizeof(int), + hipMemcpyDeviceToHost) == hipSuccess) + std::fprintf(stderr, "[r3d] devstate s=%d seqused=%d kvbase=%p\n", s, su, + (const void*)kvb); + } + int first = -1; + if (kvb && + hipMemcpy(&first, (const char*)A.bt, sizeof(int), hipMemcpyDeviceToHost) == hipSuccess && + first >= 0) { + /* The block's bytes are spoken by address only: a D2H of the cache base page faults + * the engine process where the kernel's own read is fine, so the content check stays + * with the board, and the table + base are what the served run speaks. */ + std::fprintf(stderr, "[r3d] devstate first_block=%d (content not read: see the board)\n", + first); + } + } + /* The table bounds the walk, as in the reference: a context with more blocks than the + * table has columns stops at the table, which is what the reference does and therefore + * what the fixture and the served numbers say. */ + A.scale = scale > 0.0f ? scale : 1.0f / std::sqrt((float)kHeadDim); + A.splits = splits > 0 ? splits : 1; + A.waves = waves; + A.part = A.splits > 1 ? (float*)(uintptr_t)scratch : nullptr; + if (A.splits > 1 && !scratch) return -5; /* RAD_E_SCRATCH */ + return 0; +} + +/* The narrowest workgroup that carries the caller's q_len. A wave carries 32 / gqa query rows, and + * a row slot whose row is past q_len computes a clamped duplicate: at the decode band's q_len = 7 + * with gqa = 8 a four-wave workgroup spends 9 of its 16 row slots on duplicates, twice the walk for + * half the outputs. The tile is the same 8 KiB at every width -- 16 tokens a block, staged once per + * workgroup -- so a narrower workgroup is the same cache read spread over more workgroups, and + * 512 -> 1024 of them is the fill the counters say the op is short of (15% issue at the band, + * 3.7% at eight sequences, where splits=8 buys 3.6x). Prefill keeps four waves: its q_len is the + * whole chunk, every slot is used, and a smaller workgroup would only re-read the cache. + * The accumulation order does not depend on the width: the softmax sum is over keys, ascending, + * inside one lane, and the rows a wave holds are the same rows shifted by wave * TOKS. */ +int pick_waves(int q_len, int gqa) +{ + const int rows = 32 / (gqa > 0 ? gqa : 1); + const int w = (q_len + rows - 1) / rows; + return w <= 1 ? 1 : (w <= 2 ? 2 : 4); /* the ladder the grid is cut on: 1, 2, 4 */ +} + +/* The rows one sequence of a batch contributes, as well as a host can know them: the plane's row + * count over the sequence count, rounded up. With a descriptor the true lengths are device memory + * and a launcher reads none of it, so this is what the width and the split count are picked on for a + * ragged step. Both choices move duplicated row slots and grid blocks; neither can move a result, + * which is why the average is legal as a proxy and a per-sequence length is not needed. */ +int avg_rows(int rows, int num_seqs) { return num_seqs > 0 ? (rows + num_seqs - 1) / num_seqs : rows; } + +/* Every width the ladder can return, at every gqa, must be instantiated and dispatched: pick_waves + * is `ceil(q_len / (32/gqa))` clamped to the ladder, so gqa = 4 asks for W = 4 at q_len > 16, + * gqa = 2 at q_len > 32, gqa = 1 at q_len > 64 -- and the prefill entry passes kWaves = 4 + * unconditionally. The launcher dispatches through `if constexpr (waves_ok<...>::value)`, so a + * missing instantiation compiles the kernel call out: the entry returns RAD_OK, hipGetLastError() + * is clean, and the output plane keeps what the caller put there. A silent no-op is the worst + * failure a kernel row can have: the engine reads its own input back as the attention output. The + * gate therefore asserts the whole ladder, at every gqa -- every width it admits is a width some + * q_len can ask for. */ +template struct waves_ok { + static const bool value = (W == 1) || (W == 2) || (W == 4); +}; + +int tok_per_block(int gqa, int waves) { return waves * (32 / (gqa > 0 ? gqa : 1)); } + +/* The decode entry's `splits`, when the caller asked for the widest legal: enough workgroups to + * fill the card (16 CUs x two workgroups at four waves a SIMD) and no more, on a doubling ladder. */ +int pick_splits(int tiles, int num_seqs, int kv_heads) +{ + const long long blocks = (long long)tiles * num_seqs * kv_heads; + int sp = 1; + while (sp < 8 && blocks * sp < 32) sp *= 2; + return sp; +} + +static void dev_speak(const DevRec& r); /* the record, spoken; defined with the ring below */ + +int launch(const Args& A, long out, long stream) +{ + Args B = A; + B.out = (uint16_t*)(uintptr_t)out; + const int gqa = A.n_head / A.kv_heads; + const int waves = A.waves > 0 ? A.waves : kWaves; + const int tpb = tok_per_block(gqa, waves); + /* The grid's row count. Rectangular: every sequence has the same tile count, so the product is + * exact and is the grid. Ragged: the tile count is + * sum_s ceil(len_s / tpb), which lives in device memory, so the launch uses the bound + * sum_s ceil(len_s / tpb) <= ceil(rows / tpb) + n_seq - 1 + * (ceil(x) + ceil(y) <= ceil(x + y) + 1, inducted over the sequences), and `map_seq` sends a grid + * row past the last tile straight home. The slack is at most n_seq - 1 empty workgroups, and an + * empty one stages nothing: it reads n_seq descriptor entries and returns. */ + const int tiles = A.cu ? (A.rows + tpb - 1) / tpb + A.n_seq - 1 + : (A.q_len + tpb - 1) / tpb * A.n_seq; + dim3 grid((unsigned)tiles, (unsigned)A.kv_heads, + (unsigned)(A.splits > 1 ? A.splits : 1)); + const bool fp8 = A.kv8 != nullptr; + const bool causal = A.causal != 0; + hipStream_t st = (hipStream_t)(uintptr_t)stream; + +#define R3D_ATTN(FP8V, CAUSALV, SPLITV, GQAV, WAVESV) \ + R3D_KLAUNCH((attn_kernel), grid, \ + dim3(WAVESV * 32), st, B) + +#define R3D_ATTN_SEL(GQAV, WAVESV) \ + do { \ + if constexpr (waves_ok::value) { \ + /* `sel` is three bits, and all eight combinations are reachable: a single-sequence \ + * causal decode picks splits 4 on its own (pick_splits(1, 1, 8) = 4), so sel 6 and 7 \ + * are the engine's most common split shape. Each combination needs its own arm: a \ + * causal-with-splits launch routed into the non-causal instantiation takes its maximum \ + * over keys the row must not see, the softmax loses its top weight to a future key, \ + * and the reduce amplifies the loss into a 1/sum of the wrong size. All eight arms \ + * exist. */ \ + if (sel == 0) R3D_ATTN(false, false, false, GQAV, WAVESV); \ + else if (sel == 1) R3D_ATTN(true, false, false, GQAV, WAVESV); \ + else if (sel == 2) R3D_ATTN(false, true, false, GQAV, WAVESV); \ + else if (sel == 3) R3D_ATTN(true, true, false, GQAV, WAVESV); \ + else if (sel == 4) R3D_ATTN(false, false, true, GQAV, WAVESV); \ + else if (sel == 5) R3D_ATTN(true, false, true, GQAV, WAVESV); \ + else if (sel == 6) R3D_ATTN(false, true, true, GQAV, WAVESV); \ + else R3D_ATTN(true, true, true, GQAV, WAVESV); \ + } \ + } while (0) + +#define R3D_ATTN_GQA(GQAV) \ + do { \ + if (waves == 1) R3D_ATTN_SEL(GQAV, 1); \ + else if (waves == 2) R3D_ATTN_SEL(GQAV, 2); \ + else R3D_ATTN_SEL(GQAV, 4); \ + } while (0) + + const int sel = (fp8 ? 1 : 0) | (causal ? 2 : 0) | (A.splits > 1 ? 4 : 0); + /* The flag is cleared HERE, after the arguments are staged and before the chevron, and read + * straight back after it. `hipGetLastError()` reports the first error raised since it was last + * cleared, so a check that does not clear first attributes to this launch whatever the process + * raised before it: in a served process, the op that ran last. A synchronous launch clears a + * pending asynchronous error before the check, so `HIP_LAUNCH_BLOCKING=1` hides a + * misattribution of exactly this kind. A healthy step refused by a symptom it did not cause is + * the failure mode; the launch is not. */ + (void)hipGetLastError(); + switch (gqa) { + case 1: R3D_ATTN_GQA(1); break; + case 2: R3D_ATTN_GQA(2); break; + case 4: R3D_ATTN_GQA(4); break; + default: R3D_ATTN_GQA(8); break; + } +#undef R3D_ATTN_GQA +#undef R3D_ATTN_SEL +#undef R3D_ATTN + { + const hipError_t ke = hipGetLastError(); + if (ke != hipSuccess) { + /* A launch failure names what it saw: the error, the grid, the workgroup and the width + * the launcher chose. */ + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] attn: %s on the attn launch: grid (%u, %u, %u) block " + "%d waves %d gqa %d splits %d rows %d n_seq %d jcap %d\n", + hipGetErrorName(ke), grid.x, grid.y, grid.z, waves * 32, waves, gqa, + A.splits, A.rows, A.n_seq, A.jcap); + return -4; /* RAD_E_DEVICE */ + } + } + + if (B.trace_buf) { /* the record, spoken at the launch that wrote it: one sync, under the flag */ + (void)hipStreamSynchronize(st); + DevRec rec; + if (hipMemcpy(&rec, (const void*)B.trace_buf, sizeof rec, hipMemcpyDeviceToHost) == hipSuccess) + dev_speak(rec); + } + + if (A.splits > 1) { + const long long rows = A.rows; /* the plane's rows: cu[n_seq], or n_seq * q_len */ + const long long total = rows * A.n_head; + dim3 rg((unsigned)((total + 3) / 4)); + (void)hipGetLastError(); /* the same rule, the same reason */ + R3D_KLAUNCH(attn_reduce, rg, dim3(128), st, B, rows); + const hipError_t re = hipGetLastError(); + if (re != hipSuccess) { + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] attn: %s on the reduce launch: grid (%u, 1, 1) block " + "128 rows %lld heads %d splits %d\n", hipGetErrorName(re), + rg.x, rows, A.n_head, A.splits); + return -4; + } + } + return 0; +} + +} // namespace + +extern "C" int r3d_attn_decode_h128(long q, long kv, long bt, long seqused, long k_desc, + long v_desc, long cu, long out, int num_seqs, int q_len, + int head_dim, int gqa, int n_head, int block_size, int bt_cols, int bt_rs, int bt_cs, int max_ctx, + int window, int causal, float scale, int kv_dt, long q_ld, + long out_ld, int splits, long scratch, long stream) +{ + /* `cu` is the ragged query descriptor and it is served: with it, `q_len` is the query plane's + * row count (see the launchers' header) and the rows per sequence are cu[s+1] - cu[s]. The + * width and the split count are picked on the average sequence, because the descriptor is on the + * device and this function reads no device memory -- both numbers choose how many row slots are + * duplicated, and neither touches a result. */ + if (splits < 0) return -2; + if (gqa <= 0 || n_head <= 0 || n_head % gqa) return -2; + if (cu && num_seqs <= 0) return -2; + Args A; + const int kv_heads = n_head / gqa; + const int per = cu ? avg_rows(q_len, num_seqs) : (q_len > 0 ? q_len : 1); + const int waves = pick_waves(per, gqa); + const int tpb = tok_per_block(gqa, waves); + const int tiles = per > 0 ? (per + tpb - 1) / tpb : 1; + int sp = splits > 0 ? splits : pick_splits(tiles, num_seqs, kv_heads); + const int e = fill(A, q, kv, bt, seqused, k_desc, v_desc, cu, cu ? q_len : 0, num_seqs, + cu ? 0 : q_len, head_dim, gqa, n_head, block_size, bt_cols, bt_rs, bt_cs, + max_ctx, window, causal, scale, kv_dt, q_ld, out_ld, sp, scratch, waves); + if (e) return e; + return launch(A, out, stream); +} + +extern "C" int r3d_attn_prefill_h128(long q, long kv, long bt, long seqused, long k_desc, + long v_desc, long cu, long out, int num_seqs, int q_len, + int head_dim, int gqa, int n_head, int block_size, int bt_cols, int bt_rs, int bt_cs, + int max_ctx, int window, int causal, float scale, int kv_dt, + long q_ld, long out_ld, long scratch, long stream) +{ + (void)scratch; /* the prefill kernel has no split pass, so no partials */ + /* The width is kWaves with a descriptor or without one. A rectangular prefill's q_len is the + * whole chunk, so every slot of a four-wave workgroup is used; a ragged step's rows are laid + * out by the same workgroup, and the width that matters on a step with only a few rows in it is + * how many waves the GPU gets, not how many slots go unused. A 5-row step at gqa 8 is one + * workgroup per KV head: two waves is 2 x 2 wavefronts over 16 CUs, four waves is 2 x 4, and + * the measured 5-row launch at 2048 keys is 16.7 ms at four waves against 19.3 at two, with the + * duplicate slots costing nothing because a wave walks its tile once whatever rows it carries. + * A step whose rows are one per sequence is a decode step and goes to the decode entry, which + * picks its width on the average sequence -- that is where a narrow workgroup is the win. */ + Args A; + const int waves = kWaves; + const int e = fill(A, q, kv, bt, seqused, k_desc, v_desc, cu, cu ? q_len : 0, num_seqs, + cu ? 0 : q_len, head_dim, gqa, n_head, block_size, bt_cols, bt_rs, bt_cs, max_ctx, window, causal, + scale, kv_dt, q_ld, out_ld, 1, 0, waves); + if (e) return e; + A.splits = 1; + A.part = nullptr; + return launch(A, out, stream); +} + +/* ================================================================== shims + * + * The paged geometry as the tensors state it: n_seq from `seqused`, n_head and head_dim from the + * query, kv_heads from the cache, block_size from the cache, max_ctx from the cache's block count, + * q_len from the query's row count over n_seq. Params fill in what the tensors cannot say (gqa, + * causal, window, scale). */ +namespace { + +enum { P_Q = 0, P_KV = 1, P_BT = 2, P_SU = 3, P_KDS = 4, P_VDS = 5, P_CU = 6, P_OUT = 7 }; + +/* ---- arming the device record ring ---------------------------------------------------------- + * + * The kernel's four globals (`r3d_dev_budget`, `r3d_dev_launches`, `r3d_dev_widx`, `r3d_dev_ring`) + * are plugin-owned, at file scope, `extern "C"` so the names are the ones the code object carries. + * `RadArgs` is the row's ABI and the plan builds it, so nothing joins it; the kernel's launch + * parameters are fixed, so nothing joins them. The shim's whole instrument surface is therefore four + * symbols: + * + * hipGetSymbolAddress, once, cached -- the counter, for the plan line to quote + * hipMemcpyToSymbol of the budget, under RAD_R3D_TRACE ONLY -- 0 means the kernel records nothing + * hipMemcpy of the ring, under RAD_R3D_TRACE -- the drain: the records to stderr, host-side + * hipMemcpyToSymbol of the write index -- the drain's reset, so a record is spoken once + * + * The budget is re-written on every traced call, not once per process, and `RAD_R3D_DEV` is its + * size (default 64). Re-arming is one 4-byte copy under a flag that already does four device reads + * a line, and it buys the property the board needs: a harness can arm exactly -- arm 3, launch 10, + * count 3 -- between launches, with the kernel untouched. The last write wins, so a served ladder + * re-arms at every prefill and the budget never runs dry mid-request. + * + * The drain runs on every traced call too, BEFORE the arming: it speaks the records the kernel has + * written since the last call. For a played step there is no shim call in between, so its lines land + * at the next step's shim call, one step behind the step they describe. The record's `L` and `ctx` + * restore the order, and the plan line's `dev_launches=` quote is the counter the kernel itself ran, + * so the two prints of one step line up and the gap between them is the played pass, measured. + * + * Inert when the flag is unset: `dev_ring_drain` and `dev_trace_arm` return before the runtime call, + * the budget keeps its initial 0, and every kernel gates on it. Nothing here is on the served path + * at all: the shim calls them from inside its existing `r3d_trace_on()` arm. + */ +enum { kDevPrintDefault = 64 }; + +template +void* dev_sym(void** slot, const char* name, const T& symbol) +{ + if (*slot) return *slot; + void* p = nullptr; + const hipError_t e = hipGetSymbolAddress(&p, HIP_SYMBOL(symbol)); /* the T& overload */ + *slot = (e == hipSuccess) ? p : nullptr; + if (e != hipSuccess) + std::fprintf(stderr, "[r3d dev] %s: hipGetSymbolAddress -> %s\n", name, + hipGetErrorName(e)); + return *slot; +} + +void* g_dev_budget = nullptr; /* hipGetSymbolAddress cache, resolved once */ +void* g_dev_launches = nullptr; + +unsigned long long dev_launch_count() +{ + /* `hipMemcpyFromSymbol`, not `hipGetSymbolAddress` + `hipMemcpy`: the arming's + * `hipMemcpyToSymbol` resolves the stub the runtime owns, and in the engine process a + * `hipGetSymbolAddress` on a dlopened plugin's symbol can hand back an address the kernel's + * module does not write to -- the read is a copy of the initial value, forever. The same stub + * resolution the arming uses is the one the read must use. */ + unsigned long long n = 0; + (void)hipMemcpyFromSymbol(&n, HIP_SYMBOL(r3d_dev_launches), sizeof n); + return n; +} + +void* g_dev_widx = nullptr; +void* g_dev_ring = nullptr; + +/* One record, spoken. The format is the line the board parses: the same field names in the same + * order, `ids=` the row's columns, `kh` the fold of the FIRST block it walks and `khL` the fold of + * the LAST, `idsum` a fold of every column so a long row is one comparable number. */ +static void dev_speak(const DevRec& r) +{ + std::fprintf(stderr, "[r3d dev] L=%llu dec=%d n_seq=%d rows=%d q_len=%d s=%d len=%d span=%d " + "start=%d ctx=%lld pos=%lld jcap=%d splits=%d waves=%d kv=%p bt=%p su=%p cu=%p " + "q=%p out=%p bt0=%d bt1=%d bt2=%d slot0=%lld qh=%016llx kh=%016llx ids=", + (unsigned long long)r.L, r.dec, r.n_seq, r.rows, r.q_len, r.s, r.len, r.span, + r.start, (long long)r.ctx, (long long)r.pos, r.jcap, r.splits, r.waves, + (const void*)r.kv, (const void*)r.bt, (const void*)r.su, (const void*)r.cu, + (const void*)r.q, (const void*)r.out, r.b[0], r.b[1], r.b[2], (long long)r.slot0, + (unsigned long long)r.qh, (unsigned long long)r.kh); + for (int c = 0; c < r.ncols && c < kDevIds; ++c) + std::fprintf(stderr, "%s%d", c ? "," : "", r.b[c]); + std::fprintf(stderr, " ncols=%d bL=%d slotL=%lld khL=%016llx idsum=%lld rowok=%d\n", r.ncols, + r.spare, (long long)r.slotL, (unsigned long long)r.khL, (long long)r.idsum, + r.rowok); +} + +/* The ring, spoken. The drain is a D2H of at most kDevRing records (55 KiB) on a traced call: one + * sync per shim call, under the flag only. The index is the kernel's own, so the drain can never + * read past what the kernel wrote, and the reset is to 0, not to a moving base: a record is spoken + * exactly once, and the counter -- which the drain does not touch -- is the launch census. */ +void dev_ring_drain() +{ + if (!r3d_trace_on()) return; + /* The reads go through `hipMemcpyFromSymbol`, the same stub resolution the arming's + * `hipMemcpyToSymbol` uses (see `dev_launch_count`): in the engine process a + * `hipGetSymbolAddress` on a dlopened plugin's symbol is not the address the kernel writes. */ + unsigned w = 0; + if (hipMemcpyFromSymbol(&w, HIP_SYMBOL(r3d_dev_widx), sizeof w) != hipSuccess) return; + if (w == 0) return; + static DevRec buf[kDevRing]; + const unsigned keep = w < (unsigned)kDevRing ? w : (unsigned)kDevRing; + if (hipMemcpyFromSymbol(buf, HIP_SYMBOL(r3d_dev_ring), (size_t)keep * sizeof(DevRec)) != hipSuccess) + return; + for (unsigned i = 0; i < keep; ++i) dev_speak(buf[i]); + if (w > keep) + std::fprintf(stderr, "[r3d dev] ring: %u records written, %u kept, %u counted and dropped " + "-- the counter is the truth\n", w, keep, w - keep); + const unsigned zero = 0u; + (void)hipMemcpyToSymbol(HIP_SYMBOL(r3d_dev_widx), &zero, sizeof zero); +} + +void dev_trace_arm() +{ + if (!r3d_trace_on()) return; /* the gate: with the flag unset, nothing here */ + int want = kDevPrintDefault; + if (const char* e = std::getenv("RAD_R3D_DEV")) { + const int v = std::atoi(e); + if (v > 0) want = v; /* a harness arms exactly; 0 disables */ + else if (v == 0) want = 0; + } + static bool said = false; + const unsigned long long seen = dev_launch_count(); + if (!dev_sym(&g_dev_budget, "r3d_dev_budget", HIP_SYMBOL(r3d_dev_budget))) return; + const hipError_t e = hipMemcpyToSymbol(HIP_SYMBOL(r3d_dev_budget), &want, sizeof want); + if (!said || e != hipSuccess) { + said = true; + std::fprintf(stderr, "[r3d dev] armed: budget=%d launches_at_arm=%llu %s\n", want, + (unsigned long long)seen, e == hipSuccess ? "ok" : hipGetErrorName(e)); + } +} + + +/* ---- the plan line: the one number a launcher has never been able to read ---------------------- + * + * `cu_seqlens` is device memory -- the header's rule is that a launcher reads none of it -- and the + * walk's bound is a single value inside it: `cu[0]`. The served descriptors start at row 0. Under + * RAD_R3D_TRACE=1 this stops being an inference: the shim copies the descriptor's `n_seq + 1` i32 + * and prints them, once per shape. + * + * Inert when the flag is unset. Everything below sits behind `r3d_trace_on()`, the cached flag load + * `R3D_NO` already pays on a path that is failing anyway: no copy, no latch, no syscall, and no + * operand the served path did not already touch. + * + * The reads, all of them bounded. The descriptor's plane holds exactly `n_seq + 1` ints -- the shim + * has proved `r3d_numel(CU) == n_seq + 1` above -- and the copy is capped at `kCuPrint` of them, + * with the LAST entry taken by its own one-int read when the plane is wider, so the printed total is + * the total and nothing past the plane is touched. `seqused` is read for ONE int, its first, because + * `ctx` is `seqused[0]` and a plan line that cannot say where the walk bounds is + * half a line. A null pointer is never dereferenced: the descriptor is read only after `r3d_has(CU)` + * said it carries bytes, and `SU->data` was required at the top of the shim. `hipMemcpyDefault` is + * placement-agnostic, so the same line prints for a vram plane and for a host-mapped one. + * + * The latch is keyed on the shape -- n_seq, the plane's rows, the kernel's q_len, the table's + * columns -- because the engine calls this shim once a layer a step and 42 identical lines are + * noise. It is a plain static array with no lock: the worst a race can do here is print a shape + * twice, and nothing at all when the flag is off. */ +enum { kCuPrint = 64, kPlanShapes = 512 }; + +/* RAD_R3D_TRACE=2 is the same instrument with ctx in the shape key (see plan_once). Read once. */ +bool r3d_trace_wide() +{ + static int wide = -1; + if (wide < 0) { + const char* e = std::getenv("RAD_R3D_TRACE"); + wide = (e && e[0] == '2') ? 1 : 0; + } + return wide != 0; +} + +/* The shape key: n_seq, the plane's rows, the kernel's q_len, the table's + * columns. `ctx` rides along ONLY under RAD_R3D_TRACE=2, which is the wide form of the same + * instrument: a serving engine's requests all share the shape (rows 1, one sequence, 128 columns) + * and differ only in how deep the context has grown, so with the narrow key the block table prints + * once for the FIRST request and the requests that matter -- the ones after six blocks are in play + * -- never print. The default (=1) is the narrow key. */ +struct PlanKey { long long n_seq, rows, q_len, cols, ctx; }; + +bool plan_once(long long n_seq, long long rows, long long q_len, long long cols, long long ctx, + bool by_ctx) +{ + static PlanKey seen[kPlanShapes]; + static int n = 0; + for (int i = 0; i < n; ++i) + if (seen[i].n_seq == n_seq && seen[i].rows == rows && seen[i].q_len == q_len && + seen[i].cols == cols && (!by_ctx || seen[i].ctx == ctx)) + return false; + if (n < kPlanShapes) seen[n++] = PlanKey{n_seq, rows, q_len, cols, ctx}; + return true; +} + +void plan_line(bool decode, const RadTensor* Q, const RadTensor* KV, const RadTensor* O, + const RadTensor* CU, const RadTensor* SU, const RadTensor* BT, const void* scratch, + long long n_seq, long long rows, long long q_len, long long bt_cols, long long bt_rs, + long long bt_cs, int block_size, int max_ctx, int waves, int splits, bool by_ctx) +{ + /* The walk's bound, the same expression fill() uses: the TABLE's columns times the block, + * capped by the cache's context (jend = min(ctx, max_blocks * block_size)). */ + const long long reach = (long long)bt_cols * block_size; + const long long jcap = reach < max_ctx ? reach : (long long)max_ctx; + + long long ctx = -1; /* seqused[0], the first sequence's context */ + int ctx0 = 0; + if (r3d_p(SU) && hipMemcpy(&ctx0, r3d_p(SU), sizeof(int), hipMemcpyDefault) == hipSuccess) + ctx = ctx0; + + /* The latch lives here, after the one-int ctx read, because the wide key is keyed on it. This + * whole function is called only under the flag, so the served path pays none of it. */ + if (!plan_once(n_seq, rows, q_len, bt_cols, ctx, by_ctx)) return; + + std::fprintf(stderr, + "[r3d] plan: %s n_seq=%lld rows=%lld q_len=%lld cu rank=%u numel=%lld ctx=%lld " + "bt cols=%lld pitch=%lld max_ctx=%d -> jcap=%lld waves=%d splits=%d", + decode ? "decode" : "prefill", n_seq, rows, q_len, + r3d_has(CU) ? (unsigned)CU->rank : 0u, r3d_has(CU) ? r3d_numel(CU) : 0LL, ctx, + bt_cols, bt_rs, max_ctx, jcap, waves, splits); + + /* The ADDRESSES the launch bakes. The engine captures this step into a graph after two eager + * decode steps -- one request generating twelve tokens calls this shim for the prefill and for + * two decode steps, and for nothing after that -- and a replay re-runs the kernels with the + * ARGUMENTS frozen at capture. The planes a step reads are named by address in those arguments, + * so if a later request's plan lives at different addresses, a replay is reading the earlier + * request's planes and no per-row fixture, ladder or descriptor print can see it. `%p` of the + * five operands this step reads and the one it writes, nothing dereferenced. */ + std::fprintf(stderr, " q=%p kv=%p bt=%p cu=%p su=%p out=%p part=%p", + r3d_p(Q), r3d_p(KV), r3d_p(BT), r3d_p(CU), r3d_p(SU), r3d_p(O), scratch); + + /* The kernel's own launch counter, quoted on the shim's line so the two prints of one step line + * up: the shim sees a served request's prefill and its first two decode steps, the kernel sees + * every one, and the gap between the two numbers IS the played pass. One 8-byte device read, + * under the flag, on a line that is already reading three planes. */ + std::fprintf(stderr, " dev_launches=%llu", (unsigned long long)dev_launch_count()); + + if (!r3d_has(CU)) { /* an absent optional operand is ABSENT, not a refusal: the + rectangular step is the common case and it says so */ + std::fprintf(stderr, " cu=absent (rectangular)"); + } else { + int cuh[kCuPrint]; + const int take = (int)(n_seq + 1 < kCuPrint ? n_seq + 1 : kCuPrint); + if (hipMemcpy(cuh, r3d_p(CU), (size_t)take * sizeof(int), hipMemcpyDefault) != + hipSuccess) { + std::fprintf(stderr, " cu=copy failed"); + } else { + long long cu_last = -1; + if (n_seq + 1 <= kCuPrint) cu_last = cuh[(int)n_seq]; + else { + int last = 0; /* the plane's last int, nothing beyond it */ + if (hipMemcpy(&last, (const int*)r3d_p(CU) + n_seq, sizeof(int), + hipMemcpyDefault) == hipSuccess) + cu_last = last; + } + std::fprintf(stderr, " cu[0]=%d cu[n_seq]=%lld", cuh[0], cu_last); + if (n_seq + 1 <= 8) /* the whole descriptor, when it is short */ + for (int i = 0; i <= (int)n_seq; ++i) + std::fprintf(stderr, " cu[%d]=%d", i, cuh[i]); + } + } + + /* The block table's own entries for the row this step walks. The walk's arithmetic -- which + * block holds key j -- is the one part of the plan this file cannot check from the descriptor, + * and a reused block id inside one row, or an id the cache does not have, is invisible to every + * per-row fixture (the drivers deal their ids from a shuffled pool, so they cannot produce the + * first). Bounded three ways: at most `kCuPrint` columns of ONE row, only columns the shim has + * already proved the plane covers (the reach check above), and row 1's first entry only when + * there is a row 1. A -1 is an unmapped block and prints as -1, which is what the kernel sees. */ + if (r3d_has(BT)) { + const int take = (int)(bt_cols < kCuPrint ? bt_cols : kCuPrint); + int bth[kCuPrint]; + const int* btp = (const int*)r3d_p(BT); + bool got = true; + for (int i = 0; i < take; ++i) + if (hipMemcpy(&bth[i], btp + (long long)i * bt_cs, sizeof(int), + hipMemcpyDefault) != hipSuccess) { got = false; break; } + std::fprintf(stderr, " bt0="); + if (!got) std::fprintf(stderr, "(copy failed)"); + else { + std::fprintf(stderr, "["); + for (int i = 0; i < take; ++i) std::fprintf(stderr, "%s%d", i ? "," : "", bth[i]); + std::fprintf(stderr, "]"); + if (take < bt_cols) std::fprintf(stderr, " (%lld cols)", bt_cols); + if (n_seq >= 2) { + int r1 = 0; + if (hipMemcpy(&r1, btp + bt_rs, sizeof(int), hipMemcpyDefault) == hipSuccess) + std::fprintf(stderr, " bt1[0]=%d", r1); + } + } + } + std::fprintf(stderr, "\n"); +} + +int attn_shim(const RadArgs* a, RadStream s, bool decode) +{ + if (a->n_t < 8) return R3D_NO(RAD_E_INVAL); + const RadTensor* Q = r3d_opt(a, P_Q); + const RadTensor* KV = r3d_opt(a, P_KV); + const RadTensor* BT = r3d_opt(a, P_BT); + const RadTensor* SU = r3d_opt(a, P_SU); + const RadTensor* O = r3d_opt(a, P_OUT); + const RadTensor* KDS = r3d_opt(a, P_KDS); + const RadTensor* VDS = r3d_opt(a, P_VDS); + const RadTensor* CU = r3d_opt(a, P_CU); + if (!Q || !KV || !BT || !SU || !O) return R3D_NO(RAD_E_INVAL); + if (!Q->data || !KV->data || !BT->data || !SU->data || !O->data) return R3D_NO(RAD_E_INVAL); + /* `cu_seqlens` present is a ragged batch, and this file serves it: the row map, the positions, + * the mask and the walk all key off the sequence a row belongs to, which is what the descriptor + * says it is (see "the ragged batch" in the header). The descriptor is device memory, so what + * the shim can check here is its shape and dtype; what it cannot see -- cu[0] == 0, monotonicity, + * cu[n_seq] == the plane's row count -- the kernel clamps, exactly as libref's row loop does. */ + const bool ragged = r3d_has(CU); + + const int head_dim = (int)r3d_geti_or(a, "head_dim", r3d_dim(Q, (int)Q->rank - 1)); + if (head_dim != kHeadDim) return R3D_NO(RAD_E_SHAPE); + const int gqa = (int)r3d_geti_or(a, "gqa", 1); + if (gqa != 1 && gqa != 2 && gqa != 4 && gqa != 8) return R3D_NO(RAD_E_SHAPE); + const int causal = (int)r3d_geti_or(a, "causal", 1); + const int window = (int)r3d_geti_or(a, "window", 0); + const float scale = (float)r3d_getf(a, "scale", 0.0); + + /* The kernel's f16 query path is written -- `A.q16` makes the widening a copy -- but the + * launcher's signature carries one dtype slot, `kv_dt`, and it is the cache's, so the shim has + * no way to tell the kernel that q is f16: the flag would sit at zero and the kernel would + * widen f16 codes as bf16, a 2^9 scale error, not a rounding difference. Refused until `q_dt` + * joins the signature. A row set that widens `q_dtype` to "bf16 f16" must land with that + * parameter. */ + if (Q->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (O->dtype != Q->dtype) return R3D_NO(RAD_E_DTYPE); + if (KV->dtype != RAD_BF16 && KV->dtype != RAD_F8E4M3) return R3D_NO(RAD_E_DTYPE); + if (BT->dtype != RAD_I32 || SU->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + const bool quant = KV->dtype == RAD_F8E4M3; + /* A quantised cache with no descale plane is a cache with scale 1.0, not a refused geometry. + * The reference reads the planes only when they are there: + * const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f; + * const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f; + * and says it in prose ("the scales are the reader's descales, default 1.0"). + * The op's operand description describes both planes as ABSENT, so a fixture that draws this + * op hands every implementation null descales; refusing them is refusing the case class. The + * kernel already carries the null through and widens at 1.0 (`A.kds ? ... : 1.0f`). */ + const bool kgiven = KDS && KDS->data, vgiven = VDS && VDS->data; + if (!quant && (kgiven || vgiven)) + return R3D_NO(RAD_E_SHAPE); /* a bf16 cache has no scales: the caller believes something + the op does not have, and dropping that quietly is worse */ + if (quant && kgiven && !r3d_is_f32(KDS)) return R3D_NO(RAD_E_DTYPE); + if (quant && vgiven && !r3d_is_f32(VDS)) return R3D_NO(RAD_E_DTYPE); + + const int n_head = (int)r3d_geti_or(a, "n_head", r3d_dim(Q, (int)Q->rank - 2)); + if (n_head <= 0 || n_head % gqa) return R3D_NO(RAD_E_SHAPE); + const int kv_heads = n_head / gqa; + const int block_size = (int)r3d_geti_or(a, "block_size", r3d_dim(KV, 2)); + if (block_size != kBlock) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(KV, 1) != kv_heads) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(KV, 3) < 2 * kHeadDim) return R3D_NO(RAD_E_SHAPE); + const long long nb = r3d_dim(KV, 0); + const int max_ctx = (int)(nb * block_size); + const int max_blocks = (int)((max_ctx + block_size - 1) / block_size); + + const long long n_seq = r3d_numel(SU); + if (n_seq < 1 || n_seq > 65536) return R3D_NO(RAD_E_SHAPE); + /* The descriptor is [n_seq + 1] i32, contiguous: the kernel reads it with int indices, so an + * i64 plane is not a wider form of the same operand, it is the wrong operand, and the fix is the + * plane the op's description names. `seqused` is read the same way and is checked below. */ + if (ragged) { + if (CU->dtype != RAD_I32) { r3d_trace_desc("cu_seqlens", CU); return R3D_NO(RAD_E_DTYPE); } + if (!r3d_contig(CU)) { r3d_trace_desc("cu_seqlens", CU); return R3D_NO(RAD_E_STRIDE); } + if (r3d_numel(CU) != n_seq + 1) { r3d_trace_desc("cu_seqlens", CU); return R3D_NO(RAD_E_SHAPE); } + if (!r3d_aligned(CU->data, 4)) return R3D_NO(RAD_E_ALIGN); + } + long long qh = 0, qt = 0, qld = 0; + if (!r3d_head_rows(Q, kHeadDim, &qt, &qh, &qld) || qh != n_head) { r3d_trace_desc("q", Q); + r3d_trace_desc("out", O); return R3D_NO(RAD_E_STRIDE); } + long long oh = 0, ot = 0, old = 0; + if (!r3d_head_rows(O, kHeadDim, &ot, &oh, &old) || oh != n_head) { r3d_trace_desc("out", O); + return R3D_NO(RAD_E_STRIDE); } + if (qld % 8 || old % 8) return R3D_NO(RAD_E_STRIDE); + /* Rows per sequence: the plane's row count divided by the sequence count when the batch is + * rectangular, and nothing at all when it is ragged -- the reference's `q_len = cus ? 0 : + * rows / n_seq` (the reference's reading), with the plane's row count (its `rows`, and the number a + * descriptor's cu[n_seq] equals) carried to the launcher as the row count. A ragged batch is not + * required to divide: 5 rows over 3 sequences is the case the engine sends, and `qt % n_seq` is + * exactly the shape it arrives in. */ + if (qt < 1) return R3D_NO(RAD_E_SHAPE); + if (qt > 2147483000LL) return R3D_NO(RAD_E_SHAPE); /* the kernel's row index is 32-bit */ + if (!ragged && qt % n_seq) return R3D_NO(RAD_E_SHAPE); + const long long q_len = ragged ? qt : qt / n_seq; /* the per-sequence length, rectangular */ + const long long rows = qt; /* the plane's rows, both forms */ + if (q_len < 1) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(O) < rows * n_head * kHeadDim) return R3D_NO(RAD_E_SHAPE); + /* The descales are per (sequence, KV head), the reference's indexing: `s * kv_heads + kh`. */ + if (quant && kgiven && (r3d_numel(KDS) < n_seq * kv_heads || !r3d_contig(KDS))) + return R3D_NO(RAD_E_SHAPE); + if (quant && vgiven && (r3d_numel(VDS) < n_seq * kv_heads || !r3d_contig(VDS))) + return R3D_NO(RAD_E_SHAPE); + if (quant && (kgiven != vgiven)) return R3D_NO(RAD_E_SHAPE); /* half a pair is a caller bug */ + /* The cache is dense and the launcher assumes it: a slot's halves must land on a 16-byte + * boundary at every slot, so the cache's strides have to be the dense ones. */ + if (!r3d_contig(KV)) { r3d_trace_desc("kv", KV); return R3D_NO(RAD_E_STRIDE); } + /* The table is the engine's, sized to the step, so its geometry comes from the tensor and not + * from the band: `max_blocks` is the TABLE's columns, the row pitch is `stride[rank-2]` and the + * column stride `stride[rank-1]` (the reference's table read). A five-token prompt carries + * [n_seq, 1]: one block per sequence, because nothing is behind it. What the shim insists on is + * that every index the walk can reach is inside the plane -- the last row's pitch plus the last + * column it can name: a contiguity check asks for a table as wide as the cache and refuses a + * step the engine sends. */ + const long long bt_cols = BT->rank >= 2 ? r3d_dim(BT, (int)BT->rank - 1) : (n_seq ? r3d_numel(BT) / n_seq : 0); + const long long bt_rs = BT->rank >= 2 ? BT->stride[BT->rank - 2] : bt_cols; + const long long bt_cs = BT->rank >= 2 ? BT->stride[BT->rank - 1] : 1; + if (bt_cols < 1 || bt_rs < 1 || bt_cs < 1) { r3d_trace_desc("block_tables", BT); + return R3D_NO(RAD_E_STRIDE); } + const long long bt_reach = (n_seq - 1) * bt_rs + (bt_cols - 1) * bt_cs + 1; + if (r3d_numel(BT) < bt_reach) { r3d_trace_desc("block_tables", BT); + std::fprintf(stderr, "[r3d] block table: %lld entries, the walk reaches %lld\n", + (long long)r3d_numel(BT), bt_reach); + return R3D_NO(RAD_E_STRIDE); } + if (!r3d_contig(SU)) { r3d_trace_desc("seqused", SU); return R3D_NO(RAD_E_STRIDE); } + if (!r3d_aligned(Q->data, 16) || !r3d_aligned(KV->data, 16) || !r3d_aligned(O->data, 16)) + return R3D_NO(RAD_E_ALIGN); + + int splits = decode ? (int)r3d_geti_or(a, "splits", 0) : 1; + if (splits < 0) return R3D_NO(RAD_E_SHAPE); + /* The width the launcher will cut the grid on. A ragged batch has no per-sequence length to pick + * on -- the descriptor is on the device -- so the average sequence decides, as it does in the + * entry itself. It moves duplicated row slots between tiles and no result. */ + const long long per = ragged ? (rows + n_seq - 1) / n_seq : q_len; + const int waves = pick_waves((int)per, gqa); + const int tiles = (int)((per + tok_per_block(gqa, waves) - 1) / tok_per_block(gqa, waves)); + if (splits == 0) splits = decode ? pick_splits(tiles, (int)n_seq, kv_heads) : 1; + if (splits > 64) splits = 64; + if (splits > 1) { + /* The arena the engine offers is the bound: halve the split count until the partials fit, + * down to 1, which needs none -- and one slice is the whole walk in one block, the same + * keys in the same order, so it is not a degraded answer, it is the answer without the + * optimisation. A row that refuses a band because an optimisation has no room is a row that + * tells the user to go away; the number is the same either way. */ + for (;;) { + if (splits <= 1) { splits = 1; break; } + const long long need = qt * n_head * (long long)splits * kPartStride * 4; + if (a->scratch && a->scratch_bytes >= (size_t)need) break; + splits /= 2; + } + if (r3d_trace_on() && splits > 1) + std::fprintf(stderr, "[r3d] attn: %d slices into %zu of %zu bytes needed\n", + splits, a->scratch_bytes, (size_t)(qt * n_head * + (long long)splits * kPartStride * 4)); + } + + /* The plan line: what the descriptor actually says, once per shape, under the flag only. The + * `q_len` printed is the one the kernel is given -- 0 with a descriptor, the per-sequence length + * without one (the reference's reading) -- and `rows` is the plane's row count, which is what + * cu[n_seq] is required to equal. Printed AFTER every check: a refused step's shape is the + * refusal lines' business, not this one's. */ + /* The kernel is the one instrument that a played step runs through: its records sit in the ring + * until a shim call drains them, so drain FIRST -- the records written since the last call, the + * played steps included -- and THEN arm the budget this launch will spend, under the flag only + * (both functions gate themselves on the same cached load). */ + dev_ring_drain(); + dev_trace_arm(); + + if (r3d_trace_on()) + plan_line(decode, Q, KV, O, CU, SU, BT, splits > 1 ? (const void*)a->scratch : nullptr, + n_seq, rows, ragged ? 0LL : q_len, bt_cols, bt_rs, bt_cs, block_size, max_ctx, + waves, splits, r3d_trace_wide()); + + /* The entries take the descriptor's row count where a rectangular batch has its per-sequence + * length: `rows` is the plane's, which is what cu[n_seq] equals and what libref counts off the + * tensor, and `q_len` is the per-sequence length only when there is no descriptor. */ + const int e = decode + ? r3d_attn_decode_h128(r3d_addr(Q), r3d_addr(KV), r3d_addr(BT), r3d_addr(SU), + r3d_addr(KDS), r3d_addr(VDS), r3d_addr(CU), r3d_addr(O), (int)n_seq, + (int)(ragged ? rows : q_len), + head_dim, gqa, n_head, block_size, (int)bt_cols, (int)bt_rs, + (int)bt_cs, max_ctx, window, causal, scale, + (int)KV->dtype, qld, old, splits, + (long)(uintptr_t)(splits > 1 ? a->scratch : nullptr), + (long)(uintptr_t)s) + : r3d_attn_prefill_h128(r3d_addr(Q), r3d_addr(KV), r3d_addr(BT), r3d_addr(SU), + r3d_addr(KDS), r3d_addr(VDS), r3d_addr(CU), r3d_addr(O), (int)n_seq, + (int)(ragged ? rows : q_len), head_dim, gqa, n_head, block_size, + (int)bt_cols, (int)bt_rs, (int)bt_cs, max_ctx, window, + causal, scale, (int)KV->dtype, qld, old, + (long)(uintptr_t)nullptr, (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_DTYPE : e == -2 ? RAD_E_SHAPE + : e == -3 ? RAD_E_ALIGN : e == -4 ? RAD_E_DEVICE + : e == -5 ? RAD_E_SCRATCH : RAD_E_INVAL); +} + +} // namespace + +extern "C" int r3d_rad_attn_decode_h128(const RadArgs* a, RadStream s) +{ + return attn_shim(a, s, true); +} + +extern "C" int r3d_rad_attn_prefill_h128(const RadArgs* a, RadStream s) +{ + return attn_shim(a, s, false); +} diff --git a/libr3d/r3d_codecs.h b/libr3d/r3d_codecs.h new file mode 100644 index 00000000..485ebde2 --- /dev/null +++ b/libr3d/r3d_codecs.h @@ -0,0 +1,359 @@ +/* r3d_codecs.h -- the numeric codecs, in the one spelling every libr3d unit and the host use. + * + * These define what a result is, so they are stated once: rad_plugin.h's bf16 / f16 / fp8 / int8 + * rounders, restated so a device kernel can call them. rad_plugin.h's are `static inline` host + * functions, which a `__global__` cannot reach, and libref -- the oracle every libr3d row is + * checked against at kbench -- is built out of them. The mirror is therefore not a style choice, + * and r3d_selftest.cpp compares the two over the whole fp8 code space, the whole bf16 code space + * and 2^20 random f32s, so a drift of one ulp is a test failure here and not a tolerance argument + * at kbench. + * + * The contract, from ref_common.h and rad_plugin.h: f32 accumulation, IEEE round-to-nearest-ties- + * to-even narrowing, no fused multiply-add and no reassociation, subnormals kept. Widening is + * exact. `-ffp-contract=off` is a correctness flag, and rad_hipify puts it on every HIP source. + * + * R3D_HD is `__host__ __device__` in a HIP translation unit and nothing in a host one, which is how + * the same header serves a kernel and r3d_selftest.cpp. The pieces that want a GPU instruction are + * behind __HIP_DEVICE_COMPILE__ and have a plain-C++ twin a device build never takes. + */ +#ifndef R3D_CODECS_H +#define R3D_CODECS_H + +#include +#include + +/* HIP first, and before R3D_HD: `__forceinline__` is a macro of hip_runtime.h's, so a unit that + * includes this header without including the runtime first -- r3d_common.h includes the codecs + * before it -- would read `__forceinline__` as a type name. The runtime declares no + * `__host__ __device__` memcpy, which is why the bitcasts below go through bits_of and float_of. + * A host translation unit -- the row table, the operand descriptions, r3d_selftest.cpp -- takes the + * #else and pulls in no ROCm header at all. */ +#if defined(__HIPCC__) +#include +#endif + +#if defined(__HIPCC__) +#define R3D_HD __device__ __host__ __forceinline__ +#else +#define R3D_HD inline +#endif + +/* The bit cast, in one place. Device code cannot call `memcpy` and the HIP headers do not declare a + * `__host__ __device__` one on every release, so the device path is the compiler's bit cast; the + * host path keeps memcpy, which the optimiser folds to a move, because GCC only grew + * `__builtin_bit_cast` in C++20 mode and r3d_selftest.cpp is built at C++17 by the tree's host + * compiler. */ +R3D_HD uint32_t bits_of(float f) { +#if defined(__HIPCC__) + return __builtin_bit_cast(uint32_t, f); +#else + uint32_t u; + std::memcpy(&u, &f, sizeof u); + return u; +#endif +} + +R3D_HD float float_of(uint32_t u) { +#if defined(__HIPCC__) + return __builtin_bit_cast(float, u); +#else + float f; + std::memcpy(&f, &u, sizeof f); + return f; +#endif +} + + +/* ================================================================== bf16 + * + * bf16 is f32's top half: widening is a shift, narrowing one add and a shift. + * + * `(u >> 16) & 1` is the tie-break -- it adds one more than the halfway point when the surviving + * bit is odd, so ties go to even. Overflow carries into the bf16 infinity; a NaN is forced quiet so + * it cannot round into an infinity, which is what rad_f32_to_bf16 does and what libref does. */ +R3D_HD float bf16_to_f32(uint16_t h) { + const uint32_t u = (uint32_t)h << 16; + return float_of(u); +} + +R3D_HD uint16_t f32_to_bf16(float f) { + const uint32_t u = bits_of(f); + if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t)((u >> 16) | 0x0040u); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +/* The same rounding, stopped one shift short: the rounded value sitting in a word's high half, the + * form a packed store wants. gfx11 in this ROCm has no v_cvt_pk_bf16_f32 (llvm-mc rejects it on + * gfx1100, gfx1102 and gfx1151), so a bf16 pair is two of these and one byte permute. */ +R3D_HD uint32_t bf16_hi_rne(float f) { + const uint32_t u = bits_of(f); + return u + 0x7fffu + ((u >> 16) & 1u); +} + +/* Two such words as one bf16 pair, `lo`'s half in the low half of the result: one v_perm_b32. */ +R3D_HD uint32_t bf16_pack_hi(uint32_t lo, uint32_t hi) { +#if defined(__HIP_DEVICE_COMPILE__) + return __builtin_amdgcn_perm(hi, lo, 0x07060302u); +#else + return ((lo >> 16) & 0xffffu) | (hi & 0xffff0000u); +#endif +} + +R3D_HD uint32_t bf16x2_rne(float lo, float hi) { + return bf16_pack_hi(bf16_hi_rne(lo), bf16_hi_rne(hi)); +} + +/* A bf16 pair word's two values as floats: a shift and a mask, no conversion. */ +R3D_HD float bf16w_lo(uint32_t w) { + const uint32_t u = w << 16; + return float_of(u); +} +R3D_HD float bf16w_hi(uint32_t w) { + const uint32_t u = w & 0xffff0000u; + return float_of(u); +} + +/* ================================================================== f16 + * + * RTNE both ways with subnormals kept, as rad_f16_to_f32 and rad_f32_to_f16 do -- not the hardware + * convert, whose rounding mode a caller could have changed and which flushes subnormal halves. */ +R3D_HD float f16_to_f32(uint16_t h) { + const uint32_t s = (uint32_t)(h >> 15) << 31; + const uint32_t e = (uint32_t)(h >> 10) & 0x1fu; + uint32_t m = (uint32_t)h & 0x3ffu; + uint32_t u; + if (e == 0u) { + if (m == 0u) { + u = s; + } else { + int sh = 0; /* subnormal: renormalise into f32's range */ + while (!(m & 0x400u)) { m <<= 1; ++sh; } + m &= 0x3ffu; + u = s | ((uint32_t)(127 - 15 - sh + 1) << 23) | (m << 13); + } + } else if (e == 0x1fu) { + u = s | 0x7f800000u | (m << 13); + } else { + u = s | ((e - 15u + 127u) << 23) | (m << 13); + } + return float_of(u); +} + +R3D_HD uint16_t f32_to_f16(float f) { + const uint32_t u = bits_of(f); + const uint32_t s = (u >> 16) & 0x8000u; + const uint32_t a = u & 0x7fffffffu; + + if (a >= 0x7f800000u) /* inf or nan */ + return (uint16_t)(s | 0x7c00u | (a > 0x7f800000u ? ((a >> 13) & 0x3ffu) | 0x200u : 0u)); + if (a >= 0x47800000u) return (uint16_t)(s | 0x7c00u); /* overflow -> inf */ + if (a < 0x33000000u) return (uint16_t)s; /* underflow -> zero */ + + const int e = (int)(a >> 23) - 127; + uint32_t m = a & 0x7fffffu; + if (e < -14) { /* subnormal half */ + const int sh = -14 - e + 13; + m |= 0x800000u; + const uint32_t lo = m & ((1u << sh) - 1u); + uint32_t q = m >> sh; + const uint32_t half = 1u << (sh - 1); + if (lo > half || (lo == half && (q & 1u))) ++q; + return (uint16_t)(s | q); + } + uint32_t q = m >> 13; + const uint32_t lo = m & 0x1fffu; + uint32_t he = (uint32_t)(e + 15); + if (lo > 0x1000u || (lo == 0x1000u && (q & 1u))) ++q; + if (q == 0x400u) { q = 0; ++he; } /* rounding carried into the exp */ + if (he >= 0x1fu) return (uint16_t)(s | 0x7c00u); + return (uint16_t)(s | (he << 10) | q); +} + +/* Two f32 as one dword of two f16, `lo` in the low half. + * + * v_cvt_pkrtz_f16_f32 rounds toward zero, which is not RTNE, so this is only ever called with + * values f16 represents exactly: a bf16 widened (seven mantissa bits into ten) or an E4M3 code + * (three into three). For those the two spellings give the same bits and the instruction is free. */ +R3D_HD uint32_t f16x2_pack(float lo, float hi) { +#if defined(__HIP_DEVICE_COMPILE__) + /* The builtin answers as a pair of __fp16; the bits are the dword the dot2 reads. */ + return __builtin_bit_cast(uint32_t, __builtin_amdgcn_cvt_pkrtz(lo, hi)); +#else + return (uint32_t)f32_to_f16(lo) | ((uint32_t)f32_to_f16(hi) << 16); +#endif +} + +/* A dword of two bf16 as a dword of two f16. + * + * Exact over f16's normal range, and that is what makes the dot2 path sound: a bf16 has seven + * mantissa bits and an f16 ten, so within [2^-14, 65504] a widening costs no rounding and a dot + * product over widened bf16 accumulates the sums libref forms over its bf16 operands. + * + * Outside it the widening is not exact, and the two edges behave differently. Above 65504 a + * magnitude becomes an infinity (the packing instruction saturates, which is the kinder of the two + * answers). Below 2^-14 the operand is an f16 subnormal, whose grid is a power of two coarser than + * bf16's at the same magnitude, so a widening truncates toward zero -- and below 2^-24 it flushes. + * The truncation is what the packing instruction does, `v_cvt_pkrtz_f16_f32` rounding toward zero. + * + * The low edge costs a served model nothing: an activation below 2^-14 times a weight of a + * hundredth is 1e-18, against an accumulator of order one, so it is not a term the sum can see; + * and a scale-reduced operand is scaled back up before it is used, which is why the quantised rows + * put the scale on the block, not the element. What would be visible is a weight stream whose + * magnitudes live below 2^-14, and no checkpoint's do. The rows whose band can reach 65504 say so + * in their `shape` text. */ +R3D_HD uint32_t bf16x2_to_f16x2(uint32_t w) { + return f16x2_pack(bf16w_lo(w), bf16w_hi(w)); +} + +/* ================================================================== fp8 e4m3 ("e4m3fn") + * + * 1-4-3, bias 7, no infinity, S1111111 the only NaN, 448 the largest finite. The KV-cache and + * block-scaled weight format, so the attention oracle and every fp8 row depend on its rounding. + * + * RDNA3 has no instruction for it: v_cvt_pk_fp8_f32 and v_cvt_pk_f32_fp8 need the fp8 feature, + * which RDNA3 does not have. The builtins are *declared* for gfx11 -- so `__has_builtin` is true + * here, which is the trap a `__has_builtin` guard falls into, and libr4d's guards are exactly that + * -- and rejected at instruction selection. Both directions are bit maths, about eleven VALU an + * encode and six a decode. */ +R3D_HD float e4m3_to_f32(uint8_t b) { + const uint32_t s = (uint32_t)(b >> 7) << 31; + const uint32_t e = (uint32_t)(b >> 3) & 0xfu; + uint32_t m = (uint32_t)b & 0x7u; + uint32_t u; + if (e == 0u) { + if (m == 0u) { + u = s; + } else { + int sh = 0; /* subnormal: 2^-9 * m/8 */ + while (!(m & 0x8u)) { m <<= 1; ++sh; } + m &= 0x7u; + u = s | ((uint32_t)(127 - 6 - sh) << 23) | (m << 20); + } + } else if (e == 0xfu && m == 0x7u) { + u = s | 0x7fc00000u; /* the single NaN encoding */ + } else { + u = s | ((e - 7u + 127u) << 23) | (m << 20); + } + return float_of(u); +} + +/* Saturates at 448 rather than overflowing: a NaN from one large activation spreads through the + * whole row, and every fp8 cast in this project clamps for that reason. The clamp is inside the + * codec here because there is no instruction to clamp in front of. */ +R3D_HD uint8_t f32_to_e4m3(float f) { + const uint32_t u = bits_of(f); + const uint8_t s = (uint8_t)((u >> 24) & 0x80u); + const uint32_t a = u & 0x7fffffffu; + if (a > 0x7f800000u) return (uint8_t)(s | 0x7fu); /* nan */ + if (a >= 0x43e00000u) return (uint8_t)(s | 0x7eu); /* >= 448: the largest finite */ + const int e = (int)(a >> 23) - 127; + uint32_t m = a & 0x7fffffu; + /* The smallest subnormal is 2^-9, so everything below half of it (exponent -11 and below) + * rounds to zero. Exponent -10 is [2^-10, 2^-9): its tie point 2^-10 rounds to the even zero + * and the rest up to 2^-9, which the subnormal branch does with a 24-bit shift. */ + if (e < -10) return s; + if (e < -6) { /* subnormal fp8 */ + const int sh = -6 - e + 20; + m |= 0x800000u; + const uint32_t lo = m & ((1u << sh) - 1u); + uint32_t q = m >> sh; + const uint32_t half = 1u << (sh - 1); + if (lo > half || (lo == half && (q & 1u))) ++q; + return (uint8_t)(s | q); + } + uint32_t q = m >> 20; + const uint32_t lo = m & 0xfffffu; + int ee = e + 7; + if (lo > 0x80000u || (lo == 0x80000u && (q & 1u))) ++q; + if (q == 0x8u) { q = 0; ++ee; } + if (ee > 15 || (ee == 15 && q >= 7u)) return (uint8_t)(s | 0x7eu); + return (uint8_t)(s | ((uint32_t)ee << 3) | q); +} + +/* Two codes in one dword, the low element in the low byte: the store a wave's lane does. */ +R3D_HD uint32_t e4m3x2_pack(float lo, float hi) { + return (uint32_t)f32_to_e4m3(lo) | ((uint32_t)f32_to_e4m3(hi) << 8); +} + +/* A dword of two E4M3 codes as a dword of two f16. + * + * Exact -- e4m3 has four exponent and three mantissa bits, f16 five and ten -- and this is the fp8 + * matrix path: a code becomes the f16 the checkpoint means, dot2 multiplies it, and the block + * scale is applied once per block. RDNA3 has no fp8 hardware, so the decode is VALU, and it is + * paid where the weight bytes are being read anyway. */ +R3D_HD uint32_t e4m3x2_to_f16x2(uint32_t w) { + return f16x2_pack(e4m3_to_f32((uint8_t)(w & 0xffu)), e4m3_to_f32((uint8_t)(w >> 8))); +} + +/* ================================================================== int8 + * + * The symmetric int8 twin: amax/127, RTNE, saturating. f16 holds every int8 exactly, so widening + * into a dot product is exact and the scale is the only float in the path. */ +R3D_HD int8_t f32_to_i8_rtne(float f) { + if (!(f == f)) return 0; + /* Round to nearest, ties to even, in integer arithmetic. A tie at the top of the range would + * round to a code that does not exist (+128), so the clamp is applied after the rounding, not + * as an early return: 127.5 goes to the even 128 and then clamps to 127, which is what + * rad_round_even_sat gives. */ + const float fl = __builtin_floorf(f); + const float frac = f - fl; + int32_t q = (int32_t)fl; + if (frac > 0.5f) ++q; + else if (frac == 0.5f && (q & 1)) ++q; + if (q > 127) q = 127; + if (q < -128) q = -128; + return (int8_t)q; +} + +R3D_HD uint32_t i8x2_pack(float lo, float hi) { + return (uint32_t)(uint8_t)f32_to_i8_rtne(lo) | ((uint32_t)(uint8_t)f32_to_i8_rtne(hi) << 8); +} + +R3D_HD uint32_t i8x2_to_f16x2(uint32_t w) { + return f16x2_pack((float)(int8_t)(uint8_t)(w & 0xffu), (float)(int8_t)(uint8_t)(w >> 8)); +} + +/* ================================================================== the dot product + * + * Two f16 products into an f32 accumulator, one instruction: v_dot2acc_f32_f16, which + * __builtin_amdgcn_fdot2 lowers to on every gfx11 target (checked by reading the emitted asm on + * gfx1100, gfx1102 and gfx1151). RDNA3 pairs it as v_dual_dot2acc_f32_f16 where the scheduler can, + * which is how libr3d's inner loops reach the matrix unit's absence without noticing. + * + * The selector is FALSE, always. RDNA3 has no bf16 dot2, and this compiler accepts the bf16 + * selector and emits the f16 instruction anyway: a bf16 pair passed with sel=true is read as two + * f16s and the products are nonsense, silently, on every gfx11 target. bf16 operands are widened + * with bf16x2_to_f16x2, which is exact. + * + * The two products go into `acc` in the order written, and a kernel that walks k ascending + * reproduces libref's summand-for-summand: the reference loop is `s += a[k]*b[k]` with + * -ffp-contract=off. The match is not bit-exact and cannot be: `v_dot2acc_f32_f16` folds the two + * products and the accumulator with guard bits and rounds once, where the reference rounds each + * product and each sum. The difference is under an f32 ulp a pair, a random walk of about + * sqrt(K/2) ulps over a K-long dot, which is a thousandth of the bf16 the store narrows to -- so it + * sits inside what `rad-kbench` measures, exactly as libr4d's WMMA accumulation does. What is + * required, and what every loop here keeps, is that the *order* of the summands be the reference's: + * k ascending, one accumulator per output element, no reassociation across lanes. + * + * The host path below is the same arithmetic with each product rounded first, which is what a test + * needs it to be. It is not the hardware's rounding. */ +R3D_HD float dot2_f16x2(uint32_t a, uint32_t b, float acc) { +#if defined(__HIP_DEVICE_COMPILE__) + typedef __fp16 v2h __attribute__((ext_vector_type(2))); + return __builtin_amdgcn_fdot2(__builtin_bit_cast(v2h, a), __builtin_bit_cast(v2h, b), acc, + false); +#else + const uint32_t alo = a & 0xffffu, ahi = a >> 16; + const uint32_t blo = b & 0xffffu, bhi = b >> 16; + return acc + f16_to_f32((uint16_t)alo) * f16_to_f32((uint16_t)blo) + + f16_to_f32((uint16_t)ahi) * f16_to_f32((uint16_t)bhi); +#endif +} + +/* Four f16 products into one accumulator: the step every libr3d matmul runs. The two dot2s are a + * dependency chain of two; a kernel keeps four of these chains in flight. */ +R3D_HD float dot4_f16x4(uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1, float acc) { + return dot2_f16x2(a1, b1, dot2_f16x2(a0, b0, acc)); +} + +#endif /* R3D_CODECS_H */ diff --git a/libr3d/r3d_common.h b/libr3d/r3d_common.h new file mode 100644 index 00000000..ce40c8e8 --- /dev/null +++ b/libr3d/r3d_common.h @@ -0,0 +1,256 @@ +/* r3d_common.h -- the RDNA3 seams a kernel needs: the wave's lane maths, the loads, the block + * reduce, the occupancy and LDS conventions. + * + * What RDNA3 gives, measured on the ROCm this tree builds against (AMD clang 24; `__has_builtin` + * off --offload-device-only, and llvm-mc -show-encoding per target). The codecs are in r3d_codecs.h; + * this header is what is left. + * + * v_dot2acc_f32_f16 yes, every gfx11 target, from __builtin_amdgcn_fdot2, and RDNA3 pairs + * it as v_dual_dot2acc_f32_f16 where the scheduler can. The matrix work. + * v_dot2 with bf16 no, and the builtin's bf16 selector is accepted and ignored -- the f16 + * instruction is emitted -- so bf16 is widened, never asserted. + * WMMA the mnemonic is unreachable -- every v_wmma_* is rejected by the + * assembler on gfx1100, gfx1102, gfx1151 and gfx1201 alike, and inline + * asm dies in amdgcn-link -- but the builtin is not: + * __builtin_amdgcn_wmma_f32_16x16x16_f16_w32 compiles for the three gfx11 + * targets and emits a real tile instruction. Measured here against dot2 at + * four occupancies, 1.99 against 1.97 TFLOP/s: RDNA3's AI accelerator is a + * 2x f16-rate feature and a paired dot2 is already at that rate, so the + * tile buys a fragment layout and a block-alignment requirement and no + * throughput. No fragment layouts here, so no repacked weights, so no + * layout hook: a dot2 GEMM reads a weight in the order it is stored. + * fp8 convert no (needs the fp8 feature); the builtins are declared and die at + * instruction selection, which is why the codecs are software. + * v_cvt_pkrtz_f16_f32 yes. Used only where it is exact. + * v_cvt_pk_bf16_f32 no on gfx1100/1102/1151 in this build, so bf16 packs are software. + * DPP16, v_permlanex16 yes, RDNA1 onward. The lane maths below is libr4d's, unchanged: the + * encodings are the same silicon, and they were verified on hardware. + * ballot_w32, readlane, + * readfirstlane, ds_bpermute, + * v_perm_b32, exp2f, rcpf, + * s_barrier, fence, + * sched_group_barrier yes. + * transposed loads no: neither global_load_tr_b128 (RDNA4) nor ds_read_b64_tr_b16 (dropped + * by RDNA4, kept here as a fact about gfx11 -- this ROCm's assembler + * rejects it too). A transpose is done in registers. + * + * Wave32 is gfx11's default and every kernel here is written for it; the guard below fires if a + * build asks for wave64, because that computes garbage rather than running slower. + * + * The register file is the one number that is NOT the same as RDNA4's: a gfx11 SIMD has 1024 VGPRs + * for a wave32, allocated in groups of 8, against gfx1201's 1536. R3D_WAVES is stated per kernel, + * and a kernel's budget is computed against 1024. + */ +#ifndef R3D_COMMON_H +#define R3D_COMMON_H + +#include "r3d_codecs.h" + +#include +#include + +#if defined(__HIP_DEVICE_COMPILE__) && defined(__AMDGCN_WAVEFRONT_SIZE) +#if __AMDGCN_WAVEFRONT_SIZE != 32 +#error "libr3d kernels are written for wave32, gfx11's default; a wave64 build computes garbage" +#endif +#endif + +enum : int { kWave = 32 }; + +/* A 16-byte staging register as a native vector. HIP's uint4 is a class template wrapping a union, + * and an array of them carried across a loop is kept in scratch by LLVM 22 and 24; an + * ext_vector_type array is promoted to registers. Loaded and stored whole only. */ +typedef unsigned int r3d_u32x4 __attribute__((ext_vector_type(4))); +typedef unsigned int r3d_u32x2 __attribute__((ext_vector_type(2))); + +/* ================================================================== the occupancy a kernel is + * built for + * + * Fixes the waves per SIMD the compiler schedules for. Left unstated, the scheduler picks the + * target itself and the choice moves between compiler releases. gfx11's budget is 1024 VGPRs a + * SIMD at wave32, in granules of 8: a kernel asking for 5 waves has 204 registers to spend. */ +#define R3D_WAVES(n) __attribute__((amdgpu_waves_per_eu((n), (n)))) + +/* ================================================================== exp2 + * + * The hardware transcendental. libr4d's rule applies: exp2f, powf and sincosf are the accurate + * forms, not the __ approximations -- rope positions reach 262144, past __sincosf's argument + * reduction, and libref uses libm. exp2f itself is the one place the hardware op is exactly what + * the reference computes, because both sides round the same result once. */ +__device__ __forceinline__ float ex2(float x) { + return __builtin_amdgcn_exp2f(x); +} + +__device__ __forceinline__ float rcp(float x) { return __builtin_amdgcn_rcpf(x); } + +/* ================================================================== one element, one register + * + * A 16-bit element of global memory, zero-extended into a whole register (global_load_u16). Read as + * `uint16_t` it lands in a register half (global_load_d16_b16) whose other half the waitcnt pass + * then waits for; through a generic pointer it is also a flat load. The pointer must address global + * memory, which every caller's operand is. + * + * libr4d notes that LLVM 24 gives gfx12 real 16-bit registers and the packability that follows; + * gfx11 does not have them, so keeping bf16 in whole registers from load to store is the plain + * reading as well as the portable one. */ +typedef const uint16_t __attribute__((address_space(1))) *r3d_gu16; +__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r3d_gu16)p; } +__device__ __forceinline__ uint32_t ldg_u32(const uint32_t* p) { return *(const __attribute__((address_space(1))) uint32_t*)p; } +__device__ __forceinline__ float ldg_f32(const float* p) { + return *(const __attribute__((address_space(1))) float*)p; +} + +/* ================================================================== lane maths + * + * A wave is 32 lanes, two rows of sixteen. Reductions are XOR butterflies, in the order a + * __shfl_xor loop runs in, so the result is bit-identical to that loop -- which is what libref + * sums, since the reference sums a row in ascending index order and a wave of lanes maps to + * consecutive elements. + * + * `__shfl_xor` lowers to ds_bpermute_b32 plus s_wait_dscnt, an LDS round trip that dominates a + * dependency chain. DPP16's ROW_XMASK (control 0x160 | N) makes the partner read a modifier on the + * consuming VALU op, and N = 16 crosses the two rows of a wave32 with v_permlanex16, still one VALU + * op. Row and bank masks are all-ones because every lane participates; bound_ctrl is moot because + * every lane has a partner. These are libr4d's encodings, verified on hardware. */ +template +__device__ __forceinline__ uint32_t r3d_xor_lane_u32(uint32_t v) { + static_assert(N >= 1 && N <= 16 && (N & (N - 1)) == 0, "a lane xor within the wave"); + if constexpr (N < 16) + return (uint32_t)__builtin_amdgcn_update_dpp(0, (int)v, 0x160 | N, 0xf, 0xf, true); + else + return (uint32_t)__builtin_amdgcn_permlanex16((int)v, (int)v, 0x76543210u, 0xFEDCBA98u, + false, false); +} + +template +__device__ __forceinline__ float r3d_xor_lane(float v) { + return __uint_as_float(r3d_xor_lane_u32(__float_as_uint(v))); +} + +/* A 64-bit value's partner: the halves exchanged separately, as a 64-bit shuffle does. */ +template +__device__ __forceinline__ unsigned long long r3d_xor_lane_u64(unsigned long long v) { + const uint32_t lo = r3d_xor_lane_u32((uint32_t)v); + const uint32_t hi = r3d_xor_lane_u32((uint32_t)(v >> 32)); + return ((unsigned long long)hi << 32) | lo; +} + +/* v_permlanex16 swaps only with identity selectors (each 4-bit field names the source lane in the + * other half; sel0 covers lanes 0-7, sel1 lanes 8-15); zero selectors silently broadcast lane 0. */ +__device__ __forceinline__ float swap16(float x) { return r3d_xor_lane<16>(x); } + +/* v + the partner's v, the partner read by DPP so the add carries it. */ +template +__device__ __forceinline__ float r3d_dpp_xor_add(float v) { + return v + __uint_as_float(__builtin_amdgcn_update_dpp(0, __float_as_uint(v), CTRL, 0xF, 0xF, + true)); +} + +__device__ __forceinline__ float wave_sum(float v) { + v += swap16(v); /* xor 16 -- crosses the two rows of sixteen */ + v = r3d_dpp_xor_add<0x168>(v); /* xor 8 -- row_xmask from here down */ + v = r3d_dpp_xor_add<0x164>(v); /* xor 4 */ + v = r3d_dpp_xor_add<0x162>(v); /* xor 2 */ + v = r3d_dpp_xor_add<0x161>(v); /* xor 1 */ + return v; +} + +__device__ __forceinline__ float wave_max(float v) { + v = fmaxf(v, r3d_xor_lane<16>(v)); + v = fmaxf(v, r3d_xor_lane<8>(v)); + v = fmaxf(v, r3d_xor_lane<4>(v)); + v = fmaxf(v, r3d_xor_lane<2>(v)); + v = fmaxf(v, r3d_xor_lane<1>(v)); + return v; +} + +/* The same butterflies over a group of W lanes (a power of two up to the wave), in the order + * `for (o = W/2; o; o >>= 1) v = op(v, __shfl_xor(v, o))` runs them, so bit-identical to it. A row + * of sixteen lanes -- the sixteen columns a lane owns in a bf16 pair layout -- uses W = 16. */ +template +__device__ __forceinline__ float r3d_xor_sum(float v) { + static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave"); + if constexpr (W >= 32) v += r3d_xor_lane<16>(v); + if constexpr (W >= 16) v += r3d_xor_lane<8>(v); + if constexpr (W >= 8) v += r3d_xor_lane<4>(v); + if constexpr (W >= 4) v += r3d_xor_lane<2>(v); + if constexpr (W >= 2) v += r3d_xor_lane<1>(v); + return v; +} + +template +__device__ __forceinline__ float r3d_xor_max(float v) { + static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave"); + if constexpr (W >= 32) v = fmaxf(v, r3d_xor_lane<16>(v)); + if constexpr (W >= 16) v = fmaxf(v, r3d_xor_lane<8>(v)); + if constexpr (W >= 8) v = fmaxf(v, r3d_xor_lane<4>(v)); + if constexpr (W >= 4) v = fmaxf(v, r3d_xor_lane<2>(v)); + if constexpr (W >= 2) v = fmaxf(v, r3d_xor_lane<1>(v)); + return v; +} + +/* A wave's inclusive prefix sum in registers: row_shr 1, 2, 4 and 8 within each row of sixteen, + * then the other row's total from one readlane. Lane L ends with the sum over lanes 0..L. Replaces + * an LDS step-doubling scan, which costs two barriers a round. Integer, so combine order is free. + * Every lane must be active. */ +__device__ __forceinline__ uint32_t wave_prefix_u32(uint32_t x, int lane) { + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x111, 0xF, 0xF, true); /* row_shr:1 */ + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x112, 0xF, 0xF, true); /* row_shr:2 */ + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x114, 0xF, 0xF, true); /* row_shr:4 */ + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x118, 0xF, 0xF, true); /* row_shr:8 */ + const uint32_t lo = (uint32_t)__builtin_amdgcn_readlane((int)x, 15); + return lane >= 16 ? x + lo : x; +} + +/* ================================================================== a block's sum + * + * Wave sum, one LDS round trip, then every thread adds the wave partials in wave order. The order + * is the contract: libref sums a row in ascending index order, the waves cover consecutive + * elements, and adding the partials in wave order is the same bracketing at any thread count. + * `lds` holds NWAVES floats. */ +template +__device__ __forceinline__ float block_sum(float v, float* lds) { + constexpr int NWAVES = NTHREADS / kWave; + const uint32_t lane = threadIdx.x & (kWave - 1); + const uint32_t w = threadIdx.x / kWave; + v = wave_sum(v); + if (lane == 0) lds[w] = v; + __syncthreads(); + if constexpr (NWAVES == 1) return lds[0]; + float t = lds[0]; +#pragma unroll + for (int i = 1; i < NWAVES; ++i) t += lds[i]; + return t; +} + +/* ================================================================== scheduling + * + * LLVM single-buffers LDS and drains before every dependent read unless told otherwise; on gfx11 + * the matrix unit is absent so there is nothing to overlap a load with, and the barrier the + * kernels need is the plain one. */ +__device__ __forceinline__ void sched_barrier() { __builtin_amdgcn_sched_barrier(0); } +__device__ __forceinline__ void group_barrier() { __syncthreads(); } + +/* ================================================================== the geometry constants + * + * A gfx11 GPU's wave slots: a CU has 4 SIMDs, a SIMD holds 16 wave32s, so 64 slots a CU. HIP's + * multiProcessorCount reports CUs on gfx11 (it reports WGPs on gfx12, which is where libr4d's 2048 + * comes from), and a launch whose grid passes 64 * multiProcessorCount waves has more work than + * slots: the tail waves start after another wave retires. A row-per-block kernel with one wave a + * block is exactly that cliff, and its row count is where the cliff is. + * + * A launcher's question, so a host function: this HIP declares no device-side hipGetDevice or + * hipDeviceGetAttribute, and a __device__ body does not compile at all. */ +static inline int wave_slot_count() { + int dev = 0, cu = 0; + (void)hipGetDevice(&dev); + (void)hipDeviceGetAttribute(&cu, hipDeviceAttributeMultiprocessorCount, dev); + return 64 * cu; +} + +/* The LDS a workgroup gets is 64 KiB, the same figure RDNA4 gives, and no kernel in libr3d needs + * more. There is no hipFuncSetAttribute opt-in: 64 KiB of dynamic shared memory is available as + * soon as it is asked for. */ +enum : int { kLdsCap = 64 * 1024 }; + +#endif /* R3D_COMMON_H */ diff --git a/libr3d/r3d_dflash_f32.hip b/libr3d/r3d_dflash_f32.hip new file mode 100644 index 00000000..39904757 --- /dev/null +++ b/libr3d/r3d_dflash_f32.hip @@ -0,0 +1,309 @@ +/* r3d_dflash_f32.hip -- DFlash2's candidate walk, `dflash_select`, on the card. + * + * A block-diffusion drafter proposes every position of a block in one backbone pass, so position + * l+1 is not conditioned on what the drafter chose at l. This op restores that dependence: it walks + * the `steps` positions in order and, at each, picks the candidate that maximises + * + * score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * hp[l][r] * succ[cand[l, c]][r] + * + * where pid(0) is the anchor -- the token the target just committed, read at + * `anchor[m * anchor_stride]` -- and pid(l) is the walk's own previous pick, `cand[l-1, chosen]`. + * `hp` absent is a plane of ones, which drops the trilinear form to a low-rank bigram (DSpark's + * Markov head). libref's `ref_dflash_select` is the law, and this file transcribes its arithmetic + * and its order. + * + * ============================== why it is a kernel and not a GEMM ============================== + * + * The walk is serial in l: the predecessor of step l is not known until step l-1 has been decided, + * so the [steps, K, K] edge tensor cannot be scored in advance -- scoring it computes K times the + * edges that are ever read. What is parallel is the sequences (M of them) and, inside a step, the K + * candidates. So a block takes `256 / top_k` sequences and gives each lane one (sequence, + * candidate) pair: the lane runs the rank sum for its own edge, in the reference's order, and one + * lane per sequence scans the K scores and takes the pick. The loop over `steps` stays serial, with + * the two LDS round trips per step (the scores out, the pick back) that the dependence requires. + * + * The rank sum is the whole cost: at the band (steps=7, top_k=16, rank=256, M=256) a walk is + * 7 * 16 * 256 = 28672 fused terms, and the bytes it touches are the K successor rows a step reads, + * 16 * 512 B of bf16, so the op is a gather over `succ` [n_vocab, rank] -- 66.8 MiB of codebook at + * the band, of which the walk reads M * steps * K = 28672 rows, about 14.7 MiB, plus one + * predecessor row a step. There is no arithmetic to hide that behind, which is why the sum is a + * plain ascending chain and not a tree: a tree buys nothing here and costs the agreement. + * + * ============================== agreement, and where this file declines ============================== + * + * Bit-exact by construction, not by tolerance: + * + * - the rank sum is `sc = unary; for (i = 0; i < rank; ++i) sc += ax[i] * succ[i];` -- ascending + * in r, one accumulator, no reduction, no tree, with `-ffp-contract=off` so no FMA fusion + * changes the rounding of a term; + * - `ax[i] = pred[pid][i] * hp[l][i]` is rounded to f32 before it meets `succ`, because the + * reference writes it into a float array first (and with `hp` absent it is `pred * 1.0f`, which + * is the same value); + * - the argmax is a strict `>` over c ascending, so the earliest candidate wins a tie and a NaN + * never displaces the incumbent -- the reference's loop, statement for statement; + * - a predecessor outside the vocabulary contributes zero, and a candidate outside it is scored + * by `unary` alone: both are the reference's tests (`pid >= 0 && pid < nv`, `tok >= 0 && + * tok < nv`), and both are why padding rows -- a shard's unused rows, a block shorter than + * `steps` -- are legal inputs; + * - the pick of step l is written to `tokens[m, l]` and becomes pid(l+1) unchanged, including + * when it is out of range for the codebooks. + * + * Declines, all of them the shim's, none reachable from a row that carries the constraints its row + * states: a codebook (`pred`, `succ`, `hp`) that is not bf16, because this is the bf16 + * instantiation -- the band's `dtype` is the codebooks' width and a row asks for bf16 (RAD_E_DTYPE); + * `unary` that is not f32, `cand`/`anchor`/`tokens` that are not i32, exactly as the schema's + * operand list types them (RAD_E_DTYPE); a codebook whose rows are not contiguous -- the gather is + * `token * rank + r` and a row stride inside the row is not that (RAD_E_STRIDE); `top_k` above 256, + * which is one lane a candidate and no more candidates than lanes (RAD_E_UNSUPPORTED); and a `cand` + * plane that describes more sequences than the band's `M`, which is `band_rows` refusing and is + * RAD_E_SHAPE, not a truncation. + */ + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_codecs.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr uint32_t kThr = 256; /* 8 waves: the block's (sequence, candidate) lanes */ +constexpr uint32_t kKMax = kThr; /* one lane a candidate, so top_k <= 256 */ + +/* Whole-register loads of the planes the walk gathers through. bf16 is a 16-bit load and the + * library's codec, which is the same decode libref's `ldt` performs. */ +__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) { + return (int32_t)ldg_u32((const uint32_t*)p); +} +__device__ __forceinline__ float ldg_f32(const float* p) { return *(const float*)p; } +__device__ __forceinline__ uint16_t ldg_u16(const uint16_t* p) { return *(const uint16_t*)p; } + +/* ------------------------------------------------------------------ the walk + + * `per` sequences per block, `K` candidates per sequence, so lane (s, c) owns the edge + * (sequence s, candidate c) of the step in hand. `hp` may be null: then the `hp` factor is 1.0f, + * exactly as the reference's `(hp ? ldt(hp, ...) : 1.0f)` writes it. */ +__global__ __launch_bounds__(kThr) void dflash_select_kernel( + const int32_t* __restrict__ cand, const float* __restrict__ un, + const uint16_t* __restrict__ hp, const int32_t* __restrict__ anc, + const uint16_t* __restrict__ pred, const uint16_t* __restrict__ succ, + int32_t* __restrict__ out, uint32_t M, uint32_t steps, uint32_t K, uint32_t R, uint32_t nv, + uint32_t astr, long long cand_ld, long long un_ld, long long hp_ld, long long pred_ld, + long long succ_ld, long long tok_ld, uint32_t per) { + + __shared__ int32_t s_pid[kThr]; /* the walk's predecessor, one per sequence */ + __shared__ float s_sc[kThr]; /* this step's K scores, one per lane */ + + const uint32_t s = threadIdx.x / K; /* the sequence this lane walks for */ + const uint32_t c = threadIdx.x - s * K; /* the candidate this lane scores */ + const uint32_t seq0 = blockIdx.x * per + s; + /* A block of 256 lanes holds ceil(256 / K) sequences and the last group can be partial. A lane + * with no sequence replays the last real one: it reaches every __syncthreads() and its stores + * are suppressed, and the loads it performs are in range because the sequence it replays is. */ + const uint32_t seq = seq0 < M ? seq0 : M - 1; + const bool mine = seq0 < M; + + /* pid(0): the anchor, at `m * anchor_stride` in a flat plane. The reference reads it through + * `ld_int`, so a negative id is a legal "no predecessor" and not an error. */ + int32_t pid = ldg_i32(anc + (size_t)seq * (size_t)astr); + const bool has_hp = (hp != nullptr); + + for (uint32_t l = 0; l < steps; ++l) { + const uint32_t r = seq * steps + l; /* cand/unary/hp are one row per (m, l) */ + const size_t cb = (size_t)r * (size_t)cand_ld; + const int32_t tok = ldg_i32(cand + cb + c); + float sc = ldg_f32(un + (size_t)r * (size_t)un_ld + c); + + /* A predecessor outside the vocabulary contributes nothing; a candidate outside it is + * scored by `unary` alone. Both tests are the reference's, and both are why a shard's + * padding rows and a block shorter than `steps` are legal inputs. */ + const bool have_p = pid >= 0 && (uint32_t)pid < nv; + const bool have_s = tok >= 0 && (uint32_t)tok < nv; + if (have_s) { + const uint16_t* pp = pred + (size_t)(have_p ? pid : 0) * (size_t)pred_ld; + const uint16_t* sp = succ + (size_t)tok * (size_t)succ_ld; + const uint16_t* hpb = hp + (size_t)r * (size_t)hp_ld; + for (uint32_t i = 0; i < R; ++i) { + /* ax[i], rounded to f32 where the reference writes it into its float array, and + * then the ascending chain. 1.0f for a missing hp is the reference's own factor. */ + const float ax = have_p + ? bf16_to_f32(ldg_u16(pp + i)) * (has_hp ? bf16_to_f32(ldg_u16(hpb + i)) : 1.0f) + : 0.0f; + sc += ax * bf16_to_f32(ldg_u16(sp + i)); + } + } + s_sc[threadIdx.x] = sc; /* == s_sc[s * K + c] */ + __syncthreads(); + + if (c == 0) { + /* The reference's argmax: strict `>`, c ascending, so the earliest candidate wins a + * tie and a NaN never takes the lead from a number. */ + uint32_t best_c = 0; + float best_s = -INFINITY; + for (uint32_t j = 0; j < K; ++j) { + const float v = s_sc[s * K + j]; + if (v > best_s) { best_s = v; best_c = j; } + } + const int32_t pick = ldg_i32(cand + cb + best_c); + if (mine) out[(size_t)seq * (size_t)tok_ld + l] = pick; + s_pid[s] = pick; /* pid(l+1), out-of-range included */ + } + __syncthreads(); + pid = s_pid[s]; + } +} + +/* ------------------------------------------------------------------ shim helpers */ + +/* The plane's row pitch, from the plane: `rows` is its row count and `ld` the pitch a row's + * elements start at, K apart. A rank-1 plane is a run of rows K apart, which is what the + * reference's rowoff does for one. */ +static inline int rows_pitch(const RadTensor* t, long long K, long long* rows, long long* ld) { + const long long p = r3d_rows_pitch(t, K, rows); + if (p < 0) return RAD_E_STRIDE; + if (K <= 0 || *rows <= 0 || *rows > 0x7fffffffLL) return RAD_E_SHAPE; + if (p < K) return RAD_E_SHAPE; + *ld = p; + return RAD_OK; +} + +/* A codebook: [n, rank] bf16 with contiguous rows, because the gather is `token * rank + r`. */ +static inline int codebook_ok(const RadTensor* t, long long rank) { + if (!t || !t->data) return RAD_E_INVAL; + if (!r3d_is_bf16(t)) return RAD_E_DTYPE; + if (!r3d_aligned(r3d_p(t), 2)) return RAD_E_ALIGN; + if (rank > 0 && t->rank >= 1 && r3d_stride(t, (int)t->rank - 1) != 1) return RAD_E_STRIDE; + return RAD_OK; +} + +static inline int r3d_launch_status(int rc) { + if (rc == 0) return RAD_OK; + switch (rc) { + case -1: return RAD_E_INVAL; + case -2: return RAD_E_SHAPE; + case -3: return RAD_E_STRIDE; + default: return RAD_E_DEVICE; + } +} + +} /* namespace */ + +#define R3D_NEED(x) \ + do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0) + +/* ================================================================== launcher + * + * cand [M*steps][top_k] i32, candidate token ids, -1 for padding + * unary [M*steps][top_k] f32, the candidate-independent half of the score + * hp [M*steps][rank] bf16, the step's factor; 0 (absent) is a plane of ones + * anchor [M*anchor_stride] i32, the token each walk starts from, at m*anchor_stride + * pred [n_vocab][rank] bf16, the predecessor codebook + * succ [n_vocab][rank] bf16, the successor codebook the walk gathers with its picks + * tokens [M][steps] i32, out: the accepted prefix, one pick a step + * + * 0, -1 null, -2 bad extent, -3 pitch, -4 the HIP launch failed. No allocation, no synchronisation. + */ +extern "C" int r3d_dflash_select(long cand, long unary, long hp, long anchor, long pred, long succ, + long tokens, int M, int steps, int top_k, int rank, int n_vocab, + int anchor_stride, long long cand_ld, long long un_ld, + long long hp_ld, long long pred_ld, long long succ_ld, + long long tok_ld, long stream) { + if (!cand || !unary || !anchor || !pred || !succ || !tokens) return -1; + if (M <= 0 || steps <= 0 || top_k <= 0 || rank <= 0 || n_vocab <= 0 || anchor_stride <= 0) + return -2; + if ((unsigned)top_k > kKMax) return -2; /* one lane a candidate */ + if (!cand_ld) cand_ld = top_k; + if (!un_ld) un_ld = top_k; + if (!hp_ld) hp_ld = rank; + if (!pred_ld) pred_ld = rank; + if (!succ_ld) succ_ld = rank; + if (!tok_ld) tok_ld = steps; + if (cand_ld < top_k || un_ld < top_k) return -3; + if (hp_ld < rank || pred_ld < rank || succ_ld < rank) return -3; + if (tok_ld < steps) return -3; + const uint32_t per = (kThr + (uint32_t)top_k - 1) / (uint32_t)top_k; + R3D_KLAUNCH(R3D_KNAME(dflash_select_kernel), dim3((M + per - 1) / per), dim3(kThr), + (hipStream_t)(uintptr_t)stream, (const int32_t*)(uintptr_t)cand, + (const float*)(uintptr_t)unary, (const uint16_t*)(uintptr_t)hp, + (const int32_t*)(uintptr_t)anchor, (const uint16_t*)(uintptr_t)pred, + (const uint16_t*)(uintptr_t)succ, (int32_t*)(uintptr_t)tokens, (uint32_t)M, + (uint32_t)steps, (uint32_t)top_k, (uint32_t)rank, (uint32_t)n_vocab, + (uint32_t)anchor_stride, cand_ld, un_ld, hp_ld, pred_ld, succ_ld, tok_ld, per); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== shim + * + * libref's operand list is {cand, unary, hp?, anchor, pred, succ, tokens} and its parameter list is + * {M, steps, top_k, rank, n_vocab, anchor_stride?, dtype}. Sequences come from `cand` -- the plane + * holds M * steps * top_k ids -- through `band_rows`, so a plane describing more sequences than the + * band's M is refused, not truncated. `rank` and `n_vocab` fall back to the predecessor codebook's + * own shape, as the reference's do, and `anchor_stride` defaults to 1. + */ +extern "C" int r3d_rad_dflash_select(const RadArgs* a, RadStream stream) { + const RadTensor* cand = r3d_opt(a, 0); + const RadTensor* un = r3d_opt(a, 1); + const RadTensor* hp = r3d_opt(a, 2); /* OPD_O: absent is a plane of ones */ + const RadTensor* anc = r3d_opt(a, 3); + const RadTensor* pred = r3d_opt(a, 4); + const RadTensor* succ = r3d_opt(a, 5); + const RadTensor* tok = r3d_opt(a, 6); + if (!cand || !cand->data || !un || !un->data || !anc || !anc->data || !pred || !pred->data || + !succ || !succ->data || !tok || !tok->data) + return R3D_NO(RAD_E_INVAL); + + /* The band names the codebooks' width; this is the bf16 instantiation. */ + const char* dt = r3d_gets(a, "dtype"); + if (dt && !r3d_dt_named(RAD_BF16, dt)) return R3D_NO(RAD_E_DTYPE); + + const long long steps = r3d_geti_or(a, "steps", 0); + const long long K = r3d_geti_or(a, "top_k", 0); + const long long astr = r3d_geti_or(a, "anchor_stride", 1); + long long R = r3d_geti_or(a, "rank", pred->rank >= 2 ? r3d_dim(pred, (int)pred->rank - 1) : 0); + long long nv = r3d_geti_or(a, "n_vocab", + pred->rank >= 2 ? r3d_dim(pred, (int)pred->rank - 2) : 0); + const long long band_M = r3d_geti_or(a, "M", 0); + if (steps <= 0 || K <= 0 || astr <= 0 || R <= 0 || nv <= 0) return R3D_NO(RAD_E_SHAPE); + if (K > (long long)kKMax) return R3D_NO(RAD_E_UNSUPPORTED); + if (steps > 0x7fffffffLL / (K * 256) ) return R3D_NO(RAD_E_SHAPE); + + /* Sequences from the plane, the band as a ceiling -- band_rows refuses, it does not truncate. */ + const long long all = steps * K; + if (all <= 0 || r3d_numel(cand) % all) return R3D_NO(RAD_E_SHAPE); + const long long M = r3d_numel(cand) / all; + if (M <= 0 || (band_M > 0 && M > band_M)) return R3D_NO(RAD_E_SHAPE); + + /* The reference's extent tests, in its order. */ + if (r3d_numel(un) < M * steps * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(anc) < (M - 1) * astr + 1) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(tok) < M * steps) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(pred) < nv * R || r3d_numel(succ) < nv * R) return R3D_NO(RAD_E_SHAPE); + if (hp && hp->data && r3d_numel(hp) < M * steps * R) return R3D_NO(RAD_E_SHAPE); + + if (!r3d_is_i32(cand)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(un)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_i32(anc)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_i32(tok)) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(codebook_ok(pred, R)); + R3D_NEED(codebook_ok(succ, R)); + if (hp && hp->data) R3D_NEED(codebook_ok(hp, R)); + if (!r3d_aligned(r3d_p(cand), 4) || !r3d_aligned(r3d_p(un), 4) || !r3d_aligned(r3d_p(anc), 4) || + !r3d_aligned(r3d_p(tok), 4)) + return R3D_NO(RAD_E_ALIGN); + + long long cand_ld = 0, un_ld = 0, tok_ld = 0, rows = 0; + R3D_NEED(rows_pitch(cand, K, &rows, &cand_ld)); + R3D_NEED(rows_pitch(un, K, &rows, &un_ld)); + R3D_NEED(rows_pitch(tok, steps, &rows, &tok_ld)); + long long hp_ld = R, pred_ld = R, succ_ld = R; + if (hp && hp->data) R3D_NEED(rows_pitch(hp, R, &rows, &hp_ld)); + R3D_NEED(rows_pitch(pred, R, &rows, &pred_ld)); + R3D_NEED(rows_pitch(succ, R, &rows, &succ_ld)); + + return r3d_launch_status(r3d_dflash_select( + r3d_addr(cand), r3d_addr(un), (hp && hp->data) ? r3d_addr(hp) : 0L, r3d_addr(anc), + r3d_addr(pred), r3d_addr(succ), r3d_addr(tok), (int)M, (int)steps, (int)K, (int)R, (int)nv, + (int)astr, cand_ld, un_ld, hp_ld, pred_ld, succ_ld, tok_ld, (long)(uintptr_t)stream)); +} diff --git a/libr3d/r3d_fp8_dequant.h b/libr3d/r3d_fp8_dequant.h new file mode 100644 index 00000000..4ee6dbd7 --- /dev/null +++ b/libr3d/r3d_fp8_dequant.h @@ -0,0 +1,79 @@ +/* r3d_fp8_dequant.h -- the E4M3 -> f16 decoder as a table, for the rows that read fp8 codes. + * + * WHY THIS EXISTS, WITH THE MEASUREMENT THAT ASKED FOR IT + * + * gfx11 has no instruction that converts E4M3 to f16. clang lists `__builtin_amdgcn_cvt_pk_f16_fp8` + * for the target, and a build that calls it on gfx1102 contains ZERO `v_cvt_pk_f16_fp8` in its ISA: + * the builtin is software here, lowered to the same exponent work `e4m3_to_f32` does. r3d_codecs.h's + * codec is two `e4m3_to_f32` (a dozen instructions of shifts, exponent bias and subnormal handling + * each) plus a pack, about 25 instructions a pair, 100 an eight-code group. Measured on the + * vocabulary head at M=1 (r3d_vocab_bf16.hip, RX 7600 / gfx1102 / 32 CU): 13.603 ms a token at + * 19.6 GB/s of codes, 8x above the 1.64 ms the codes' 255 MiB floor at this row's own 163 GB/s, and + * the ALU was the binding resource, not DRAM. + * + * E4M3 has 256 bit patterns and every one of them has an f16 value (f16's exponent range covers + * E4M3's, its subnormals included, and E4M3's NaN maps to an f16 NaN). So the decoder is a + * 256-entry table of 512 bytes, and eight LDS reads replace the hundred ALU instructions. That is + * the whole idea, and the table goes in LDS -- not __constant__, whose broadcast is a liability here + * because every lane decodes a DIFFERENT code, and divergent constant indexes serialise. + * + * Cost: 512 bytes of LDS a block, one fill of 256 stores at block start plus a barrier. Conflict + * behaviour on the reads: 16-bit loads at data-dependent addresses, so a wavefront's 32 lanes land + * on 16 bank words; random codes give roughly two lanes per word, and measured cost is about two + * cycles a read -- eight reads an eight-code group against the codec's hundred instructions. + * + * The table is EXACT: it is built by calling the codec once per entry, so it is the codec, moved + * from the loop to the block's start. Nothing about the arithmetic changes, and a row's rel_l2 + * against its reference is unchanged by this header. The one thing to keep: the table must be filled + * before any lane reads it, so every use is `..._init` then the barrier it contains, then reads. + * + * int8 codes do NOT want a table: `v_cvt_f32_i8` is a hardware instruction, so + * r3d_codecs.h's i8x2_to_f16x2 is two converts and a pack. This header serves the fp8 codes. + * + * Header-only, like the rest of libr3d. Include it in a .hip after r3d_codecs.h. + */ +#ifndef R3D_FP8_DEQUANT_H +#define R3D_FP8_DEQUANT_H + +#include "r3d_codecs.h" + +#define R3D_E4M3_TBL 256 /* every E4M3 bit pattern, in order, as the f16 it means */ +#define R3D_E4M3_TBL_BYTES (R3D_E4M3_TBL * 2) + +/* Fill the block's table: `tbl` is __shared__ uint16_t[R3D_E4M3_TBL]. The barrier is inside it, + * because the only correct order is fill-then-read and the row should not have to remember it. */ +__device__ __forceinline__ void r3d_e4m3_f16_init(uint16_t* tbl, int tid, int nthr) +{ + for (int i = tid; i < R3D_E4M3_TBL; i += nthr) + tbl[i] = f32_to_f16(e4m3_to_f32((uint8_t)i)); + __syncthreads(); +} + +/* Two codes (the low 16 bits of a dword) as one f16 pair, the pair layout dot2_f16x2 reads: the + * first code in the low half. Same answer as e4m3x2_to_f16x2, eight table reads per eight codes. */ +__device__ __forceinline__ uint32_t r3d_e4m3x2_ld(const uint16_t* tbl, uint32_t pair) +{ + const uint16_t lo = tbl[pair & 0xffu]; + const uint16_t hi = tbl[(pair >> 8) & 0xffu]; + return (uint32_t)lo | ((uint32_t)hi << 16); +} + +/* Eight codes (two dwords, straddling pairs as always) as four f16 pairs. The sibling of + * codes8_to_f16x4 in r3d_vocab_bf16.hip; the int8 side of that helper stays with the codec, because + * int8 has a hardware convert and fp8 does not. */ +__device__ __forceinline__ void r3d_e4m3x8_ld(const uint16_t* tbl, uint2 c, uint32_t* w) +{ + const uint32_t d0 = c.x, d1 = c.y; + w[0] = r3d_e4m3x2_ld(tbl, d0 & 0xffffu); + w[1] = r3d_e4m3x2_ld(tbl, d0 >> 16); + w[2] = r3d_e4m3x2_ld(tbl, d1 & 0xffffu); + w[3] = r3d_e4m3x2_ld(tbl, d1 >> 16); +} + +/* One code, for the rows that decode a scalar a step (an activation tile staged a byte a lane). */ +__device__ __forceinline__ uint16_t r3d_e4m3_ld(const uint16_t* tbl, uint8_t code) +{ + return tbl[code]; +} + +#endif /* R3D_FP8_DEQUANT_H */ diff --git a/libr3d/r3d_gemm_bf16_nt_m16.hip b/libr3d/r3d_gemm_bf16_nt_m16.hip new file mode 100644 index 00000000..439e11f4 --- /dev/null +++ b/libr3d/r3d_gemm_bf16_nt_m16.hip @@ -0,0 +1,374 @@ +/* r3d_gemm_bf16_nt_m16.hip -- the skinny bf16 GEMM, M <= 16: the linear a token is made of. + * + * y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store. + * + * The band is decode and speculative verify, where the weight is the cost and the activation is + * free: the kernel is built so the whole weight plane streams once, and so every output's sum is + * the sum libref forms. + * + * ---- the lane map -------------------------------------------------------------------------- + * + * One output element a lane, walking k ascending. A wave covers MT rows of the activation by + * 32/MT rows of the weight: lane l owns (m = l % MT, n = n0 + l / MT), MT being the template + * argument -- the request's M rounded up to 1, 2, 4, 8 or 16. Lanes sharing an n read the same + * weight words, so the wave issues 32/MT loads per step and broadcasts them to MT lanes each; + * lanes sharing an m read the same activation words out of LDS. A lane therefore owns its own + * accumulator from 0 to K and never exchanges a value with another lane: its chain is + * + * acc = 0; for k ascending: acc = dot2(pair k+1, dot2(pair k, acc)) + * + * with pairs taken two k at a time, which is `s += a[k]*b[k]` in ascending k, summand for summand, + * the loop r4d_gemm_bf16_nt_tiled's contract quotes and ref_gemm.h's quant_tile runs. There is no + * wave reduction anywhere in this kernel, so nothing reassociates: at sk = 1 the output is + * bit-identical to libref's, not merely within a tolerance. + * + * Rows past M and columns past N are clamped, not skipped -- a tail lane re-reads the last real row + * and its result is dropped at the store -- so the k loop stays uniform and the loads stay + * straight-line. + * + * ---- where the bytes come from -------------------------------------------------------------- + * + * The activation is staged in LDS and widened on the way in: one row is M <= 16 elements wide per + * k, so a tile is MT * 128 bf16 (4.25 KiB at MT = 16) and one 16-byte load a thread. Staging + * converts bf16 -> f16 once per element with bf16x2_to_f16x2, which is exact, so the dot2 reads + * f16 pairs straight out of LDS and the widening is paid N/MT times less often than it would be + * read. The pitch is 68 dwords: 68 mod 32 = 4, so the eight lanes of a ds_read_b128 phase land on + * banks 4 apart -- conflict-free -- and 68 * 4 = 272 keeps a 16-byte LDS read aligned. + * + * The weight is NOT staged. M is tiny, so a staged tile would be read by 32/MT lanes and then + * thrown away; LDS staging buys reuse a skinny shape does not have. Weight bytes go straight from + * global memory into registers, widened there by four v_cvt_pkrtz per eight values (one per dword, + * so one convert per two dot2 products -- the price of the dot2 path being the widening the staged + * row pays once per element), and live for the four products they feed. + * Each wave keeps NT = 32/MT rows resident in L1 (NT lines of 128 B, 4 KiB at MT = 1, the worst + * case), which is what makes 16-byte-per-lane strided reads across NT rows cost what they fetch. + * + * ---- the register budget -------------------------------------------------------------------- + * + * A gfx11 SIMD has 1024 VGPRs for a wave32. The loop is one accumulator, four activation pairs, + * four weight dwords, one 16-byte staging quad and a handful of pointers and counters: about 24 + * live VGPRs, so the kernel is nowhere near the 128 that R3D_WAVES(8) -- eight waves a SIMD, + * 1024/8 -- asks for. The target is stated for the reason r3d_common.h gives: unstated, the + * scheduler picks the occupancy itself, and this kernel's throughput is waves in flight, since + * every wave is waiting on a memory load that takes hundreds of cycles. Eight waves a block of + * 256 threads is the default, and `wv` is the axis a tuner walks. + * + * ---- split-K -------------------------------------------------------------------------------- + * + * At M = 1 a wide N is the only parallelism there is, and N = 48 (a GDN a|b projection) gives three + * waves on a 32-CU card. `sk` splits K into that many contiguous slabs, each owned by one + * blockIdx.y, each writing an f32 partial to the caller's `scratch` arena; a second kernel on the + * same stream adds the partials per output in ascending split order and narrows once. + * + * The order matters and is stated: summing sk per-slab partials is NOT the ascending sum libref + * forms. Each partial is an ascending sum over its own slab, and the slab sums are then added in + * ascending slab order, which brackets the products differently than a single running chain does. + * sk = 1 is the bit-identical case; sk > 1 agrees to the last bits, which is the same contract + * libr4d's tiled row states about its slices. The row is verified at every sk kbench measures. + * + * `sk == 0` means "the largest legal split for this K" off the axis's ladder {16, 8, 4, 2, 1}, + * legality being K % (sk * 8) == 0: a slice must end where the inner loop stops, on a group of the + * eight k (four f16 pairs) a lane consumes per step, so a slice boundary never falls inside a + * step. The staged tile is 128 k wide and its last tile is ragged, which is what lets a slice be + * 8 k long, and the cap of 16 is the split the row's scratch hook sizes the arena for. + * + * ---- `nt` ----------------------------------------------------------------------------------- + * + * RDNA3 has no global_load_tr_b128 (that is RDNA4) and no cache-swizzle field on a global load. So + * `nt` is an axis that measures a knob the ISA does not special-case: nt = 1 issues the weight + * reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache modifier + * and no swizzle -- a plain stream -- and nt = 0 issues the same 16-byte reads through the generic + * pointer, which lowers to flat_load_dwordx4. Nothing is invented here; the axis exists so kbench + * can price the two lowerings and record that on this card they are the same stream. + */ + +/* hip_runtime.h first: it defines __forceinline__, which r3d_codecs.h's R3D_HD spells, and + * r3d_common.h reaches the codecs before it reaches the runtime. */ +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr int kBlockThreads = 256; // eight waves, the default +constexpr int kWaves = kBlockThreads / kWave; +constexpr int kKTile = 128; // k a staged tile of a covers +constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row +constexpr int kMTMax = 16; // the band's upper bound + +/* The split rule, in one place so the launch, the shim and the row's gemm_tune_valid agree. + * `kUnit` is the k a lane's step consumes -- eight elements, four f16 pairs -- and a slice must be + * whole steps, so a split is legal when K divides by sk * kUnit. The ladder is the row's `sk` axis + * descending, and its top is the split the scratch hook sizes for: a wider split the arena cannot + * hold is not a legal default. */ +constexpr int kUnit = 8; +inline int pick_sk(long long K, int maxsk) +{ + static const int kLadder[] = { 16, 8, 4, 2, 1 }; + for (int s : kLadder) + if (s <= maxsk && K % ((long long)s * kUnit) == 0) return s; + return 1; +} + +/* A 16-byte weight read. NT true is the address-space-1 form: global_load_b128, no cache modifier, + * no swizzle, the plain stream the row's `nt` axis names. NT false goes through the generic + * pointer, which the compiler lowers to flat_load_dwordx4. */ +template +__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p) +{ + if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p; + else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); +} + +__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p) +{ + return *(const r3d_u32x4*)p; +} + +/* y[M,N] = a[M,K] @ b[N,K]^T, one output element a lane. + * + * `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the + * narrowed bf16 the caller asked for. With sk > 1 every split writes its own f32 partial, dense + * [sk][M][N], and gemm_split_reduce adds them. */ +template +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel( + const uint16_t* __restrict__ A, const uint16_t* __restrict__ B, + uint16_t* __restrict__ Y, float* __restrict__ Part, + int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab) +{ + /* Staged activation, widened to f16 pairs on the way in. One allocation for the widest MT: + * this kernel is instantiated for MT = 1, 2, 4, 8 and 16 and 4.25 KiB is not worth a template. */ + __shared__ uint32_t s_a[kMTMax * kAPitch]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + const uint32_t waves = blockDim.x / kWave; + constexpr uint32_t kNT = kWave / MT; // weight rows a wave covers + + const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * kNT + lane / MT; + const uint32_t m = lane & (MT - 1); + const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1)); + const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1)); + + const int kbeg = (int)blockIdx.y * kslab; + const int kend = kbeg + kslab < K ? kbeg + kslab : K; + + const uint16_t* w = B + (size_t)n_real * w_ld; + float acc = 0.0f; + + for (int kt = kbeg; kt < kend; kt += kKTile) { + const int kl = std::min(kKTile, kend - kt); + + /* Stage: eight elements a unit, MT * (kl/8) units, 256 threads. A row past M re-reads the + * last real row, whose products the store drops. */ + const int nu = (kl + 7) / 8; + /* blockDim.x, not the 256-thread default: the wv axis launches one, two, four or eight + * waves, and a stage loop that strides the block constant leaves units staged only for + * the waves that exist -- wv = 1 stages 32 of MT*16 units and the k loop reads the rest of + * the tile out of LDS that was never written. */ + for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) { + const int r = i / nu, c = (i % nu) * 8; + const int rr = r < M ? r : M - 1; + const uint16_t* src = A + (size_t)rr * a_ld + kt + c; + uint32_t* dst = s_a + (size_t)r * kAPitch + c / 2; + if (c + 8 <= kl) { + const r3d_u32x4 q = *(const __attribute__((address_space(1))) r3d_u32x4*)src; + *(r3d_u32x4*)dst = r3d_u32x4{ + bf16x2_to_f16x2(q.x), bf16x2_to_f16x2(q.y), + bf16x2_to_f16x2(q.z), bf16x2_to_f16x2(q.w) }; + } else { + uint32_t p[4] = { 0, 0, 0, 0 }; + for (int e = 0; e < kl - c; e += 2) { + const uint32_t lo = ldg_u16(src + e); + const uint32_t hi = (e + 1 < kl) ? ldg_u16(src + e + 1) : 0u; + p[e / 2] = bf16x2_to_f16x2(lo | (hi << 16)); + } + for (int e = 0; e < (kl - c + 1) / 2; ++e) dst[e] = p[e]; + } + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)m * kAPitch; + const int kf = kl & ~7; + for (int k = 0; k < kf; k += 8) { + const r3d_u32x4 aw = lds_a(ap + k / 2); + const r3d_u32x4 b16 = ldw(w + kt + k); + /* The weight is widened here and it is not optional: dot2's operands are f16, and a + * bf16 bit pattern read as f16 is a different number -- bf16's 1.0 (0x3F80) is 1.875 -- + * and any magnitude at or above 2^16 is an infinity. Feeding the bytes straight in is + * the trap this ISA sets for a bf16 GEMM that reaches for v_dot2acc_f32_f16, and it + * arrives as an output uncorrelated with the reference at rel ~ 1, with infinities in + * it, which reads as a numerics problem and is a reading problem. Four + * v_cvt_pk_rtz_f16_f32_e32 per eight values, each with the pair's two VALU of unpack, + * so the widening costs one ALU slot per product the dot2 makes; RDNA3 pairs some of + * the dots as v_dual_dot2acc_f32_f16 with the converts riding alongside. */ + const r3d_u32x4 bw = r3d_u32x4{ bf16x2_to_f16x2(b16.x), bf16x2_to_f16x2(b16.y), + bf16x2_to_f16x2(b16.z), bf16x2_to_f16x2(b16.w) }; + acc = dot4_f16x4(aw.x, aw.y, bw.x, bw.y, acc); + acc = dot4_f16x4(aw.z, aw.w, bw.z, bw.w, acc); + } + /* The ragged end of the last slab, ascending. A split is legal only when its slab is whole + * tiles, so this runs at sk = 1 with a K that is not a multiple of 128. */ + for (int k = kf; k < kl; ++k) + acc = acc + bf16_to_f32((uint16_t)ldg_u16(A + (size_t)m_real * a_ld + kt + k)) + * bf16_to_f32((uint16_t)ldg_u16(w + kt + k)); + group_barrier(); // the next tile's stage must not race this one's reads + } + + const bool keep = (n0 < (uint32_t)N) && (m < (uint32_t)M); + if (!keep) return; + if constexpr (SPLIT) { + /* Partial plane [sk][M][N]: split-major, so the reducer reads sk values M*N apart and this + * store keeps the same [M][N] shape at every split. */ + Part[((size_t)blockIdx.y * M + m) * N + n0] = acc; + } else { + Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc); // narrowed once, here + } +} + +/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one narrowing. + * + * This is the order libref's ascending sum produces at sk = 1 and not at sk > 1: each partial is + * ascending over its own slab, and the slab sums bracket the products differently than one chain + * does. The difference is in the last bits and is the split's, not a bug in it. */ +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_split_reduce( + const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk) +{ + const int mn = M * N; + const int stride = gridDim.x * kBlockThreads; + for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) { + const int m = i / N, n = i - m * N; + const float* p = Part + (size_t)m * N + n; + float v = p[0]; + for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N]; + Y[(size_t)m * y_ld + n] = f32_to_bf16(v); + } +} + +} // namespace + +/* y[M,N] = a[M,K] @ b[N,K]^T, bf16 in and out, f32 accumulate, M <= 16. + * + * a [M][K] bf16, `a_ld` elements a row (0 = K) + * b [N][K] bf16, row-major, k contiguous + * y [M][N] bf16, `y_ld` elements a row (0 = N) + * + * `sk` splits K (0 = the largest legal split), `wv` is waves per block (0 = 8), `nt` picks the + * weight load's lowering (see the file header), and `scratch` is the f32 partial arena, + * sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null pointer, -2 a shape it + * does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */ +extern "C" int r3d_gemm_nt_bf16_m16(long a, long b, long y, int M, int N, int K, int a_ld, + int y_ld, int sk, int wv, int nt, long scratch, long stream) +{ + if (!a || !b || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > kMTMax) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (sk == 0) sk = pick_sk(K, 16); + if (sk < 1) return -2; + if (K % ((long long)sk * kUnit)) return -2; + if (sk > 1 && !scratch) return -1; + if (wv <= 0) wv = kWaves; + if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2; + + const int mt = M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax; + const int kslab = K / sk; + +#define R3D_M16_NT(MTV, NTV) \ + do { \ + const int nt_ = (N + (kWave / MTV) - 1) / (kWave / MTV); \ + const dim3 grid((nt_ + wv - 1) / wv, (unsigned)sk), block((unsigned)(wv * kWave)); \ + if (sk > 1) { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, K, kslab); \ + const int mn = M * N; \ + const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \ + R3D_KLAUNCH(gemm_split_reduce, dim3(nb), dim3(kBlockThreads), (hipStream_t)stream, \ + (const float*)scratch, (uint16_t*)y, M, N, y_ld, sk); \ + } else { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, K, kslab); \ + } \ + } while (0) +#define R3D_M16_MT(MTV) do { if (nt) R3D_M16_NT(MTV, true); else R3D_M16_NT(MTV, false); } while (0) + switch (mt) { + case 1: R3D_M16_MT(1); break; + case 2: R3D_M16_MT(2); break; + case 4: R3D_M16_MT(4); break; + case 8: R3D_M16_MT(8); break; + default: R3D_M16_MT(16); break; + } +#undef R3D_M16_MT +#undef R3D_M16_NT + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ============================================================== the plugin ABI entry point + * + * gemm_nt's operand list is [a, b, y] and its parameters M, N, K, dtype (libref's pGemm/oGemm). */ +enum { G_A = 0, G_B, G_Y }; + +#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0) +static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; } + +extern "C" int r3d_rad_gemm_nt_bf16_m16(const RadArgs* a, RadStream s) +{ + const RadTensor* A = r3d_opt(a, G_A); + const RadTensor* B = r3d_opt(a, G_B); + const RadTensor* Y = r3d_opt(a, G_Y); + if (!A || !B || !Y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(A)); + R3D_NEED(dt_bf16(B)); + R3D_NEED(dt_bf16(Y)); + + const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1)); + const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2)); + if (K < 1 || N < 1) return R3D_NO(RAD_E_SHAPE); + /* The row count comes from the output, never from `M`, which is the band's upper bound. */ + const long long nel = r3d_numel(Y); + if (nel < N || nel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = nel / N; + if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + + long long arows = 0, yrows = 0; + const long long a_ld = r3d_rows_pitch(A, K, &arows); + const long long y_ld = r3d_rows_pitch(Y, N, &yrows); + if (a_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (arows < M || yrows < M) return R3D_NO(RAD_E_SHAPE); + /* The weight must be dense: every wave reads b[n][k] at n * K + k, and a pitch the launcher + * does not carry cannot be described to it. */ + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + /* 16-byte weight loads, at a row base and at a tile base, both multiples of 8 elements. */ + if (a_ld % 8) return R3D_NO(RAD_E_STRIDE); + if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN); + + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + int wv = c.wv > 0 ? c.wv : kWaves; + if (wv > kWaves) wv = kWaves; + if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return R3D_NO(RAD_E_SHAPE); + int sk = c.sk > 0 ? c.sk : pick_sk(K, 16); + if (sk > 16) return R3D_NO(RAD_E_SHAPE); // the scratch hook sizes for 16 + if (K % ((long long)sk * kUnit)) return R3D_NO(RAD_E_SHAPE); + if (sk > 1) { + const long long need = (long long)sk * M * N * 4; + if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH); + } + + const int e = r3d_gemm_nt_bf16_m16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)N, + (int)K, (int)a_ld, (int)y_ld, sk, wv, c.nt, + (long)(uintptr_t)(sk > 1 ? a->scratch : nullptr), + (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE + : e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); +} diff --git a/libr3d/r3d_gemm_fp8a16_nt_m1.hip b/libr3d/r3d_gemm_fp8a16_nt_m1.hip new file mode 100644 index 00000000..a110186d --- /dev/null +++ b/libr3d/r3d_gemm_fp8a16_nt_m1.hip @@ -0,0 +1,524 @@ +/* r3d_gemm_fp8a16_nt_m1.hip -- the same skinny shape against a block-scaled weight. + * + * y[M,N] = a[M,K] @ b[N,K]^T, b stored as E4M3 codes with one f32 scale per (pb1 x pb2) block, + * f32 accumulate, narrowed once by the store. `a_scale`, when present, means the activation is + * coded too -- quant_act_fp8's E4M3 codes with one f32 per (row, group) -- which is the fp8a8 + * form the row table names `fp8a8`. + * + * RDNA3 has no fp8 instruction: the builtins are declared for gfx11 and die at instruction + * selection. So the codes are decoded in software, and the decode is free of cost in the sense + * that matters here: E4M3 is four exponent and three mantissa bits, f16 is five and ten, so + * e4m3x2_to_f16x2 is EXACT and the dot2 multiplies the numbers the checkpoint means. Nothing is + * rounded between the code and the product, which is why this row's output is libref's to the bit + * at sk = 1 and not merely inside fp8 quantisation noise. + * + * ---- the lane map -------------------------------------------------------------------------- + * + * The same as r3d_gemm_bf16_nt_m16's: lane l owns the output (m = l % MT, n = n0 + l / MT) for the + * template's MT = ceil(M) in {1,2,4,8,16}, walks k ascending and holds its own accumulator. One + * difference is forced by the format, and it is the one that makes this kernel what it is: a lane + * consumes sixteen codes per step, because that is what sixteen bytes are, and sixteen bytes is + * one global_load_b128. Eight dot2 per step, so the weight stream is one 16-byte load per eight + * matrix instructions -- the decode (eight v_perms and shifts, exact) sits between them and is the + * reason this kernel's rate is not the bf16 row's. + * + * A lane owns one (m, n) pair, so a lane owns one scale per block: `n / pb1` picks b_scale's row + * and the block index picks its column, and both are hoisted out of the block's sixteen-element + * steps. The activation's scale, when the activation is coded, is `m`'s row at the same block + * index. Lanes sharing an n agree on it, which is why no lane-to-lane exchange is needed. + * + * ---- where the scale multiplies ------------------------------------------------------------- + * + * ref_gemm.h's quant_tile, and quant_dot beside it, is the spec, and the order it writes is the + * order this kernel runs: + * + * for gi ascending: sub = 0 + * for k in the group, ascending: sub += a[k] * b[k] (from the CODES) + * acc = acc + (sub * sa) * sb + * + * with sa = a_scale[m][gi] or 1, and sb = b_scale[n / pb1][gi]. The scale multiplies the finished + * block, once, at the block's end -- not every product: scaling each product is equal in exact + * arithmetic and differs in the last bits, which moves an fp8 code and so moves a token. And + * `(sub * sa) * sb` is an order, not a formula: the parentheses are libref's, and the products are + * summed from the raw codes with no scale folded into them. This kernel accumulates a block's + * sub-sum into a register of its own, so the bracketing is the reference's, and the widening is + * exact, so at sk = 1 the output is bit-identical to it. + * + * ---- the activation --------------------------------------------------------------------------- + * + * Staged in LDS per block of the weight's K, widened on the way in: bf16 -> f16 for fp8a16, E4M3 -> + * f16 for fp8a8, both exact. One row of a is M <= 16 elements wide per k, so a staged block is + * MT * 128 values, 4.25 KiB at MT = 16, and the pitch is 68 dwords: 68 mod 32 = 4, so a + * ds_read_b128's eight lanes land on banks four apart, and 272 bytes a row keeps the 16-byte reads + * aligned. The weight is not staged: with M <= 16 a staged tile has 32/MT readers, so staging + * trades a wave's worth of L1 residency for a round trip through LDS and buys nothing. + * + * ---- split-K -------------------------------------------------------------------------------- + * + * `sk` contiguous slices, one per blockIdx.y, each writing its f32 partial to `scratch` and a + * second kernel adding them per output in ascending slice order. Each partial is a chain of + * `(sub * sa) * sb` terms over its own slices of blocks, so at sk = 1 the chain is libref's + * exactly; sk > 1 brackets the block terms by slice, which is the split's doing and agrees to the + * last bits. Legality is K % (sk * group) == 0 -- a slice that ends mid-block cannot apply that + * block's scale -- which is the row's gemm_tune_valid rule, unit = group. + * + * ---- `nt` ----------------------------------------------------------------------------------- + * + * No transposed load on this ISA and no cache field on a global load. nt = 1 issues the weight + * reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache + * modifier and no swizzle; nt = 0 issues the same 16-byte reads through the generic pointer. The + * axis measures the two lowerings, and on this card it measures the same stream twice. + */ + +#include // __forceinline__, which r3d_codecs.h's R3D_HD spells + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr int kBlockThreads = 256; +constexpr int kWaves = kBlockThreads / kWave; +constexpr int kMTMax = 16; +constexpr int kStep = 16; // codes a lane takes per step: one 16-byte load +constexpr int kAPitch = 68; // dwords a staged activation row (128 values + 4) +constexpr int kGroupMax = 128; // the stage is sized for one 128-wide block per row + +/* A slice is legal when it is a whole number of scale blocks, so the split ladder is capped by + * the scratch hook's widest split and stepped by the block the weight carries. */ +int pick_sk(long long K, int group, int maxsk) +{ + static const int kLadder[] = { 16, 8, 4, 2, 1 }; + for (int s : kLadder) + if (s <= maxsk && K % ((long long)s * group) == 0) return s; + return 1; +} + +template +__device__ __forceinline__ r3d_u32x4 ldc(const uint8_t* p) // 16 codes +{ + if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p; + else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); +} + +__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p) +{ + return *(const r3d_u32x4*)p; +} + +__device__ __forceinline__ uint32_t ldg_u8(const uint8_t* p) +{ + return *(const __attribute__((address_space(1))) uint8_t*)p; +} + +/* The weight's 16 codes as eight f16 pairs, exact. + * + * e4m3x2_to_f16x2 decodes the TWO codes in a dword's low half, so a 16-byte load -- four dwords, + * sixteen codes -- is eight decodes, each fed the 16-bit pair it wants: the pairs straddle the + * dwords, four dwords in, eight pairs out. Feeding the codec whole dwords decodes eight codes and + * leaves the rest of the step multiplying registers that were never written, which is the quiet + * version of this bug: the answer comes back a fraction of its size, not a NaN. */ +__device__ __forceinline__ void codes_to_f16x8(const r3d_u32x4 c, uint32_t* w) +{ + const uint32_t d[4] = { c.x, c.y, c.z, c.w }; +#pragma unroll + for (int j = 0; j < 8; ++j) + w[j] = e4m3x2_to_f16x2((d[j >> 1] >> (16 * (j & 1))) & 0xffffu); +} + +/* y[M,N] = a[M,K] @ dequant(b)[N,K]^T. `A8` is the fp8a8 form: a carries E4M3 codes and a_scale + * carries one f32 per (row, block); without it a is bf16 and read directly. */ +template +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel( + const uint8_t* __restrict__ A, const float* __restrict__ AScale, + const uint8_t* __restrict__ B, const void* __restrict__ BScale, int bs16, + uint16_t* __restrict__ Y, float* __restrict__ Part, + int M, int N, int K, int group, int pb1, int a_ld, int y_ld, int kslab, int nkb) +{ + __shared__ uint32_t s_a[kMTMax * kAPitch]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + const uint32_t waves = blockDim.x / kWave; + constexpr uint32_t kNT = kWave / MT; + + const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * kNT + lane / MT; + const uint32_t m = lane & (MT - 1); + const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1)); + const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1)); + + const int kbeg = (int)blockIdx.y * kslab; + const int kend = kbeg + kslab < K ? kbeg + kslab : K; + + const uint8_t* w = B + (size_t)n_real * K; + /* b_scale is the container's `weight_scale_inv`, and the op's shape hook writes it bf16 for the + * whole quantised family -- `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})`; f32 belongs to the + * separate `fp8a8f32` spelling. Both are read here; bf16 widens to f32 exactly, since every + * bf16 value is representable in f32, so the widening is free and the products are unchanged. */ + const size_t bsrow = (size_t)(n_real / pb1) * nkb; + const float* bsF = bs16 ? nullptr : (const float*)BScale + bsrow; + const uint16_t* bsH = bs16 ? (const uint16_t*)BScale + bsrow : nullptr; + const float* as = A8 ? AScale + (size_t)m_real * nkb : nullptr; + + float acc = 0.0f; + + /* One scale block per round: stage the block's activation, walk the block's k, fold the block's + * scale in at the end. `kb` is the block's first k, which is where the scales are indexed. */ + for (int kb = kbeg; kb < kend; kb += group) { + const int gl = std::min(group, kend - kb); + const int gi = kb / group; + + /* Stage gl elements of MT activation rows, widened to f16 pairs. Eight values a unit: a + * 16-byte load for a bf16 row, an 8-byte one for a coded row, which is why the coded row's + * pitch check is eight, not sixteen. A row past M re-reads the last real row. */ + constexpr int kUnit = 8; + const int nu = (gl + kUnit - 1) / kUnit; + for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) { // see the m16 unit's note on wv + const int r = i / nu, c = (i % nu) * kUnit; + const int rr = r < M ? r : M - 1; + const int cnt = std::min(kUnit, gl - c); + uint32_t* dst = s_a + (size_t)r * kAPitch + c / 2; + if constexpr (A8) { + const uint8_t* src = A + (size_t)rr * a_ld + kb + c; // codes: bytes and elements agree + for (int e = 0; e < cnt; e += 8) { + const uint8_t* sp = src + e; + uint32_t q[2]; + if (cnt - e >= 8) { + const r3d_u32x2 b8 = + *(const __attribute__((address_space(1))) r3d_u32x2*)sp; + q[0] = b8.x; q[1] = b8.y; + } else { + uint32_t pack[2] = { 0, 0 }; + for (int t = 0; t < cnt - e; ++t) + pack[t >> 2] |= (uint32_t)ldg_u8(sp + t) << (8 * (t & 3)); + q[0] = pack[0]; q[1] = pack[1]; + } + uint32_t p[4] = { e4m3x2_to_f16x2(q[0] & 0xffffu), + e4m3x2_to_f16x2(q[0] >> 16), + e4m3x2_to_f16x2(q[1] & 0xffffu), + e4m3x2_to_f16x2(q[1] >> 16) }; +#pragma unroll + for (int t = 0; t < 4; ++t) + if (e + 2 * t < gl) dst[e / 2 + t] = p[t]; + } + } else { + /* A is a byte pointer here because the coded form codes it: cast first, then the + * row and k offsets are ELEMENT offsets, which for bf16 is twice the byte count. */ + const uint16_t* src = (const uint16_t*)A + (size_t)rr * a_ld + kb + c; + for (int e = 0; e < cnt; e += 8) { + uint32_t p[4]; + if (cnt - e >= 8) { + const r3d_u32x4 b16 = + *(const __attribute__((address_space(1))) r3d_u32x4*)(src + e); + p[0] = bf16x2_to_f16x2(b16.x); + p[1] = bf16x2_to_f16x2(b16.y); + p[2] = bf16x2_to_f16x2(b16.z); + p[3] = bf16x2_to_f16x2(b16.w); + } else { +#pragma unroll + for (int t = 0; t < 4; ++t) { + const uint32_t lo = ldg_u16(src + e + 2 * t); + const uint32_t hi = (e + 2 * t + 1 < gl) + ? ldg_u16(src + e + 2 * t + 1) : 0u; + p[t] = bf16x2_to_f16x2(lo | (hi << 16)); + } + } +#pragma unroll + for (int t = 0; t < 4; ++t) + if (e + 2 * t < gl) dst[e / 2 + t] = p[t]; + } + } + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)m * kAPitch; + float sub = 0.0f; + const int gf = (gl / kStep) * kStep; + for (int k = 0; k < gf; k += kStep) { + const r3d_u32x4 a0 = lds_a(ap + k / 2); + const r3d_u32x4 a1 = lds_a(ap + k / 2 + 4); + uint32_t b[8]; + codes_to_f16x8(ldc(w + kb + k), b); + sub = dot4_f16x4(a0.x, a0.y, b[0], b[1], sub); + sub = dot4_f16x4(a0.z, a0.w, b[2], b[3], sub); + sub = dot4_f16x4(a1.x, a1.y, b[4], b[5], sub); + sub = dot4_f16x4(a1.z, a1.w, b[6], b[7], sub); + } + /* The last partial block, when K is not a whole block: ascending, two k at a time, each + * code decoded on its own. The launcher refuses a K that is not a multiple of the block + * (a ragged block would read past the scale plane), so this is a shape the kernel carries + * for completeness and the row never issues. */ + for (int k = gf; k < gl; k += 2) { + const uint32_t aw = ap[k / 2]; + const uint32_t c0 = ldg_u8(w + kb + k); + const uint32_t c1 = (k + 1 < gl) ? ldg_u8(w + kb + k + 1) : 0u; + const uint32_t pw = e4m3x2_to_f16x2(c0 | (c1 << 8)); + sub = dot2_f16x2(aw, pw, sub); + } + group_barrier(); // the next block's stage must not race this one's reads + + /* The block's finished sub-sum, scaled once, in libref's parentheses. */ + const float sa = A8 ? as[gi] : 1.0f; + acc = acc + (sub * sa) * (bs16 ? bf16_to_f32(bsH[gi]) : bsF[gi]); + } + + const bool keep = (n0 < (uint32_t)N) && (m < (uint32_t)M); + if (!keep) return; + if constexpr (SPLIT) { + Part[((size_t)blockIdx.y * M + m) * N + n0] = acc; + } else { + Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc); + } +} + +/* The split reduction, the m16 unit's, in the same order: v = ((p0 + p1) + p2) + ... ascending by + * slice, then one narrowing. Ascending slice order is libref's ascending sum only at sk = 1; past + * that the block terms are bracketed by slice, which is the split's cost and is stated as such. */ +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_reduce( + const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk) +{ + const int mn = M * N; + const int stride = gridDim.x * kBlockThreads; + for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) { + const int m = i / N, n = i - m * N; + const float* p = Part + (size_t)m * N + n; + float v = p[0]; + for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N]; + Y[(size_t)m * y_ld + n] = f32_to_bf16(v); + } +} + +} // namespace + +/* y[M,N] = a[M,K] @ dequant(b)[N,K]^T over E4M3 codes, M <= 16, f32 accumulate, bf16 out. + * + * a [M][K] bf16 (fp8a16) or E4M3 codes (fp8a8, when `a_scale` is present) + * a_scale [M][ceil(K/group)] f32, or 0 + * b [N][K] E4M3 codes, row-major, k contiguous + * b_scale [ceil(N/pb1)][ceil(K/pb2)] bf16 (the container's weight_scale_inv) or f32, block-major + * y [M][N] bf16, `y_ld` elements a row (0 = N) + * + * `group` is the code group along K (pb2, the checkpoint's block width); `pb1` the rows sharing a + * scale row (0 = group). `sk` splits K (0 = the widest legal), `nt` the weight load's lowering, + * `scratch` the f32 partial arena, sk * M * N * 4 bytes, required when the split is on. Returns 0, + * -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 HIP failed. */ +extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M, + int N, int K, int group, int pb1, int pb2, int a_ld, int y_ld, + int sk, int nt, long scratch, int bs_dt, long stream) +{ + if (!a || !b || !b_scale || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > kMTMax) return -2; + if (group <= 0) group = R3D_FP8_BLOCK; + if (pb1 <= 0) pb1 = group; + if (pb2 == 0) pb2 = group; + if (pb2 != group) return -2; // one block: the K block IS the code group + if (group > kGroupMax) return -2; + if (group % kStep) return -2; // a block must be whole lane steps + if (K % group) return -2; // a ragged block reads past the scale plane + const int nkb = K / group; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + const int a8 = a_scale != 0; + if (a8 && (a_ld % 8)) return -3; // 8-byte code staging + if (!a8 && (a_ld % 8)) return -3; // 16-byte widened staging + if (sk == 0) sk = pick_sk(K, group, 16); + if (sk < 1) return -2; + if (K % ((long long)sk * group)) return -2; + if (sk > 1 && !scratch) return -1; + + const int bs16 = (bs_dt == RAD_BF16); /* anything else, 0 included, reads the plane as f32 */ + const int mt = M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax; + const int kslab = K / sk; + const int nrowb = (N + pb1 - 1) / pb1; + if ((long long)nrowb * nkb <= 0) return -2; + +#define R3D_Q_NT(MTV, A8V, NTV) \ + do { \ + const int nt_ = (N + (kWave / MTV) - 1) / (kWave / MTV); \ + const dim3 grid((nt_ + kWaves - 1) / kWaves, (unsigned)sk), dim3_blk(kBlockThreads); \ + if (sk > 1) { \ + R3D_KLAUNCH(R3D_KNAME((gemm_q_kernel)), grid, dim3_blk, \ + (hipStream_t)stream, (const uint8_t*)a, (const float*)a_scale, \ + (const uint8_t*)b, (const void*)b_scale, bs16, (uint16_t*)y, \ + (float*)scratch, M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \ + const int mn = M * N; \ + const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \ + R3D_KLAUNCH(gemm_q_reduce, dim3(nb), dim3(kBlockThreads), (hipStream_t)stream, \ + (const float*)scratch, (uint16_t*)y, M, N, y_ld, sk); \ + } else { \ + R3D_KLAUNCH(R3D_KNAME((gemm_q_kernel)), grid, dim3_blk, \ + (hipStream_t)stream, (const uint8_t*)a, (const float*)a_scale, \ + (const uint8_t*)b, (const void*)b_scale, bs16, (uint16_t*)y, \ + (float*)nullptr, M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \ + } \ + } while (0) +#define R3D_Q_A8(MTV, A8V) do { if (nt) R3D_Q_NT(MTV, A8V, true); else R3D_Q_NT(MTV, A8V, false); } while (0) +#define R3D_Q_MT(MTV) do { if (a8) R3D_Q_A8(MTV, true); else R3D_Q_A8(MTV, false); } while (0) + switch (mt) { + case 1: R3D_Q_MT(1); break; + case 2: R3D_Q_MT(2); break; + case 4: R3D_Q_MT(4); break; + case 8: R3D_Q_MT(8); break; + default: R3D_Q_MT(16); break; + } +#undef R3D_Q_MT +#undef R3D_Q_A8 +#undef R3D_Q_NT + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The declaration in r3d.h carries no scale dtype, and the weight's block scales are bf16 for the + * whole quantised family (see the entry above), so the family needs a second spelling. `_ex` adds + * `bs_dt`, the b_scale plane's RadDataType: RAD_BF16 reads it as bf16, anything else -- 0 included + * -- reads it as f32, which is exactly what the entry below, and every caller written before the + * bf16 discovery, asks for. The shim takes the dtype off the operand and calls `_ex`; the old entry + * forwards, so a raw caller of the old name sees the behaviour it was written against. */ +extern "C" int r3d_gemm_nt_q_fp8(long a, long a_scale, long b, long b_scale, long y, int M, int N, + int K, int group, int pb1, int pb2, int a_ld, int y_ld, int sk, + int nt, long scratch, long stream) +{ + return r3d_gemm_nt_q_fp8_ex(a, a_scale, b, b_scale, y, M, N, K, group, pb1, pb2, a_ld, y_ld, sk, + nt, scratch, RAD_F32, stream); +} + +/* ============================================================== the plugin ABI entry point + * + * gemm_nt_q's operands are [a, a_scale, b, b_scale, y, a_sum?, b_ref?] and its parameters M, N, K, + * group, dtype, pb1?, pb2?, split_n? (libref's pGemmQ/oGemmQ). */ +enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF }; + +#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0) +static int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; } +static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; } + +/* The trace latch for this file: distinct GEMM shapes, printed once each. A static array and a + * counter, no lock -- the flag is a diagnostic and a doubled line is a cosmetic cost, a lock in + * the served path is not. */ +struct GemmPlanKey { long long M, N, K; unsigned a_rank, as_rank; long long a_ld, y_ld; }; + +static bool gemm_plan_once(long long M, long long N, long long K, unsigned a_rank, + unsigned as_rank, long long a_ld, long long y_ld) +{ + static GemmPlanKey seen[96]; + static int n = 0; + for (int i = 0; i < n; ++i) + if (seen[i].M == M && seen[i].N == N && seen[i].K == K && seen[i].a_rank == a_rank && + seen[i].as_rank == as_rank && seen[i].a_ld == a_ld && seen[i].y_ld == y_ld) + return false; + if (n < 96) seen[n++] = GemmPlanKey{M, N, K, a_rank, as_rank, a_ld, y_ld}; + return true; +} + +extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s) +{ + const RadTensor* A = r3d_opt(a, Q_A); + const RadTensor* AS = r3d_opt(a, Q_ASCALE); + const RadTensor* B = r3d_opt(a, Q_B); + const RadTensor* BS = r3d_opt(a, Q_BSCALE); + const RadTensor* Y = r3d_opt(a, Q_Y); + if (!A || !B || !BS || !Y) return R3D_NO(RAD_E_INVAL); + /* The schemes this kernel decodes: E4M3 codes on the weight, bf16 activations (fp8a16) or + * E4M3 codes with their own scale (fp8a8). E5M2 has no decoder here. */ + if (!r3d_is_e4m3(B)) return R3D_NO(RAD_E_DTYPE); + /* The weight's block scales are bf16 for the whole quantised family -- the shape hook's + * `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})` is the container's `weight_scale_inv`, and f32 is + * the separate `fp8a8f32` spelling, which no row here claims (those bands stay with the + * reference). Accept both; the kernel widens bf16 -> f32 at the load, exactly and for free. */ + const bool bs16 = r3d_is_bf16(BS); + if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_bf16(Y)); + const bool a8 = AS != nullptr; + if (a8) { + if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_f32(AS)); + } else { + R3D_NEED(dt_bf16(A)); + } + + const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1)); + const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2)); + if (K < 1 || N < 1) return R3D_NO(RAD_E_SHAPE); + const long long nel = r3d_numel(Y); + if (nel < N || nel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = nel / N; // never from the `M` parameter + if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); + + /* The block geometry, and the disagreement libref refuses: `group` is what the selector + * matched on, and pb2 is the checkpoint's, and they describe the same bytes. */ + const long long group = r3d_geti_or(a, "group", R3D_FP8_BLOCK); + const long long pb1 = r3d_geti_or(a, "pb1", group), pb2 = r3d_geti_or(a, "pb2", group); + if (group != R3D_FP8_BLOCK) return R3D_NO(RAD_E_SHAPE); + if (pb2 != 0 && pb2 != group) return R3D_NO(RAD_E_SHAPE); + if (pb1 <= 0) return R3D_NO(RAD_E_SHAPE); + if (K % group) return R3D_NO(RAD_E_SHAPE); + const long long nkb = (K + group - 1) / group, nrowb = (N + pb1 - 1) / pb1; + if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(BS) < nrowb * nkb) return R3D_NO(RAD_E_SHAPE); + if (AS && r3d_numel(AS) < M * nkb) return R3D_NO(RAD_E_SHAPE); + /* `a_sum` removes an activation zero point this grid does not have, and `b_ref` is an mxfp4 + * scale reference: libref refuses both beside these schemes (gemm_ntq_impl), so we do. */ + if (r3d_opt(a, Q_ASUM)) return R3D_NO(RAD_E_UNSUPPORTED); + if (r3d_opt(a, Q_BREF)) return R3D_NO(RAD_E_UNSUPPORTED); + + long long arows = 0, yrows = 0; + const long long a_ld = r3d_rows_pitch(A, K, &arows); + const long long y_ld = r3d_rows_pitch(Y, N, &yrows); + if (a_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (arows < M || yrows < M) return R3D_NO(RAD_E_SHAPE); + if (!r3d_contig(B) || !r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE); + if (AS && !r3d_contig(AS)) return R3D_NO(RAD_E_STRIDE); + /* The scale planes have no pitch argument in the launcher, so they must be dense, and their + * stated grid must be the one the kernel walks. */ + if (r3d_dim(BS, 1) != 0 && BS->shape[BS->rank - 1] != nkb && r3d_numel(BS) != nrowb * nkb) + return R3D_NO(RAD_E_SHAPE); + if ((a8 && (a_ld % 8)) || (!a8 && (a_ld % 8))) return R3D_NO(RAD_E_STRIDE); + if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN); + + /* The plan's own numbers for the M<=16 band, under RAD_R3D_TRACE=1 and once per distinct + * shape -- the same instrument the tiled row carries, in the row that serves the short steps. + * It lives here because the served collapse begins at 15 prompt tokens, a step the tiled shim + * never sees: the ladder's numbers below 17 are M=5..16 and the tiled row's line cannot speak + * for them. M is derived off the activation's output the way the row derives it (line 430: + * numel(y)/N, never the `M` parameter), and nothing is read that the checks above did not + * already require. With the flag unset this is one cached getenv and a return: no copy, no + * latch slot, no new operand read, no syscall. */ + if (r3d_trace_on() && gemm_plan_once(M, N, K, A->rank, AS ? AS->rank : 0u, a_ld, y_ld)) { + std::fprintf(stderr, "[r3d] plan: gemm M=%lld (band M<=%d) N=%lld K=%lld group=%lld " + "a rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld rows=%lld " + "a_scale %s numel=%lld y rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld " + "Mpad=%lld\n", + M, kMTMax, N, K, group, (unsigned)A->rank, r3d_numel(A), + r3d_dim(A, 0), r3d_dim(A, 1), a_ld, arows, + AS ? "rank=2" : "absent (fp8a16, bf16 activations)", + AS ? r3d_numel(AS) : 0LL, (unsigned)Y->rank, r3d_numel(Y), r3d_dim(Y, 0), + r3d_dim(Y, 1), y_ld, (M + 15) / 16 * 16); + r3d_trace_desc("gemm a", A); + r3d_trace_desc("gemm y", Y); + if (AS) r3d_trace_desc("gemm a_scale", AS); + } + + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + int sk = c.sk > 0 ? c.sk : pick_sk(K, (int)group, 16); + if (sk > 16) return R3D_NO(RAD_E_SHAPE); // the scratch hook sizes for 16 + if (K % ((long long)sk * group)) return R3D_NO(RAD_E_SHAPE); + if (sk > 1) { + const long long need = (long long)sk * M * N * 4; + if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH); + } + + const int e = r3d_gemm_nt_q_fp8_ex(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), + r3d_addr(Y), (int)M, (int)N, (int)K, (int)group, (int)pb1, + (int)pb2, (int)a_ld, (int)y_ld, sk, c.nt, + (long)(uintptr_t)(sk > 1 ? a->scratch : nullptr), + (int)BS->dtype, /* bf16 weight_scale_inv or f32 */ + (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE + : e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); +} diff --git a/libr3d/r3d_gemm_fp8a8_gated.hip b/libr3d/r3d_gemm_fp8a8_gated.hip new file mode 100644 index 00000000..9f365467 --- /dev/null +++ b/libr3d/r3d_gemm_fp8a8_gated.hip @@ -0,0 +1,678 @@ +/* r3d_gemm_fp8a8_gated.hip -- gemm_nt_q_gated: the gated MLP's GEMM, its gate and its quantiser in + * one launch. 48 bands on one 2B model (N=12288 K=2048 group=128 dtype=fp8a8 act=silu, M=64 x47 + * and M=16), and the reason the [M, N] bf16 intermediate never exists. + * + * y[M,n] = gate(a[M,K] @ b[N,K]^T), quantised: n = N/2, gate half = b's rows [0, n), + * up half = [n, N). `q` is E4M3 codes over y, `scale` one f32 per (row, `group` of n), and + * `out_bf16`, when bound, is exactly the bf16 the codes were taken over. + * + * The law is ref_gemm_nt_q_gated and it is transcribed in its order: + * + * row[j] = quant_dot(ma, mb, SA, SB, m, j, K) over the FULL N, j ascending + * gt = round_bf16(row[i]), up = round_bf16(row[n + i]) BOTH halves, before the gate + * sg = 1 / (1 + exp(-gt)) the gate is the FIRST half + * h = f32_to_bf16((act == silu ? gt * sg : sg) * up) the activation is not narrowed + * fp8_row(h, n, group) amax -> scale[m, group], codes + * + * Both halves are narrowed before the gate because the unfused pair writes a bf16 [M, N] tensor and + * re-reads it: the fused form must be byte-identical to the pair it replaces, so the narrowing that + * the store performed is kept, and `out_bf16` is what the pair's tensor held. The activation itself + * is NOT narrowed -- `gt * sg` is formed in f32 from the narrowed gate, and the product with `up` + * rounds once, at the store. + * + * ---- the lane map: one lane owns a PAIR of dots ----------------------------------------------- + * + * The gate couples column i with column n + i, and a wave covers 32 consecutive columns, so the + * partner column is 192 waves away for the band's n = 6144: no lane-to-lane exchange reaches it, and + * staging a whole row through LDS to reach it costs a round trip of the [M, N] tensor this op exists + * to avoid. So the lane owns BOTH products of its column: it walks k ascending with two accumulators + * and reads two weight rows, `i` and `n + i`. The weight traffic is unchanged -- the pair of rows is + * exactly the traffic the unfused GEMM spent on the two columns -- and the coupling is free. + * + * A block covers ONE group of `group` output columns and RP = 256 / group rows, so a lane is + * + * i = blockIdx.x * group + (tid % group) m = blockIdx.y * RP + tid / group + * + * and a wave's 32 lanes are 32 consecutive columns of one group of one row, for group >= 32. That + * alignment is what closes the epilogue inside the block: the group's amax is a wave max folded over + * the group's group/32 waves in LDS, the scale is one store, the codes are one byte a lane. The + * whole op -- product, gate, quantiser -- is one launch and no scratch, which is why the row is + * concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`) and why the bf16 row of the + * intermediate is not written, read, or allocated. + * + * ---- the two streams: fp8a8 at M <= 8 reads the codes, the rest stages them ------------------- + * + * The band's served case is a decode: one row, the whole 12288 x 2048 operand, 42 calls a token. + * The shape above is built for the band's declared ceiling (M = 64, 47 of the 48 bands) and serves + * that height well; at M = 1 it spends 987 us on 24 MiB of codes, 25 GB/s, and the reason is not + * the loads. It is the path a code takes: global -> LDS stage -> decode -> dot, with two + * `group_barrier`s per k-block holding the block in step, and a decoder of ten VALU a code (RDNA3 + * has no fp8 instruction: r3d_codecs.h, and the builtins that look like one are rejected at + * instruction selection on gfx1102). + * + * So the arm is chosen by the row count, in the launcher, from the same band key: + * + * M <= 8 and fp8a8 read the activation and both weight rows straight from memory, 16 bytes at + * a time, decode them out of a 256-entry table the block builds once, and + * multiply. No shared memory between a load and a dot, no barrier in the + * k-loop, six loads in flight. + * M >= 9, and every fp8a16 case the shape above, with the same table decoder in place of the + * arithmetic one. At these heights the grid is 48 x M/2 blocks and occupancy, + * not the window, is what feeds the stream; the stage pays for itself. + * + * Measured on the band, vram, GPU 2, nine launches timed on their own, best/median: + * + * M = 1 987.4 / 1154.9 -> 171.3 / 181.6 us (147 GB/s of codes; the card's 163 GB/s + * M = 2 1120.6 / 1196.5 -> 166.2 / 177.1 us floor for 24 MiB is 154 us, and the same + * M = 4 1417.3 / 1581.2 -> 221.0 / 229.6 us sixteen loads with no decode and no dot + * M = 8 1874.0 / 2318.0 -> 403.4 / 412.3 us run in 139 us) + * M = 16 2949.3 / 3226.1 -> 1055.0 / 1160.6 us + * M = 32 5123.4 / 5405.1 -> 1660.6 / 1705.0 us + * M = 64 8395.3 / 9051.0 -> 2786.5 / 2877.3 us + * + * The two numbers behind the shape, both from the band's own stream (24 MiB of codes, vram, 11 + * launches, this kernel's loop with the epilogue off): staged through LDS and decoded arithmetically + * 497 us; read straight and decoded from the table 187 us; the read alone 139 us. The table alone + * moves M = 64 from 8395 us to 2786 us -- two thirds of the tall arm's gain is the decoder, and it + * costs nothing in registers (109 a lane, four waves a SIMD, zero spills). + * + * Two things in this file are load-bearing. The table's argument is a PAIR, not an index (see + * build_e4m3_table). And the decoded pairs go from the table into the dot inline, never through an + * array (see the tall arm's step_body). + * + * ---- where the scale multiplies ------------------------------------------------------------- + * + * quant_dot, unchanged from r3d_gemm_fp8a16_nt_m1.hip: per group of k a sub-sum from zero over + * ascending k of the CODES' products, then `acc = acc + (sub * sa) * sb` -- the parentheses are the + * reference's, the scale multiplies the finished block once, and `sa` is `a_scale[m][gi]` (1 when + * the activation carries no scale plane). Each lane's two chains are the two calls the unfused pair + * makes, so the bracketing is the pair's, element for element. + * + * b_scale is bf16: this op's shape hook writes `o.t(RAD_BF16, {nb, kb})` with no f32 spelling, so + * the plain entry reads the plane as bf16 and the `_ex` twin takes the dtype, as the fp8 GEMM's + * does. bf16 -> f32 widening is exact, so an f32 plane carrying the same values must produce + * bit-identical output; the driver tests exactly that. + * + * ---- the epilogue's one transcendental ------------------------------------------------------- + * + * libref's sigmoid is `1.0f / (1.0f + (float)std::exp((double)(-x)))`. There is no f64 ALU on this + * card (1:64, emulated), and the band asks for M*n = 393216 exponentials a layer, which is + * attention's regime and not the sampler's. `expf` is the accurate device form, as in + * r3d_gated_quant_fp8's kernel (r3d_quant_fp8.hip), not `__expf`; what it feeds is a bf16 + * narrowing, whose ulp is 2^-8 against the transcendental's ~1e-7, so the narrowing lands the same + * bf16 everywhere but on a tie. The count of those ties is in the row's prose, measured. + * + * ---- what the launcher refuses ---------------------------------------------------------------- + * + * M > 64 (the bands' ceiling, and past it the weight stream -- M reads of an [N, K] plane from L2 -- + * is the wall, which is a tiled kernel's problem, not this one's); N odd (the reference's own + * `N & 1` test); a group that is not a power of two in [32, 256] (a wave must sit inside one group, + * and the block is one group wide); group > n, where the reference defaults the QUANTISER's group to + * n and leaves the weight's K block at the stated width: two widths this kernel reads as one, so it + * refuses rather than serve a geometry whose two grids disagree; K % group != 0, because a ragged K + * block reads past the scale plane; sk > 1, because no K slab closes an epilogue that needs the + * whole row. Refusals are codes: -1 null, -2 shape, -3 pitch, -4 HIP. + * + * ---- relayout: none, and it is a claim --------------------------------------------------------- + * + * libref reads the gated weight [N, K] row-major; libr4d stores fp8a8 weights in WMMA fragment order + * (`r4d.fp8.w.frag64`). The two readings are ~1.35 apart, a relative error, not noise, so this row + * carries no relayout and says so: a row that inherits the fp8 GEMM's unrelayout scores 1.35 against + * the per-op oracle and reads as a broken kernel. The stored order is the reading order here, which + * is the library's rule for every row. + */ + +#include // __forceinline__, which r3d_codecs.h's R3D_HD spells + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr int kBlockThreads = 256; +constexpr int kWaves = kBlockThreads / kWave; +constexpr int kStep = 16; // codes a lane takes per step: one 16-byte load +constexpr int kWin = 64; // codes a lane takes per WINDOW: four loads per stream +constexpr int kGroupMin = 32; // a wave's 32 columns must sit inside one group +constexpr int kGroupMax = 256; // a block is one group wide, at 256 threads +constexpr int kMMax = 64; // the bands' ceiling: 47 of the 48 are M = 64 +constexpr float kTopE4M3 = 448.0f; // q8_group's top for E4M3: the largest finite code + +/* The E4M3 decoder as a table: 256 f16, one entry per code. The codec's arithmetic decode is ten + * VALU a code (r3d_codecs.h -- RDNA3 has no fp8 instruction, and the builtins that look like one + * are rejected at instruction selection), and this kernel decodes every weight code it multiplies, + * twice over at RP = 2, which at M = 1 is every code in the operand. The table costs two + * `ds_read_u16` and a pack a PAIR, and it is exact by construction: the entry for code c is the + * dword the arithmetic path returns for c, computed by that path at the block's first instruction. + * The unit test reads all 256 entries back and compares them with the codec. */ +__device__ __forceinline__ void build_e4m3_table(uint16_t* tab, uint32_t tid) +{ + for (uint32_t u = tid; u < 128; u += kBlockThreads) + /* The codec's argument is a PAIR, low code in the low byte; the entry is indexed by code. + * Feeding it the index alone fills the even entries and decodes code 0 into every odd one, + * so the kernel multiplies half the plane by zero -- the board's `codes256` case, whose + * weight is the code enumeration, shows it: rel_l2 9.6e-01, not a NaN. */ + *(uint32_t*)&tab[2 * u] = e4m3x2_to_f16x2((u * 2) | ((u * 2 + 1) << 8)); +} + +__device__ __forceinline__ uint32_t tab_pair(const uint16_t* tab, uint32_t pair) +{ + const uint32_t lo = *(const uint16_t __attribute__((address_space(3))) *)(tab + (pair & 0xffu)); + const uint32_t hi = *(const uint16_t __attribute__((address_space(3))) *)(tab + (pair >> 8)); + return lo | (hi << 16); +} + +/* One step of the skinny arm: sixteen codes of activation and sixteen of weight, both coded, both + * out of the same table. This is the whole of the reference's inner step -- `sub += a[k] * b[k]`, + * k ascending -- with the pairs decoded as each dot consumes them. Four dot4, the pairs in order, + * one accumulator; nothing about it depends on where the bytes came from. */ +__device__ __forceinline__ float dot_coded_step(const uint16_t* tab, const r3d_u32x4 a, + const r3d_u32x4 c, float sub) +{ + sub = dot4_f16x4(tab_pair(tab, a.x & 0xffffu), tab_pair(tab, a.x >> 16), + tab_pair(tab, c.x & 0xffffu), tab_pair(tab, c.x >> 16), sub); + sub = dot4_f16x4(tab_pair(tab, a.y & 0xffffu), tab_pair(tab, a.y >> 16), + tab_pair(tab, c.y & 0xffffu), tab_pair(tab, c.y >> 16), sub); + sub = dot4_f16x4(tab_pair(tab, a.z & 0xffffu), tab_pair(tab, a.z >> 16), + tab_pair(tab, c.z & 0xffffu), tab_pair(tab, c.z >> 16), sub); + sub = dot4_f16x4(tab_pair(tab, a.w & 0xffffu), tab_pair(tab, a.w >> 16), + tab_pair(tab, c.w & 0xffffu), tab_pair(tab, c.w >> 16), sub); + return sub; +} + +/* One step's sixteen codes into the accumulator: four dot4, the pairs decoded out of the table as + * each dot consumes them. Materialising the eight pairs first and feeding the dots from the array + * is what the register file cannot afford here: the scheduler hoists the sixteen table reads, so + * all eight decoded pairs are live at once on top of the window's loads. Consuming a pair in the + * dot that wants it keeps two registers live where the array keeps eight -- which is the + * difference between this arm compiling at zero spills and spilling 374 bytes against the + * 128-register budget a 256-thread block gets at four waves a SIMD. The order is unchanged: the + * pairs ascend, four dot4 a step, into one accumulator. */ +__device__ __forceinline__ float dot_step(const uint16_t* tab, const r3d_u32x4 c, + const r3d_u32x4 a0, const r3d_u32x4 a1, float sub) +{ + sub = dot4_f16x4(a0.x, a0.y, tab_pair(tab, c.x & 0xffffu), tab_pair(tab, c.x >> 16), sub); + sub = dot4_f16x4(a0.z, a0.w, tab_pair(tab, c.y & 0xffffu), tab_pair(tab, c.y >> 16), sub); + sub = dot4_f16x4(a1.x, a1.y, tab_pair(tab, c.z & 0xffffu), tab_pair(tab, c.z >> 16), sub); + sub = dot4_f16x4(a1.z, a1.w, tab_pair(tab, c.w & 0xffffu), tab_pair(tab, c.w >> 16), sub); + return sub; +} + + +template +__device__ __forceinline__ r3d_u32x4 ldc(const uint8_t* p) // 16 codes +{ + if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p; + else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); +} + +__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p) { return *(const r3d_u32x4*)p; } + +/* q8_group's clamp, with q8_group's comparisons: fminf/fmaxf replace a NaN with the bound, and a NaN + * activation is a value the reference encodes as the format's NaN, not as +-top. */ +__device__ __forceinline__ float clamp_top(float c) +{ + if (c > kTopE4M3) c = kTopE4M3; + if (c < -kTopE4M3) c = -kTopE4M3; + return c; +} + +/* y[M,n] = gate(a @ b^T), with the quantiser. GROUP is the block's width in output columns AND the + * weight's K block AND the quantiser's group: one `group` parameter, three grids, which is what the + * op states: kb, nb and ng are derived from the one key. ACT is the gate, A8 the coded activation, + * NT the weight load's lowering. + * + * The activation is staged in LDS per K block, widened to f16 pairs on the way in -- E4M3 -> f16 and + * bf16 -> f16 are both exact over f16's normal range. A block stages RP * GROUP values, 512 bytes at + * every supported GROUP, and a wave reads its row's 16 values per step as one broadcast ds_read: all + * 32 lanes of a wave own the same m, so all 32 read the same address. The weight is not staged: a + * lane streams two rows of it and no other lane reads them with it. */ +template +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_kernel( + const uint8_t* __restrict__ A, const float* __restrict__ AScale, + const uint8_t* __restrict__ B, const void* __restrict__ BScale, int bs16, + uint8_t* __restrict__ Q, float* __restrict__ S, uint16_t* __restrict__ Y, + int M, int N, int K, int a_ld, int q_ld, int y_ld, int nkb, int ng) +{ + constexpr int RP = kBlockThreads / GROUP; // rows a block carries + constexpr int AP = GROUP / 2; // dwords a staged activation row (f16 pairs) + constexpr int WPG = GROUP / kWave; // waves covering one group of columns + static_assert(RP >= 1 && WPG >= 1 && RP * WPG == kWaves, "a block is one group wide"); + + __shared__ uint32_t s_a[RP * AP]; + __shared__ float s_mx[kWaves]; + __shared__ uint16_t s_tab[256]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + + /* The block's decoder, filled before any lane reads it: 128 dwords, one per pair of codes, by + * the codec's own arithmetic. The cost is 128 decodes a block -- at the band's M = 64 that is + * 0.02% of the block's decodes, and at M = 1 it is paid once per block for 128 codes x 16 k + * blocks of table reads. */ + build_e4m3_table(s_tab, tid); + group_barrier(); + + const uint32_t gidx = blockIdx.x; // the group of output columns + const uint32_t mloc = tid / GROUP; // this lane's row within the block + const uint32_t i = gidx * GROUP + (tid % GROUP); // the fused column + const uint32_t m = (uint32_t)blockIdx.y * RP + mloc; + + const int n = N / 2; + /* A ragged last group runs past n: the pair's rows are clamped, so no lane reads past the weight + * plane, and its stores are guarded below. A row past M re-reads the last real row. */ + const int i_real = (int)(i < (uint32_t)n ? i : (uint32_t)(n - 1)); + const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1)); + + const uint8_t* wg = B + (size_t)i_real * K; // the gate's row + const uint8_t* wu = B + (size_t)(n + i_real) * K; // the up's row, n rows further on + /* b_scale is [ceil(N/group)][ceil(K/group)]: make_scales gives rblk = group (fewer scale rows + * than operand rows is a block grid), so a row's scale row is its row index over the block. */ + const size_t bsg = (size_t)((uint32_t)i_real / GROUP) * (size_t)nkb; + const size_t bsu = (size_t)((uint32_t)(n + i_real) / GROUP) * (size_t)nkb; + const float* bsF = bs16 ? nullptr : (const float*)BScale; + const uint16_t* bsH = bs16 ? (const uint16_t*)BScale : nullptr; + const float* as = A8 ? AScale + (size_t)m_real * nkb : nullptr; + + float acc_g = 0.0f, acc_u = 0.0f; + + /* One scale block per round, `nkb` of them: stage the block's activation, walk the block's k + * with two chains, fold the block's two scales in at the block's end. K is a multiple of GROUP, + * which the launcher requires, so every block is whole and the staging loop has no tail. */ + /* The skinny arm's activation pointer: the row, in bytes. */ + const uint8_t* ar = (A8 && WIN) ? (const uint8_t*)A + (size_t)m_real * a_ld : nullptr; + + for (int kb = 0; kb < K; kb += GROUP) { + const int gi = kb / GROUP; + /* The staged round, and the barrier around it, belong to the tall arms. At the skinny height + * -- M <= 8, the threshold `R3D_GT_G` selects on, 16 KiB of activation at the band's K -- + * the whole activation is M*K bytes and the 48 column groups of a row all + * read the same slice of it, so it lives in L1 from the first k-block on and staging it + * through shared memory buys nothing but a barrier a block a k-block. The numbers: the + * same stream read straight from memory 187 us, the same stream staged through LDS 497 us, + * at 48 blocks, 24 MiB of codes, on a part of this family. */ + if constexpr (!WIN) { + constexpr int kUnit = 8; // codes (fp8a8) or elements (bf16) a unit + constexpr int nu = GROUP / kUnit; +#pragma unroll + for (int u = (int)tid; u < RP * nu; u += kBlockThreads) { + const int r = u / nu, c = (u % nu) * kUnit; + const int rm = (int)((uint32_t)blockIdx.y * RP + (uint32_t)r); + const int rr = rm < M ? rm : M - 1; + uint32_t* dst = s_a + (size_t)r * AP + c / 2; + if constexpr (A8) { + const r3d_u32x2 b8 = *(const __attribute__((address_space(1))) r3d_u32x2*)( + A + (size_t)rr * a_ld + kb + c); + dst[0] = e4m3x2_to_f16x2(b8.x & 0xffffu); + dst[1] = e4m3x2_to_f16x2(b8.x >> 16); + dst[2] = e4m3x2_to_f16x2(b8.y & 0xffffu); + dst[3] = e4m3x2_to_f16x2(b8.y >> 16); + } else { + /* Cast to the element pointer FIRST: the row and k offsets are ELEMENT offsets, + * which for bf16 is twice the byte count (r3d_gemm_fp8a16_nt_m1.hip). */ + const r3d_u32x4 b16 = *(const __attribute__((address_space(1))) r3d_u32x4*)( + (const uint16_t*)A + (size_t)rr * a_ld + kb + c); + dst[0] = bf16x2_to_f16x2(b16.x); + dst[1] = bf16x2_to_f16x2(b16.y); + dst[2] = bf16x2_to_f16x2(b16.z); + dst[3] = bf16x2_to_f16x2(b16.w); + } + } + group_barrier(); + + } + + const uint32_t* ap = s_a + (size_t)mloc * AP; + /* One chain at a time. The gate's product, k ascending into `sub_g`, then the up's into + * `sub_u` -- the two chains are the two calls the unfused pair makes, they share nothing, + * and each one's bracketing is that call's, element for element. + * + * Sequencing them, rather than interleaving them step by step, is what the register file + * asks for. The window is eight 16-byte loads a stream; holding both streams' windows + * live at once is 64 registers of loads on top of the decode's temporaries, the staged + * activation's reads, the two accumulators and the block's pointers, and at 256 threads + * (four waves a SIMD, 128 registers a lane) it spills 365 bytes. One chain's window is + * 32 registers, and the arm compiles clean. + * + * On the band's stream -- 24 MiB of codes, vram, 11 launches, GPU 2, this kernel's loop + * with the epilogue off: 16-byte step with the arithmetic decoder 584 us; table decoder, + * same step 453 us; table, window 64 283 us; table, window 128 187 us; the same sixteen + * loads with no decode and no dot 139 us. The op without the table decoder and the window + * spends 1474 us a call. */ + float sub_g, sub_u; + if constexpr (WIN) { + /* The skinny arm, M <= 8 (the threshold `R3D_GT_G` selects on): read the codes, decode + * them out of the block's table, multiply + * them. No shared memory between the load and the dot, and no barrier in the k-loop -- + * the two chains, gate then up, k ascending inside each, the scales folded at the block's + * end, the epilogue below untouched. + * + * Three loads a step, sixteen bytes each: the activation's sixteen codes, the gate's, + * the up's. Six of them are in flight at the depth below, against the 163 GB/s the card + * does; the tall arms feed the same stream with occupancy, at 32 waves a CU. + * + * On this band's stream (24 MiB of codes, vram, 11 launches, GPU 2, epilogue off): + * the staged shape 497 us; the same codes read straight 187 us; the same sixteen loads + * with no decode and no dot 139 us. The op without the table decoder and the window + * spends 1474 us a call. */ + constexpr int kNS = GROUP / kStep; // steps a block + constexpr int kD = 2; // loads a chain in flight + auto chain = [&](const uint8_t* w, float sub) { + auto ld = [&](int st) { + return ldc(w + kb + (st < kNS ? st : kNS - 1) * kStep); + }; + /* Named registers, not an array: an array indexed across a round -- even with the + * round count constant and the loop marked for unrolling -- puts the codes in the + * private segment, 572 bytes a lane, and every code crosses scratch on its way from + * the load to the dot. Two named dwords-in-four, prefetched two steps ahead, keep + * the same six loads in flight and the frame at zero. */ + r3d_u32x4 c0 = ld(0), c1 = ld(1); +#pragma unroll + for (int st = 0; st < kNS; st += kD) { + __builtin_amdgcn_sched_barrier(0); + const r3d_u32x4 a0 = ldc(ar + kb + (st + 0) * kStep); + const r3d_u32x4 a1 = ldc(ar + kb + (st + 1) * kStep); + const r3d_u32x4 n0 = ld(st + kD + 0), n1 = ld(st + kD + 1); + sub = dot_coded_step(s_tab, a0, c0, sub); + sub = dot_coded_step(s_tab, a1, c1, sub); + c0 = n0; + c1 = n1; + } + return sub; + }; + sub_g = chain(wg, 0.0f); + sub_u = chain(wu, 0.0f); + } else { + /* The tall arms: one 16-code step a round, both streams in the same round. + * At M >= 8 the block grid is 48 x M/2 blocks, the wave slots are full, and the stream + * is fed by occupancy -- 109 registers a lane, four waves a SIMD, 32 waves a CU. The + * window is a skinny-arm fix: it buys its loads per lane at 32 registers, which on + * this arm is a fifth wave a SIMD given up, and on the 47 bands at M = 64 that is the + * whole op. Measured: windowed at M = 64 costs more than it saves. */ + sub_g = 0.0f; + sub_u = 0.0f; + /* The round's unroll depth is a register decision, and at group = 32 it is the whole + * decision: the block is two steps wide, so `unroll 2` is a full unroll, the scheduler + * takes all thirty-two table reads of the two chains and hoists them above the dots, + * and the arm lands at 128 registers with 12 spilled (the same arm at group >= 64, in + * the same file, is 106 to 112 with none). Left as a loop the body is one step. */ + /* Inline, from the table into the dot, on purpose. Materialising the eight decoded + * pairs into an array on the way -- the shape the arithmetic decoder above feeds -- + * puts the plane about a third away from the reference at every tall height (M = 7: + * rel_l2 6.6e-01; M = 64: -nan), with the table itself exact on the device, entry by + * entry and pair by pair. The array form is the one that miscomputes here; do not + * restore it as a tidy-up. */ + auto step_body = [&](int k) { + const r3d_u32x4 a0 = lds_a(ap + k / 2); + const r3d_u32x4 a1 = lds_a(ap + k / 2 + 4); + sub_g = dot_step(s_tab, ldc(wg + kb + k), a0, a1, sub_g); + sub_u = dot_step(s_tab, ldc(wu + kb + k), a0, a1, sub_u); + }; + if constexpr (GROUP <= 32) { +#pragma unroll 1 + for (int k = 0; k < GROUP; k += kStep) step_body(k); + } else { +#pragma unroll 2 + for (int k = 0; k < GROUP; k += kStep) step_body(k); + } + } + if constexpr (!WIN) + group_barrier(); // the next block's stage must not race this one's reads + + /* The two finished sub-sums, each scaled once, in libref's parentheses. */ + const float sa = A8 ? as[gi] : 1.0f; + acc_g = acc_g + (sub_g * sa) * (bs16 ? bf16_to_f32(bsH[bsg + gi]) : bsF[bsg + gi]); + acc_u = acc_u + (sub_u * sa) * (bs16 ? bf16_to_f32(bsH[bsu + gi]) : bsF[bsu + gi]); + } + + /* ---- the epilogue: narrow both halves, gate, quantise the group -------------------------- */ + const float gt = bf16_to_f32(f32_to_bf16(acc_g)); + const float up = bf16_to_f32(f32_to_bf16(acc_u)); + const float sg = 1.0f / (1.0f + expf(-gt)); + const uint16_t h = f32_to_bf16((ACT == R3D_ACT_SILU ? gt * sg : sg) * up); + + const bool keep = (i < (uint32_t)n) && (m < (uint32_t)M); + if (keep && Y) Y[(size_t)m * y_ld + i] = h; + /* A column past n, and a row past M, contribute 0.0f: padding takes no part in the amax and + * takes no store, which is quant_act_fp8's rule for a ragged row. */ + const float am = keep ? fabsf(bf16_to_f32(h)) : 0.0f; + + float mx = wave_max(am); // fmaxf skips a NaN, as `if (m > amax)` does + if (lane == 0) s_mx[wave] = mx; + group_barrier(); + mx = s_mx[mloc * WPG]; +#pragma unroll + for (int w = 1; w < WPG; ++w) mx = fmaxf(mx, s_mx[mloc * WPG + w]); + + const float sc = mx > 0.0f ? mx * (1.0f / kTopE4M3) : 1.0f; + /* One store per (row, group): the group's WPG waves all hold the same max, so the first writes + * and the rest stand down. `scale` is dense -- the launcher takes no pitch for it -- so a row is + * `ng` scales and the group index is the block's. */ + if (keep && lane == 0 && (wave % WPG) == 0) S[(size_t)m * ng + gidx] = sc; + + if (keep) { + const float inv = 1.0f / sc; + Q[(size_t)m * q_ld + i] = f32_to_e4m3(clamp_top(bf16_to_f32(h) * inv)); + } +} + +} // namespace + +/* y[M,n] = gate(a[M,K] @ dequant(b)[N,K]^T), E4M3 codes out, n = N/2 inside. + * + * a [M][K] E4M3 codes (fp8a8, with `a_scale`) or bf16 (fp8a16) + * a_scale [M][ceil(K/group)] f32, dense, or 0 + * b [N][K] E4M3 codes, row-major, k contiguous: gate rows [0,n), up rows + * [n,N) + * b_scale [ceil(N/group)][ceil(K/group)] bf16 (the op's stated dtype) or f32, block-major + * q [M][n] E4M3 codes, `q_ld` elements a row (0 = n) + * scale [M][ceil(n/group)] f32, DENSE (no pitch is taken) + * out_bf16 [M][n] bf16, `y_ld` elements a row (0 = n), optional: the pre-gate... + * the gated bf16 tensor the codes were taken over + * + * `group` is the weight's K block, the weight's row block and the output quantiser's group at once, + * which is what the op's single key states; 0 takes the checkpoint's 128. `act` is R3D_ACT_SILU + * (down_proj's input) or R3D_ACT_SIGMOID (a gated attention o_proj's). `sk` is accepted as 0/1 and + * refused above it: the epilogue needs a whole row. `nt` selects the weight load's lowering. + * `scratch` is unused -- the op needs no arena, which is what keeps the row concurrent. + * + * Returns 0, -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 HIP + * failed. */ +extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale, long q, long scale, + long out_bf16, int M, int N, int K, int group, int act, + int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch, + int bs_dt, long stream) +{ + if (!a || !b || !b_scale || !q || !scale) return -1; + if (M < 1 || N < 2 || (N & 1) || K < 1) return -2; + if (M > kMMax) return -2; + if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return -2; + const int n = N / 2; + if (group <= 0) group = R3D_FP8_BLOCK; + if (group > n) return -2; // two grids, one key: see the header + if (group < kGroupMin || group > kGroupMax || (group & (group - 1))) return -2; + if (K % group) return -2; // a ragged block reads past the scales + const int nkb = K / group, ng = (n + group - 1) / group; + if (!a_ld) a_ld = K; + if (!q_ld) q_ld = n; + if (!y_ld) y_ld = n; + if (a_ld % 8) return -3; // 8-code (and 8-element) staging + if (sk == 0) sk = 1; + if (sk > 1) return -2; // no K slab closes this epilogue + (void)scratch; + + const int bs16 = (bs_dt == RAD_BF16); /* anything else, 0 included, reads the plane as f32 */ + const int a8 = a_scale != 0; + const int rp = kBlockThreads / group; + const dim3 grid((unsigned)ng, (unsigned)((M + rp - 1) / rp)), blk(kBlockThreads); + +/* The skinny arms -- the decode's height -- take the windowed stream; the tall arms keep + * the step. One number, two kernels, and the band key that names them is the same one. + * + * M <= 8 is the shipped threshold and it is a tunable, not a fact. With the table decoder in both + * arms, N=12288 K=2048 group=128 vram: at M=8 skinny 402 against staged 754, at M=16 skinny 955 + * against staged 1030 -- so the crossover is above 16; M=9..15 is unmeasured. Decode lives at M=1 + * and a draft's verify at M<=8, which is what the threshold is chosen for; a prefill at 9..16 rows + * would take the skinny arm on the M=16 numbers, for about 7%. */ +#define R3D_GT_G(G, A, A8, NTV) \ + do { \ + if (A8 && M <= 8) R3D_GT_W(G, A, A8, NTV, true); \ + else R3D_GT_W(G, A, A8, NTV, false); \ + } while (0) +#define R3D_GT_W(G, A, A8, NTV, WV) \ + R3D_KLAUNCH(R3D_KNAME((gated_kernel)), grid, blk, (hipStream_t)stream, \ + (const uint8_t*)a, (const float*)a_scale, (const uint8_t*)b, \ + (const void*)b_scale, bs16, (uint8_t*)q, (float*)scale, (uint16_t*)out_bf16, \ + M, N, K, a_ld, q_ld, y_ld, nkb, ng) +#define R3D_GT_NT(G, A, A8) do { if (nt) R3D_GT_G(G, A, A8, true); else R3D_GT_G(G, A, A8, false); } while (0) +#define R3D_GT_A8(G, A) do { if (a8) R3D_GT_NT(G, A, true); else R3D_GT_NT(G, A, false); } while (0) +#define R3D_GT_ACT(G) do { if (act == R3D_ACT_SILU) R3D_GT_A8(G, R3D_ACT_SILU); \ + else R3D_GT_A8(G, R3D_ACT_SIGMOID); } while (0) +#define R3D_GT(G) do { switch (group) { case G: R3D_GT_ACT(G); break; default: break; } } while (0) + R3D_GT(32); + R3D_GT(64); + R3D_GT(128); + R3D_GT(256); +#undef R3D_GT +#undef R3D_GT_ACT +#undef R3D_GT_A8 +#undef R3D_GT_NT +#undef R3D_GT_W +#undef R3D_GT_G + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The declaration in r3d.h carries no scale dtype, and this op's shape hook states bf16 -- the hook + * has no f32 spelling at all -- so the plain entry reads bf16 and the `_ex` twin above carries the + * key. A caller with an f32 scale plane (the `fp8a8f32` reading of the unfused GEMM) lands on `_ex` + * with RAD_F32; the kernel widens bf16 -> f32 exactly, so the two agree to the bit. */ +extern "C" int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, long q, long scale, + long out_bf16, int M, int N, int K, int group, int act, + int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch, + long stream) +{ + return r3d_gemm_nt_q_gated_ex(a, a_scale, b, b_scale, q, scale, out_bf16, M, N, K, group, act, + a_ld, q_ld, y_ld, sk, nt, scratch, RAD_BF16, stream); +} + +/* ============================================================== the plugin ABI entry point + * + * gemm_nt_q_gated's operands are [a, a_scale, b, b_scale, q, scale, out_bf16?] and its parameters + * M, N, K, group, dtype, act (libref's pGemmQGated/oGemmQGated: `act` REQUIRED, `a_scale` REQUIRED, + * `out_bf16` optional). The shape hook declines every scheme but fp8a8, so the row binds fp8a8 and + * the shim reads the coded activation off the operands. */ +enum { G_A = 0, G_ASCALE, G_B, G_BSCALE, G_Q, G_SCALE, G_OB }; + +#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0) +static int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; } +static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; } +static int dt_e4m3(const RadTensor* t) { return r3d_is_e4m3(t) ? RAD_OK : RAD_E_DTYPE; } + +extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s) +{ + const RadTensor* A = r3d_opt(a, G_A); + const RadTensor* AS = r3d_opt(a, G_ASCALE); + const RadTensor* B = r3d_opt(a, G_B); + const RadTensor* BS = r3d_opt(a, G_BSCALE); + const RadTensor* Q = r3d_opt(a, G_Q); + const RadTensor* SC = r3d_opt(a, G_SCALE); + const RadTensor* OB = r3d_opt(a, G_OB); + if (!A || !B || !BS || !Q || !SC) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_e4m3(B)) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_e4m3(Q)); + R3D_NEED(dt_f32(SC)); + if (OB) R3D_NEED(dt_bf16(OB)); + /* The activation: E4M3 codes with a per-(row, group) f32 scale (fp8a8, the scheme this op's + * shape hook and every band states), or bf16 with no scale (fp8a16, which the hook declines, so + * no band arrives: the kernel carries the path because the launcher does, and the shim accepts + * it on the operands). E5M2 has no decoder here. */ + const bool a8 = AS != nullptr; + if (a8) { + if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_f32(AS)); + } else { + R3D_NEED(dt_bf16(A)); + } + /* b_scale is bf16 -- `o.t(RAD_BF16, {nb, kb})` is this op's own line in the hook, and the + * container's `weight_scale_inv` for the whole quantised family. f32 is accepted because the + * widening is exact and the kernel reads both: the driver's bf16/f32 pair must agree element + * for element. */ + const bool bs16 = r3d_is_bf16(BS); + if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE); + + /* `act` is required by the schema (P_STR, not P_STRO): an implementation may compile one gate, + * and an optional parameter would let the row resolve for the other. libref's default is -1 and + * it refuses it; so does this shim, with no `mode` integer spelling to fall back on. */ + const int act = r3d_act_code(a, "act", nullptr, -1); + if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return R3D_NO(RAD_E_INVAL); + + const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1)); + const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2)); + if (K < 1 || N < 2 || (N & 1)) return R3D_NO(RAD_E_SHAPE); + const long long n = N / 2; + + /* Rows come from `q`, never from the `M` parameter, which is the band's upper bound. libref + * reads numel(q) / n; on a plane whose pitch exceeds n that counts the padding, so the shape's + * own row count clamps it. A dense plane -- every case the fixture draws -- reads the same + * number either way. */ + const long long qnel = r3d_numel(Q); + if (qnel < n || qnel % n) return R3D_NO(RAD_E_SHAPE); + long long M = qnel / n; + if (Q->rank >= 2 && r3d_dim(Q, (int)Q->rank - 2) < M) M = r3d_dim(Q, (int)Q->rank - 2); + if (M < 1 || M > kMMax) return R3D_NO(RAD_E_SHAPE); + + /* The group: the weight's K block, the weight's row block and the quantiser's group, from the + * one key the op states. The reference defaults 0 to `group`-as-stated for the grids and + * `g > n` to n for the quantiser alone; this kernel reads one width, so a group wider than the + * fused width is refused rather than served on a grid the two sides do not share. */ + const long long group = r3d_geti_or(a, "group", R3D_FP8_BLOCK); + if (group < kGroupMin || group > kGroupMax || (group & (group - 1))) return R3D_NO(RAD_E_SHAPE); + if (group > n) return R3D_NO(RAD_E_SHAPE); + if (K % group) return R3D_NO(RAD_E_SHAPE); + const long long nkb = K / group, nb = (N + group - 1) / group, ng = (n + group - 1) / group; + if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(BS) < nb * nkb) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(SC) < M * ng) return R3D_NO(RAD_E_SHAPE); + if (AS && r3d_numel(AS) < M * nkb) return R3D_NO(RAD_E_SHAPE); + if (OB && r3d_numel(OB) < M * n) return R3D_NO(RAD_E_SHAPE); + + long long arows = 0, qrows = 0, srows = 0, yrows = 0; + const long long a_ld = r3d_rows_pitch(A, K, &arows); + const long long q_ld = r3d_rows_pitch(Q, n, &qrows); + const long long y_ld = OB ? r3d_rows_pitch(OB, n, &yrows) : n; + if (a_ld < 0 || q_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE); + /* `yrows` is only a promise when the plane is there. `r3d_rows_pitch` leaves the count at zero + * for a null operand, and an absent optional output is a null operand by contract (r3d_args.h), + * so testing `yrows` unconditionally reads "the row is missing" from "the caller asked for no + * bf16 mirror". */ + if (arows < M || qrows < M || (OB && yrows < M)) return R3D_NO(RAD_E_SHAPE); + if (a_ld % 8) return R3D_NO(RAD_E_STRIDE); // 8-code / 8-element staging + /* The scale planes travel without a pitch argument, so they must be dense, and `scale`'s grid + * must be the one the kernel walks: `ng` scales a row. */ + if (!r3d_contig(B) || !r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE); + if (AS && !r3d_contig(AS)) return R3D_NO(RAD_E_STRIDE); + if (r3d_rows_pitch(SC, ng, &srows) != ng) return R3D_NO(RAD_E_STRIDE); + if (srows < M) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(BS, 1) != 0 && BS->shape[BS->rank - 1] != nkb && r3d_numel(BS) != nb * nkb) + return R3D_NO(RAD_E_SHAPE); + if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN); + + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + /* Split-K is the axis this kernel cannot honour: a K slab produces a partial product, and the + * epilogue needs the finished row -- its bf16 narrowing, the gate's partner column, the group's + * amax. A caller that states sk > 1 is refused here, at the row, not answered slowly. */ + if (c.sk > 1) return R3D_NO(RAD_E_SHAPE); + + const int e = r3d_gemm_nt_q_gated_ex( + r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(Q), r3d_addr(SC), + r3d_addr(OB), (int)M, (int)N, (int)K, (int)group, act, (int)a_ld, (int)q_ld, (int)y_ld, 1, + c.nt, 0L, (int)BS->dtype, (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE + : e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); +} diff --git a/libr3d/r3d_gemm_fp8a8_tiled.hip b/libr3d/r3d_gemm_fp8a8_tiled.hip new file mode 100644 index 00000000..7ec9ce39 --- /dev/null +++ b/libr3d/r3d_gemm_fp8a8_tiled.hip @@ -0,0 +1,1200 @@ +/* r3d_gemm_fp8a8_tiled.hip -- gemm_nt_q at prefill M, fp8a8, on a tiled f16 dot. + * + * ---- why this row exists ------------------------------------------------------------------------ + * + * The graph, at the vocabulary head: + * + * W placement: 'blk.0.attn_norm.weight' is grouped with a weight only a host kernel can read, so + * the whole group stays in the container's mapping + * E rank 0: 'blk.0.attn_norm.weight' was placed on the mapped tier, which reads the container + * where it lies, and its stored form is not the container's (widened at load) + * + * The chain is arithmetic, not policy: `gemm_nt_q` has no device row at prefill M, so its bands + * resolve to a host kernel, so the layer's weights stay in the container's mapping, so the layer's + * NORM weights are grouped with them, so the mapped tier is asked to perform the widening the norms' + * stored form needs, so startup stops. `--placement all_vram` is already the default and there is no + * grouping flag. The row that breaks the chain is the one the README names: the tiled + * quantised GEMM at prefill M. This file is that row. + * + * ---- the bands (42 layers + the drafter, per --debug-graph) ------------------------------------- + * + * gemm_nt_q N=12288 K= 2048 group=128 dtype=fp8a8 M=2048 x44 the gated MLP, 2 x 6144 + * gemm_nt_q N= 2560 K= 2048 group=128 dtype=fp8a8 M=2048 x44 qkv: 2048 + 2 x 256 + * gemm_nt_q N= 2048 K= 6144 group=128 dtype=fp8a8 M=2048 x44 o-proj + * gemm_nt_q N= 2048 K= 2048 group=128 dtype=fp8a8 M=2048 x44 + * gemm_nt_q N= 2048 K=10240 group=128 dtype=fp8a8 M=2048 x3 the drafter + * + * M=16 and M=1 are served, by gemm_nt_q_fp8a8_m16. The vocab prefill (N=130560 dtype=w2a8 M=1792) is + * the 2-bit grid and not this row's. Constraints bind the BAND's keys: dtype in {fp8a8}, group == + * 128, M >= 17, K % 128. Below M=17 the m16 rows are the served path and this row says so. The floor + * is `kMMin`, and it is the sibling row's declared ceiling plus one; the w2a8 arm below carries the + * same floor, with the reason for it. + * + * ---- the law, transcribed ----------------------------------------------------------------------- + * + * gemm_nt_q's law, in the registry: "The group sub-sum is accumulated from the raw codes and scaled + * once per group, which is what an int8 or fp8 WMMA kernel does." In code, the reference's + * quant_dot -- the same body r3d_gemm_fp8a8_gated.hip and r3d_gemm_fp8a16_nt_m1.hip carry: + * + * for g in groups: sub = 0 + * for k in g, ascending: sub = sub + code_a[m][k] * code_b[n][k] + * acc = acc + (sub * a_scale[m][g]) * b_scale[n/128][g] + * + * The codes are the raw E4M3 values, widened exactly into f32; the scale multiplies the finished + * block ONCE, and the parentheses are the reference's. Operands, from gemm_q_shape, in schema + * order: a E4M3 {M,K}; a_scale F32 {M, ceil(K/group)}; b E4M3 {N,K} (the checkpoint's own bytes); + * b_scale BF16 {ceil(N/group), ceil(K/group)} -- f32 at fp8a8f32; y BF16 {M,N}; a_sum ABSENT for + * fp8a8 because fp8a8 is symmetric; b_ref absent. y is bf16 with one narrowing at the store, f32 + * accumulate throughout. + * + * ---- the fold, and where it goes ---------------------------------------------------------------- + * + * The tile is f16, so the two scale streams enter as f16 multiplies at staging: the activation's + * `a_scale[m][g]` per staged row, the weight's `b_scale[nb][g]` once a chunk -- TN is 128, the scale + * plane's row extent, so a tile is one scale-row, and kKC 32 divides 128, so a chunk sits inside one + * k-block. The products are separable: (a*sa)*(b*sb) = (a*b)*sa*sb, so folding each side is the same + * sum, formed a different way, and the accumulator stays one f32 register per output -- 64 a lane. + * The alternative, a per-group partial scaled into the accumulator, needs 64 more registers on an arm + * that is at 237 VGPRs, and spills. + * + * The fold goes through v_mul_f16, never through f16x2_pack. That builtin is v_cvt_pkrtz_f16_f32, + * rounds toward zero, and r3d_codecs.h restricts it to values f16 represents exactly; a folded + * product is not one, and on the vocabulary head the truncation measured rel_l2 2.8e-04 against the + * fold law with 0.53 of outputs inside 2 ulps, where the f16 multiply gives 4.5e-06 and 1.000. + * + * Against the reference's law the fold costs the two f16 roundings of the staged values: measured + * rel_l2 2.77e-04 at the head's band, which is half an f16 ulp (2^-12 = 2.44e-04) and 250x finer than + * the E4M3 code's own quantum (2^-4). Against a model of the fold itself it is 4.5e-06 -- the dot's + * fused rounding, the pair-dot folding two products into the accumulator per step. This row's board + * reports both numbers, per band. + * + * ---- the decoder is a table, and that is measured ---------------------------------------------- + * + * gfx11 has no fp8->f16 instruction: clang lists __builtin_amdgcn_cvt_pk_f16_fp8 and a gfx1102 build + * that calls it contains zero of them in its ISA, so the builtin is software. r3d_fp8_dequant.h + * replaces the codec with a 256-entry f16 table in LDS, 512 bytes, eight reads an eight-code group. + * Measured on the vocabulary head's bands (the A/B is one source, -DR3D_NO_E4M3_TBL for the codec): + * M=8 speculation 2.500 -> 0.924 ms a token, 2.70x; M=2048 prefill 323.978 -> 322.661 ms, flat; and + * M=1 12.999 -> 13.293 ms, NOT moved: at M=1 the decoder is not the binding resource, and the + * limiting access there is the 8-byte code load, not the ALU. + * + * ---- what the board measures -------------------------------------------------------------------- + * + * Five bands, M=2048, GPU 2 (RX 7600, gfx1102, 32 CU), the container managed with its pages + * prefetched to the card, every number on a placement line: + * + * N=12288 K= 2048 28.171 ms 3659 GFLOP/s 0.0138 ms/token the gated MLP, x44 + * N= 2560 K= 2048 5.911 ms 3633 GFLOP/s 0.0029 ms/token qkv 2048 + 2 x 256 + * N= 2048 K= 6144 14.699 ms 3506 GFLOP/s 0.0072 ms/token o-proj, x44 + * N= 2048 K= 2048 4.381 ms 3922 GFLOP/s 0.0021 ms/token x44 + * N= 2048 K=10240 29.798 ms 2883 GFLOP/s 0.0145 ms/token the drafter, x3 + * + * 2883-3922 GFLOP/s is 27-36% of this card's dense f16 peak (10.8 TFLOP/s), above the vocabulary + * head's fp8 3369 and within 4% of its bf16 4067. The bytes floor is 0.051-0.257 ms a band at the + * 163 GB/s the head's row streams, and 2MNK/(K+N) is ~1900 flops a byte at M=2048: prefill is + * compute-bound here, as it should be, and these bands are the box's fp8a8 prefill numbers. + * + * The floors, as the gate uses them. The fold's is 2^-11 a staged rounding, twice, on S = + * sqrt(sum_k (a_k b_k)^2) -- the quadrature scale of the DEQUANTISED terms -- so 9.8e-4 S. The + * store's is bf16's own ulp, 3.9e-3 of the output's binade, and at a bf16 output the store is the + * binding one: rel_l2 lands at 1.71e-03 against BOTH the reference's per-group law and the fold + * model, 83% of outputs are bit-exact bf16, 99.93% are within the fold's floor plus one store ulp, + * and 0 outputs are beyond eight fold floors plus two store ulps, on every band. |y| alone is not a + * denominator: a sum of 2048 random products is as often near zero as not, and a relative test + * against it is a coin flip. S is the denominator, and it is why the per-output gate is + * fold-bound + store-ulp and not a multiple of |y|'s ulp. + * + * ---- the open item, with numbers, and what is NOT the kernel ------------------------------------- + * + * The grid is (ceil(N/128), ceil(M/128)) at one block a CU (64 f32 accumulators a lane). Measured + * per block, the fast shapes cost a constant 18.4-18.5 us a block (16 tiles: 4.72 ms/256; 20 tiles: + * 5.911/320). Column-tile counts 19 and 21 do not: at the same M and K, N=2432 (19 tiles) is + * 64.283 ms and 64.301 ms in two isolated processes (211 us a block, 11.4x) and N=2688 (21 tiles) is + * 129.383 ms (385 us a block, 20.9x). Deterministic to 0.1%, and it is a grid-shape cliff, not + * arithmetic -- the board is CLEAN at both. Every column-tile count the graph issues is even (96, 20, + * 16, 16, 16), so no band the graph runs lands on it; the first thing to try is the block-index + * swizzle that tile-count cliffs usually answer to, and `nt` streaming loads second. + * + * Separately, and named so nobody reads it as the kernel: the qkv shape measures 5.911, 5.919 and + * 6.002 ms as the FIRST case of a process and 85.669 / 85.847 ms as the SECOND case of the band + * sequence, same binary, same seed, same grid, CLEAN board both ways, 250 GFLOP/s when slow. A + * 14.5x deterministic placement artefact of a fixture that allocates and frees a 24 MiB managed + * container in the case before it; at 0.2 GB/s the slow run is reading b over PCIe, in the mapped + * tier's class, which is the placement law this file's header states. The row's number for the qkv + * band is 5.911 ms; the sequence's 85.8 ms is the fixture's, and the engine ships the weights to + * VRAM at load and reads them 44 times, which is the case the 5.911 measures. + * + * ---- where the bytes live, named on every line -------------------------------------------------- + * + * The head's bands, one kernel, three placements, measured: VRAM 13.6 ms a token; the mapped tier + * (hipHostMalloc) 643 ms; managed and left alone 2071 ms, 122 MB/s, because managed pages do not + * migrate for a read-mostly device access on this box. This row's operands are host-readable for the + * same reason the head's are -- the shim reads the container's header on the host, the kernel reads + * the same bytes on the card -- so the board allocates with hipMallocManaged and prefetches, and says + * which placement produced which number. Plain malloc faults 700. + * + * ---- what is refused, and where ----------------------------------------------------------------- + * + * The shim, at its own lines, each naming its fix: n_t < 5 (E_INVAL); a_sum present on an fp8a8 band + * (E_DTYPE -- fp8a8 is symmetric, a zero belongs to an asymmetric grid, and that is + * r3d_gemm_nt_q_w2a8.hip); a container carrying a zero plane (E_DTYPE, the same reason); planes that + * are not codes + scale, a codes plane tiled by anything but one code a cell, sub-byte codes + * (w4a16's ground), e5m2 and the rest, a scale that is a table, an integer scale (E_DTYPE, each its + * own line); a scale block that is not {group, group} (E_SHAPE); a plane that does not cover the + * band, ceil() arithmetic included (E_SHAPE); a plane whose row_bytes is shorter than its row + * (E_STRIDE); dtype of a not E4M3, a_scale not f32, b codes not E4M3, b_scale not bf16/f16/f32, y + * not bf16 (E_DTYPE); M < 17 (E_UNSUPPORTED: gemm_nt_q_fp8a8_m16 serves that); group != 128 + * (E_SHAPE: the fold indexes 128 and kKC 32 divides it); K % 128 (E_SHAPE); pitches that a vector + * load cannot walk (E_STRIDE); addresses not 16-byte aligned (E_ALIGN); absurd shapes (E_INVAL). + * The kernel's shape rule is stated here, because "shape this kernel does not serve" is a coverage + * claim, and coverage is caught by the fixture, not the board. + * The tile is 128 wide, so a ragged N is covered by ceil(): the last column tile stages the columns + * past N as zeros, writes the columns it owns and guards its stores column by column -- N needs NO + * divisibility, and `N % 128` is not a band key gemm_nt_q carries (r3d_rows.cpp's pGemmQ is M, N, + * K, group, dtype, pb1, pb2, split_n), so a check that wanted one could only ever refuse a shape + * the row advertised. M is the same in rows: ceil(M/128) row-tiles, rows past M stage zeros, write + * nothing, and M=65, 129, 258 and 512 -- the 27B fixture's geometries -- are served. + * K % 128 IS a rule, and it is the kernel's and not a coverage one: a 32-code chunk must sit inside + * one scale group (kKC 32 divides the group 128) and the scale plane is indexed by group, so a + * ragged K reads the scale plane past its columns. The scale plane is read at ceil(N/128) x + * ceil(K/128), exactly as the reference's `scaled_rows` covers it; the codes plane at rows == N, + * cols == K. Those two are equalities because that IS the reference's coverage rule, and every + * other shape test on this path is a covering one. + * + * And the keys, the same class of rule: the band's shape arrives as M, N, K -- gemm_q_shape reads + * exactly those and pGemmQ names them -- and n_vocab and n_embd are logits_gemm's keys, not this + * op's: read them and N and K are 0, the axis test fires, and a row whose constraints match the + * bands refuses them all at launch, invisible at planning, because the graph reports constraint + * matches and never asks the shim. N and K therefore fall back to r3d_dim(B, 0) and r3d_dim(B, 1) + * -- the weight IS [N, K], so when the band names no key the operand answers, and the operand is + * the authority the engine filled. + * + * The launcher's private codes are -1 a null plane, -2 a shape, -3 a pitch, -4 HIP, -5 an address, + * and the driver names them apart from the RAD codes, which collide numerically. + * + * ---- relayout: none, and it is a claim ---------------------------------------------------------- + * + * The codes plane is read row-major [N, K], the order the container stores it in and the order + * libref reads. libr4d keeps fp8a8 weights in WMMA fragment order (r4d.fp8.w.frag64, + * r3d_gemm_fp8a8_gated.hip's header): the two readings are ~1.35 apart, a relative error, not noise. + * So this row carries no relayout and no unrelayout, and the hook is a reader, not a mover -- the + * same claim the gated row makes, for the same reason. + */ + +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_fp8_dequant.h" +#include "r3d_tiling.h" /* the LDS row law: srow, srow_pair */ +#include "r3d_launch.h" +#include "rad_planes.h" + +#include +#include +#include + +namespace { + +constexpr int kBlockThreads = 256; +constexpr int kTM = 128; /* rows a tile */ +constexpr int kTN = 128; /* columns a tile: one scale-row */ +constexpr int kKC = 32; /* k a chunk: divides the group */ +constexpr int kGroup = 128; /* R3D_FP8_BLOCK: the band's group */ +/* The complement of gemm_nt_q_fp8a8_m16's declared ceiling, read from the row table: its name + * says M <= 16, so this floor is 17 and M=17..64 is covered. M=17..64 is a batched decode step, + * the most common shape a serving card sees; a floor above it leaves those bands to the host -- + * 209 bands a pass, six of them -- and one host band is what drags the whole model into one host + * run. The tile is 128 rows, so a band of 17 computes 128: 2x wasted at M=64, 7.5x at M=17, and + * 1.8 TFLOP/s on the card is still two orders above the host loop. */ +constexpr int kMMin = 17; + +/* LDS row: 8-element granularity keeps the swizzle uint4-aligned, the rule every tiled row here + * follows (r3d_vocab_bf16.hip's srow, the same function for the same reason). */ +/* srow / srow_pair: r3d_tiling.h, the family's law in one place. */ + +/* The staged side of the same family, typed next to the row law so a kernel's staging and its + * swizzle are read together. u16v is a 16-byte streamed load -- 32 U4 codes, 16 E4M3 codes, and + * the uint4 the tile is written in -- memcpy'd in, never cast: an unaligned cast is UB and the + * compilers say so in bytes of spill. u8v, its 8-byte sibling (8 E4M3 codes, 32 U2 codes, the f32 + * pair a scale row is read in), is declared with the streamed-load helper below. + * + * The scale row, which is why the two arms read a different number of scalars a staged tile: + * fp8a8 b_scale's block is {group, group} = {128, 128}, the block the shape function names, and + * the tile is 128 columns wide, so a staged chunk of 128 rows shares ONE scale: a single + * scalar read a tile, indexed by (n0/128, k0/128). + * w2a8 the grid's block is {1, group}, the same rule that fixes the scale's dtype at f16, so + * the tile's 128 rows are 128 scale rows: 128 scalar reads a chunk, and + * the zero rides with them, 128 more. That is the decode row's pattern -- its scale_at per + * staged 8-group IS the {1, group} case -- and it is kept: the scale is read where the grid + * puts it, not where the tile would like it. A staged row's pair is (scale, zero) and the + * value it stages is (code - zero) * scale, in f16 arithmetic, one v_mul_f16 and one + * v_sub_f16 a code. */ +typedef uint32_t __attribute__((ext_vector_type(4))) u16v; /* a 16-byte streamed load */ + +/* The two operands' scale planes, read the way the container hands them. */ +struct ActQ { + const float* scale; /* a_scale, f32: [M][ceil(K/group)], or [M] with gmode 0 */ + long long row; /* elements a row: ceil(K/group) in group mode, 1 in row mode */ + int gmode; /* 1: one scale per (row, group) -- `a_scale[m][g]`; + * 0: one per ROW -- `a_scale[m]`, the ZP_I8_ROW form */ +}; + +struct WQ { + const uint8_t* codes; /* b's codes plane, [N][K] */ + const uint8_t* scale; /* b_scale's plane: the {128,128} block, or the {1,group} row */ + const uint8_t* zero; /* the asym grid's zero plane, one per (row, group); null if none */ + long long code_row; /* bytes a codes row */ + long long scale_row; /* bytes a scale row */ + long long zero_row; /* bytes a zero row */ + int sdt; /* 0 bf16, 1 f16, 2 f32 */ + int cdt; /* 0 E4M3, 1 int8, 2 U2, 3 U4 */ + int srows; /* 0: scale rows are 128-blocks (fp8a8); 1: scale rows are rows (w2a8, w4a8_asym) */ +}; + +__device__ __forceinline__ int i8_dw(int L) +{ + return (L & ~3) | ((L & 1) << 1) | ((L & 2) >> 1); +} + +/* (code - zero) * scale, in f16 arithmetic, for a sub-byte code read through the block's table: + * the table holds f16(i) for the grid's code values, so the code's decode is one LDS read, the + * scale one v_mul_f16 and the zero one v_sub_f16. This IS the reference's `sub(g) = is(g) - + * z[n][g] * a_sum[g][m]`, formed per element: sum over a group of (a * (q - z) * sb) is the + * reference's bracketed (sum a*q - z * sum a) * sb, term for term. */ +__device__ __forceinline__ uint32_t fold_pair_q(uint32_t codepair, const uint16_t* tbl, + _Float16 s, _Float16 zf, int bits) +{ + const uint32_t m = (1u << bits) - 1u; + /* The table entry is an f16 BIT PATTERN, so it is bit_cast, not converted: a converting cast + * stages 16384 for the code 0x4000, where the value is zero (the board's number was 217). The + * zero comes off BEFORE the scale -- the grid's zero is an integer code and code minus zero is + * exact in f16 for a 4-bit code and a U8 zero, so the staged value costs ONE rounding (the + * multiply) where (code*s) - (z*s) costs two and cancels. */ + const _Float16 a = (__builtin_bit_cast(_Float16, tbl[codepair & m]) - zf) * s; + const _Float16 b = (__builtin_bit_cast(_Float16, tbl[(codepair >> bits) & m]) - zf) * s; + return (uint32_t)__builtin_bit_cast(uint16_t, a) | + ((uint32_t)__builtin_bit_cast(uint16_t, b) << 16); +} + +__device__ __forceinline__ float scale_w(const WQ h, int nb, int g) +{ + const uint8_t* p = h.scale + (long long)nb * h.scale_row + (long long)g * (h.sdt == 2 ? 4 : 2); + if (h.sdt == 2) { float f; __builtin_memcpy(&f, p, 4); return f; } + const uint16_t u = *(const uint16_t*)p; + return h.sdt == 1 ? f16_to_f32(u) : bf16_to_f32(u); +} + +/* The scale of (row n, group g), in the grid the plane is laid out in. This one line is the whole + * difference between the two grids' scale rows, so it is written once and named for the ROWS: + * fp8a8 b_scale's rows are 128-row blocks ({group, group}) -> the tile's row n lives in block + * n>>7, one scalar serves the tile's 128 rows. + * w2a8 b_scale's rows are the weight's rows ({1, group}) -> row n, 128 scalars a staged chunk. + * The srows flag must match the grid: a scale read from the wrong row is not noise, it is a + * systematic few percent -- the head's bands at rel_l2 1.6e-02 against a fold floor of 1.8e-03 -- + * and it passes any gate set loosely enough. */ +__device__ __forceinline__ float scale_at_w(const WQ h, int n, int g) +{ + return scale_w(h, h.srows ? n : (n >> 7), g); +} + +__device__ __forceinline__ float zero_at_w(const WQ h, int n, int g) +{ + if (!h.zero) return 0.0f; + return (float)h.zero[(long long)n * h.zero_row + g]; /* U8: the plane's practical form */ +} + +/* quant_act_i8's step order: column c sits at (c & ~12) | ((c & 4) << 1) | ((c & 8) >> 1), the + * swap of bits 2 and 3, which is its own inverse. Bits 2 and 3 of a column are + * bits 0 and 1 of its DWORD index, so a dword's four codes stay four contiguous bytes and the + * staging reads a 16-code run's dwords in the order 0, 2, 1, 3. Nothing straddles a dword. */ + + +/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. NOT + * f16x2_pack, which truncates -- see the header and r3d_codecs.h. */ +__device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc) +{ + const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16); + const _Float16 a = __builtin_bit_cast(_Float16, lo16); + const _Float16 b = __builtin_bit_cast(_Float16, hi16); + const _Float16 s = (_Float16)sc; + const _Float16 rl = a * s, rh = b * s; + return (uint32_t)__builtin_bit_cast(uint16_t, rl) | + ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16); +} + +/* Eight codes -> eight f16 pairs, through the table. int8 codes take the codec's hardware convert, + * which is two v_cvt_f32_i8 and a pack; there is no such instruction for E4M3. */ +__device__ __forceinline__ void codes8(const uint2 c, int cdt, const uint16_t* tbl, uint32_t* w) +{ + if (!cdt) { r3d_e4m3x8_ld(tbl, c, w); return; } + const uint32_t d[2] = { c.x, c.y }; +#pragma unroll + for (int j = 0; j < 4; ++j) + w[j] = i8x2_to_f16x2((d[j >> 1] >> (16 * (j & 1))) & 0xffffu); +} + +template +__device__ __forceinline__ uint2 loadc8s(const uint8_t* p) +{ + typedef uint32_t __attribute__((ext_vector_type(2))) u8v; + u8v v; + if (NT) v = __builtin_nontemporal_load((const u8v*)p); + else __builtin_memcpy(&v, p, 8); + uint2 r; + __builtin_memcpy(&r, &v, 8); + return r; +} + +/* + * The tile: 128 rows x 128 columns of y, 256 threads, eight waves, eight outputs a side a lane -- + * 64 f32 accumulators a lane, grid (N/kTN) x ceil(M/kTM). k is walked in chunks of 32; both sides + * arrive as E4M3 codes, decode through the block's table and leave staging as f16 with their scale + * folded in, so the dot loop is the vocabulary head's dot loop and nothing in it scales anything. + */ +template /* CDT: 0 E4M3, 1 int8, 2 U2, 3 U4 */ +__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) +fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __restrict__ b, WQ h, + void* __restrict__ y, int M, int N, int K, int a_ld, int y_ld) +{ + __shared__ __align__(16) uint16_t sA[kTM * kKC]; + __shared__ __align__(16) uint16_t sB[kTN * kKC]; + __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; + + const int tid = (int)threadIdx.x; + if (ARM == 0) { + r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* E4M3 -> f16, the decoder table */ + } else { + /* The asym grid's codes are unsigned integers: U2 has 4 values, U4 has 16. The same + * 512 bytes, filled with f16(i) -- exact for every code the grid can hold. */ + for (int i = tid; i < 16; i += kBlockThreads) sTbl[i] = f32_to_f16((float)i); + __syncthreads(); + } + const int m0 = (int)blockIdx.y * kTM; + const int n0 = (int)blockIdx.x * kTN; + const int rg = tid >> 4, cg = tid & 15; + + float acc[8][8]; +#pragma unroll + for (int i = 0; i < 8; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) acc[i][j] = 0.0f; + + const int m_r = m0 + rg * 8, n_c = n0 + cg * 8; + const int nb = n0 / kGroup; /* TN == the scale plane's row */ + + /* The asym arm's staged row, one per thread for the whole tile: the B staging's row loop is + * `nn = tid; nn < kTN; nn += kBlockThreads`, so thread tid stages row n0+tid in every chunk. + * That is what makes the {1, group} grid's scalars cheap to read: the pair a row needs changes + * only when the k-group changes (kKC 32 divides kGroup 128, so every fourth chunk), and the + * load can be issued a chunk ahead, where its round trip overlaps the dot. + * + * At the 2-bit head's band M=64 N=12288 K=2048, the pair read inside the fold is 210.835 ms, + * 15.3 GFLOP/s; read once a group with a chunk's lead, 2.4 ms, 1344 GFLOP/s. + * The scalar is 128 a chunk -- the grid puts the scale at the row, so that is where it is read, + * and the decode row's pattern is kept -- with one row per thread there is no second load to + * overlap it with, and a round trip on the staging critical path is 64 of them a tile, paid in + * full. The values are identical either way; this is placement of a load, not arithmetic. */ + const int b_row = n0 + tid; + const bool b_has = (ARM == 1) && (tid < kTN) && (b_row < N); + _Float16 s_cur = (_Float16)0.0f, zf_cur = (_Float16)0.0f; + if (b_has) { + s_cur = (_Float16)scale_at_w(h, b_row, 0); + zf_cur = (_Float16)zero_at_w(h, b_row, 0); + } + /* NAMED NON-RESULT: the codes stream is NOT limited by loads in flight. A one-chunk lead on + * the row's codes load -- 8 bytes (U2) or 16 (U4) a row a chunk, issued before the fold -- + * measures 24.430 ms against 24.585 ms at M=64 N=130560 K=2048, 0.6%, bit-identical output. + * The scalar load is the cost because it sits on the critical path with nothing to overlap; the + * stream is not waiting for latency, it is paying sector count: kKC 32 codes a row a chunk is + * 8 bytes drawn from a 512-byte-strided plane, so every row costs a full 64-byte sector and the + * band moves 8x the bytes it uses. 3.7 GB/s useful, 30 GB/s of sectors, and the card is not + * near the sector limit: the shape is the limit. The lever is a wider k-chunk (kKC 64 = 16 bytes + * a row = 4x amplification, kKC 128 = one group a chunk = 2x), paid for in LDS and occupancy -- + * a tiling pass on this arm, not a load lead. */ + + for (int k0 = 0; k0 < K; k0 += kKC) { + const int g = k0 / kGroup; /* one group a chunk: 32 | 128 */ + const float sb = scale_w(h, nb, g); /* one scale for the whole tile */ + +#pragma unroll + for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) { + const int mm = j / (kKC / 8), c8 = j % (kKC / 8); + const int m = m0 + mm, k = k0 + c8 * 8; + uint4 staged = make_uint4(0, 0, 0, 0); + if (m < M) { + if (ARM == 0) { + /* A row's scale, once a staged run: a_scale is (row, group) and the run is + * inside one group. */ + /* The row form contributes no g: `aq.gmode` is 0 and the term is a select, so + * one scale a row costs one IADD and no branch in the staging loop. */ + const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)]; + uint32_t w[4]; + codes8(loadc8s(a + (long long)m * a_ld + k), 0, sTbl, w); + staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa), + fold_pair(w[2], sa), fold_pair(w[3], sa)); + } else { + /* The w2a8 activation: int8 codes in quant_act_i8's step order, read four codes + * a dword at the permuted dword address, and ONE scale per ROW (ZP_I8_ROW: + * quant_act_i8 scales a whole row, not a group). */ + const float sa = aq.scale[(long long)m * aq.row]; + const int L0 = k >> 2; + const uint8_t* ap = a + (long long)m * a_ld; + const uint32_t d0 = *(const uint32_t*)(ap + (i8_dw(L0) << 2)); + const uint32_t d1 = *(const uint32_t*)(ap + (i8_dw(L0 + 1) << 2)); + const uint32_t d[2] = { d0, d1 }; + uint32_t w[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) + w[q] = i8x2_to_f16x2((d[q >> 1] >> (16 * (q & 1))) & 0xffffu); + staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa), + fold_pair(w[2], sa), fold_pair(w[3], sa)); + } + } + *(uint4*)&sA[srow(mm, c8, kKC)] = staged; + } + if (ARM == 0) { +#pragma unroll + for (int j = tid; j < kTN * (kKC / 8); j += kBlockThreads) { + const int nn = j / (kKC / 8), c8 = j % (kKC / 8); + const int n = n0 + nn, k = k0 + c8 * 8; + uint4 staged = make_uint4(0, 0, 0, 0); + if (n < N) { + uint32_t w[4]; + codes8(loadc8s(h.codes + (long long)n * h.code_row + k), h.cdt, sTbl, w); + staged = make_uint4(fold_pair(w[0], sb), fold_pair(w[1], sb), + fold_pair(w[2], sb), fold_pair(w[3], sb)); + } + *(uint4*)&sB[srow(nn, c8, kKC)] = staged; + } + } else { + /* The sub-byte weight, w2a8 (U2, four codes a byte, a row is K>>2 bytes) and + * w4a8_asym (U4, two a byte, K>>1). A lane takes the whole 32-code chunk in one load: + * 8 bytes of U2, 16 of U4, k0 is a multiple of 128 so both are aligned. The scale AND + * the zero are per (row, group) -- the grid's block is {1, group} -- so every staged + * row reads its own pair of scalars: the decode row's pattern, 128 scalar reads a chunk + * where the fp8a8 arm reads one. */ + constexpr int BITS = (CDT == 2) ? 2 : 4; + constexpr int FIELD = 2 * BITS; /* bits a pair of codes occupies */ +#pragma unroll + for (int nn = tid; nn < kTN; nn += kBlockThreads) { + const int n = n0 + nn; + uint4 st[4] = { make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0), + make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0) }; + if (n < N) { + const _Float16 s = s_cur, zf = zf_cur; /* the group's pair, prefetched */ + if (b_has && k0 + kKC < K && (k0 + kKC) / kGroup != g) { + const int gn = (k0 + kKC) / kGroup; + s_cur = (_Float16)scale_at_w(h, b_row, gn); + zf_cur = (_Float16)zero_at_w(h, b_row, gn); + } + uint32_t d[4] = { 0, 0, 0, 0 }; + const uint8_t* cp = h.codes + (long long)n * h.code_row + + (k0 >> (CDT == 2 ? 2 : 1)); + if (CDT == 2) { uint2 v; __builtin_memcpy(&v, cp, 8); d[0] = v.x; d[1] = v.y; } + else { u16v v; __builtin_memcpy(&v, cp, 16); + d[0] = v.x; d[1] = v.y; d[2] = v.z; d[3] = v.w; } + uint32_t w[16]; +#pragma unroll + for (int q = 0; q < 16; ++q) { + /* Pair q of the chunk sits at bit FIELD*q of the row: a 4-bit field for U2 + * (eight to a dword), an 8-bit field for U4 (four to a dword). Neither + * straddles a dword, which is why the field is read from one word. */ + const int bit = q * FIELD; + w[q] = fold_pair_q((d[bit >> 5] >> (bit & 31)) & ((1u << FIELD) - 1u), + sTbl, s, zf, BITS); + } + st[0] = make_uint4(w[0], w[1], w[2], w[3]); + st[1] = make_uint4(w[4], w[5], w[6], w[7]); + st[2] = make_uint4(w[8], w[9], w[10], w[11]); + st[3] = make_uint4(w[12], w[13], w[14], w[15]); + } +#pragma unroll + for (int q = 0; q < 4; ++q) *(uint4*)&sB[srow(nn, q, kKC)] = st[q]; + } + } + __syncthreads(); + +#pragma unroll + for (int kc = 0; kc < kKC; kc += 2) { + uint32_t af[8], bf[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) + af[i] = *(const uint32_t*)&sA[srow_pair(rg * 8 + i, kc, kKC)]; +#pragma unroll + for (int j = 0; j < 8; ++j) + bf[j] = *(const uint32_t*)&sB[srow_pair(cg * 8 + j, kc, kKC)]; +#pragma unroll + for (int i = 0; i < 8; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]); + } + __syncthreads(); + } + + /* y is bf16: one narrowing, 16-byte runs of eight columns. Rows past M write nothing. */ +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int m = m_r + i; + if (m >= M) break; + uint16_t* row = (uint16_t*)y + (long long)m * y_ld; + if (n_c + 8 <= N) { + uint32_t p[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) + p[j] = (uint32_t)f32_to_bf16(acc[i][2 * j]) | + ((uint32_t)f32_to_bf16(acc[i][2 * j + 1]) << 16); + *(uint4*)(row + n_c) = make_uint4(p[0], p[1], p[2], p[3]); + } else { + /* The ragged N tail, unrolled: a dynamic index into acc[i] would put the 64 + * accumulators in local memory, which is the trap this family of kernels documents. */ +#pragma unroll + for (int j = 0; j < 8; ++j) + if (n_c + j < N) row[n_c + j] = f32_to_bf16(acc[i][j]); + } + } +} + +/* ------------------------------------------------------------------ the launcher ------------------ */ +/* The launcher speaks the internal codes the shim maps (-3 stride, -4 device, -5 align), so a + * refusal here prints what it saw and returns -3, not the ABI code: the shim would translate -4 into + * E_DEVICE and the message the user reads would name the wrong thing. */ +#define L_STR(why, a1, v1, a2, v2) \ + do { \ + if (r3d_trace_on()) \ + std::fprintf(stderr, "[r3d] %s:%d %s: %s = %lld, %s = %lld\\n", \ + __FILE__, __LINE__, (why), (a1), (long long)(v1), (a2), \ + (long long)(v2)); \ + return R3D_NO(-3); \ + } while (0) + +int launch(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K, int group, + int a_ld, long long b_row, int as_ld, long long bs_row, int y_ld, int nt, long stream, + int sdt, int cdt, long zv = 0, long long z_row = 0, int srows = 0, int arm = 0) +{ + if (!av || !asv || !bvc || !bsv || !yv) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (group != kGroup) return -2; /* the fold indexes 128; kKC 32 divides it */ + if (K % kGroup) return -2; /* a ragged k-block reads past the scale plane */ + if (nt < 0 || nt > 1) return -2; + if (a_ld % 8) L_STR("a pitch: 8-byte code loads, 8 codes a lane", "a_ld", a_ld, "K", K); + if (b_row & 7) L_STR("b row pitch is not 8-aligned", "b_row", b_row, "N", N); + /* The activation's scale row, which is a DIFFERENT thing in the two arms: fp8a8 carries one + * scale per (row, group) so the row is ceil(K/group) columns; w2a8 and w4a8_asym scale the + * whole row (ZP_I8_ROW: quant_act_i8's law), so it is one column a row and as_ld 1 is the + * legal pitch, not a broken one. The check is per arm for the same reason the staging is. */ + /* The activation's scales arrive in two forms, both the reference's: one per (row, group) at + * width ceil(K/group), and one per ROW at width 1 (the ZP_I8_ROW form -- which is what a per-row + * quantiser produces, and what this checkpoint's plan binds for the served model). Row mode is + * `as_ld == 1` and the kernel drops the group term. */ + if (arm == 0 && as_ld != 1 && as_ld < (K + kGroup - 1) / kGroup) L_STR( + "a_scale: neither one per row nor one per (row, group)", "as_ld", as_ld, + "ceil(K/group)", (K + kGroup - 1) / kGroup); + if (arm == 1 && as_ld < 1) return -3; + if (y_ld % 8) L_STR("y pitch: 16-byte bf16 store runs", "y_ld", y_ld, "N", N); + if (a_ld < K) L_STR("a pitch shorter than K", "a_ld", a_ld, "K", K); + if (y_ld < N) L_STR("y pitch shorter than N", "y_ld", y_ld, "N", N); + if ((av & 7) || (bvc & 7) || (yv & 7) || (asv & 3) || (bsv & 3)) return -5; + if (bs_row & (sdt == 2 ? 3 : 1)) return -3; /* a scale row is 4 bytes a column for f32, 2 for + bf16/f16: ceil(K/128) = 3 columns is 6 bytes. */ + if (arm == 1) { + if (!(arm == 1 && (cdt == 2 || cdt == 3))) return -2; + if (!zv) return -1; /* the asym grid has no spelling without a zero */ + if (z_row < 1) return -3; + if (zv & 1) return -5; + if (cdt == 3 && (bvc & 15)) return -5; /* a 16-byte U4 load; U2 loads 8 */ + } + + const dim3 blk(kBlockThreads); + const dim3 grd((unsigned)((N + kTN - 1) / kTN), (unsigned)((M + kTM - 1) / kTM)); + ActQ aq{ (const float*)(uintptr_t)asv, (long long)as_ld, as_ld != 1 }; + WQ h{ (const uint8_t*)(uintptr_t)bvc, (const uint8_t*)(uintptr_t)bsv, + (const uint8_t*)(uintptr_t)zv, b_row, bs_row, z_row, sdt, cdt, srows }; + hipStream_t s = (hipStream_t)(uintptr_t)stream; +#define R3D_RUN(ARM, CD) \ + do { \ + if (nt) fp8a8_tiled_kernel<1, ARM, CD><<>>( \ + (const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \ + h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); \ + else fp8a8_tiled_kernel<0, ARM, CD><<>>( \ + (const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \ + h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); \ + } while (0) + if (arm == 0) { if (cdt == 1) R3D_RUN(0, 1); else R3D_RUN(0, 0); } + else { if (cdt == 3) R3D_RUN(1, 3); else R3D_RUN(1, 2); } +#undef R3D_RUN + const hipError_t le = hipGetLastError(); + if (le != hipSuccess) { + if (r3d_trace_on()) + std::fprintf(stderr, "[launch] arm=%d cdt=%d nt=%d grid(%u,%u) block(%u) M=%d N=%d K=%d: %s\n", + arm, cdt, nt, grd.x, grd.y, kBlockThreads, M, N, K, hipGetErrorString(le)); + return -4; + } + return 0; +} + +/* libref's float_scale_dt and enc_scaled_rows, inlined: libref keeps them static inline in its own + * header, so a row that transcribes a layout hook transcribes its helpers with it. Checks and + * order unchanged. */ +bool float_scale_dt(uint32_t dt) { return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; } + +bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n) +{ + if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return false; + if (n != 2 || !sel) return false; /* sel_roles(enc, sel, n, "codes","scale") */ + const char* want[2] = { "codes", "scale" }; + for (int i = 0; i < 2; ++i) { + if (sel[i] < 0 || sel[i] >= enc->n_planes) return false; + if (std::strncmp(enc->plane[sel[i]].role, want[i], RAD_ENC_STR) != 0) return false; + } + const RadEncPlane& c = enc->plane[sel[0]]; + const RadEncPlane& sc = enc->plane[sel[1]]; + return c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 && + (c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && sc.kind == RAD_PLANE_TILED && + float_scale_dt(sc.dtype); +} + +} // namespace + +/* ================================================================================================== + * The layout hook: b (operand 2) as codes + one scale. + * + * `ref_layout_gemm_q` is the w2a8/w4a8 grid's hook: it is `layout_scaled(operand, 3, -1, ...)` over + * `sel_roles("scale","zero")` with block {1, group}, and it reads `zp_grid(dtype)` first -- and + * zp_grid has no "fp8a8" entry (it lists w2a8, w4a8_asym, w4a16_asym, w5a16, w4a8i8_asym, w5a8i8), + * so the reference's own gemm_nt_q hook ANSWERS NOTHING for dtype=fp8a8: it returns E_DTYPE, the + * placement finds no reader, and the group stays mapped. That is the chain's first link, and it is + * why this hook is the head's class and not that one: two planes, "codes" and "scale", NO zero + * plane (fp8a8 is symmetric), codes tiled one a cell, the scale on the block the shape function + * names -- {group, group}. Body: layout_scaled(operand, 2, -1, ...) as ref_layout_head's is. + * ================================================================================================== */ +/* The writer for the layout this hook names -- the same rad_planes_relayout, the same operand guard, + * the same reason: the plan asks for the container's codes and per-block scales as one operand, and + * the loader converts at load with the row's help and nobody else's. */ +extern "C" int r3d_relayout_gemm_q_fp8_weight(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n_planes, void* dst, + int64_t dst_bytes) +{ + /* The query and the writer are one plan; see r3d_layout_gemm_q_fp8_weight. */ + const char* dt = r3d_pgets(p, n_p, "dtype"); + if (dt && (std::strcmp(dt, "w2a8") == 0 || std::strcmp(dt, "w4a8_asym") == 0)) + return r3d_relayout_gemm_nt_q_w2a8(p, n_p, operand, enc, sel, planes, n_planes, dst, + dst_bytes); /* the decode row's plan, one writer */ + if (operand != 2) return R3D_NO(RAD_E_UNSUPPORTED); + return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes); +} + +/* The grids this row reads behind operand 2, in two branches that never borrow each other's + * checks. fp8a8 is the symmetric pair (codes, scale) on {1,1} + {group,group}. w2a8 and + * w4a8_asym are the ZERO-POINT triple (codes, scale, zero) on {1,1} + {1,group} + {1,group}: + * ref_layout_gemm_q's plane rules with the codes plane riding along, because this row's plan puts + * all three behind b. The dtype names which grid, and the codes dtype follows it (zp_grid: + * w2a8 -> U2, w4a8_asym -> U4) -- a grid and a code width that disagree is a container this row + * cannot read, at its own line. */ +/* A layout query answers in the engine's own vocabulary and leaves no trace, and a model that will + * not load says only that two rows want one weight in two forms. This prints the question and the + * answer -- operand, band dtype, planes offered, code returned -- under RAD_R3D_TRACE=1. */ +static int r3d_layout_trace(const char* who, int operand, const char* dt, int n_planes, int rc) { + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] %s: operand %d dtype %s planes %d -> %d\n", who, operand, + dt ? dt : "(none)", n_planes, rc); + return rc; +} + +extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n, RadLayout* out) +{ + const char* dt = r3d_pgets(p, n_p, "dtype"); + if (dt && (std::strcmp(dt, "w2a8") == 0 || std::strcmp(dt, "w4a8_asym") == 0)) + return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, r3d_layout_gemm_nt_q_w2a8(p, n_p, operand, enc, sel, planes, n, out)); + + if (n < 2 || operand != 2) return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_UNSUPPORTED); /* b is operand 2 of gemm_nt_q */ + + /* The packed grids ask the DECODE ROW what the container looks like, and get the answer by + * calling its hook -- `r3d_layout_gemm_nt_q_w2a8`: codes plain on operand 2, the (scale, zero) + * pair joined on operand 3, the {1, group} block, the f16 scale, the unsigned zero. The engine + * settles one stored form per weight across every row of the op that reads it and says so at + * declare time -- `weight 'dspark.draft_head.scale' is wanted in two stored forms: + * 'rad.planes' by gemm_nt_q_w2a8_m16 and '(as it is)' by gemm_nt_q_w2a8_tiled. A weight is + * stored once` -- so a tile that wants the trio joined behind `b` is not a different plan, it is + * a model that will not load. Two rows describing one weight in one function cannot drift; the + * arm's board measures this arrangement as `decodeform`, 1.660e-03 against the joined fixture's + * 1.677e-03, the same law's noise. */ + + if (!enc_scaled_rows(enc, sel, n)) return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + const long long group = r3d_pgeti_or(p, n_p, "group", 0); + if (group <= 0) return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the band names the block */ + if (enc->plane[sel[1]].block[0] != group || enc->plane[sel[1]].block[1] != group) + return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* {group, group} */ + return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, rad_planes_layout(enc, sel, planes, n, out)); +} + +/* ================================================================================================== + * The planes' entry: the caller has resolved the two planes and hands their addresses. The band is + * fp8a8, group 128, y bf16. Codes row-major, scales [ceil(N/128)][ceil(K/128)], read as bf16 -- + * fp8a8's stated dtype; the f32 spelling (fp8a8f32) arrives through the shim, which reads the dtype + * off the plane. b_row and bs_row of 0 mean the dense pitch. + * ================================================================================================== */ +extern "C" int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, + int M, int N, int K, int group, int a_ld, long long b_row, + int as_ld, long long bs_row, int y_ld, int nt, long stream) +{ + const int st = launch(a, a_scale, b_codes, b_scale, y, M, N, K, group, a_ld, b_row ? b_row : K, + as_ld, bs_row ? bs_row : (long long)((K + kGroup - 1) / kGroup) * 2, y_ld, + nt, stream, 0, 0); + if (st == -1) return R3D_NO(RAD_E_INVAL); + if (st == -2) return R3D_NO(RAD_E_SHAPE); + if (st == -3) return R3D_NO(RAD_E_STRIDE); + if (st == -5) return R3D_NO(RAD_E_ALIGN); + if (st == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} + +/* ================================================================================================== + * The RadArgs shim. Schema positions: a 0, a_scale 1, b 2, b_scale 3, y 4, a_sum 5, b_ref 6. The + * placement joins b and b_scale into one container, so 3 is absent and the container's header is + * read here, on the host; a caller that resolved the planes itself passes 3 and takes the plain + * path. Same kernel, same law, one branch. + * ================================================================================================== */ + +/* RadStream, the ABI's type: RadLaunchFn is int (*)(const RadArgs*, RadStream) and RadStream is + * void* (rad_abi.h, rad_types.h). A shim that takes a long runs -- same width, same convention -- + * and is a function-pointer type the row table has to be lied to about. The entry below keeps long + * because it takes addresses as longs; the cast is here, at the boundary. */ + +/* The plan line's latch: one print per distinct shape this shim sees, keyed on what the line prints + * -- M, N, K, the activation's rank, the scale's rank and the two pitches -- because the served plan + * runs this shim 176 times a forward pass and 42 copies of one line are noise. A plain static array + * with no lock: the worst a race does is print a shape twice, and the flag-off path never reaches + * it. The sibling decode row (gemm_nt_q_fp8a8_m16) has no such line: the shapes below M=17 are its + * served path, and the ones above it are what this line is for. */ +struct GemmPlanKey { long long M, N, K; unsigned a_rank, as_rank; long long a_ld, y_ld; }; + +static bool gemm_plan_once(long long M, long long N, long long K, unsigned a_rank, unsigned as_rank, + long long a_ld, long long y_ld) +{ + static GemmPlanKey seen[96]; + static int n = 0; + for (int i = 0; i < n; ++i) + if (seen[i].M == M && seen[i].N == N && seen[i].K == K && seen[i].a_rank == a_rank && + seen[i].as_rank == as_rank && seen[i].a_ld == a_ld && seen[i].y_ld == y_ld) + return false; + if (n < 96) seen[n++] = GemmPlanKey{M, N, K, a_rank, as_rank, a_ld, y_ld}; + return true; +} + +extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) +{ + if (!args || args->n_t < 5) return R3D_NO(RAD_E_INVAL); + const RadTensor* A = r3d_opt(args, 0); + const RadTensor* AS = r3d_opt(args, 1); + const RadTensor* B = r3d_opt(args, 2); + const RadTensor* BS = r3d_opt(args, 3); + const RadTensor* Y = r3d_opt(args, 4); + const RadTensor* ASUM = r3d_opt(args, 5); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL); + + /* The band's keys, from the schema this row is declared against: gemm_nt_q carries M, N, K, + * group, dtype (r3d_rows.cpp pGemmQ) -- NOT n_vocab/n_embd, which belong to logits_gemm. Read + * the wrong keys and N and K are 0, every launch is refused below at the shape check, the op + * resolves to a host kernel for every band, the planner puts the whole model in one host run, + * and a norm weight two tiers away refuses to load. Falling back to the weight's own dims keeps + * a caller that names no N/K working, and says which operand is the authority. */ + const long long M_band = r3d_geti_or(args, "M", 0), N0 = r3d_geti_or(args, "N", 0); + const long long K0 = r3d_geti_or(args, "K", 0); + const long long N = N0 > 0 ? N0 : r3d_dim(B, 0); + const long long K = K0 > 0 ? K0 : r3d_dim(B, 1); + const long long group = r3d_geti_or(args, "group", 0); + if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE); + if (K > (1 << 24)) return R3D_NO(RAD_E_INVAL); /* absurd: a 16M-wide K is a 2 GiB code plane per row */ + if (group != kGroup) return R3D_NO(RAD_E_SHAPE); /* the fold indexes 128 */ + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); + if (ASUM && r3d_p(ASUM)) + return R3D_NO(RAD_E_DTYPE); /* fp8a8 is symmetric: a_sum is an asymmetric grid's, and + r3d_gemm_nt_q_w2a8.hip reads that one */ + + /* ---- b: a container of codes + scale, or the two planes as tensors -------------------------- */ + const void* bvc = r3d_p(B); + const void* bsv = nullptr; + long long b_row = 0, bs_row = 0; + int sdt = 0, cdt = 0; + const RadPlanesHeader* ph = (const RadPlanesHeader*)rad_planes_header(bvc); + if (ph) { + /* find answers with the bytes and points into the container; no copy. */ + const RadPlanesEntry* ce = nullptr; + const RadPlanesEntry* se = nullptr; + if (rad_planes_find(bvc, "zero", nullptr)) + return R3D_NO(RAD_E_DTYPE); /* codes+scale+zero is gemm_nt_q's asymmetric grid: w2a8 */ + if (ph->n_planes != 2) return R3D_NO(RAD_E_DTYPE); + const void* cb = rad_planes_find(bvc, "codes", &ce); + const void* sb = rad_planes_find(bvc, "scale", &se); + if (!cb || !sb) return R3D_NO(RAD_E_DTYPE); /* a joined weight that is not codes + scale */ + if (ce->kind != RAD_PLANE_TILED || ce->block[0] != 1 || ce->block[1] != 1) + return R3D_NO(RAD_E_DTYPE); /* codes: one a cell, tiled plain */ + if (ce->dtype != RAD_F8E4M3 && ce->dtype != RAD_I8) { + if (rad_dtype_bytes(ce->dtype, 8) < 8) + return R3D_NO(RAD_E_DTYPE); /* sub-byte codes: w4a16's ground */ + return R3D_NO(RAD_E_DTYPE); /* e5m2 and the rest: no decoder here */ + } + if (se->kind != RAD_PLANE_TILED) return R3D_NO(RAD_E_DTYPE); + if (se->dtype == RAD_BF16) sdt = 0; + else if (se->dtype == RAD_F16) sdt = 1; + else if (se->dtype == RAD_F32) sdt = 2; + else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not float_scale_dt */ + if (se->block[0] != group || se->block[1] != group) + return R3D_NO(RAD_E_SHAPE); /* per-(row, group) is gemm_nt_q's w2a8 grid; per-row is + not cover's indexing of the plane */ + bvc = cb; bsv = sb; b_row = ce->row_bytes; bs_row = se->row_bytes; + cdt = ce->dtype == RAD_I8; + const long long sb_r = (N + group - 1) / group, sb_c = (K + group - 1) / group; + if (ce->rows != N || ce->cols != K) return R3D_NO(RAD_E_SHAPE); + if (se->rows != sb_r || se->cols != sb_c) return R3D_NO(RAD_E_SHAPE); + if (ce->row_bytes < K) return R3D_NO(RAD_E_STRIDE); /* a packed row is not this form */ + if (se->row_bytes < sb_c * (sdt == 2 ? 4 : 2)) return R3D_NO(RAD_E_STRIDE); + } else { + if (!BS || !r3d_p(BS)) + return R3D_NO(RAD_E_DTYPE); /* a weight that is neither a container nor a scale + tensor: gemm_nt_q's shape hook names the two */ + b_row = K; + const long long sb_r = (N + group - 1) / group, sb_c = (K + group - 1) / group; + /* b_scale as a CONTAINER -- the codes plain on b, the scale joined behind b_scale. The + * sibling decode row uses that spelling for the shared weight, and + * r3d_relayout_gemm_q_fp8_weight writes it for a band whose encoding names its container at + * operand 3, so the plan can hand it here. The header is read on the host, where it lives + * (the same call b's arm makes above); the kernel gets the scale plane's BYTES and the row + * pitch off the ENTRY, which is the identical answer the two-tensor spelling gives. + * A `zero` plane stays refused: fp8a8's activation quantiser is symmetric and this arm has + * no zero to fold -- the reference refuses the grid for it outright -- so a row that + * computed through a zero plane would be inventing a number the oracle has no law for. The + * asymmetric grid is gemm_nt_q's w2a8 form and r3d_gemm_nt_q_w2a8 owns that spelling. */ + const RadPlanesHeader* sph = (const RadPlanesHeader*)rad_planes_header(r3d_p(BS)); + if (sph) { + if (rad_planes_find(r3d_p(BS), "zero", nullptr)) + return R3D_NO(RAD_E_DTYPE); /* codes + scale + zero: r3d_gemm_nt_q_w2a8's grid, + not this arm's -- nor libref's */ + const RadPlanesEntry* se = nullptr; + const void* sb = rad_planes_find(r3d_p(BS), "scale", &se); + if (!sb || !se) + return R3D_NO(RAD_E_DTYPE); /* a joined stream with no `scale` plane: + r3d_relayout_gemm_q_fp8_weight is its writer */ + if (se->kind != RAD_PLANE_TILED) return R3D_NO(RAD_E_DTYPE); + if (se->dtype == RAD_BF16) sdt = 0; + else if (se->dtype == RAD_F16) sdt = 1; + else if (se->dtype == RAD_F32) sdt = 2; + else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not float_scale_dt */ + if (se->block[0] != group || se->block[1] != group) + return R3D_NO(RAD_E_SHAPE); /* per-row scales are the w2a8 grid; the 128x128 + quantiser writes one scale a (128 rows x 128 codes) */ + if (se->rows != sb_r || se->cols != sb_c) return R3D_NO(RAD_E_SHAPE); + if (se->row_bytes < sb_c * (sdt == 2 ? 4 : 2)) return R3D_NO(RAD_E_STRIDE); + bsv = sb; + bs_row = se->row_bytes; + } else { + bsv = r3d_p(BS); + long long bs_rows = 0; + const long long bs_pitch = r3d_rows_pitch(BS, sb_c, &bs_rows); + if (bs_pitch < 0 || bs_rows < sb_r) return R3D_NO(RAD_E_STRIDE); + if (BS->dtype == RAD_BF16) sdt = 0; + else if (BS->dtype == RAD_F16) sdt = 1; + else if (BS->dtype == RAD_F32) sdt = 2; + else return R3D_NO(RAD_E_DTYPE); + if (r3d_dim(BS, 0) < sb_r || r3d_dim(BS, 1) < sb_c) return R3D_NO(RAD_E_SHAPE); + bs_row = bs_pitch * (sdt == 2 ? 4 : 2); /* the kernel walks the plane's bytes */ + } + if (B->dtype == RAD_F8E4M3) cdt = 0; + else if (B->dtype == RAD_I8) cdt = 1; + else if (rad_dtype_bytes(B->dtype, 8) < 8) return R3D_NO(RAD_E_DTYPE); + else return R3D_NO(RAD_E_DTYPE); + if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(B, 0) != N || r3d_dim(B, 1) != K) return R3D_NO(RAD_E_SHAPE); + } + + if (A->dtype != RAD_F8E4M3) return R3D_NO(RAD_E_DTYPE); + if (AS->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); + if (Y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); /* gemm_q_shape: y is bf16, one narrowing */ + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + + long long a_rows = 0; + long long a_ld = r3d_rows_pitch(A, K, &a_rows); + /* THE STEP'S M IS THE ACTIVATION'S ROW COUNT. The band key `M` is an upper bound, and the + * engine's own line says so -- its refusal names the step's M against the band's declared bound + * -- so reading the key as the value would refuse a step shorter than the band. libref derives + * M from the operands (the plane, not the plan), and the m16 row does it the same way. The key + * keeps its job as the ceiling the plan promised not to exceed. */ + if (a_ld < K || a_rows < 1) { + /* A group-quantised activation is the same row-major K codes the kernel wants, described in + * the rank the quantiser writes them in: [M][ceil(K/group)][group], contiguous, the row + * exactly K wide. `r3d_rows_pitch` asks for the width by name and a rank-3 plane whose last + * axis is the group does not answer it, so the plane is asked directly: contiguous and + * dividing by K is a plane of rows K wide. */ + if (rad_tensor_is_contiguous(A) && K > 0 && r3d_numel(A) % K == 0) { + const long long r = r3d_numel(A) / K; + if (r >= 1) { a_ld = K; a_rows = r; } + } + } + if (a_ld < K || a_rows < 1) { r3d_trace_desc("a", A); + std::fprintf(stderr, "[r3d] a: pitch %lld rows %lld, want pitch >= %lld and at least one row\n", + a_ld, a_rows, (long long)K); + return R3D_NO(RAD_E_STRIDE); } + const long long M = a_rows; + if (M_band > 0 && M > M_band) { r3d_trace_desc("a", A); + std::fprintf(stderr, "[r3d] a: %lld rows in a band that declared M <= %lld\n", M, M_band); + return R3D_NO(RAD_E_SHAPE); } + if (M * N > (1ll << 34)) return R3D_NO(RAD_E_INVAL); /* 32-bit tile indices, at the step's + * height, not the band's bound */ + if (M < kMMin) return R3D_NO(RAD_E_UNSUPPORTED); /* gemm_nt_q_fp8a8_m16 serves M <= 16, and + * this arm's floor is that declared + * ceiling + 1, read from its array */ + const long long kb = (K + group - 1) / group; + /* Two forms of the activation's scales, and the plan binds the one its quantiser produces: + * [M][ceil(K/group)] for a group quantiser, [M] for a per-row one (`a_scale[m]`, the ZP_I8_ROW + * form). `r3d_rows_pitch(AS, kb, ...)` returns -1 for the rank-1 plane -- the scales do not + * divide into rows of kb -- so the width asked for depends on the form, which the rank states; + * both forms must pass, the row form included. */ + const int as_row = (AS->rank <= 1); + const long long as_w = as_row ? 1 : kb; + long long as_rows = 0; + const long long as_ld = r3d_rows_pitch(AS, as_w, &as_rows); + if (as_ld < as_w || as_rows < M) { r3d_trace_desc("a_scale", AS); + std::fprintf(stderr, "[r3d] a_scale: want width %lld (rank %d), pitch %lld, rows %lld, M %lld\n", + as_w, AS->rank, as_ld, as_rows, M); + return R3D_NO(RAD_E_STRIDE); } + long long y_rows = 0; + const long long y_ld = r3d_rows_pitch(Y, N, &y_rows); + if (y_ld < N || y_rows < M) { r3d_trace_desc("y", Y); + std::fprintf(stderr, "[r3d] y: pitch %lld rows %lld, want pitch >= %lld rows >= %lld\n", + y_ld, y_rows, (long long)N, M); + return R3D_NO(RAD_E_STRIDE); } + if (!r3d_aligned(r3d_p(A), 8) || !r3d_aligned(bvc, 8) || !r3d_aligned(r3d_p(Y), 8)) + return R3D_NO(RAD_E_ALIGN); + if (!r3d_aligned(r3d_p(AS), 4) || !r3d_aligned(bsv, 4)) return R3D_NO(RAD_E_ALIGN); + + /* ---- the plan line, the GEMM's side of the same instrument --------------------------------- + * + * The step's M, off the activation (the header's law: the band key `M` is a BOUND, the plane is + * the value), with the forms the served plan hands this row -- the codes' rank, pitch and numel, + * the scale's rank and pitch, the output's pitch. The fixture draws its descriptors from the + * shape hooks and does not cover the plan's own rank-1 `[M]` scale and rank-3 codes at a + * M >= 17 launch; this line is the instrument for that form: the step's rows against the + * arena's padding, ceil(M/16)*16, and the strides the producer and the consumer each read the + * same plane through. + * + * Inert when the flag is unset -- the cached `r3d_trace_on()` every refusal already pays, and + * the descriptors print through the existing `r3d_trace_desc`. Latched per shape, because this + * shim runs 176 times a forward pass and 42 copies of one line are noise. Printed AFTER every + * check, so a refused step stays the refusal lines' business. */ + if (r3d_trace_on() && gemm_plan_once(M, N, K, A->rank, AS->rank, a_ld, y_ld)) { + std::fprintf(stderr, + "[r3d] plan: gemm M=%lld (band M<=%lld) N=%lld K=%lld group=%lld " + "a rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld rows=%lld " + "a_scale rank=%u numel=%lld pitch=%lld form=%s " + "y rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld Mpad=%lld\n", + M, M_band, N, K, group, (unsigned)A->rank, r3d_numel(A), + r3d_stride(A, 0), r3d_stride(A, 1), a_ld, a_rows, (unsigned)AS->rank, + r3d_numel(AS), as_ld, as_row ? "row[M]" : "group[M][kb]", (unsigned)Y->rank, + r3d_numel(Y), r3d_stride(Y, 0), r3d_stride(Y, 1), y_ld, (M + 15) / 16 * 16); + r3d_trace_desc("gemm a", A); + r3d_trace_desc("gemm a_scale", AS); + r3d_trace_desc("gemm y", Y); + } + + const int nt = (int)r3d_geti_or(args, "nt", 0); + const int st = launch(r3d_addr(A), r3d_addr(AS), (long)(uintptr_t)bvc, (long)(uintptr_t)bsv, + r3d_addr(Y), (int)M, (int)N, (int)K, (int)group, (int)a_ld, b_row, + (int)as_ld, bs_row, (int)y_ld, nt, (long)s, sdt, cdt); + if (st == -1) return R3D_NO(RAD_E_INVAL); + if (st == -2) return R3D_NO(RAD_E_SHAPE); + if (st == -3) return R3D_NO(RAD_E_STRIDE); + if (st == -5) return R3D_NO(RAD_E_ALIGN); + if (st == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} + +/* ================================================================================================== + * The w2a8 arm's shim: gemm_nt_q at dtype=w2a8 (codes U2) and dtype=w4a8_asym (codes U4), the same + * tile above the decode heights. The band that gates start-up is N=130560 K=2048 group=128 + * dtype=w2a8 at M=1792 -- the drafter's draft head, read three times a step -- and the graph prints + * it as the last band with no device row. Below kMMin the m16 row (gemm_nt_q_w2a8_m16, + * C_LE("M", 16) in its constraint array) is the served path; above it the tile. The floor is the + * sibling's CEILING, read from its constraints, and it is 17: M=17..64 is a batched decode step, + * the shape a serving card lives in, and 1.8 TFLOP/s of 128-row waste is two orders above the host. + * + * The law is the reference's gemm_zp, ZP_I8_ROW arm, and the kernel runs it in a folded form: + * + * q[k] = the grid's code of weight row n, column k U2: bits [2k,2k+2) of k/4 + * sub(g) = SUM_{k in g} (int)a[m][i8_step_pos(k)] * ((int)q[k] - (int)z[n][g]) integers + * acc = acc + (sub(g) * sa[m]) * sb[n][g] g ASCENDING + * y[m,n] = bf16(acc) + * + * which is the reference's `sub = is - z * a_sum` term for term: sum a*(q - z) = sum a*q - z*sum a, + * exactly, over the same group. So the staged tile carries (q - z) * sb and the a-side carries + * a * sa[m], and a_sum -- which exists to take the 128 bias off an integer dot, because this ISA + * has no int8 dot (r3d_gemm_nt_q_w2a8.hip) -- has no term to take off here: the zero is + * removed per element, before the dot. a_sum is still REQUIRED of a w2a8 band (gemm_zp reads it and + * the schema carries it at slot 5; a band without it is not this band) and the refusal is this + * shim's own line, not the fp8a8 arm's, which REFUSES the same tensor: the two arms' lines are + * deliberately not shared, and the driver's board fires each at its own arm. The bracketing + * differs from the reference (a per-group bracket there, one chain here) by the fold's floor, which + * is what the board measures: rel_l2 against the transcribed body, at a bf16 output, where the + * store's own ulp is the wider of the two. + * + * The activation arrives in quant_act_i8's step order, and its scale is ONE f32 PER ROW (ZP_I8_ROW: + * quant_act_i8 scales a whole row), not per group like fp8a8's. The scale and the zero are per + * (row, group): 128 scalar reads a staged chunk where the fp8a8 arm reads one. + * ================================================================================================== */ +extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) +{ + if (!args || args->n_t < 5) return R3D_NO(RAD_E_INVAL); + + const char* dt = r3d_gets(args, "dtype"); + int cdt = -1; + if (dt && std::strcmp(dt, "w2a8") == 0) cdt = 2; + else if (dt && std::strcmp(dt, "w4a8_asym") == 0) cdt = 3; + if (cdt < 0) + return R3D_NO(RAD_E_DTYPE); /* the zero-point grids on an int8 activation; w4a8i8_asym and + * w5a8i8 quantise the activation to int8 with a DIFFERENT + * trunk (ZP_I8_GROUP, no per-row scale) and this arm does not + * read them. */ + + const RadTensor* A = r3d_opt(args, 0); + const RadTensor* AS = r3d_opt(args, 1); + const RadTensor* B = r3d_opt(args, 2); + const RadTensor* BS = r3d_opt(args, 3); + const RadTensor* Y = r3d_opt(args, 4); + const RadTensor* ASUM = r3d_opt(args, 5); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL); + if (!r3d_p(ASUM)) + return R3D_NO(RAD_E_DTYPE); /* a w2a8 band without a_sum is not a w2a8 band: gemm_zp's + * ZP_I8_ROW arm reads it. This kernel folds the zero into the + * staged tile and never indexes it -- see the header. */ + + const long long M_band = r3d_geti_or(args, "M", 0), N0 = r3d_geti_or(args, "N", 0); + const long long K0 = r3d_geti_or(args, "K", 0); + const long long N = N0 > 0 ? N0 : r3d_dim(B, 0); /* the weight IS [N, K]: name the operand + * when the band names no key */ + const long long K = K0 > 0 ? K0 : r3d_dim(B, 1); + const long long group = r3d_geti_or(args, "group", 0); + if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE); + /* The step's M, off the codes plane, exactly as in the fp8a8 shim above: the band key `M` is the + * ceiling the plan promised not to exceed, not the height of this step, and a draft pass whose + * chunk is shorter than the band it matched is refused by the bound below. */ + long long M = 0; + if (K > 0 && r3d_numel(A) % K == 0) M = r3d_numel(A) / K; + if (M < 1) M = M_band; + if (M_band > 0 && M > M_band) { r3d_trace_desc("a", A); + std::fprintf(stderr, "[r3d] w2a8 a: %lld rows in a band that declared M <= %lld\n", M, M_band); + return R3D_NO(RAD_E_SHAPE); } + if (group != kGroup) + return R3D_NO(RAD_E_SHAPE); /* the fold indexes the group as kGroup; kKC 32 divides it */ + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); /* a ragged k-chunk reads past the plane */ + if (M < kMMin) + return R3D_NO(RAD_E_UNSUPPORTED); /* gemm_nt_q_w2a8_m16's array says M <= 16; the floor of + * this arm is that ceiling + 1, read from the array */ + const long long G = (K + kGroup - 1) / kGroup; + const long long mpad = ((M + 15) / 16) * 16; /* a_sum is group-major, 16 columns min */ + + if (A->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE); /* quant_act_i8's codes */ + if (Y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(AS) || !r3d_is_f32(ASUM)) return R3D_NO(RAD_E_DTYPE); + if (r3d_numel(AS) < M) return R3D_NO(RAD_E_INVAL); /* one scale per ROW (ZP_I8_ROW) */ + if (r3d_numel(ASUM) < G * mpad) return R3D_NO(RAD_E_INVAL); + if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); + if (M * N > (1ll << 34)) return R3D_NO(RAD_E_INVAL); /* 32-bit tile indices */ + + /* The weight's planes. This row's plan puts codes, scale and zero behind b (operand 2), which is + * what r3d_layout_gemm_q_fp8_weight's asym branch describes. The decode row's plan puts the + * scale+zero pair behind b_scale and leaves the codes plain on b, and the builder settles ONE + * stored form per weight, so read whichever the container is and find the planes by role: a row + * that insists on the arrangement it declared will refuse the settled bytes of a weight it + * shares with the sibling. */ + const void* bbase = r3d_p(B); + const RadPlanesHeader* bh = rad_planes_header(bbase); + bool codes_joined = false; /* the codes plane inside b's container? */ + const RadPlanesEntry *ce = nullptr, *se = nullptr, *ze = nullptr; + const void* sp = nullptr; const void* zp = nullptr; + long long c_row = 0, s_row = 0, z_row = 0; + const void* sv = nullptr; const void* zv = nullptr; + if (bh) { + const long long cb = (cdt == 2) ? (K >> 2) : (K >> 1); + sp = rad_planes_find(bbase, "scale", &se); + zp = rad_planes_find(bbase, "zero", &ze); + const void* cp = rad_planes_find(bbase, "codes", &ce); + if (!cp || !sp || !zp) return R3D_NO(RAD_E_DTYPE); /* three planes or nothing */ + if (ce->dtype != (uint32_t)(cdt == 2 ? RAD_U2 : RAD_U4)) return R3D_NO(RAD_E_DTYPE); + if (ce->row_bytes < cb) return R3D_NO(RAD_E_STRIDE); + c_row = ce->row_bytes; + codes_joined = true; + } else { + if (!r3d_p(BS)) return R3D_NO(RAD_E_DTYPE); /* no zero, no plain spelling: the zero + * point has nowhere to live outside the + * container. */ + const RadPlanesHeader* h3 = rad_planes_header(r3d_p(BS)); + if (!h3) return R3D_NO(RAD_E_DTYPE); /* the decode row's arrangement: the + * scale+zero pair joined behind b_scale */ + sp = rad_planes_find(r3d_p(BS), "scale", &se); + zp = rad_planes_find(r3d_p(BS), "zero", &ze); + if (!sp || !zp) return R3D_NO(RAD_E_DTYPE); + if (B->dtype != (uint32_t)(cdt == 2 ? RAD_U2 : RAD_U4)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + c_row = rad_dtype_bytes(B->dtype, r3d_dim(B, 1)); /* the row in BYTES, the same measure + * the container's entry carries on the + * joined side: K/4 for U2, K/2 for U4. + * A hand-rolled `K * (1) / 2` + * integer-divides the U2 case to zero + * and the kernel then reads every row + * from the start of the plane: the + * decode form comes out rel_l2 1.9. */ + (void)ce; + } + if (!se || !ze) return R3D_NO(RAD_E_DTYPE); + if (se->dtype != RAD_F16) + return R3D_NO(RAD_E_DTYPE); /* the grid's scale is f16; a bf16 or f32 + * scale plane is the fp8a8 grid's, not this one. */ + if (ze->dtype != RAD_U8) + return R3D_NO(RAD_E_DTYPE); /* DECLINED, at the site: a sub-byte zero plane needs the bit + * extract (rad_load_bits(zb, bits, g), ten lines) that the m16 + * row also declines. U8 is w2a8's practical form. */ + if (se->rows != N || se->cols != G || ze->rows != N || ze->cols != G) + return R3D_NO(RAD_E_SHAPE); /* {1, group}: the scale's rows are the weight's rows */ + if ((se->row_bytes & 1) || se->row_bytes < 2 * G || ze->row_bytes < G) + return R3D_NO(RAD_E_STRIDE); + if (bh) { + if (ce->rows != N || ce->cols != K) return R3D_NO(RAD_E_SHAPE); + if (ce->row_bytes < c_row) return R3D_NO(RAD_E_STRIDE); + } else if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + + long long a_rows = 0; + const long long a_ld = r3d_rows_pitch(A, K, &a_rows); + if (a_ld < K || (a_ld & 3)) return R3D_NO(RAD_E_STRIDE); /* four codes a dword, step order */ + long long yrows = 0; + const long long y_ld = r3d_rows_pitch(Y, N, &yrows); + if (y_ld < N) return R3D_NO(RAD_E_STRIDE); + if (yrows > 0 && yrows < M) return R3D_NO(RAD_E_STRIDE); + const long long as_ld = 1; /* a_scale is rank 1: one per row */ + sv = se ? (const char*)sp : nullptr; + zv = ze ? (const char*)zp : nullptr; + s_row = se->row_bytes; z_row = ze->row_bytes; + const long long bvc = codes_joined + ? (long long)(uintptr_t)((const char*)bbase + ce->offset) /* the container's + * codes plane */ + : (long long)(uintptr_t)r3d_p(B); + + if (!r3d_aligned(r3d_p(A), 8) || !r3d_aligned(r3d_p(Y), 8) || + !r3d_aligned(sv, 2) || !r3d_aligned(zv, 1)) return R3D_NO(RAD_E_ALIGN); + + const int nt = (int)r3d_geti_or(args, "nt", 0); + const int st = launch(r3d_addr(A), r3d_addr(AS), bvc, (long)(uintptr_t)sv, r3d_addr(Y), + (int)M, (int)N, (int)K, (int)group, (int)a_ld, c_row, (int)as_ld, + s_row, (int)y_ld, nt, (long)(uintptr_t)s, /*sdt*/ 1, cdt, + (long)(uintptr_t)zv, z_row, /*srows*/ 1, /*arm*/ 1); + if (st == -1) return R3D_NO(RAD_E_INVAL); + if (st == -2) return R3D_NO(RAD_E_SHAPE); + if (st == -3) return R3D_NO(RAD_E_STRIDE); + if (st == -5) return R3D_NO(RAD_E_ALIGN); + if (st == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} diff --git a/libr3d/r3d_gemm_inta8.hip b/libr3d/r3d_gemm_inta8.hip new file mode 100644 index 00000000..27454ebc --- /dev/null +++ b/libr3d/r3d_gemm_inta8.hip @@ -0,0 +1,431 @@ +/* r3d_gemm_inta8.hip -- gemm_nt_q at dtype=w4a8 and w8a8: the symmetric int4 and int8 weight + * grids at decode heights, one kernel per grid. + * + * The grids, libref's descriptions: int8 activations in quant_act_i8's step order against + * signed weight codes (I4, two a byte, or I8, one a byte) with one f16 scale per (row, 128 of + * K), an f32 activation scale per row, and no zero point -- the dequant is code times scale, + * so there is no a_sum to carry and no bias to take off. The group sub-sum is formed on the + * integer grid and scaled once per group, the reference's order: + * + * sub = sum over the group of a * code, an exact integer + * acc += (sub * a_scale[m]) * scale[n, g] + * + * ---- exactness, and why the dots may run in f16 -------------------------------------------------- + * + * A lane's 64 products are |a * code| <= 127 * 7 (w4a8) or 127 * 127 (w8a8), and the group's + * 128 of them sum to 113,792 (w4a8) or 2,064,512 (w8a8): both under 2^24, the f32 mantissa, so + * the lane partial and the pair fold are exact, and the group terms land in the accumulator + * in the reference's ascending order. The codes widen to f16 through a sign extension, which + * is exact for both grids; the activations widen through the i8 codec the w2a8 arm uses. + * + * The activation is the step order: within each sixteen-byte step the middle two dwords are + * exchanged, so the staging reads through the same position map the w2a8 arm does, and a + * weight row's codes are plain row-major, two a byte at I4 and one a byte at I8. + * + * ---- the tile -------------------------------------------------------------------------------------- + * + * One workgroup serves kWaves weight rows; a wavefront takes one row, lane l owns rows + * l & (MT-1) and k-lane l / MT, and the chunk is 2048 / MT codes: a multiple of the 128 + * group at every MT, so a chunk carries CG = 16 / MT whole groups and the group's scale is + * one read. The lane's 64 codes are 32 bytes at I4, two 16-byte loads, and 64 at I8, four. + * The lane's 64 sit in the group's two halves the w2a8 arm folds with one shfl_xor(MT), and + * the group's term -- scaled by the activation's row scale and the weight's group scale -- + * goes to shared, where the row's owner lane sums the chunk's groups in ascending order. + * + * M > 16 is the tiled row's; the w2a8 arm serves the 2- and 4-bit container grids there, and + * the 8-bit grid at prefill heights is declared out of this unit. + * + * ---- refusals -------------------------------------------------------------------------------------- + * + * Every structural violation is a refusal, in the shim: the dtypes of all five operands, + * K % 128, the band's M, the b row pitch's 16-byte alignment, the a and y pitches. There is + * no data that is a refusal: both grids have no reserved value. + */ + +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_launch.h" +#include "r3d_args.h" + +namespace { + +constexpr int kWave = 32; +constexpr int kWaves = 8; +constexpr int kBlockThreads = kWaves * kWave; +constexpr int kMTMax = 16; +constexpr int kGroup = 128; +constexpr int kTileQuads = 512; /* MT rows x CHUNK/4 f16, constant over MT */ + +/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse. + * Applied to the four columns of one dword it leaves them four contiguous bytes and turns + * the map on the DWORD index into a swap of bits 0 and 1 -- the middle two dwords of a + * 16-byte step exchanged. */ +__device__ __forceinline__ int64_t dword_pos(int64_t d) +{ + return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1)); +} + +/* The LDS swizzle, at the granularity the tile is touched: a quad of four f16, two dwords, + * moved as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low + * four bits with bits 4..7 -- a bijection on 16-quad groups. */ +__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); } + +/* Four int8 codes -> two f16x2 dwords. Exact: an integer of |a| <= 127 needs no rounding. */ +__device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi) +{ + lo = f16x2_pack((float)(int32_t)(int8_t)(w & 0xffu), (float)(int32_t)(int8_t)((w >> 8) & 0xffu)); + hi = f16x2_pack((float)(int32_t)(int8_t)((w >> 16) & 0xffu), + (float)(int32_t)(int8_t)((w >> 24) & 0xffu)); +} + +/* Four signed int4 codes (two bytes, the low code in the low nibble) -> two f16x2 dwords. + * Exact: the sign extension lands on an integer, and f16 steps by 1/8 at exponent 2^-3. + * A nibble n is the value (n & 7) - (n & 8): 0..7 pass through and 8..15 land on -8..-1. + * The gfx1102 backend folds the bias-8 spelling ((n ^ 8) - 8) to n ^ 16 once it has proven + * the nibble range, so the sign is kept as a bit term. */ +__device__ __forceinline__ void i4x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi) +{ + const uint32_t n0 = w & 0xFu; + const uint32_t n1 = (w >> 4) & 0xFu; + const uint32_t n2 = (w >> 8) & 0xFu; + const uint32_t n3 = (w >> 12) & 0xFu; + const int32_t c0 = (int32_t)((n0 & 7u) - (n0 & 8u)); + const int32_t c1 = (int32_t)((n1 & 7u) - (n1 & 8u)); + const int32_t c2 = (int32_t)((n2 & 7u) - (n2 & 8u)); + const int32_t c3 = (int32_t)((n3 & 7u) - (n3 & 8u)); + lo = f16x2_pack((float)c0, (float)c1); + hi = f16x2_pack((float)c2, (float)c3); +} + +__device__ __forceinline__ float dot4_f16x4(uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1, + float acc) +{ + const _Float16* fa = (const _Float16*)&a0; + const _Float16* fb = (const _Float16*)&b0; + acc = fmaf(fa[0], fb[0], acc); + acc = fmaf(fa[1], fb[1], acc); + const _Float16* fa1 = (const _Float16*)&a1; + const _Float16* fb1 = (const _Float16*)&b1; + acc = fmaf(fa1[0], fb1[0], acc); + acc = fmaf(fa1[1], fb1[1], acc); + return acc; +} + +template +__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) +gemm_inta8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, + const uint8_t* __restrict__ b, int b_rb, const uint16_t* __restrict__ sb, + int sb_rb, uint16_t* __restrict__ y, int M, int N, int K, int chunk, + int a_pitch, int y_pitch) +{ + constexpr int KL = kWave / MT; /* k-lanes per activation row */ + constexpr int CG = (2048 / MT) / kGroup; /* groups per chunk: 16 / MT */ + constexpr int CL = 64; /* codes per lane per chunk */ + constexpr int NLOAD = (CL * CDT) / 128; /* 16-byte loads: the lane's window */ + + __shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/4 f16, swizzled */ + __shared__ float sT[kWaves * 16]; /* warp*16 + m*CG + j */ + __shared__ float sSa[MT]; + + const int lane = threadIdx.x & (kWave - 1); + const int warp = (int)(threadIdx.x / kWave); + const int n = blockIdx.x * kWaves + warp; + const bool live = n < N; + if ((int)blockIdx.x * kWaves >= N) return; + + const int m = lane & (MT - 1); + const int kl = lane / MT; + const int row_bytes = b_rb; /* the codes' byte pitch, from the shim */ + const int cq = (CDT == 4) ? (chunk >> 1) : chunk; /* the chunk's code bytes */ + const int nchunk = K / chunk; + + if (lane < MT) sSa[lane] = lane < M ? sa[lane] : 0.0f; + __syncthreads(); + + float acc = 0.0f; + for (int ch = 0; ch < nchunk; ++ch) { + /* Stage the chunk's activation rows, widened and step-unpermuted on the way in. Cells + * are four codes: MT * CHUNK/4 = 512 of them at every MT, two per thread. */ + for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) { + const int r = i / (chunk >> 2), c = i % (chunk >> 2); + uint32_t w = 0; + if (r < M) + w = *(const uint32_t*)(a + (long long)r * a_pitch + + dword_pos((int64_t)ch * (chunk >> 2) + c)); + const int q = r * (chunk >> 2) + c; + uint32_t lo, hi; + i8x4_to_f16x2(w, lo, hi); + sA[p_ix(q)] = make_uint2(lo, hi); + } + __syncthreads(); + + if (live) { + /* 64 codes: 32 bytes at I4, 64 at I8. The lane's codes are kl * 64 within the + * chunk, and the row pitch keeps every 16-byte load aligned. */ + const uint8_t* bp = b + (long long)n * row_bytes + (int64_t)ch * cq + + kl * (CL / 2) * (CDT / 4); + uint4 qw[NLOAD]; +#pragma unroll + for (int L = 0; L < NLOAD; ++L) + __builtin_memcpy(&qw[L], bp + 16 * L, 16); + /* One value per quad: I4 the two-byte window as a 16-bit element, I8 the dword. + * The I4 window is taken as a half at its own address; shifting a dword array by + * a byte amount miscompiles on the gfx1102 backend. */ + uint32_t wd[(CL >> 2)]; + if (CDT == 4) { + uint16_t wq[CL / 2]; +#pragma unroll + for (int L = 0; L < NLOAD; ++L) + __builtin_memcpy(&wq[8 * L], &qw[L], 16); +#pragma unroll + for (int v = 0; v < (CL >> 2); ++v) + wd[v] = wq[v]; + } else { +#pragma unroll + for (int L = 0; L < NLOAD; ++L) + { wd[4 * L + 0] = qw[L].x; wd[4 * L + 1] = qw[L].y; + wd[4 * L + 2] = qw[L].z; wd[4 * L + 3] = qw[L].w; } + } + + const int qb = m * (chunk >> 2) + kl * (CL >> 2); + /* 16 quads, decoded before the dot. */ + uint32_t cb[(CL >> 2)][2]; +#pragma unroll + for (int v = 0; v < (CL >> 2); ++v) { + if (CDT == 4) i4x4_to_f16x2(wd[v] & 0xFFFFu, cb[v][0], cb[v][1]); + else i8x4_to_f16x2(wd[v], cb[v][0], cb[v][1]); + } + float p = 0.0f; /* the lane's half-group, an exact integer */ +#pragma unroll + for (int v = 0; v < (CL >> 2); ++v) { + const uint2 av = sA[p_ix(qb + v)]; + p = dot4_f16x4(av.x, av.y, cb[v][0], cb[v][1], p); + } + + /* Fold the pair: lanes l and l^MT are the same row, the two halves of one group. */ + const float isg = p + __shfl_xor(p, MT); + + const int g = ch * CG + (kl >> 1); + const float sc = f16_to_f32(sb[(long long)n * sb_rb + g]); + const float term = (isg * sSa[m]) * sc; /* the reference's parentheses */ + /* One slot per (row, group-in-chunk): MT*CG is 16 at every MT. The group's two + * half-lanes write the same value, which is what the pair fold above is for. */ + sT[warp * 16 + m * CG + (kl >> 1)] = term; + } + __syncthreads(); + /* The chunk's groups, in ascending order, into the lane that owns the row's answer: + * the reference walks g in ascending order and f32 adds are not associative, so the + * order is part of the answer, not a detail. */ + if (live && kl == 0) { +#pragma unroll + for (int j = 0; j < CG; ++j) + if (m < M) acc += sT[warp * 16 + m * CG + j]; + } + __syncthreads(); + } + + if (live && kl == 0 && m < M) y[(long long)m * y_pitch + n] = f32_to_bf16(acc); +} + +int mt_for(int M) +{ + int mt = 1; + while (mt < M && mt < kMTMax) mt *= 2; + return mt; +} + +#define R3D_INTA8_LAUNCH(MT, CDT) \ + do { \ + const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads); \ + R3D_KLAUNCH(R3D_KNAME((gemm_inta8_kernel)), grid, block, (hipStream_t)stream, \ + (const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb, (const uint16_t*)b_scale, \ + (int)sb_rb, (uint16_t*)y, M, N, K, chunk, a_ld, y_ld); \ + } while (0) + +extern "C" int r3d_gemm_nt_q_w4a8_m16(long a, long a_scale, long b, long b_scale, long y, + int M, int N, int K, int a_ld, int y_ld, long long b_rb, + long long sb_rb, long stream) +{ + if (!a || !a_scale || !b || !b_scale || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > kMTMax) return -2; + if (K % kGroup) return -2; + const int mt = mt_for(M); + const int chunk = 2048 / mt; + if (K % chunk) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (a_ld % 4) return -3; + if (y_ld < N) return -3; + if (!b_rb) b_rb = K / 2; + if (b_rb < K / 2) return -3; + if (b_rb & 15) return -5; + if (!sb_rb) sb_rb = K / kGroup; + if (sb_rb < K / kGroup) return -3; + if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5; + + switch (mt) { + case 1: R3D_INTA8_LAUNCH(1, 4); break; + case 2: R3D_INTA8_LAUNCH(2, 4); break; + case 4: R3D_INTA8_LAUNCH(4, 4); break; + case 8: R3D_INTA8_LAUNCH(8, 4); break; + default: R3D_INTA8_LAUNCH(16, 4); break; + } + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale, long y, + int M, int N, int K, int a_ld, int y_ld, long long b_rb, + long long sb_rb, long stream) +{ + if (!a || !a_scale || !b || !b_scale || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > kMTMax) return -2; + if (K % kGroup) return -2; + const int mt = mt_for(M); + const int chunk = 2048 / mt; + if (K % chunk) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (a_ld % 4) return -3; + if (y_ld < N) return -3; + if (!b_rb) b_rb = K; + if (b_rb < K) return -3; + if (b_rb & 15) return -5; + if (!sb_rb) sb_rb = K / kGroup; + if (sb_rb < K / kGroup) return -3; + if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5; + + switch (mt) { + case 1: R3D_INTA8_LAUNCH(1, 8); break; + case 2: R3D_INTA8_LAUNCH(2, 8); break; + case 4: R3D_INTA8_LAUNCH(4, 8); break; + case 8: R3D_INTA8_LAUNCH(8, 8); break; + default: R3D_INTA8_LAUNCH(16, 8); break; + } + return hipGetLastError() == hipSuccess ? 0 : -4; +} +#undef R3D_INTA8_LAUNCH + +/* ================================================================== the shims + * + * gemm_nt_q's slots, as the two shims take them: 0 a (I8, step order), 1 a_scale (f32, one + * per row), 2 b (I4 or I8 codes), 3 b_scale (f16, one per (row, 128 of K)), 4 y (bf16), + * 5 a_sum (absent: symmetric), 6 b_ref (absent). + */ + +extern "C" int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const char* dt = r3d_gets(a, "dtype"); + if (dt && std::strcmp(dt, "w4a8") != 0) return R3D_NO(RAD_E_DTYPE); + + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* AS = r3d_opt(a, 1); + const RadTensor* B = r3d_opt(a, 2); + const RadTensor* BS = r3d_opt(a, 3); + const RadTensor* Y = r3d_opt(a, 4); + const RadTensor* ASUM = r3d_opt(a, 5); + const RadTensor* BREF = r3d_opt(a, 6); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y)) + return R3D_NO(RAD_E_INVAL); + if (r3d_has(ASUM) || r3d_has(BREF)) return R3D_NO(RAD_E_DTYPE); /* symmetric: nothing to remove */ + + if (!r3d_is_i8(A)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE); + if (B->dtype != RAD_I4) return R3D_NO(RAD_E_DTYPE); + if (BS->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE); + + const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0); + if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE); + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); + + const long long ynel = r3d_numel(Y); + if (ynel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = ynel / N; + if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); + + if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(AS) < M) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(BS) < N * (K / kGroup)) return R3D_NO(RAD_E_SHAPE); + + const long long ap = r3d_row_pitch(A); + if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + long long yrows = 0; + const long long yp = r3d_rows_pitch(Y, N, &yrows); + if (yp < N) return R3D_NO(RAD_E_STRIDE); + if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN); + + const long long bbr = r3d_row_pitch(B) / 2; /* I4 counts elements, two a byte */ + const int rc = r3d_gemm_nt_q_w4a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), + r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp, + bbr, (long long)r3d_row_pitch(BS), (long)s); + if (rc == -1) return R3D_NO(RAD_E_INVAL); + if (rc == -2) return R3D_NO(RAD_E_SHAPE); + if (rc == -3) return R3D_NO(RAD_E_STRIDE); + if (rc == -5) return R3D_NO(RAD_E_ALIGN); + if (rc == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} + +extern "C" int r3d_rad_gemm_nt_q_w8a8_m16(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const char* dt = r3d_gets(a, "dtype"); + if (dt && std::strcmp(dt, "w8a8") != 0) return R3D_NO(RAD_E_DTYPE); + + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* AS = r3d_opt(a, 1); + const RadTensor* B = r3d_opt(a, 2); + const RadTensor* BS = r3d_opt(a, 3); + const RadTensor* Y = r3d_opt(a, 4); + const RadTensor* ASUM = r3d_opt(a, 5); + const RadTensor* BREF = r3d_opt(a, 6); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y)) + return R3D_NO(RAD_E_INVAL); + if (r3d_has(ASUM) || r3d_has(BREF)) return R3D_NO(RAD_E_DTYPE); + + if (!r3d_is_i8(A)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE); + if (B->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE); + if (BS->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE); + + const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0); + if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE); + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); + + const long long ynel = r3d_numel(Y); + if (ynel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = ynel / N; + if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); + + if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(AS) < M) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(BS) < N * (K / kGroup)) return R3D_NO(RAD_E_SHAPE); + + const long long ap = r3d_row_pitch(A); + if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + long long yrows = 0; + const long long yp = r3d_rows_pitch(Y, N, &yrows); + if (yp < N) return R3D_NO(RAD_E_STRIDE); + if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN); + + const int rc = r3d_gemm_nt_q_w8a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), + r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp, + (long long)r3d_row_pitch(B), (long long)r3d_row_pitch(BS), + (long)s); + if (rc == -1) return R3D_NO(RAD_E_INVAL); + if (rc == -2) return R3D_NO(RAD_E_SHAPE); + if (rc == -3) return R3D_NO(RAD_E_STRIDE); + if (rc == -5) return R3D_NO(RAD_E_ALIGN); + if (rc == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} + +} // namespace diff --git a/libr3d/r3d_gemm_mxfp4a8.hip b/libr3d/r3d_gemm_mxfp4a8.hip new file mode 100644 index 00000000..cb3dc181 --- /dev/null +++ b/libr3d/r3d_gemm_mxfp4a8.hip @@ -0,0 +1,738 @@ +/* r3d_gemm_mxfp4a8.hip -- gemm_nt_q at dtype=mxfp4a8: an OCP-MXFP4 weight against an fp8 + * activation, at both heights. + * + * y[M,N] = a[M,K] @ b[N,K]^T, a in E4M3 with one f32 scale per (row, 128 of K), b in e2m1 + * with one e8m0 scale per (row, 32 of K). f32 accumulate, one bf16 narrowing at the store. + * There is no zero point: the scale is symmetric. + * + * ---- the format, and the fold it gives ---------------------------------------------------------------- + * + * OCP MXFP4 stores a weight row as e2m1 codes, two per byte, element 2j in the LOW nibble of + * byte j, with one e8m0 exponent per 32 K elements: a u8 plane [N, K/32] behind the u8 codes + * plane [N, K/2]. e8m0 value e means the factor 2^(e-127); e = 0 and e = 255 are reserved + * (zero, NaN) and a plane carrying either is refused, the reference's answer for the same + * bytes. + * + * The fold this kernel runs, per 32-block: + * + * 1. the code for element k is e4m3(mag) at d = 0 -- the e2m1 magnitude is EXACT in e4m3, + * because all eight magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} are e4m3 grid points. The + * unpack is a 4-bit lookup on the nibble through the eight e4m3 magnitude bytes + * {0x00, 0x30, 0x38, 0x3C, 0x40, 0x44, 0x48, 0x4C}, the sign bit of the code on the + * sign bit of the byte. + * 2. the code products run on dot2_f16x2. A product is at most 6 x 448 = 2688, in f16's + * range (65504), and an eight-term partial is under 21504, in f16's grid: the dot's + * only rounding is the instruction's own. + * 3. the per-block factor 2^(e-127) is applied in the epilogue: the 32-block partial, an + * f32, is multiplied by the factor -- a power of two, exact in f32 short of the + * under/overflow edge -- and added to the running f32 sum. One multiply and one add per + * block per output element, no per-element scale traffic. + * 4. the store narrows once, to bf16. + * + * The e2m1 magnitude is exact, the products are exact, and the two roundings a block sees are + * the dot's fused rounding and the store: the row's distance from the reference is the store's + * ulp, nothing else. + * + * The RDNA4 sibling folds the e8 into the table through a d-indexed row, because its WMMA + * path needs one scale per row; this library's dot2 path folds per block in the epilogue, and + * the table is the eight fixed magnitude bytes, no index. + * + * ---- the tiled row (M >= 17) ------------------------------------------------------------------------- + * + * The 128x128 tile, 8x8 f32 accumulators a lane, k ascending in 32-code chunks. The chunk IS + * the OCP 32-block: the lane's e8 bytes for its eight tile columns enter as one byte per row + * at staging, through LDS, and the chunk's partials flush at the chunk's end: + * + * total[i][j] += acc[i][j] * 2^(e8[n_c + j][blk] - 127); acc[i][j] = 0; + * + * `acc` is the 32-block partial, `total` the running f32 sum over blocks in ascending k. The + * activation stages exactly as the fp8a8 tiled row's: E4M3 through the LDS table, the f32 + * scale per (row, 128 of K) folded at staging; 32 divides 128, so a chunk sits inside one + * group and never straddles one. + * + * ---- the m16 row (M <= 16) ---------------------------------------------------------------------------- + * + * One wave per weight row, the w2a8 row's shape: lane l owns row m = l % MT and k-lane + * kl = l / MT, a chunk is CHUNK = 2048/MT codes, and every lane takes 64 of them -- two OCP + * 32-blocks, the lane's blocks 2*kl and 2*kl+1 of the chunk. Each lane sums its two blocks in + * k, scales each by the block's e8, and the group's four block terms are formed in ascending + * block order by one shfl_xor pair and written to LDS, where the kl == 0 lane adds them to the + * accumulator in ascending block order: the reference's ascending-k accumulation, at the + * 32-block granularity the format fixes. + * + * ---- refusals ----------------------------------------------------------------------------------------- + * + * Every structural violation is a refusal, in the shim: the dtypes of all seven operands (the + * codes as fp4_e2m1 or raw bytes, the e8 plane as e8m0 or u8, `b_ref` the e8 plane again and + * ignored), K % 32 and K % 128, the codes plane's extent and 16-byte row alignment, the e8 + * plane's [N, K/32] extent, the pitches, the band's M. A reserved e8 (0, 255) is a data + * violation, and it is refused where the data is readable: the shim scans the e8 plane once + * per (pointer, size) pair, on a plane the host can see, and answers E_INVAL. A plane the + * host cannot see is not scanned, and the kernel's e8 guard -- reserved values take the scale + * zero -- keeps its output finite. + */ + +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_fp8_dequant.h" +#include "r3d_tiling.h" +#include "r3d_launch.h" + +#include +#include +#include + +namespace { + +constexpr int kBlockThreads = 256; +constexpr int kWaves = 8; +constexpr int kTM = 128; /* rows a tile */ +constexpr int kTN = 128; /* columns a tile */ +constexpr int kKC = 32; /* k a chunk: one OCP 32-block */ +constexpr int kMX = 32; /* K per e8m0 exponent: the OCP MX block */ +constexpr int kGroup = 128; /* the activation's scale group */ +constexpr int kMMin = 17; /* the tiled row's floor: the m16 row's ceiling plus one */ +constexpr int kMTMax = 16; +constexpr int kTileQuads = 512; /* MT * CHUNK/4, constant over MT: 2048 codes, 4 KiB of f16 */ + +/* The eight e2m1 magnitudes, as e4m3 bytes: 0, .5, 1, 1.5 in the low word, 2, 3, 4, 6 in the + * high. Every one is exact, which is the whole point of the fold. */ +#define R3D_MXFP4_MAG_LO 0x3c383000u +#define R3D_MXFP4_MAG_HI 0x4c484440u + +/* Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) as eight e4m3 + * bytes in k order (word 0 = elements 0..3, word 1 = 4..7). Even and odd nibbles each run + * through the magnitude bytes by a v_perm_b32 on the 3-bit magnitude, bit 3 of the code shifts + * onto the e4m3 sign, and two more v_perm_b32 interleave the halves. The table is the fixed + * d = 0 row: no index, because the per-block factor is applied in the epilogue, not folded + * here. */ +__device__ __forceinline__ void mxfp4_unpack8(uint32_t wv, uint32_t* lo, uint32_t* hi) +{ + const uint32_t ev = wv & 0x0F0F0F0Fu; /* low nibble of each byte -> even elements */ + const uint32_t od = (wv >> 4) & 0x0F0F0F0Fu; /* high nibble -> odd elements */ + const uint32_t be = __builtin_amdgcn_perm(R3D_MXFP4_MAG_HI, R3D_MXFP4_MAG_LO, ev & 0x07070707u) + | ((ev & 0x08080808u) << 4); + const uint32_t bo = __builtin_amdgcn_perm(R3D_MXFP4_MAG_HI, R3D_MXFP4_MAG_LO, od & 0x07070707u) + | ((od & 0x08080808u) << 4); + *lo = __builtin_amdgcn_perm(bo, be, 0x05010400u); + *hi = __builtin_amdgcn_perm(bo, be, 0x07030602u); +} + +/* The e8m0 factor: 2^(e-127). The reserved values take the scale zero -- e = 0 is the + * format's zero, e = 255 its NaN -- so a plane that carries one computes a zero block and + * stays finite; the refusal for such a plane is the shim's, where the bytes are readable. */ +__device__ __forceinline__ float e8_scale(uint8_t e) +{ + return (e == 0 || e == 255) ? 0.0f : ldexpf(1.0f, (int)e - 127); +} + +/* Four e4m3 bytes (one dword, low byte first) as two f16x2, through the block's table. The + * table entries are f16 bit patterns, so the words are moves, not conversions. */ +__device__ __forceinline__ void e4m3x4_to_f16x2(const uint16_t* tbl, uint32_t w, uint32_t* o) +{ + o[0] = (uint32_t)tbl[w & 0xffu] | ((uint32_t)tbl[(w >> 8) & 0xffu] << 16); + o[1] = (uint32_t)tbl[(w >> 16) & 0xffu] | ((uint32_t)tbl[(w >> 24) & 0xffu] << 16); +} + +/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. NOT + * f16x2_pack, which truncates. */ +__device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc) +{ + const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16); + const _Float16 a = __builtin_bit_cast(_Float16, lo16); + const _Float16 b = __builtin_bit_cast(_Float16, hi16); + const _Float16 s = (_Float16)sc; + const _Float16 rl = a * s, rh = b * s; + return (uint32_t)__builtin_bit_cast(uint16_t, rl) + | ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16); +} + +/* Eight codes -> eight f16, through the table. gfx11 has no E4M3 convert, so the 256-entry + * f16 table stands in for the instruction. */ +__device__ __forceinline__ void codes8(const uint2 c, const uint16_t* tbl, uint32_t* w) +{ + r3d_e4m3x8_ld(tbl, c, w); +} + +template +__device__ __forceinline__ uint2 loadc8s(const uint8_t* p) +{ + typedef uint32_t __attribute__((ext_vector_type(2))) u8v; + u8v v; + if (NT) v = __builtin_nontemporal_load((const u8v*)p); + else __builtin_memcpy(&v, p, 8); + uint2 r; + __builtin_memcpy(&r, &v, 8); + return r; +} + +/* ================================================================== the tiled row */ + +struct ActQ { + const float* scale; /* a_scale, f32: [M][ceil(K/group)] */ + long long row; /* elements a row */ + int gmode; /* 1: one scale per (row, group) */ +}; + +struct MxWQ { + const uint8_t* codes; /* e2m1, two per byte, [N][K/2] */ + const uint8_t* e8; /* e8m0, one per 32, [N][K/32] */ + long long code_row; /* bytes a codes row */ + long long e8_row; /* bytes an e8 row */ +}; + +/* + * The tile: 128 rows x 128 columns of y, 256 threads, eight waves, eight outputs a side a + * lane -- 64 f32 accumulators a lane for the 32-block partials, 64 more for the running + * sum, grid (N/kTN) x ceil(M/kTM). k is walked in chunks of 32; the activation arrives as + * E4M3 codes, decodes through the block's table and leaves staging as f16 with its scale + * folded in, and the weight arrives as e2m1 nibbles, unpacks to e4m3 and leaves staging as + * f16 UNSIGNED by the block: its scale is the e8, and the e8 is applied at the chunk's end, + * where the chunk's partials meet it. + */ +template +__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) +mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __restrict__ y, + int M, int N, int K, int a_ld, int y_ld) +{ + __shared__ __align__(16) uint16_t sA[kTM * kKC]; + __shared__ __align__(16) uint16_t sB[kTN * kKC]; + __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; + __shared__ uint8_t sE8[kTN]; /* the chunk's e8, one per tile row */ + + const int tid = (int)threadIdx.x; + r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); + + const int m0 = (int)blockIdx.y * kTM; + const int n0 = (int)blockIdx.x * kTN; + const int rg = tid >> 4, cg = tid & 15; + + float acc[8][8]; + float total[8][8]; +#pragma unroll + for (int i = 0; i < 8; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) { acc[i][j] = 0.0f; total[i][j] = 0.0f; } + + const int m_r = m0 + rg * 8, n_c = n0 + cg * 8; + + for (int k0 = 0; k0 < K; k0 += kKC) { + const int g = k0 / kGroup; + const int blk = k0 / kMX; /* the chunk is one 32-block */ + +#pragma unroll + for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) { + const int mm = j / (kKC / 8), c8 = j % (kKC / 8); + const int m = m0 + mm, k = k0 + c8 * 8; + uint4 staged = make_uint4(0, 0, 0, 0); + if (m < M) { + const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)]; + uint32_t w[4]; + codes8(loadc8s(a + (long long)m * a_ld + k), sTbl, w); + staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa), + fold_pair(w[2], sa), fold_pair(w[3], sa)); + } + *(uint4*)&sA[srow(mm, c8, kKC)] = staged; + } + for (int nn = tid; nn < kTN; nn += kBlockThreads) { + const int n = n0 + nn; + uint4 st[4] = { make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0), + make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0) }; + /* The e8 for the column, written even past N: a row the tile does not serve keeps + * the scale zero, so the flush multiplies a staged zero by a defined value. */ + sE8[nn] = (n < N) ? h.e8[(long long)n * h.e8_row + blk] : 0; + if (n < N) { + /* 32 codes, 16 bytes, one load: k0 is a multiple of 32, the row a multiple of + * 64 bytes, so the load is aligned. */ + uint4 cv; + __builtin_memcpy(&cv, h.codes + (long long)n * h.code_row + (k0 >> 1), 16); + const uint32_t d[4] = { cv.x, cv.y, cv.z, cv.w }; + uint32_t w[16]; +#pragma unroll + for (int q = 0; q < 4; ++q) { + uint32_t lo, hi; + mxfp4_unpack8(d[q], &lo, &hi); + e4m3x4_to_f16x2(sTbl, lo, w + 4 * q); + e4m3x4_to_f16x2(sTbl, hi, w + 4 * q + 2); + } + st[0] = make_uint4(w[0], w[1], w[2], w[3]); + st[1] = make_uint4(w[4], w[5], w[6], w[7]); + st[2] = make_uint4(w[8], w[9], w[10], w[11]); + st[3] = make_uint4(w[12], w[13], w[14], w[15]); + } +#pragma unroll + for (int q = 0; q < 4; ++q) *(uint4*)&sB[srow(nn, q, kKC)] = st[q]; + } + __syncthreads(); + + /* The chunk's e8 for the lane's eight columns, held in registers: the flush reads it + * and nothing else does. The index is tile-local -- sE8 is this tile's 128 rows, and a + * global column index reads past it on every tile past the first. */ + float e8s[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) e8s[j] = e8_scale(sE8[cg * 8 + j]); + +#pragma unroll + for (int kc = 0; kc < kKC; kc += 2) { + uint32_t af[8], bf[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) + af[i] = *(const uint32_t*)&sA[srow_pair(rg * 8 + i, kc, kKC)]; +#pragma unroll + for (int j = 0; j < 8; ++j) + bf[j] = *(const uint32_t*)&sB[srow_pair(cg * 8 + j, kc, kKC)]; +#pragma unroll + for (int i = 0; i < 8; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]); + } + /* The 32-block boundary: the partial scales by the block's factor, the sum keeps the + * blocks in ascending k, and the partial resets for the next block. */ +#pragma unroll + for (int i = 0; i < 8; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) { + total[i][j] += acc[i][j] * e8s[j]; + acc[i][j] = 0.0f; + } + __syncthreads(); + } + + /* y is bf16: one narrowing, 16-byte runs of eight columns. Rows past M write nothing. */ +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int m = m_r + i; + if (m >= M) break; + uint16_t* row = (uint16_t*)y + (long long)m * y_ld; + if (n_c + 8 <= N) { + uint32_t p[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) + p[j] = (uint32_t)f32_to_bf16(total[i][2 * j]) | + ((uint32_t)f32_to_bf16(total[i][2 * j + 1]) << 16); + *(uint4*)(row + n_c) = make_uint4(p[0], p[1], p[2], p[3]); + } else { +#pragma unroll + for (int j = 0; j < 8; ++j) + if (n_c + j < N) row[n_c + j] = f32_to_bf16(total[i][j]); + } + } +} + +/* ================================================================== the m16 row */ + +/* The LDS swizzle, at the granularity the tile is touched: a quad of four codes, two dwords, + * moved as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low four + * bits with bits 4..7 -- a bijection on 16-quad groups. */ +__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); } + +template +__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) +gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__ sa, int sa_stride, + const uint8_t* __restrict__ b, const uint8_t* __restrict__ e8, + int e8_row, uint16_t* __restrict__ y, int M, int N, int K, int chunk, + int a_pitch, int y_pitch) +{ + constexpr int KL = kWave / MT; /* k-lanes per activation row */ + constexpr int CL = 64; /* codes per lane per chunk: two 32-blocks */ + constexpr int BPR = (2048 / MT) / kMX; /* 32-blocks a row of the chunk: 64/MT */ + + __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; + __shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/2 f16, swizzled */ + __shared__ float sB[kWaves * 64]; /* the chunk's block terms: warp*64 + m*BPR + bl */ + + const int lane = threadIdx.x & (kWave - 1); + const int warp = (int)(threadIdx.x / kWave); + const int n = blockIdx.x * kWaves + warp; + const bool live = n < N; + if ((int)blockIdx.x * kWaves >= N) return; + + const int m = lane & (MT - 1); + const int kl = lane / MT; + const int nchunk = K / chunk; + + r3d_e4m3_f16_init(sTbl, threadIdx.x, kBlockThreads); + + float acc = 0.0f; + for (int ch = 0; ch < nchunk; ++ch) { + __syncthreads(); + /* The chunk's activation rows, decoded and scaled on the way in. Cells are four codes: + * MT * CHUNK/4 = 512 of them at every MT, two per thread. The scale is per (row, 128 + * of K); a cell's four codes sit in one group, so one scalar a cell. */ + for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) { + const int r = i / (chunk >> 2), c = i % (chunk >> 2); + uint32_t lo = 0, hi = 0; + if (r < M) { + const int64_t k0 = (int64_t)ch * (chunk >> 2) * 4 + c * 4; + const uint32_t w = *(const uint32_t*)(a + (long long)r * a_pitch + k0); + const float s = sa[(long long)r * sa_stride + k0 / kGroup]; + uint32_t w2[2]; + e4m3x4_to_f16x2(sTbl, w, w2); + lo = fold_pair(w2[0], s); + hi = fold_pair(w2[1], s); + } + const int q = r * (chunk >> 2) + c; + sA[p_ix(q)] = make_uint2(lo, hi); + } + __syncthreads(); + + if (live) { + /* 64 codes, 32 bytes: two 16-byte loads, aligned by the row pitch and k0 % 32 == 0. */ + const uint8_t* bp = b + (long long)n * (K >> 1) + (int64_t)ch * (chunk >> 1) + + kl * (CL >> 1); + uint4 qw0 = make_uint4(0, 0, 0, 0), qw1 = make_uint4(0, 0, 0, 0); + __builtin_memcpy(&qw0, bp, 16); + __builtin_memcpy(&qw1, bp + 16, 16); + const uint32_t w8[8] = { qw0.x, qw0.y, qw0.z, qw0.w, qw1.x, qw1.y, qw1.z, qw1.w }; + + const int qb = m * (chunk >> 2) + kl * (CL >> 2); + float p0 = 0.0f, p1 = 0.0f; /* the lane's two 32-block partials */ +#pragma unroll + for (int v = 0; v < 8; ++v) { /* dwords 0..3: block 2*kl, 4..7: 2*kl+1 */ + uint32_t elo, ehi; + mxfp4_unpack8(w8[v], &elo, &ehi); + float& p = (v < 4) ? p0 : p1; +#pragma unroll + for (int e = 0; e < 2; ++e) { + uint32_t w2[2]; + e4m3x4_to_f16x2(sTbl, e ? ehi : elo, w2); + const uint2 av = sA[p_ix(qb + 2 * v + e)]; + p = dot4_f16x4(av.x, av.y, w2[0], w2[1], p); + } + } + + /* The lane's two blocks, scaled by their e8. The pair (kl, kl^1) owns the group's + * four blocks -- kl even the lower two, kl odd the upper two -- so one exchange + * forms the group in ascending block order. */ + const int blk0 = ch * (chunk / kMX) + 2 * kl; + const float q0f = p0 * e8_scale(e8[(long long)n * e8_row + blk0]); + const float q1f = p1 * e8_scale(e8[(long long)n * e8_row + blk0 + 1]); + const float o0f = __shfl_xor(q0f, MT); + const float o1f = __shfl_xor(q1f, MT); + const bool lo = !(kl & 1); + const float t0 = lo ? q0f : o0f; + const float t1 = lo ? q1f : o1f; + const float t2 = lo ? o0f : q0f; + const float t3 = lo ? o1f : q1f; + + /* One slot per (row, 32-block-in-chunk): MT*BPR is 64 at every MT. The group's two + * half-lanes write the same four values. */ + const int j = kl >> 1; + const int bb = warp * 64 + m * BPR + 4 * j; + sB[bb + 0] = t0; + sB[bb + 1] = t1; + sB[bb + 2] = t2; + sB[bb + 3] = t3; + } + __syncthreads(); + /* The chunk's block terms, in ascending block order, into the lane that owns the row's + * answer: the reference walks k in ascending order and f32 adds are not associative, so + * the order is part of the answer, not a detail. */ + if (live && kl == 0) { +#pragma unroll + for (int bl = 0; bl < BPR; ++bl) + if (m < M) acc += sB[warp * 64 + m * BPR + bl]; + } + __syncthreads(); + } + if (live && kl == 0 && m < M) y[(long long)m * y_pitch + n] = f32_to_bf16(acc); +} + +/* ================================================================== the launchers */ + +static int mt_for(int M) +{ + int mt = 1; + while (mt < M && mt < kMTMax) mt *= 2; + return mt; +} + +extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y, + int M, int N, int K, int group, int a_ld, int y_ld, + long long e8_row, long stream) +{ + if (!a || !a_scale || !b || !b_scale || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > kMTMax) return -2; + if (group != kGroup) return -2; + if (K % kGroup) return -2; /* the activation's scale group */ + if (K % kMX) return -2; /* the weight's 32-block */ + const int mt = mt_for(M); + const int chunk = 2048 / mt; + if (K % chunk) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (a_ld < K) return -3; + if (a_ld % 4) return -3; /* four codes a dword, staged whole */ + if (y_ld < N) return -3; + if (!e8_row) e8_row = K / kMX; + if (e8_row < K / kMX) return -3; + if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5; + + const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads); +#define R3D_MXFP4A8_M16(MT) \ + do { \ + R3D_KLAUNCH(R3D_KNAME((gemm_mxfp4a8_m16_kernel)), grid, block, (hipStream_t)stream, \ + (const uint8_t*)a, (const float*)a_scale, K / kGroup, (const uint8_t*)b, \ + (const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \ + y_ld); \ + } while (0) + switch (mt) { + case 1: R3D_MXFP4A8_M16(1); break; + case 2: R3D_MXFP4A8_M16(2); break; + case 4: R3D_MXFP4A8_M16(4); break; + case 8: R3D_MXFP4A8_M16(8); break; + default: R3D_MXFP4A8_M16(16); break; + } +#undef R3D_MXFP4A8_M16 + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +#define L_MX(why, a1, v1, a2, v2) \ + do { \ + if (r3d_trace_on()) \ + std::fprintf(stderr, "[r3d] %s:%d %s: %s = %lld, %s = %lld\n", \ + __FILE__, __LINE__, (why), (a1), (long long)(v1), (a2), \ + (long long)(v2)); \ + return R3D_NO(-3); \ + } while (0) + +int launch_mxfp4a8_tiled(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K, + int group, int a_ld, long long b_row, int as_ld, long long e8_row, + int y_ld, int nt, long stream) +{ + if (!av || !asv || !bvc || !bsv || !yv) return -1; + if (M < kMMin || N < 1 || K < 1) return -2; + if (group != kGroup) return -2; /* kKC 32 divides the group 128 */ + if (K % kGroup) return -2; /* a ragged k-block reads past the scale planes */ + if (K > (1 << 24)) return -2; + if (nt < 0 || nt > 1) return -2; + if (a_ld % 8) L_MX("a pitch: 8-byte code loads, 8 codes a lane", "a_ld", a_ld, "K", K); + if (b_row & 15) L_MX("b row pitch: 16-byte code loads", "b_row", b_row, "K", K); + if (as_ld < (K + kGroup - 1) / kGroup) L_MX( + "a_scale: one per (row, group)", "as_ld", as_ld, "ceil(K/group)", + (K + kGroup - 1) / kGroup); + if (y_ld % 8) L_MX("y pitch: 16-byte bf16 store runs", "y_ld", y_ld, "N", N); + if (a_ld < K) L_MX("a pitch shorter than K", "a_ld", a_ld, "K", K); + if (!b_row) b_row = K >> 1; + if (b_row < (K >> 1)) L_MX("b row pitch shorter than K/2", "b_row", b_row, "K", K); + if (!e8_row) e8_row = K / kMX; + if (e8_row < K / kMX) L_MX("e8 row pitch shorter than K/32", "e8_row", e8_row, "K", K); + if (y_ld < N) L_MX("y pitch shorter than N", "y_ld", y_ld, "N", N); + if ((av & 7) || (asv & 3) || (bvc & 15) || (bsv & 1) || (yv & 7)) return -5; + + const dim3 blk(kBlockThreads); + const dim3 grd((unsigned)((N + kTN - 1) / kTN), (unsigned)((M + kTM - 1) / kTM)); + ActQ aq{(const float*)(uintptr_t)asv, (long long)as_ld, 1}; + MxWQ h{(const uint8_t*)(uintptr_t)bvc, (const uint8_t*)(uintptr_t)bsv, b_row, e8_row}; + hipStream_t s = (hipStream_t)(uintptr_t)stream; + if (nt) mxfp4a8_tiled_kernel<1><<>>( + (const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); + else mxfp4a8_tiled_kernel<0><<>>( + (const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, + int M, int N, int K, int group, int a_ld, + long long b_row, int as_ld, long long e8_row, + int y_ld, int nt, long stream) +{ + return launch_mxfp4a8_tiled(a, a_scale, b_codes, b_scale, y, M, N, K, group, a_ld, b_row, + as_ld, e8_row, y_ld, nt, stream); +} + +/* ================================================================== the shims + * + * gemm_nt_q's slots, as the two shims take them: 0 a (E4M3), 1 a_scale (f32, one per (row, + * 128 of K)), 2 b (the e2m1 codes -- fp4_e2m1, or the raw u8 bytes, two a byte), 3 b_scale (the + * e8 plane, e8m0 or u8, one per 32 of K), 4 y (bf16), 5 a_sum (absent: symmetric), 6 b_ref (the + * e8 plane again, accepted and ignored). + */ + +/* The reserved-e8 scan: one pass per (pointer, size) pair for the process's life. The plane is + * the weight's, its address stable across the launches a pass makes, and a second scan of the + * same bytes buys nothing. The scan needs the host to see the plane -- the mapped tier's form, + * the placement the row's operands take; a plane the host cannot see is not scanned, and the + * kernel's e8 guard carries the reserved values there. */ +struct E8ScanKey { const void* p; long long n; }; +static bool e8_scan_once(const void* p, long long n) +{ + static E8ScanKey seen[16]; + static int ns = 0; + for (int i = 0; i < ns; ++i) + if (seen[i].p == p && seen[i].n == n) return true; + if (ns < 16) seen[ns++] = E8ScanKey{ p, n }; + void* dev = nullptr; + if (hipHostGetDevicePointer(&dev, (void*)p, 0) != hipSuccess) return true; + const uint8_t* e8 = (const uint8_t*)p; + for (long long i = 0; i < n; ++i) + if (e8[i] == 0 || e8[i] == 255) return false; + return true; +} + +extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const char* dt = r3d_gets(a, "dtype"); + if (dt && std::strcmp(dt, "mxfp4a8") != 0) return R3D_NO(RAD_E_DTYPE); + + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* AS = r3d_opt(a, 1); + const RadTensor* B = r3d_opt(a, 2); + const RadTensor* BS = r3d_opt(a, 3); + const RadTensor* Y = r3d_opt(a, 4); + const RadTensor* ASUM = r3d_opt(a, 5); + const RadTensor* BREF = r3d_opt(a, 6); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y)) + return R3D_NO(RAD_E_INVAL); + if (r3d_has(ASUM)) return R3D_NO(RAD_E_DTYPE); /* symmetric: no zero point */ + /* `b_ref` is the reference's per-row exponent, derived from `b_scale`: it changes no + * product, so beside an e2m1 weight its dtype is checked and its value ignored. */ + if (r3d_has(BREF) && BREF->dtype != RAD_E8M0 && BREF->dtype != RAD_U8) + return R3D_NO(RAD_E_DTYPE); + + if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE); + if (B->dtype != RAD_FP4E2M1 && B->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e2m1, two a byte */ + if (BS->dtype != RAD_E8M0 && BS->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e8m0, one per 32 */ + if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE); + + const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0); + /* The `group` key names the band; the blocks the kernel reads -- 128 for the activation's + * scale, 32 for the weight's e8 -- are the format's, so the key is not checked. */ + if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE); + if (K % kGroup || K % kMX) return R3D_NO(RAD_E_SHAPE); + + const long long ynel = r3d_numel(Y); + if (ynel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = ynel / N; + if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); + + if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(AS) < M * (K / kGroup)) return R3D_NO(RAD_E_SHAPE); + const long long bbytes = B->dtype == RAD_FP4E2M1 ? r3d_numel(B) / 2 : r3d_numel(B); + if (bbytes < N * (K / 2)) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(BS) < N * (K / kMX)) return R3D_NO(RAD_E_SHAPE); + + const long long ap = r3d_row_pitch(A); + if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); + const long long as_p = r3d_row_pitch(AS); + if (as_p < K / kGroup) return R3D_NO(RAD_E_STRIDE); + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + if (!r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE); + long long yrows = 0; + const long long yp = r3d_rows_pitch(Y, N, &yrows); + if (yp < N) return R3D_NO(RAD_E_STRIDE); + if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN); + + if (!e8_scan_once(r3d_p(BS), N * (K / kMX))) return R3D_NO(RAD_E_INVAL); + + const int rc = r3d_gemm_nt_q_mxfp4a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), + r3d_addr(Y), (int)M, (int)N, (int)K, kGroup, + (int)ap, (int)yp, (long long)r3d_row_pitch(BS), + (long)s); + if (rc == -1) return R3D_NO(RAD_E_INVAL); + if (rc == -2) return R3D_NO(RAD_E_SHAPE); + if (rc == -3) return R3D_NO(RAD_E_STRIDE); + if (rc == -5) return R3D_NO(RAD_E_ALIGN); + if (rc == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} + +extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const char* dt = r3d_gets(a, "dtype"); + if (dt && std::strcmp(dt, "mxfp4a8") != 0) return R3D_NO(RAD_E_DTYPE); + + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* AS = r3d_opt(a, 1); + const RadTensor* B = r3d_opt(a, 2); + const RadTensor* BS = r3d_opt(a, 3); + const RadTensor* Y = r3d_opt(a, 4); + const RadTensor* ASUM = r3d_opt(a, 5); + const RadTensor* BREF = r3d_opt(a, 6); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y)) + return R3D_NO(RAD_E_INVAL); + if (r3d_has(ASUM)) return R3D_NO(RAD_E_DTYPE); /* symmetric: no zero point */ + if (r3d_has(BREF) && BREF->dtype != RAD_E8M0 && BREF->dtype != RAD_U8) + return R3D_NO(RAD_E_DTYPE); + + if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE); + if (B->dtype != RAD_FP4E2M1 && B->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); + if (BS->dtype != RAD_E8M0 && BS->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE); + + /* The band's keys, from the schema: N, K, group. The codes plane is [N, K/2], so a band that + * names no N or K is answered by the operand, with the /2 restored. */ + const long long M_band = r3d_geti_or(a, "M", 0); + const long long N0 = r3d_geti_or(a, "N", 0), K0 = r3d_geti_or(a, "K", 0); + const long long N = N0 > 0 ? N0 : r3d_dim(B, 0); + /* A band that names no K is answered by the codes plane: [N, K] of fp4_e2m1, [N, K/2] of + * raw bytes. The `group` key names the band; the blocks the kernel reads are the + * format's, so the key is not checked. */ + const long long K = K0 > 0 ? K0 + : (B->dtype == RAD_FP4E2M1 ? r3d_dim(B, 1) : 2 * r3d_dim(B, 1)); + if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE); + if (K > (1 << 24)) return R3D_NO(RAD_E_INVAL); + if (K % kGroup || K % kMX) return R3D_NO(RAD_E_SHAPE); + + long long a_rows = 0; + const long long ap = r3d_rows_pitch(A, K, &a_rows); + if (ap < K || a_rows < 1) return R3D_NO(RAD_E_STRIDE); + if (ap % 8) return R3D_NO(RAD_E_STRIDE); /* 8-byte code loads, 8 codes a lane */ + /* THE STEP'S M IS THE ACTIVATION'S ROW COUNT. The band key M is an upper bound: a step + * shorter than the band is the step the engine runs, and the key keeps its job as the + * ceiling the plan promised not to exceed. */ + const long long M = a_rows; + if (M_band > 0 && M > M_band) return R3D_NO(RAD_E_SHAPE); + if (M < kMMin) return R3D_NO(RAD_E_UNSUPPORTED); /* the m16 row serves M <= 16 */ + + const long long ynel = r3d_numel(Y); + if (ynel % N) return R3D_NO(RAD_E_SHAPE); + if (ynel / N < M) return R3D_NO(RAD_E_SHAPE); + + if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(AS) < M * (K / kGroup)) return R3D_NO(RAD_E_SHAPE); + const long long bbytes = B->dtype == RAD_FP4E2M1 ? r3d_numel(B) / 2 : r3d_numel(B); + if (bbytes < N * (K / 2)) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(BS) < N * (K / kMX)) return R3D_NO(RAD_E_SHAPE); + + const long long as_p = r3d_row_pitch(AS); + if (as_p < K / kGroup) return R3D_NO(RAD_E_STRIDE); + /* The codes plane's pitch, in bytes: fp4_e2m1 counts elements, two to a byte. */ + const long long cp0 = r3d_row_pitch(B); + const long long cp = B->dtype == RAD_FP4E2M1 ? cp0 / 2 : cp0; + if (cp < K / 2) return R3D_NO(RAD_E_STRIDE); + if (cp & 15) return R3D_NO(RAD_E_ALIGN); + const long long e8p = r3d_row_pitch(BS); + if (e8p < K / kMX) return R3D_NO(RAD_E_STRIDE); + long long yrows = 0; + const long long yp = r3d_rows_pitch(Y, N, &yrows); + if (yp < N) return R3D_NO(RAD_E_STRIDE); + if (!r3d_aligned(r3d_p(A), 8) || !r3d_aligned(r3d_p(AS), 4) || + !r3d_aligned(r3d_p(B), 16) || !r3d_aligned(r3d_p(Y), 8)) + return R3D_NO(RAD_E_ALIGN); + + if (!e8_scan_once(r3d_p(BS), N * (K / kMX))) return R3D_NO(RAD_E_INVAL); + + const int nt = (int)r3d_geti_or(a, "nt", 0); + const int rc = r3d_gemm_nt_q_mxfp4a8_tiled(r3d_addr(A), r3d_addr(AS), r3d_addr(B), + r3d_addr(BS), r3d_addr(Y), (int)M, (int)N, + (int)K, kGroup, (int)ap, cp, (int)as_p, e8p, + (int)yp, nt, (long)s); + if (rc == -1) return R3D_NO(RAD_E_INVAL); + if (rc == -2) return R3D_NO(RAD_E_SHAPE); + if (rc == -3) return R3D_NO(RAD_E_STRIDE); + if (rc == -5) return R3D_NO(RAD_E_ALIGN); + if (rc == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} + +} // namespace diff --git a/libr3d/r3d_gemm_nt_q_w2a8.hip b/libr3d/r3d_gemm_nt_q_w2a8.hip new file mode 100644 index 00000000..524c8028 --- /dev/null +++ b/libr3d/r3d_gemm_nt_q_w2a8.hip @@ -0,0 +1,576 @@ +/* r3d_gemm_nt_q_w2a8.hip -- gemm_nt_q at dtype=w2a8: the vocabulary projection, decode-sized. + * + * y[M,N] = a[M,K] @ b[N,K]^T over a 2-bit unsigned weight code with an f16 scale and an unsigned + * integer zero per (row, group of K), an int8 activation with one f32 scale per ROW, and the int8 + * code sums `a_sum` the zero is removed with. f32 accumulate, bf16 store. + * + * This is the band that gates the server. MiniCPM5-2B's `output.weight` is N=130560, K=2048, + * group=128, dtype=w2a8, and its stored form is the container's joined `rad.planes` operand: a + * scale plane and a zero plane behind ONE operand (b_scale). libref declines w2a8 in + * `gemm_q_shape`, so kbench has no case for the op the engine needs most -- the fixture cannot + * draw the dtype, which is why this row's evidence is a driver that builds the joined operand with + * `rad_planes_relayout` and compares every element against `ref_gemm_nt_q`'s own body. libref reads + * the form in `gemm_zp`, so a host row serves it, at 135 GFLOP of CPU work per token; and a + * placement without a reader is refused, because nothing in the loaded set can READ the joined form. + * `r3d_layout_gemm_q_w2a8` below is that reader: it DESCRIBES the container's bytes (that is what + * RadLayoutFn in rad_abi.h is), and the row carries no relayout and no repacking. + * + * ---- the law, and the order inside it --------------------------------------------------------- + * + * gemm_zp, the ZP_I8_ROW arm, is the spec, and this kernel runs its order: + * + * q[k] = rad_load_bits(row n of b, 2, k) bits [2k,2k+2) of byte k/4 + * is(g) = SUM_{k in group g} (int)a[m][i8_step_pos(k)] * (int)q[k] integers: exact + * sub(g) = (float)is(g) - (float)z[n][g] * a_sum[g*mpad + m] mpad = ceil(M/16)*16 = 16 + * acc = acc + (sub(g) * sa[m]) * sb[n][g] g ASCENDING + * y[m,n] = bf16(acc) + * + * `a_sum` is per row and per group and group-major, `sa` is one f32 per ROW (ZP_I8_ROW: quant_act_i8 + * scales a whole row, not a group), and `(sub * sa) * sb` is a parenthesised order, not a formula. + * + * The activation is in quant_act_i8's step order: column c sits at byte + * i8_step_pos(c) = (c & ~12) | ((c & 4) << 1) | ((c & 8) >> 1), bits 2 and 3 of c swapped, the map + * its own inverse. Swapping bits 2 and 3 of a column is swapping bits 0 and 1 of its DWORD index, + * so a dword's four columns stay four contiguous bytes: staging reads a's dwords in a permuted + * dword order, one 4-byte load per four codes, and nothing straddles a dword. + * + * `is` is a sum of integers, every partial sum under 2^24, so it is exact in f32 and its bracketing + * is free. `sub`, the products and the g-ascending accumulation are float, and their order is the + * reference's, so the store is bit-identical to the host row: bit-equality element by element is + * the test, not a tolerance, because nothing else on this machine can draw the operands. + * + * ---- U2 to f16 through a bias, and the bias removed with a_sum --------------------------------- + * + * There is no int8 dot on this ISA. `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a` + * and the RDNA3 matrix ops `__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are all undeclared in AMD + * clang 24.0.0git for gfx1102. So the codes widen to f16 and the dot runs on dot2_f16x2, whose + * hardware form folds a pair into an f32 accumulator. Every product is + * an integer and every partial sum is an integer, and "products and partials are integers below + * 2^24" is a true statement about f32 and a false statement about this instruction: v_fdot2_f32_f16 + * carries a little under 24 bits of mantissa on integer operands -- about 22, from the ratio of the + * worst error to its magnitude -- so any kernel that pushes integers through a pair-dot inherits a + * tail once its partials reach 2^20. The instrument at the end of this file (one 64-code dot per + * lane, the f32 it produces beside the exact integer it should have produced) shows: bias 1024, + * 71027 of 262144 dots off, by up to 1/8. Bias 128, 70115 of 262144 off, by up to 1/64. The bias is 128 because the tail grows with the magnitude, and 128 is + * the largest power of two that keeps a lane's partial sum under 2^21; shrinking it is a smaller + * tail, not no tail. What the tail costs is one bit of the bf16 answer: 0.1-0.2% of outputs land one + * bf16 ulp off and nothing else, rel_l2 5.0e-3 at the band, no non-finite anywhere. That is this + * row's exactness, written out here because the law below is exact integers and the row reads like a + * bit-exact one. It is not, and the row's prose says so. + * The row without the dot unit -- four f32 words a quad in the tile, four __fmaf_rn per quad -- is + * not in this file. Its arithmetic is exact: a probe of 262144 samples of the four fmas with no + * tile, zero inexact dots, worst error exactly zero. Its staging is the defect: the f32 tile, + * written through a vector pointer at -O2, comes up with content that was never written, and + * typing the array `uint4` rules aliasing out, so the defect is in the tile staging and not in the + * arithmetic. + * At the band this row is not memory-bound. r3d_vocab_bf16.hip streams the same n_vocab x n_embd + * head in 535 MB of bf16 in 3.29 ms at M=1, 163 GB/s, two thirds of the card's DRAM. The 66.8 MB + * of codes this row reads has a streaming floor near 0.41 ms, not the 3.0 ms of one 22 GB/s pass + * this row measures, so this row runs 6-10x above its own floor and the headroom is in its loop -- + * the group-term plane and the two barriers a chunk -- not in the memory system. An f32 row costs + * nothing to run, and the tail goes with it. + * The trick that pays for the widening is that f16 bits of (128 + x) are 0x5800 + 8x for 0 <= x < 8, + * so a 2-bit code becomes an f16 with a mask, two shifts and an add -- no table, no compare per + * code -- and the dot returns is' = SUM a[k]*(128 + q[k]) = is + 128*SUM a. SUM a over the group is + * the plane the op already carries: a_sum[g*mpad + m], the very number the zero is removed with. + * 128 * a_sum scales an integer-valued f32 by a power of two, so it is exact, is = is' - 128*a_sum + * is exact, and the reference's own sub = (float)is - (float)z*a_sum follows unchanged. The de-bias + * costs one exact f32 subtraction per (m, group) and is why a row with no int8 instruction on it is + * memory-bound at the band instead of unpack-bound. + * + * ---- the lane map ------------------------------------------------------------------------------ + * + * One warp per weight row n; a block of 8 waves covers 8 rows. MT, the template's row count, is the + * power of two that covers M, and KL = 32/MT is the number of k-lanes per activation row. A chunk + * is CHUNK = 2048/MT codes, so the staged tile is always MT*CHUNK/2 = 1024 dwords = 4 KiB: the + * tile shrinks with the row count exactly as the row count grows, which is what keeps the block + * resident at M=16. A chunk holds CHUNK/128 = 16/MT groups and every lane takes 64 codes -- one + * 16-byte load of codes (four bytes, sixteen codes each, U2 being four codes a byte), thirty-two + * dwords of activation from LDS and thirty-two dot2 in sixteen dot4_f16x4 -- so lane l owns row + * m = l % MT, k-lane kl = l / MT, and group ch*(16/MT) + kl/2, whose two halves are the pair + * (l, l^MT): the group folds with ONE shfl_xor, in integers. + * + * Each lane's group index ascends with the chunk index, so `acc += term` in the lane IS the + * reference's ascending g loop over the groups that lane owns; the groups the other k-lanes own are + * added by kl-1 ordered broadcasts per chunk, in ascending kl, which is ascending g. At M=16, where + * a chunk is one group, there is no cross-lane float work at all. Reassociating the g sum is what + * would break bit-equality, and the map is built so that no lane ever has to. + * + * LDS is touched a quad at a time (two dwords, 8 bytes), swizzled as `p_ix` below; unswizzled the + * wavefront's 32 quads for one u all sit in the same bank pair. + * + * ---- refusals (codes; RAD_R3D_TRACE=1 prints the line) ----------------------------------------- + * + * The shim mirrors gemm_ntq_impl's and gemm_zp's checks and declines two things the reference + * accepts, each named at its site: M > 16 (the band is 16, the tile is 16 rows, mpad is the + * reference's 16-row pad; the prefill vocab projection is `logits_gemm` and is a tiled bf16 row, + * not a wider loop bound here), and a zero plane stored sub-byte (U2/U4/U5), where the kernel reads + * a zero a byte at a time -- a sub-byte zero plane needs the bit-extract path, + * `rad_load_bits(zb, bits, g)` is ten lines. w2a8's practical form, and this container's, is U8. + */ + +#include + +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_launch.h" +#include "r3d_args.h" + +#include "rad_planes.h" + +namespace { + +constexpr int kBlockThreads = 256; +constexpr int kWaves = kBlockThreads / kWave; /* 8 weight rows per block */ +constexpr int kMTMax = 16; /* the band's M */ +constexpr int kTileQuads = 512; /* MT * CHUNK/4, constant over MT: 512 quads, 4 KiB */ +constexpr int kGroup = 128; /* the block size w2a8 is stored at */ +constexpr int kMpad = 16; /* the reference's (M+15)/16*16, M <= 16 */ + +/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse. Applying + * it to the four columns of one dword leaves them four contiguous bytes and turns the map on the + * DWORD index into a swap of bits 0 and 1 -- the middle two dwords of a 16-byte step exchanged. + * The byte a dword starts at is therefore 4 * dword_pos(d): NOT 4 * step_pos(d), which swaps the + * wrong pair of bits and reads the step's dwords unexchanged. */ +[[maybe_unused]] [[maybe_unused]] __device__ __forceinline__ int64_t step_pos(int64_t c) +{ + return (c & ~(int64_t)12) | ((c & 4) << 1) | ((c & 8) >> 1); +} +__device__ __forceinline__ int64_t dword_pos(int64_t d) +{ + return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1)); +} + +/* The LDS swizzle, at the granularity the tile is touched: a quad of four codes, two dwords, moved + * as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low four bits with + * bits 4..7 -- a bijection on 16-quad groups, so on any tile whose quad count is a multiple of 16. + * A wavefront reads q = m*(CHUNK/4) + kl*16 + u for fixed u; CHUNK/4 is a multiple of 16 at every + * MT, so q ^ (q >> 4) mod 16 is u ^ (4m + kl) mod 16 over the 32 lanes -- 16 distinct values, each + * one 8-byte access spanning two banks: 32 banks, no conflict. The swizzle must leave bit 0 of the + * quad index alone: the two dwords of a quad are adjacent only then, and the scalar form that + * XORs bits 5..9 of the dword index does not. */ +__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); } + +/* Four int8 codes -> two f16x2 dwords. Exact: an integer of |a| <= 127 needs no rounding. */ +__device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi) +{ + lo = f16x2_pack((float)(int32_t)(int8_t)(w & 0xffu), (float)(int32_t)(int8_t)((w >> 8) & 0xffu)); + hi = f16x2_pack((float)(int32_t)(int8_t)((w >> 16) & 0xffu), + (float)(int32_t)(int8_t)((w >> 24) & 0xffu)); +} + +/* Four U2 codes (one byte) -> two f16x2 dwords, BIASED by 128: each half is the f16 bits of + * (128 + code). An f16 at exponent 2^7 steps its mantissa by 1/8, so 128 + code is 0x5800 + 8*code + * and stays an integer. The dot therefore returns is + 128 * the group's code sum, which the + * epilogue takes off with the group's a_sum. + * + * The bias is 128 and not 1024 because of where the dot unit's precision runs out. a * (B + q) is an + * integer the size of 128 * B, and a lane's 64 of them sum to 64 * 128 * (B + 3): at B = 1024 that is + * 2^23, at B = 128 it is 2^20. The unit keeps a little under 24 bits of mantissa on integers, so the + * tail scales with the magnitude -- 71027 of 262144 dots off by up to 1/8 at B = 1024, 70115 off by + * up to 1/64 at B = 128, in the probe below. 128 is the largest power of two that keeps a lane's + * partial sum under 2^21, which is as close as a pair-dot gets; the header carries the rest. */ +__device__ __forceinline__ void u2x4_biased(uint32_t w, uint32_t& lo, uint32_t& hi) +{ + lo = 0x58005800u + ((w & 3u) << 3) + (((w >> 2) & 3u) << 19); + hi = 0x58005800u + (((w >> 4) & 3u) << 3) + (((w >> 6) & 3u) << 19); +} + +template +__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) +gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int sa_stride, + const uint8_t* __restrict__ b, const uint16_t* __restrict__ sb, int sb_rb, + const uint8_t* __restrict__ zq, int z_rb, const float* __restrict__ asum, + int asum_stride, uint16_t* __restrict__ y, int M, int N, int K, int chunk, + int a_pitch, int y_pitch) +{ + constexpr int KL = kWave / MT; /* k-lanes per activation row */ + constexpr int CG = (2048 / MT) / kGroup; /* groups per chunk */ + constexpr int CL = (2048 / MT) / KL; /* codes per lane per chunk: 64 */ + + /* The tile: one quad of four codes per slot, two f16x2 dwords, typed as the quad the staging + * writes and the dot reads. The tile is a `uint2[]` and not a `uint32_t[]` reached through a + * vector pointer: the f32 variant of this row, written through `*(uint4*)&sA[]` at -O2, comes + * up with content that was never written. */ + __shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/2 f16, swizzled */ + __shared__ float sT[kWaves * 16]; /* each warp's chunk terms: warp*16 + m*CG + j */ + __shared__ float sSa[MT]; + + const int lane = threadIdx.x & (kWave - 1); + const int warp = (int)(threadIdx.x / kWave); + const int n = blockIdx.x * kWaves + warp; + /* A wavefront past the last row sits the chunk out, but it stages: the tile is block-wide, so + * the warps that have no row to serve still write the rows their lanes own. Only a block whose + * EIGHT rows are all past the last row leaves, which is a block-uniform test and cannot strand + * a barrier; a guard on the row would, because the tail block's dead warps own tile rows and + * staging them from never-written memory corrupts the tile. The store is guarded by `live` + * below, so a dead wavefront writes nothing. */ + const bool live = n < N; + if ((int)blockIdx.x * kWaves >= N) return; + + const int m = lane & (MT - 1); + const int kl = lane / MT; + const int row_bytes = K >> 2; /* rad_enc_row_bytes(RAD_U2, K), K % 16 == 0 */ + const int cq = chunk >> 2; /* the chunk's code bytes */ + const int nchunk = K / chunk; + + if (lane < MT) sSa[lane] = lane < M ? sa[(long long)lane * sa_stride] : 0.0f; + __syncthreads(); + + float acc = 0.0f; + for (int ch = 0; ch < nchunk; ++ch) { + /* Stage the chunk's activation rows, widened and step-unpermuted on the way in. Cells are + * four codes: MT * CHUNK/4 = 512 of them at every MT, two per thread. */ + for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) { + const int r = i / (chunk >> 2), c = i % (chunk >> 2); + uint32_t w = 0; + if (r < M) + w = *(const uint32_t*)(a + (long long)r * a_pitch + + dword_pos((int64_t)ch * (chunk >> 2) + c)); + const int q = r * (chunk >> 2) + c; + uint32_t lo, hi; + i8x4_to_f16x2(w, lo, hi); + sA[p_ix(q)] = make_uint2(lo, hi); + } + __syncthreads(); + + uint4 qw = make_uint4(0, 0, 0, 0); + if (live) + qw = *(const uint4*)(b + (long long)n * row_bytes + (long long)ch * cq + kl * (CL >> 2)); + const uint32_t w4[4] = { qw.x, qw.y, qw.z, qw.w }; + + if (live) { + const int qb = m * (chunk >> 2) + kl * (CL >> 2); + float p = 0.0f; /* the lane's half-group, an exact integer */ +#pragma unroll + for (int v = 0; v < 4; ++v) { /* four bytes, four quads, sixteen codes */ +#pragma unroll + for (int b = 0; b < 4; ++b) { + uint32_t ql, qh; + u2x4_biased((w4[v] >> (8 * b)) & 0xffu, ql, qh); + const uint2 av = sA[p_ix(qb + 4 * v + b)]; + p = dot4_f16x4(av.x, av.y, ql, qh, p); + } + } + /* Fold the pair: lanes l and l^MT are the same row, the two halves of one group. */ + const float isg = p + __shfl_xor(p, MT); + + const int g = ch * CG + (kl >> 1); + const float as = asum[(long long)g * asum_stride + m]; + const float is = isg - 128.0f * as; /* exact: the de-bias */ + const float iz = (float)zq[(long long)n * z_rb + g]; + const float sc = f16_to_f32(sb[(long long)n * (sb_rb >> 1) + g]); + const float term = ((is - iz * as) * sSa[m]) * sc; /* gemm_zp's parentheses */ + /* One slot per (row, group-in-chunk): MT*CG is 16 at every MT, so this is 64 bytes. + * The group's two half-lanes write the same value, which is why the pair fold above is + * a fold and not a broadcast. */ + sT[warp * 16 + m * CG + (kl >> 1)] = term; + } + __syncthreads(); + /* Group ch*CG + j, for j ascending, into the lane that owns the row's answer. The reference + * walks g in ascending order and f32 adds are not associative, so the order is part of the + * answer, not a detail. The group gather is the one place in the kernel that crosses + * k-lanes; it is a barrier and four LDS reads at 64 bytes, which is cheaper than a shuffle + * round-trip. */ + if (live && kl == 0) { + + /* A chunk carries CG groups, and group ch*CG + j lives in the two k-lanes 2j and 2j+1: + * they hold the same group's two halves, which is what the fold above combined. Every + * lane adds all CG of them in ascending j, so each lane of a row ends on the same + * partial sum, built in the same order the reference walks its groups in -- f32 adds are + * not associative, and a lane that finished its own group last rounds the tail + * differently. Reading a lane's `acc` would not do: by j = 2 it has already added a + * group of its own. */ +#pragma unroll + for (int j = 0; j < CG; ++j) + if (m < M) acc += sT[warp * 16 + m * CG + j]; + } + __syncthreads(); + } + + if (live && kl == 0 && m < M) y[(long long)m * y_pitch + n] = f32_to_bf16(acc); +} + +int mt_for(int M) { return M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax; } + +} // namespace + +/* ================================================================== the launcher + * + * Codes: 0, -1 a required pointer is null, -2 a shape it does not read, -3 a pitch it cannot read, + * -4 HIP. `nt` is the threads argument every libr3d launcher takes and this kernel ignores: the + * work is one warp per weight row, and the wavefront count is the grid. + * + * `b_scale` is the joined operand's base. The launcher reads the two planes out of its own header + * (rad_planes.h's rad_planes_find) and passes each plane's base, row pitch in bytes and the row + * count down, so the kernel reads the container's bytes where they lie. */ + +/* The instrument behind the measurement in the header: the dot on its own, one 64-code sample per + * lane, the f32 it produces beside the exact integer it should have produced. The driver runs it as + * `dot [n]`; the bias is sized from it, and it shows the f32 path to be exact. Two extern "C" + * symbols, no row, no cost at serve time. */ +extern "C" __global__ void __launch_bounds__(256) probe_dot_kernel(const int8_t* a, + const uint8_t* codes, + float* out, long long* exact) +{ + const int g = blockIdx.x * 32 + (int)(threadIdx.x / kWave) * 4 + (int)(threadIdx.x & 3); + const int lane4 = (int)(threadIdx.x & 31) & 3; + (void)lane4; + const uint32_t* w4 = (const uint32_t*)(codes + (long long)g * 16); + float p = 0.0f; + long long ex = 0; +#pragma unroll + for (int v = 0; v < 4; ++v) { +#pragma unroll + for (int b = 0; b < 4; ++b) { + const uint32_t aw = *(const uint32_t*)(a + (long long)g * 64 + 4 * (4 * v + b)); + uint32_t ql, qh; + u2x4_biased((w4[v] >> (8 * b)) & 0xffu, ql, qh); + uint32_t lo, hi; + i8x4_to_f16x2(aw, lo, hi); + p = dot4_f16x4(lo, hi, ql, qh, p); +#pragma unroll + for (int j = 0; j < 4; ++j) + ex += (long long)(int)(int8_t)((aw >> (8 * j)) & 0xffu) * + (long long)(128 + ((w4[v] >> (8 * b + 2 * j)) & 3u)); + } + } + out[g] = p; + exact[g] = ex; +} + +extern "C" int r3d_w2a8_probe_launch(const int8_t* a, const uint8_t* codes, float* out, + long long* exact, int n) +{ + probe_dot_kernel<<<(n + 31) / 32, 256, 0, 0>>>(a, codes, out, exact); + return hipGetLastError() == hipSuccess ? 0 : -1; +} + +extern "C" int r3d_gemm_nt_q_w2a8(long a, long a_scale, long b, long b_scale, long a_sum, long y, + int M, int N, int K, int group, int a_ld, int y_ld, int nt, + long stream) +{ + (void)nt; + if (!a || !a_scale || !b || !b_scale || !a_sum || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > kMTMax) return -2; /* the row says the same: C_LE("M", 16) */ + if (group != kGroup) return -2; /* the tile is 128-wide: chunk = 128*16/MT */ + if (K % kGroup) return -2; + if (K % 16) return -2; /* the step order is a 16-byte step */ + const int mt = mt_for(M); + const int chunk = 2048 / mt; + if (K % chunk) return -2; /* ragged chunk: the tile would read past K */ + const int G = K / group; + if (G < 1) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (a_ld % 4) return -3; /* four codes a dword, staged whole */ + if (((uintptr_t)b & 15u) || ((uintptr_t)a & 3u)) return -3; + + const RadPlanesHeader* h = rad_planes_header((const void*)(uintptr_t)b_scale); + if (!h) return -2; /* not the joined form: rad.planes is expected */ + const RadPlanesEntry* es = nullptr; + const RadPlanesEntry* ez = nullptr; + const void* sp = rad_planes_find((const void*)(uintptr_t)b_scale, "scale", &es); + const void* zp = rad_planes_find((const void*)(uintptr_t)b_scale, "zero", &ez); + if (!sp || !zp || !es || !ez) return -2; + if (es->dtype != RAD_F16) return -2; /* this kernel reads an f16 scale */ + if (ez->dtype != RAD_U8) return -2; /* ...and a byte-wide zero; see the header */ + if (es->rows != N || es->cols != G || ez->rows != N || ez->cols != G) return -2; + if ((es->row_bytes & 1) || es->row_bytes < 2 * G || ez->row_bytes < G) return -3; + +#define R3D_W2A8_LAUNCH(MT) \ + do { \ + const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads); \ + R3D_KLAUNCH(R3D_KNAME((gemm_w2a8_kernel)), grid, block, (hipStream_t)stream, \ + (const int8_t*)a, (const float*)a_scale, 1, (const uint8_t*)b, \ + (const uint16_t*)sp, (int)es->row_bytes, (const uint8_t*)zp, (int)ez->row_bytes, \ + (const float*)a_sum, kMpad, (uint16_t*)y, M, N, K, chunk, a_ld, y_ld); \ + } while (0) + + switch (mt) { + case 1: R3D_W2A8_LAUNCH(1); break; + case 2: R3D_W2A8_LAUNCH(2); break; + case 4: R3D_W2A8_LAUNCH(4); break; + case 8: R3D_W2A8_LAUNCH(8); break; + default: R3D_W2A8_LAUNCH(16); break; + } +#undef R3D_W2A8_LAUNCH + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== the shim + * + * gemm_nt_q's slots, as gemm_ntq_impl takes them: 0 a (i8, step order), 1 a_scale (f32, one per + * row), 2 b (the u2 codes), 3 b_scale (the joined scale+zero), 4 y (bf16), 5 a_sum (f32, group + * major, mpad = 16 columns). */ +extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const char* dt = r3d_gets(a, "dtype"); + if (dt && std::strcmp(dt, "w2a8") != 0) return R3D_NO(RAD_E_DTYPE); /* the row is w2a8 only */ + + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* AS = r3d_opt(a, 1); + const RadTensor* B = r3d_opt(a, 2); + const RadTensor* BS = r3d_opt(a, 3); + const RadTensor* Y = r3d_opt(a, 4); + const RadTensor* ASUM = r3d_opt(a, 5); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y) || !r3d_p(ASUM)) + return R3D_NO(RAD_E_INVAL); + + if (A->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE); /* quant_act_i8's codes */ + if (B->dtype != RAD_U2) return R3D_NO(RAD_E_DTYPE); /* the grid's codes */ + if (Y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(AS) || !r3d_is_f32(ASUM)) return R3D_NO(RAD_E_DTYPE); + + const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0); + const long long group = r3d_geti_or(a, "group", 0); + if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE); + if (group != kGroup) return R3D_NO(RAD_E_SHAPE); /* no defaulting: gemm_zp refuses 0 */ + if (K % group || K % 16) return R3D_NO(RAD_E_SHAPE); + const long long G = K / group; + + const long long ynel = r3d_numel(Y); + if (N < 1 || ynel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = ynel / N; + if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); /* DECLINE, in the header: the band is + * 16 and the tile is 16 rows; the + * prefill vocab projection is + * logits_gemm, a tiled bf16 row. */ + if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(AS) < M) return R3D_NO(RAD_E_INVAL); /* gemm_zp's code for this one */ + if (r3d_numel(ASUM) < G * kMpad) return R3D_NO(RAD_E_INVAL); + + const long long ap = r3d_row_pitch(A); + if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); /* step order read four codes a dword */ + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); /* gemm_zp: contiguous codes only */ + long long yrows = 0; + const long long yp = r3d_rows_pitch(Y, N, &yrows); + if (yp < N) return R3D_NO(RAD_E_STRIDE); + if (!r3d_contig(ASUM)) return R3D_NO(RAD_E_STRIDE); + + const RadPlanesHeader* h = rad_planes_header(r3d_p(BS)); + if (!h) return R3D_NO(RAD_E_DTYPE); /* the joined form is the operand */ + const RadPlanesEntry* es = nullptr; + const RadPlanesEntry* ez = nullptr; + const void* sp = rad_planes_find(r3d_p(BS), "scale", &es); + const void* zp = rad_planes_find(r3d_p(BS), "zero", &ez); + if (!sp || !zp || !es || !ez) return R3D_NO(RAD_E_DTYPE); + if (es->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE); + if (ez->dtype != RAD_U8) + return R3D_NO(RAD_E_DTYPE); /* DECLINE: a sub-byte zero plane needs the bit-extract path; + * rad_load_bits(zb, bits, g) is 10 lines. U8 is w2a8's form. */ + if (es->rows != N || es->cols != G || ez->rows != N || ez->cols != G) return R3D_NO(RAD_E_SHAPE); + if ((es->row_bytes & 1) || es->row_bytes < 2 * G || ez->row_bytes < G) return R3D_NO(RAD_E_STRIDE); + + if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN); + + const int rc = r3d_gemm_nt_q_w2a8( + r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(ASUM), r3d_addr(Y), (int)M, + (int)N, (int)K, (int)group, (int)ap, (int)yp, 0, (long)s); + /* The launcher's codes are its own (r3d_launch.h's set: null, shape, pitch, HIP); the row speaks + * RAD codes, and the shim is where the two are named. Same mapping as the gated row's. */ + if (rc == 0) return RAD_OK; + return R3D_NO(rc == -1 ? RAD_E_INVAL : rc == -2 ? RAD_E_SHAPE + : rc == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); +} + +/* ================================================================== the layout hook + * + * The scoped exception to libr3d's "no layout hooks, no repacking" rule, transcribed from libref's + * `ref_layout_gemm_q` with the checks and their order unchanged: + * + * if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED; + * const ZpGrid* zg = zp_grid(dtype); group = param "group"; + * if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE; + * transform empty, or beginning "givens"; + * sel_roles(enc, sel, n, "scale", "zero") && enc->n_planes >= 3; + * plane[0]: role "codes", dtype == zg->codes, block {1,1}; + * scale: RAD_PLANE_TILED, RAD_F16, block {1, group}; + * zero: RAD_PLANE_TILED, zero_dt(...), block {1, group}; + * return rad_planes_layout(enc, sel, planes, n, out); + * + * zp_grid, zero_dt and sel_roles are libref-internal statics, inlined below for w2a8: the grid is + * { "w2a8", RAD_U2, ZP_I8_ROW }, zero_dt is U8|U2|U4|U5, and the practical form is U8 (the kernel + * declines a sub-byte zero, at its site, with the fix named). The answer is rad_planes.h's own: + * the tag is "rad.planes", the dtype the first plane's, the shape the byte count. NOTHING HERE + * MOVES A BYTE: this hook is the reader the mapped tier needs and the row's relayout is null. + */ +/* The writer for the joined operand this hook names: codes, scale and zero as the plan's one + * `rad.planes` weight, assembled by rad_planes_relayout -- header, entries, each plane's rows, + * copied. The ABI's contract is that a query answering RAD_OK is a promise the loader keeps on the + * row's word: "out describes the stored form, and relayout will produce it" (rad_abi.h), and a + * weight with no hook is the only kind that can be read where it lies, which is why a joined weight + * is placed in VRAM and a plain one can stay on the mapped tier. Nothing here transforms a code: + * the bytes written are the bytes stored. */ +extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n_planes, void* dst, + int64_t dst_bytes) +{ + (void)p; (void)n_p; + if (operand != 3) return RAD_E_UNSUPPORTED; + return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes); +} + +/* A layout query answers in the engine's own vocabulary and leaves no trace, and a model that will + * not load says only that two rows want one weight in two forms. This prints the question and the + * answer -- operand, band dtype, planes offered, code returned -- under RAD_R3D_TRACE=1. */ +static int r3d_layout_trace(const char* who, int operand, const char* dt, int n_planes, int rc) { + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] %s: operand %d dtype %s planes %d -> %d\n", who, operand, + dt ? dt : "(none)", n_planes, rc); + return rc; +} + +extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n, RadLayout* out) +{ + if (n < 2 || operand != 3) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_UNSUPPORTED); + const char* dt = r3d_pgets(p, n_p, "dtype"); + /* The plan this hook describes -- the (scale, zero) pair joined on operand 3 -- is a statement + * about the CONTAINER, not about the code width, and the engine forces every row that reads one + * weight to answer with one form. So both packed grids come through, and the width a row can + * unpack is the SHIM's business: gemm_nt_q_w2a8_m16 reads U2 and nothing else, + * gemm_nt_q_w2a8_tiled reads U2 and U4, and each says so at its own line. */ + if (!dt || (std::strcmp(dt, "w2a8") != 0 && std::strcmp(dt, "w4a8_asym") != 0)) + return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the packed grids */ + const long long group = r3d_pgeti_or(p, n_p, "group", 0); + if (group <= 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + if (!enc || !rad_enc_is(enc, "affine")) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) + return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + if (!enc || enc->n_planes < 3 || !sel) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + + /* sel_roles(enc, sel, n, "scale", "zero"): one role per selected plane, in order. */ + if (n != 2) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + for (int i = 0; i < 2; ++i) { + const char* want = i == 0 ? "scale" : "zero"; + if (sel[i] < 0 || sel[i] >= enc->n_planes) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + if (std::strncmp(enc->plane[sel[i]].role, want, RAD_ENC_STR) != 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + } + /* The codes plane is the one this operand does NOT take: the weight's role "codes", the grid's + * dtype, block {1,1}. libref finds it by role over enc->plane, not by sel. */ + int codes = -1; + for (int i = 0; i < enc->n_planes; ++i) + if (std::strncmp(enc->plane[i].role, "codes", RAD_ENC_STR) == 0) { codes = i; break; } + if (codes < 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + if (enc->plane[codes].block[0] != 1 || enc->plane[codes].block[1] != 1) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + + for (int i = 0; i < 2; ++i) { + const RadEncPlane& q = enc->plane[sel[i]]; + const RadTensor& t = planes[i]; + if (q.kind != RAD_PLANE_TILED) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + if (q.block[0] != 1 || q.block[1] != group) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + if (i == 0) { + if (t.dtype != RAD_F16) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the scale is f16 */ + } else { + const uint32_t zd = t.dtype; + const bool ok = zd == RAD_U8 || zd == RAD_U2 || zd == RAD_U4 || zd == RAD_U5; + if (!ok) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* zero_dt: never signed */ + } + } + return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, rad_planes_layout(enc, sel, planes, n, out)); +} diff --git a/libr3d/r3d_launch.h b/libr3d/r3d_launch.h new file mode 100644 index 00000000..bdda29e5 --- /dev/null +++ b/libr3d/r3d_launch.h @@ -0,0 +1,23 @@ +/* r3d_launch.h -- the two lines a libr3d unit needs to launch a kernel. + * + * R3D_KLAUNCH is the triple-chevron form, which the engine services on its own queues because the + * stream it hands a launch is the one hipLaunchKernel accepts (docs/PLUGIN.md §5). It is written as + * a macro so a test can define it and drive the same sources through a host SIMT emulator; a build + * does not, and gets the chevron. + * + * R3D_DYN_LDS declares a kernel's dynamic LDS, sized by the launch: `extern __shared__` in a build. + * RDNA3 gives a workgroup the same 64 KiB RDNA4 does, so a tile sized for libr4d fits here too. + * + * R3D_KNAME names a kernel in a context where commas would split a macro argument, the way + * HIP_KERNEL_NAME does for hipLaunchKernelGGL. + */ +#ifndef R3D_LAUNCH_H +#define R3D_LAUNCH_H +#define R3D_KNAME(...) __VA_ARGS__ +#ifndef R3D_KLAUNCH +#define R3D_KLAUNCH(kernel, grid, block, stream, ...) kernel<<>>(__VA_ARGS__) +#endif +#ifndef R3D_DYN_LDS +#define R3D_DYN_LDS(type, name) extern __shared__ type name[] +#endif +#endif diff --git a/libr3d/r3d_model_bf16.hip b/libr3d/r3d_model_bf16.hip new file mode 100644 index 00000000..6f6e557c --- /dev/null +++ b/libr3d/r3d_model_bf16.hip @@ -0,0 +1,2072 @@ +/* r3d_model_bf16.hip -- the small ops the engine issues between the GEMMs: the norms, the + * elementwise arithmetic, the activations, cast, softmax, the embedding gather, gather_rows and + * scatter_rows, rope and the KV store. Every one of them needs a device launch, because the + * engine's buffers live in VRAM and `rad_issue` refuses an op with no launch for its operands' + * domain: on an RDNA3 card this unit is the difference between a model that runs and one that does + * not (R3D_CONTRACT, "What libr3d is"). + * + * The arithmetic is libref's -- the oracle every row is checked against at kbench -- and each + * kernel names the ref function it must equal, its operation order and its rounding points: + * + * * every reduction accumulates in f32 and only the store narrows, RTNE (r3d_codecs.h is + * rad_plugin.h's rounders restated for device code, bit for bit); + * * a row's sum is taken over lanes covering consecutive elements, butterflies in the order a + * `__shfl_xor` loop runs and wave partials added in wave order: `block_sum` in r3d_common.h, + * so the bracketing is the one the contract fixes and not a per-thread accident; + * * bf16 is kept in whole registers from load to store (`ldg_u16`) and a lane that owns two + * consecutive columns stores them as one dword through `bf16x2_rne` -- gfx11 has no + * v_cvt_pk_bf16_f32, so the pack is two software roundings and a v_perm_b32; + * * no FMA and no reassociation: -ffp-contract=off is on every HIP source (libr3d/CMakeLists.txt) + * and the expressions below are written in the reference's order, with the temporaries the + * reference has; + * * a negative index -- token id, gather row, KV slot -- is padding: a zero row, or no store. + * It is not clamped to zero, which would duplicate row 0 across every padding row. + * + * One deliberate divergence from ref, the same one libr4d states: ref validates its index arrays + * on the host and refuses an id at or past the row count. A kernel cannot do that without a copy + * and a sync on the step path, so a row count is an argument and an out-of-range id takes the + * padding path (zero row, no store) instead of faulting. kv_store's slot bound is the one place + * the reference has an argument the launcher does not (see below). + * + * `expf`, `powf` and `sincosf` are the accurate forms, not the `__` approximations: rope positions + * reach 262144, past __sincosf's argument reduction, and libref evaluates every transcendental in + * double and rounds once (libref's ref_exp/ref_pow/ref_sin/ref_cos/ref_erf). None of these + * paths is the step's bottleneck, so the difference between libm and a device routine -- a few + * ULP of f32, against the 1/256 of a bf16 store -- is the whole of the tolerance. + * + * No fusion: `rmsnorm_add` and the gated quantisers are separate entry points the architecture + * plugin selects (spec §2.3), and live in other units. + * + * Two layers per op, as r3d.h states: a launcher that takes pointers as longs and geometry as + * ints, checks what a `__global__` cannot, computes the grid and issues one kernel on the stream it + * was handed; and the shim the row table names, which reads the operands with r3d_args.h, takes + * the dtype from the tensor and the row count from the operand, and returns a RAD status. Neither + * allocates, neither synchronises. A launcher returns 0 or -1 (null), -2 (extent), -3 (pitch), + * -4 (the HIP launch failed); a shim maps any non-zero code to RAD_E_DEVICE. + */ + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include +#include +#include + +namespace { + +constexpr uint32_t kThreads = 256; // eight wave32s: the wide row, the hidden state +constexpr uint32_t kNarrow = 32; // one wave32: the narrow row, a head of a QK norm +constexpr uint32_t kNarrowN = 256; // a row this narrow is a wave's, eight columns a lane + +/* The workgroup a row gets: one wave for the rows a wave already covers -- an attention head, a + * KV head, a QK norm, where a 256-thread group would spend three quarters of its lanes on a + * barrier -- and 256 for everything wider. */ +static inline int row_threads(int n) { return n <= (int)kNarrowN ? (int)kNarrow : (int)kThreads; } + +/* ================================================================== the seams every kernel here + * shares + * + * A whole-register store beside r3d_common.h's whole-register load. The dword form is the pair + * store; the caller has already proved the address even, in elements, from a base alignment of 4. + * The address-space cast is r3d_common.h's own, a C-style cast to the qualified type: + * reinterpret_cast refuses to change address spaces. + */ +typedef uint32_t __attribute__((address_space(1))) *r3d_gu32; +typedef float __attribute__((address_space(1))) *r3d_gf32; +typedef int32_t __attribute__((address_space(1))) *r3d_gi32; +typedef int64_t __attribute__((address_space(1))) *r3d_gi64; + +__device__ __forceinline__ void stg_u32(uint16_t* p, uint32_t v) { *(r3d_gu32)p = v; } +__device__ __forceinline__ void stg_f32(float* p, float v) { *(r3d_gf32)p = v; } +/* A dword of four codes at a byte address: the fp8 quantiser's store. */ +__device__ __forceinline__ void stg_code4(uint8_t* p, uint32_t v) { *(r3d_gu32)p = v; } +__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) { return *(r3d_gi32)(uintptr_t)p; } +__device__ __forceinline__ int64_t ldg_i64(const int64_t* p) { return *(r3d_gi64)(uintptr_t)p; } +__device__ __forceinline__ void stg_i32(int32_t* p, int32_t v) { *(r3d_gi32)p = v; } +__device__ __forceinline__ void stg_i64(int64_t* p, int64_t v) { *(r3d_gi64)p = v; } +__device__ __forceinline__ uint16_t ldg_u16_at(const uint16_t* p, uint32_t i) { return (uint16_t)ldg_u16(p + i); } + +/* The max across a workgroup, in the shape block_sum has: a wave butterfly and one LDS round trip. + * The order is free -- a max is associative, commutative and idempotent, so softmax's maximum is + * the one reduction whose bracketing cannot change the answer -- and every wave has to reach the + * LDS before any thread reads it, which is what the barrier inside is for. */ +template +__device__ __forceinline__ float block_max(float v, float* lds) { + constexpr int NWAVES = NTHREADS / kWave; + const uint32_t lane = threadIdx.x & (kWave - 1); + const uint32_t w = threadIdx.x / kWave; + v = wave_max(v); + if (lane == 0) lds[w] = v; + __syncthreads(); + float t = lds[0]; +#pragma unroll + for (int i = 1; i < NWAVES; ++i) t = fmaxf(t, lds[i]); + return t; +} + +/* ================================================================== one element, any dtype + * + * cast, fill, gather_rows, scatter_rows, embed_lookup and kv_store are one kernel over several + * dtypes, because their dtype is a runtime value in the launcher's argument list. These are + * the reference's ld_dt and st_dt over libr3d's dtype codes, and they are deliberately as + * expensive -- one switch per element, "the price of being generic" in ref's own words. None of + * them is a matmul; none of them reads one element per FLOP. + * + * The integer stores round to nearest even, saturate, and store NaN as 0 (sat_round, the + * reference's): wrapping an overflowing activation into a plausible small number is the failure + * this library has to catch, not hide. + */ +__device__ __forceinline__ float sat_round(float v, float lo, float hi) { + if (v != v) return 0.0f; + const float r = rintf(v); + return r < lo ? lo : (r > hi ? hi : r); +} + +__device__ __forceinline__ float ld_elem(int dt, const void* p, size_t i) { + switch (dt) { + case R3D_DT_BF16: return bf16_to_f32(ldg_u16_at((const uint16_t*)p, (uint32_t)i)); + case R3D_DT_F16: return f16_to_f32((uint16_t)ldg_u16((const uint16_t*)p + i)); + case R3D_DT_F32: return ldg_f32((const float*)p + i); + case R3D_DT_I32: return (float)ldg_i32((const int32_t*)p + i); + case R3D_DT_I64: return (float)ldg_i64((const int64_t*)p + i); + case R3D_DT_U8: return e4m3_to_f32(((const uint8_t*)p)[i]); // the container's fp8 byte + case R3D_DT_I8: return (float)((const int8_t*)p)[i]; + default: return 0.0f; // the shims refuse every other code; mirrors ref's ld_dt + } +} + +__device__ __forceinline__ void st_elem(int dt, void* p, size_t i, float v) { + switch (dt) { + case R3D_DT_BF16: ((uint16_t*)p)[i] = f32_to_bf16(v); break; + case R3D_DT_F16: ((uint16_t*)p)[i] = f32_to_f16(v); break; + case R3D_DT_F32: stg_f32((float*)p + i, v); break; + case R3D_DT_U8: ((uint8_t*)p)[i] = f32_to_e4m3(v); break; // saturating, RTNE + case R3D_DT_I8: ((int8_t*)p)[i] = (int8_t)sat_round(v, -128.0f, 127.0f); break; + case R3D_DT_I32: { + const float r = sat_round(v, -0x1p31f, 0x1p31f); + stg_i32((int32_t*)p + i, r >= 0x1p31f ? INT32_MAX : (int32_t)r); + break; + } + case R3D_DT_I64: { + const float r = sat_round(v, -0x1p63f, 0x1p63f); + stg_i64((int64_t*)p + i, r >= 0x1p63f ? INT64_MAX : (int64_t)r); + break; + } + default: break; + } +} + +/* The integer pair cast, which must not pass through f32: a token id above 2^24 does not survive + * one, and an i64 -> i32 copy of a table offset that rounds is a wrong row, not a near miss. */ +__device__ __forceinline__ int64_t ld_int(int dt, const void* p, size_t i) { + switch (dt) { + case R3D_DT_I32: return (int64_t)ldg_i32((const int32_t*)p + i); + case R3D_DT_I64: return ldg_i64((const int64_t*)p + i); + case R3D_DT_I8: return (int64_t)((const int8_t*)p)[i]; + case R3D_DT_U8: return (int64_t)((const uint8_t*)p)[i]; + default: return 0; + } +} + +__device__ __forceinline__ void st_int(int dt, void* p, size_t i, int64_t v) { + switch (dt) { + case R3D_DT_I32: stg_i32((int32_t*)p + i, (int32_t)v); break; + case R3D_DT_I64: stg_i64((int64_t*)p + i, v); break; + case R3D_DT_I8: ((int8_t*)p)[i] = (int8_t)v; break; + case R3D_DT_U8: ((uint8_t*)p)[i] = (uint8_t)v; break; + default: st_elem(dt, p, i, (float)v); break; + } +} + +__device__ __host__ __forceinline__ bool int_pair(int dt) { + return dt == R3D_DT_I32 || dt == R3D_DT_I64 || dt == R3D_DT_I8 || dt == R3D_DT_U8; +} + +/* The bytes an element of a dtype code occupies, on both sides of the launch: r3d_dt_size is a host + * inline, and the gather kernels walk rows in bytes. */ +__device__ __forceinline__ int dt_bytes(int dt) { + switch (dt) { + case R3D_DT_BF16: case R3D_DT_F16: return 2; + case R3D_DT_F32: case R3D_DT_I32: return 4; + case R3D_DT_I64: return 8; + case R3D_DT_U8: case R3D_DT_I8: return 1; + default: return 0; + } +} + +/* The activation, off libref's act_* set. The reference evaluates the transcendental in double + * and rounds once to f32 (libref's ref_exp/ref_erf); the device's accurate expf/erff are a + * few ULP of f32 away, and the store to bf16 keeps 8 mantissa bits. gelu is the exact erf form -- + * "gelu" means this in libref, and the tanh approximation has to be asked for by name. */ +template +__device__ __forceinline__ float act_of(float x) { + if constexpr (ACT == R3D_ACT_SIGMOID) return 1.0f / (1.0f + expf(-x)); + if constexpr (ACT == R3D_ACT_GELU) + return 0.5f * x * (1.0f + erff(x * 0.70710678118654752f)); + return x * (1.0f / (1.0f + expf(-x))); // silu: x * sigmoid(x), the product rounded once +} + +/* ================================================================== rmsnorm + * rms_rows: + * + * ss = sum_i x[i]^2 f32, ascending index order + * s = 1 / sqrt(ss/n + eps) + * y[i] = x[i] * s * (w ? w[i] + wadd : 1) * mult + * + * The mean is over the last n of the row and the gain rides every row. An absent gain is the + * constant 1 -- the shim refuses `wadd` without one, as ref does -- and the gain's dtype is read + * off the operand (WDT: R3D_DT_BF16, R3D_DT_F32, R3D_DT_N for none), because a checkpoint that + * stores its gains in f32 (a QK-norm's, an audio tower's) is read as it is. Forming 1+w in bf16 + * first loses 0.3% per channel, which is why `wadd` is added in f32 here. + * + * `mult` scales the normed row before its one rounding, for a residual branch weighted by a + * constant (Gemma 4's audio feed-forward uses 0.5); 1 leaves the product chain alone. + */ +template +__global__ __launch_bounds__(THR) void rmsnorm_kernel( + const uint16_t* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y, + uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld, int pair) { + typedef typename std::conditional::type T; + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + const T* __restrict__ xr = (const T*)x + (size_t)m * x_ld; + T* __restrict__ yr = (T*)y + (size_t)m * y_ld; + const auto ld = [](const T* p, uint32_t i) { + return F32 ? ldg_f32((const float*)p + i) : bf16_to_f32(ldg_u16_at((const uint16_t*)p, i)); + }; + + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float v = ld(xr, i); + ss += v * v; + } + ss = block_sum(ss, lds); + const float s = 1.0f / sqrtf(ss / (float)n + eps); + + const uint16_t* __restrict__ wr = (const uint16_t*)w; + const float* __restrict__ wf = (const float*)w; + /* One expression, the reference's order: ((x * s) * (w + wadd)) * mult. */ + const auto scaled = [&](uint32_t i) { + const float g = WDT == R3D_DT_N ? 1.0f + : (WDT == R3D_DT_F32 ? ldg_f32(wf + i) : bf16_to_f32(ldg_u16_at(wr, i))) + wadd; + return ld(xr, i) * s * g * mult; + }; + if (pair) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32((uint16_t*)yr + i, bf16x2_rne(scaled(i), scaled(i + 1))); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float v = scaled(i); + if (F32) stg_f32((float*)yr + i, v); + else ((uint16_t*)yr)[i] = f32_to_bf16(v); + } + } +} + +/* ================================================================== layernorm + * Two passes -- the mean, then the squared deviations about that + * mean -- and not one pass of E[x^2] - E[x]^2, which cancels badly when the mean is large against + * the spread. Biased variance (divide by n), as transformers use. The store is the third pass: + * + * y[i] = ((x[i] - mean) * s * w[i]) + b[i] + * + * with `b` optional and the gain bf16 (the launcher has no gain dtype; libref reads w's through + * its own dtype, so an f32 gain is refused by the shim, not read as bf16). + */ +template +__global__ __launch_bounds__(THR) void layernorm_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const uint16_t* __restrict__ b, + uint16_t* __restrict__ y, uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld, int pair) { + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + + float sum = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) sum += bf16_to_f32(ldg_u16_at(xr, i)); + const float mean = block_sum(sum, lds) / (float)n; + + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float d = bf16_to_f32(ldg_u16_at(xr, i)) - mean; + ss += d * d; + } + const float s = 1.0f / sqrtf(block_sum(ss, lds) / (float)n + eps); + + const auto scaled = [&](uint32_t i) { + float v = (bf16_to_f32(ldg_u16_at(xr, i)) - mean) * s * bf16_to_f32(ldg_u16_at(w, i)); + if (b) v += bf16_to_f32(ldg_u16_at(b, i)); + return v; + }; + if (pair) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32(yr + i, bf16x2_rne(scaled(i), scaled(i + 1))); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) + ((uint16_t*)yr)[i] = f32_to_bf16(scaled(i)); + } +} + +/* ================================================================== add / mul + * elementwise2, one rule per line: + * + * u = a[i]; v = b[i]; s = mul ? u*v : u+v; + * if (div != 1) s = round_to_y(s) / div; two roundings, y's dtype + * y[i] = round_to_y(s) + * + * `div` is the last sum of a mean taken pairwise -- (b0+b1+b2)/3, as a vocoder averages its + * residual blocks -- and the sum is narrowed before it is divided because the unfused pair stores + * it. 1 is the plain sum. + * + * The broadcast: b carrying exactly n elements rides every row (`bcast`, which the shim sets off + * the operand's element count, as ref does); nothing else broadcasts, so a shape bug cannot pass + * as a plausible number. The f32 pair narrows nothing on the way (round_dt(f32) is the identity), + * and `y` may be `a`: every element is read by the thread that writes it. + */ +template +__global__ __launch_bounds__(THR) void binary_kernel( + const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, uint16_t* __restrict__ y, + uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, float div) { + typedef typename std::conditional::type T; + const uint32_t m = blockIdx.x; + const T* __restrict__ ar = (const T*)a + (size_t)m * a_ld; + const T* __restrict__ br = (const T*)b + (size_t)m * b_ld; + T* __restrict__ yr = (T*)y + (size_t)m * y_ld; + + const auto ld = [](const T* p, uint32_t i) { + return F32 ? ldg_f32((const float*)p + i) : bf16_to_f32(ldg_u16_at((const uint16_t*)p, i)); + }; + const auto at = [&](uint32_t i) { + const float u = ld(ar, i), v = ld(br, i); + float s = MUL ? u * v : u + v; + if (div != 1.0f) s = F32 ? s / div : bf16_to_f32(f32_to_bf16(s)) / div; + return s; + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) { + const float lo = at(i), hi = at(i + 1); + if (F32) { + stg_f32((float*)yr + i, lo); + stg_f32((float*)yr + i + 1, hi); + } else { + stg_u32((uint16_t*)yr + i, bf16x2_rne(lo, hi)); + } + } + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float v = at(i); + if (F32) stg_f32((float*)yr + i, v); + else ((uint16_t*)yr)[i] = f32_to_bf16(v); + } + } +} + +/* ================================================================== cast + * `from`/`to` are the selector's; the bytes are what the tensors say, + * which is what ref reads and what this kernel does. An integer pair goes straight through, so a + * token id above 2^24 survives an i64 -> i32 copy; everything else widens to f32 and narrows once + * on the way out. One switch per element: cast is a bandwidth op between stages, not a hot loop. + */ +template +__global__ __launch_bounds__(THR) void cast_kernel( + const void* __restrict__ x, void* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld, + int from_dt, int to_dt, int intp) { + const uint32_t m = blockIdx.x; + /* Both pitches are in elements of their own dtype, and the row base is in bytes. */ + const char* __restrict__ xr = (const char*)x + (size_t)m * x_ld * (size_t)dt_bytes(from_dt); + char* __restrict__ yr = (char*)y + (size_t)m * y_ld * (size_t)dt_bytes(to_dt); + for (uint32_t i = threadIdx.x; i < n; i += THR) { + if (intp) st_int(to_dt, yr, i, ld_int(from_dt, xr, i)); + else st_elem(to_dt, yr, i, ld_elem(from_dt, xr, i)); + } +} + +/* ================================================================== silu / gelu / sigmoid + * unary: one element, one activation, one narrowing by the store. + * The three are one kernel with the activation as a template argument, because libr3d's rows serve + * all three and the body differs by one expression. */ +template +__global__ __launch_bounds__(THR) void unary_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, + uint32_t y_ld) { + typedef typename std::conditional::type T; + const uint32_t m = blockIdx.x; + const T* __restrict__ xr = (const T*)x + (size_t)m * x_ld; + T* __restrict__ yr = (T*)y + (size_t)m * y_ld; + const auto ld = [](const T* p, uint32_t i) { + return F32 ? ldg_f32((const float*)p + i) : bf16_to_f32(ldg_u16_at((const uint16_t*)p, i)); + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) { + const float lo = act_of(ld(xr, i)), hi = act_of(ld(xr, i + 1)); + if (F32) { + stg_f32((float*)yr + i, lo); + stg_f32((float*)yr + i + 1, hi); + } else { + stg_u32((uint16_t*)yr + i, bf16x2_rne(lo, hi)); + } + } + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float v = act_of(ld(xr, i)); + if (F32) stg_f32((float*)yr + i, v); + else ((uint16_t*)yr)[i] = f32_to_bf16(v); + } + } +} + +/* ================================================================== act_mul + * y = act(a) * b, with the activation narrowed to y's dtype first, + * because the unfused pair stores it -- the rounding is the contract, not a detail: + * + * v = act(a[i]); y[i] = round_to_y( round_to_y(v) * b[i] ) + * + * `a` and `b` are the two halves of a fused projection, so each has its own pitch. The shims serve + * silu, gelu (the exact erf form) and sigmoid; gelu_tanh and quick_gelu are libref's other two + * kActs entries and are refused, so the row's constraints state which gated MLPs reach this card. + */ +template +__global__ __launch_bounds__(THR) void act_mul_kernel( + const uint16_t* __restrict__ g, const uint16_t* __restrict__ u, uint16_t* __restrict__ y, + uint32_t n, uint32_t g_ld, uint32_t u_ld, uint32_t y_ld) { + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ gr = g + (size_t)m * g_ld; + const uint16_t* __restrict__ ur = u + (size_t)m * u_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + /* The activation, narrowed; then the product, narrowed by the store. */ + const auto at = [&](uint32_t i) { + const float v = bf16_to_f32(f32_to_bf16(act_of(bf16_to_f32(ldg_u16_at(gr, i))))); + return v * bf16_to_f32(ldg_u16_at(ur, i)); + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32(yr + i, bf16x2_rne(at(i), at(i + 1))); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) + ((uint16_t*)yr)[i] = f32_to_bf16(at(i)); + } +} + +/* ================================================================== silu_mul + * y[i] = silu(gate_up[i]) * gate_up[n + i], over ONE fused operand: + * the gate is the first half, which is the order rad-convert fuses gate and up into one weight in. + * + * Nothing is narrowed between the activation and the product. act_mul rounds the activation to y's + * dtype first because it replaces an unfused pair that stored it; silu_mul is the fused pair, so + * its product is the f32 activation times the f32 up, rounded once by the store. + */ +template +__global__ __launch_bounds__(THR) void silu_mul_kernel( + const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint32_t n, uint32_t gu_ld, + uint32_t y_ld) { + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + const auto at = [&](uint32_t i) { + return act_of(bf16_to_f32(ldg_u16_at(gr, i))) * + bf16_to_f32(ldg_u16_at(gr, n + i)); + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32(yr + i, bf16x2_rne(at(i), at(i + 1))); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) ((uint16_t*)yr)[i] = f32_to_bf16(at(i)); + } +} + +/* ================================================================== rmsnorm_quant_fp8 + * The residual add, the norm, and the E4M3 quantiser of the result in one + * pass, so the normalised activation never goes back to VRAM. The arithmetic of the quantiser is + * r3d_quant_fp8.hip's, and `q8_group` before it, bit for bit: `sc = amax * (1.0f / + * 448.0f)` (the reciprocal MULTIPLIED), `inv = 1.0f / sc`, the codes `v * inv` clamped to +-448 by + * comparisons and not by fminf/fmaxf (those replace a NaN with the bound; a NaN activation encodes + * as the format's NaN), and a group whose amax is zero takes scale 1. + * + * Two properties of ref's order are load-bearing and are kept: + * the residual sum is STORED (narrowed to bf16) before the variance reads it, so the norm is over + * the bf16 sum. That is what makes this the `add` + `rmsnorm` pair and not `rmsnorm_add`, which + * normalises the unrounded sum; + * the quantiser codes the bf16 normalised value, not the f32 one -- `out_bf16`, when asked for, + * holds exactly the bytes the codes were taken over. + * + * A group is a wave at a time, four consecutive columns a lane per 128 columns, so the amax is a + * register max plus one wave butterfly (a maximum is exact in any order) and the codes leave as + * dwords. The normalised row is RECOMPUTED in the second pass from the same operands -- hot in L2, + * and it keeps the row's length out of LDS, which is what lets one workgroup take a 5120-column row. + */ +template +__global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + uint8_t* __restrict__ q, float* __restrict__ s, uint16_t* __restrict__ ob, uint32_t n, + float eps, float wadd, uint32_t x_ld, uint32_t res_ld, uint32_t ob_ld, uint32_t q_ld, + uint32_t s_ld) { + constexpr uint32_t kChunk = 128u; /* a lane's four columns per chunk */ + constexpr uint32_t kNChunk = (uint32_t)GROUP / kChunk; /* chunks a group is: 1, 2 or 4 */ + constexpr float kTopE4M3 = 448.0f; + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ rr = res ? res + (size_t)m * res_ld : nullptr; + uint8_t* __restrict__ qr = q + (size_t)m * q_ld; + float* __restrict__ sr = s + (size_t)m * s_ld; + uint16_t* __restrict__ obr = ob ? ob + (size_t)m * ob_ld : nullptr; + + /* The row the norm is taken over: the residual plane, once the sum has been written to it. */ + const auto src = [&](uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(rr ? rr + i : xr + i)); + }; + if (rr) { + for (uint32_t i = threadIdx.x; i < n; i += THR) + rr[i] = f32_to_bf16(bf16_to_f32(ldg_u16_at(xr, i)) + bf16_to_f32(ldg_u16_at(rr, i))); + } + __syncthreads(); + + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = src(i); ss += v * v; } + ss = block_sum(ss, lds); + const float rs = 1.0f / sqrtf(ss / (float)n + eps); + __syncthreads(); + + const uint32_t wave = threadIdx.x / kWave, lane = threadIdx.x & (kWave - 1); + const uint32_t ngrp = n / (uint32_t)GROUP; + for (uint32_t g = wave; g < ngrp; g += (uint32_t)(THR / kWave)) { + const uint32_t base = g * (uint32_t)GROUP + 4u * lane; + float v[kNChunk][4]; + float am = 0.0f; + for (uint32_t j = 0; j < kNChunk; ++j) { + for (uint32_t c = 0; c < 4u; ++c) { + const uint32_t i = base + j * kChunk + c; + /* The gain's dtype is the checkpoint's, read off the operand -- WDT, the plain + * rmsnorm's leg: the gains are read as stored, and the op's `dtype` names the + * ACTIVATION, never the weight. */ + const float gain = (!w ? 1.0f + : WDT == R3D_DT_F32 ? ldg_f32((const float*)w + i) + : bf16_to_f32(ldg_u16_at((const uint16_t*)w, i))) + + wadd; + /* The normalised value narrowed to bf16, which is the value ref quantises and the + * value out_bf16 holds. */ + const float h = bf16_to_f32(f32_to_bf16(src(i) * rs * gain)); + v[j][c] = h; + const float t = std::fabs(h); + if (t > am) am = t; /* ref's `if (m > amax) amax = m`: NaN is skipped */ + } + } + am = wave_max(am); + const float sc = am > 0.0f ? am * (1.0f / kTopE4M3) : 1.0f; + const float inv = 1.0f / sc; + if (lane == 0) stg_f32(sr + g, sc); + for (uint32_t j = 0; j < kNChunk; ++j) { + float c0 = v[j][0] * inv, c1 = v[j][1] * inv, c2 = v[j][2] * inv, c3 = v[j][3] * inv; + if (c0 > kTopE4M3) c0 = kTopE4M3; else if (c0 < -kTopE4M3) c0 = -kTopE4M3; + if (c1 > kTopE4M3) c1 = kTopE4M3; else if (c1 < -kTopE4M3) c1 = -kTopE4M3; + if (c2 > kTopE4M3) c2 = kTopE4M3; else if (c2 < -kTopE4M3) c2 = -kTopE4M3; + if (c3 > kTopE4M3) c3 = kTopE4M3; else if (c3 < -kTopE4M3) c3 = -kTopE4M3; + const uint32_t lo = e4m3x2_pack(c0, c1), hi = e4m3x2_pack(c2, c3); + stg_code4(qr + base + j * kChunk, lo | (hi << 16)); + if (obr) { + stg_u32(obr + base + j * kChunk, bf16x2_rne(v[j][0], v[j][1])); + stg_u32(obr + base + j * kChunk + 2u, bf16x2_rne(v[j][2], v[j][3])); + } + } + } +} + +/* ================================================================== softmax + * In f32: + * + * mx = max_i x[i] + * e = exp(x[i] - mx); y[i] = e; sum += e ascending + * inv = 1 / sum; y[i] = y[i] * inv read back from y + * + * The maximum is subtracted first (a 60-nat row overflows f32's exp otherwise); the denominator is + * the ascending sum, which is what `block_sum` brackets. The kernel keeps `e` in a register + * between the two passes, which is exact: ref reads it back from an f32 plane, and an f32 store + * and load round nothing. The shim therefore requires y to be f32 -- a bf16 y would round `e` + * before the multiply and ref would not, and libref itself casts f32 to f32 for this op. + */ +template +__global__ __launch_bounds__(THR) void softmax_kernel( + const float* __restrict__ x, float* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld) { + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + const float* __restrict__ xr = x + (size_t)m * x_ld; + float* __restrict__ yr = y + (size_t)m * y_ld; + + float mx = -INFINITY; + for (uint32_t i = threadIdx.x; i < n; i += THR) mx = fmaxf(mx, ldg_f32(xr + i)); + mx = block_max(mx, lds); + + float sum = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float e = expf(ldg_f32(xr + i) - mx); + sum += e; + stg_f32(yr + i, e); + } + const float inv = 1.0f / block_sum(sum, lds); + for (uint32_t i = threadIdx.x; i < n; i += THR) stg_f32(yr + i, ldg_f32(yr + i) * inv); +} + +/* ================================================================== scale / fill + * scale is y = x * s, s one scalar; fill is y = v over the whole + * plane, and both narrow once, at the store. + * + * scale's scalar is the op's [1] weight plane, in device memory, and the kernel reads it: a launch + * may not copy device memory to the host, and ref reads the same single value because its operands + * are host planes. Every lane loads the same address, so it is one uniform load per block; the + * product is taken in f32 and the store narrows, which is ref's `x * s` with round_dt(f32) as the + * store. + */ +template +__global__ __launch_bounds__(THR) void scale_kernel( + const uint16_t* __restrict__ x, const void* __restrict__ sp, uint16_t* __restrict__ y, + uint32_t n, int s_dt, uint32_t x_ld, uint32_t y_ld) { + typedef typename std::conditional::type T; + const uint32_t m = blockIdx.x; + const T* __restrict__ xr = (const T*)x + (size_t)m * x_ld; + T* __restrict__ yr = (T*)y + (size_t)m * y_ld; + const float v = s_dt == R3D_DT_F32 ? ldg_f32((const float*)sp) + : bf16_to_f32(ldg_u16((const uint16_t*)sp)); + const auto ld = [](const T* p, uint32_t i) { + return F32 ? ldg_f32((const float*)p + i) : bf16_to_f32(ldg_u16_at((const uint16_t*)p, i)); + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32((uint16_t*)yr + i, bf16x2_rne(ld(xr, i) * v, ld(xr, i + 1) * v)); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float r = ld(xr, i) * v; + if (F32) stg_f32((float*)yr + i, r); + else ((uint16_t*)yr)[i] = f32_to_bf16(r); + } + } +} + +template +__global__ __launch_bounds__(THR) void fill_kernel(void* __restrict__ y, uint32_t n, uint32_t y_ld, + int dt, float v) { + const uint32_t m = blockIdx.x; + char* __restrict__ yr = (char*)y + (size_t)m * y_ld * (size_t)dt_bytes(dt); + for (uint32_t i = threadIdx.x; i < n; i += THR) st_elem(dt, yr, i, v); +} + +/* ================================================================== rope + * rope_freqs, rope_head, ref_rope -- in place on the fused qkv row, q heads + * then k heads then v untouched: + * + * inv[i] = 1 / pow(theta, (2i)/rot) the ladder, den == rot + * ang = (pos[m] / scale) * inv[i] + * c, s = cos(ang), sin(ang) + * i0, i1 = (i, i + rot/2) neox, (2i, 2i + 1) gptj + * h[i0] = x0*c - x1*s ; h[i1] = x0*s + x1*c each narrowed once + * + * The pair lives in one thread, so the in-place store needs no exchange. `scale` is the position + * scale and divides the position, as ref's rope_pos does (the value that multiplies the rotated + * pair is YaRN's magnitude, and the shims refuse YaRN, so the magnitude is 1). + * + * The frequency is recomputed per pair, not built in a plane: powf runs once per pair per head, + * off the step's critical path, and no scratch is allocated. nfreq == rot/2 always, so no pair + * sits past the ladder (ref zeroes inv[] past nfreq for the proportional ladder it supports and + * libr3d refuses). + */ +template +__global__ __launch_bounds__(THR) void rope_kernel( + uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos, uint32_t head_dim, + uint32_t n_rope_heads, uint32_t rot, float theta, float scale, uint32_t row_pitch) { + const uint32_t m = blockIdx.x; + const float div = scale != 0.0f ? scale : 1.0f; + const float p = (float)ldg_i32(pos + m) / div; + const uint32_t half = rot / 2; + const uint32_t total = n_rope_heads * half; + uint16_t* __restrict__ row = qkv + (size_t)m * row_pitch; + + for (uint32_t j = threadIdx.x; j < total; j += THR) { + const uint32_t h = j / half, i = j - h * half; + /* ref's ladder: `1.0f / ref_pow(theta, (float)(2i) / den)`, and ref_pow is the double pow + * narrowed once. powf here would put the reciprocal a ULP off, and at position 262144 a + * ULP of a frequency is a hundredth of a radian of rotation -- the ladder is the one place + * in this kernel where f32 is not enough. The angle itself stays f32, as ref's is. */ + const float inv = 1.0f / (float)std::pow((double)theta, (double)((float)(2 * i) / (float)rot)); + float s, c; + sincosf(p * inv, &s, &c); + const uint32_t i0 = h * head_dim + (GPTJ ? 2u * i : i); + const uint32_t i1 = h * head_dim + (GPTJ ? 2u * i + 1u : i + half); + const float x0 = bf16_to_f32(ldg_u16_at(row, i0)); + const float x1 = bf16_to_f32(ldg_u16_at(row, i1)); + ((uint16_t*)row)[i0] = f32_to_bf16(x0 * c - x1 * s); + ((uint16_t*)row)[i1] = f32_to_bf16(x0 * s + x1 * c); + } +} + +/* ================================================================== kv_store + * With the cache's strides read off the operand (kv_view): + * + * s = slot[t]; if (s < 0) skip; a padded row has no cache slot + * h, d = the kv head and the element; j = h*head_dim + d + * base = (s/block)*sb + h*sh + (s%block)*so + * cache[base + d*sd] = k[t*k_ld + j] * k_inv + * cache[base + (hd + d)*sd] = v[t*v_ld + j] * v_inv + * + * k and v rows are not dense: a de-interleaved projection gives [tokens, kv_heads, head_dim], and + * otherwise they are a column slice of the fused QKV plane -- 2560 wide against a 256-wide row for + * 16 heads and 2 kv heads. Deriving the stride from the shape would read every token after the + * first from the wrong rows, so the pitch is an argument. + * + * k_inv and v_inv are the reciprocal of the reader's descales and are 1 for every cache that is + * not fp8, so the multiply below is exact -- and for the fp8 cache it is the divide ref does, in + * the one place where a reciprocal costs nothing: a value times 1/scale against ref's + * `ldt(k,..) * ks` differs by at most the rounding of the reciprocal, far under the fp8 code step. + */ +template +__global__ __launch_bounds__(THR) void kv_store_kernel( + const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, const int32_t* __restrict__ sm, + void* __restrict__ kv, uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, int kv_dt, + float k_inv, float v_inv, uint32_t k_ld, uint32_t v_ld, int64_t sb, int64_t sh, int64_t so, + int64_t sd, int64_t slot_max) { + const uint32_t t = blockIdx.x; + const int32_t s = ldg_i32(sm + t); + /* A negative slot is padding and a slot at or past the cache's own span names a block the + * cache does not have: ref refuses such a launch on the host, where it can see the block + * count, and a kernel that has read the slot can only drop it. A slot lost, not a step lost. */ + if (s < 0 || (int64_t)s >= slot_max) return; + const int64_t blk = (int64_t)s / (int64_t)block_size, off = (int64_t)s % (int64_t)block_size; + + const uint32_t total = kv_heads * head_dim; + const uint16_t* __restrict__ kr = k + (size_t)t * k_ld; + const uint16_t* __restrict__ vr = v + (size_t)t * v_ld; + const int es = kv_dt == R3D_DT_BF16 ? 2 : kv_dt == R3D_DT_F16 ? 2 : 1; + char* __restrict__ plane = (char*)kv; + + for (uint32_t j = threadIdx.x; j < total; j += THR) { + const uint32_t h = j / head_dim, d = j - h * head_dim; + const int64_t cb = (blk * sb + (int64_t)h * sh + off * so) * es; + st_elem(kv_dt, plane + cb, (size_t)d * sd, bf16_to_f32(ldg_u16_at(kr, j)) * k_inv); + st_elem(kv_dt, plane + cb, (size_t)(head_dim + d) * sd, + bf16_to_f32(ldg_u16_at(vr, j)) * v_inv); + } +} + +/* ================================================================== embed_lookup + * embed_gather: + * + * id = tok[m] - vocab_offset + * x[m][i] = (0 <= id < n_vocab) ? wte[id*w_ld + i] * wscale * mult : 0 + * + * A negative id, or one at or past the table, is a zero row: padding's row, and in the + * vocab-parallel split another rank's token -- summing the ranks reconstructs x. ref validates the + * ids on the host when the table is whole and the world is one rank; a kernel cannot, so the table + * bound is an argument and an out-of-range id writes zeros. + * + * The table's dtype is the launcher's `dt`: bf16, f16, f32, or E4M3 codes with the table's one + * scale in `wscale` (embed_lookup_q's byte plane, whose scale is a parameter because quantising + * the table sees the whole table and the gather sees one row). `mult` is Gemma's sqrt(hidden), + * applied after the scale, so with wscale 1 the product is ref's single rounding. + */ +template +__global__ __launch_bounds__(THR) void embed_lookup_kernel( + const int32_t* __restrict__ ids, const void* __restrict__ wte, void* __restrict__ x, + uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, float wscale, float mult, uint32_t x_ld, + int64_t w_ld, int dt, int pair) { + const uint32_t m = blockIdx.x; + const int32_t id = ldg_i32(ids + m) - vocab_off; + char* __restrict__ xr = (char*)x + (size_t)m * x_ld * (size_t)dt_bytes(dt); + + if (id < 0 || id >= n_vocab) { + for (uint32_t i = threadIdx.x; i < n_embd; i += THR) st_elem(dt, xr, i, 0.0f); + return; + } + const char* __restrict__ wr = (const char*)wte + (int64_t)id * w_ld * (int64_t)dt_bytes(dt); + if (pair) { + uint16_t* __restrict__ xp = (uint16_t*)xr; + for (uint32_t i = 2u * threadIdx.x; i < n_embd; i += 2u * THR) + stg_u32(xp + i, bf16x2_rne(ld_elem(dt, wr, i) * wscale * mult, + ld_elem(dt, wr, i + 1) * wscale * mult)); + } else { + for (uint32_t i = threadIdx.x; i < n_embd; i += THR) + st_elem(dt, xr, i, ld_elem(dt, wr, i) * wscale * mult); + } +} + +/* ================================================================== gather_rows / scatter_rows + * y[r] = x[idx[r]] and x[idx[r]] = v[r], rows of n, and a row move + * with no arithmetic: ld_elem/st_elem is the identity for bf16, f16, f32, i32 and i64, and the + * fp8 code round trip is exact (every code decodes and re-encodes to itself). + * + * A negative index is padding: gather writes a zero row, scatter writes nothing -- an unsampled row + * of a step, a slot with no counterpart. An index at or past the operand's row count takes the + * same path, where ref refuses the launch (see the file header). + * + * scatter_rows' destination is INOUT and the write is partial: unnamed rows keep their contents, + * because the destination is often a pool other sequences are in. Its indices must be distinct -- + * RAD_OPD_F_IDX_UNIQUE says so in the schema -- since two rows landing on one destination have no + * defined winner in parallel, and an op whose oracle and kernel may disagree is not checkable. + */ +template +__global__ __launch_bounds__(THR) void gather_rows_kernel( + const void* __restrict__ x, const int32_t* __restrict__ idx, void* __restrict__ y, uint32_t n, + uint32_t x_ld, uint32_t y_ld, int dt, int32_t es, int64_t src_rows) { + const uint32_t m = blockIdx.x; + const int32_t r = ldg_i32(idx + m); + char* __restrict__ yr = (char*)y + (size_t)m * y_ld * (size_t)es; + /* A negative index is padding and an index at or past the source plane is one libref refuses on + * the host, where it can read the plane. Both take the zero row: reading x past its end is the + * failure this bound exists to stop. `src_rows` 0 says the caller had no plane count, which is a + * shim bug, not a bound. */ + if (r < 0 || (src_rows > 0 && (int64_t)r >= src_rows)) { + for (uint32_t i = threadIdx.x; i < n; i += THR) st_elem(dt, yr, i, 0.0f); + return; + } + const char* __restrict__ xr = (const char*)x + (size_t)r * x_ld * (size_t)es; + for (uint32_t i = threadIdx.x; i < n; i += THR) st_elem(dt, yr, i, ld_elem(dt, xr, i)); +} + +template +__global__ __launch_bounds__(THR) void scatter_rows_kernel( + const void* __restrict__ v, const int32_t* __restrict__ idx, void* __restrict__ x, uint32_t n, + uint32_t v_ld, uint32_t x_ld, int dt, int32_t es, int64_t dst_rows) { + const uint32_t m = blockIdx.x; + const int32_t r = ldg_i32(idx + m); + /* A negative index is padding, one at or past the destination plane is libref's refused step: + * dropped, so no row of x is written outside the plane. `dst_rows` 0 is unchecked. */ + if (r < 0 || (dst_rows > 0 && (int64_t)r >= dst_rows)) return; + const char* __restrict__ vr = (const char*)v + (size_t)m * v_ld * (size_t)es; + char* __restrict__ xr = (char*)x + (size_t)r * x_ld * (size_t)es; + for (uint32_t i = threadIdx.x; i < n; i += THR) st_elem(dt, xr, i, ld_elem(dt, vr, i)); +} + +} /* namespace */ + +/* ================================================================== the launchers + * + * Pointers as longs, geometry as ints, the stream as a long. Each checks what a `__global__` + * cannot -- nulls, non-positive extents, a pitch that does not describe the operand -- takes the + * thread count from the row width, decides the pair layout from the pitches and the base + * alignments, and issues one kernel on the stream it was handed. A pitch of 0 means "dense, so n". + */ + +/* The pair layout: a lane owning two consecutive columns, its result stored as one dword. Legal + * when n, both pitches and the base are even, so every element of every row lands on an even + * element index -- 4-byte alignment at 2 bytes an element. */ +static inline int row_pair(long base, int n, int ld1, int ld2) { + return ((n & 1) == 0) && ((ld1 & 1) == 0) && ((ld2 & 1) == 0) && ((base & 3) == 0); +} + +/* One grid, one launch, per launcher: `grid` is the row count (blockIdx.x is the row), and the + * two thread counts are the template arguments the grid was sized for. */ +#define R3D_ROW2(kernel, thr, grid, stream, ...) \ + do { \ + if ((thr) == (int)kNarrow) \ + R3D_KLAUNCH(R3D_KNAME(kernel), dim3((uint32_t)(grid)), dim3(kNarrow), \ + (hipStream_t)(uintptr_t)(stream), __VA_ARGS__); \ + else \ + R3D_KLAUNCH(R3D_KNAME(kernel), dim3((uint32_t)(grid)), dim3(kThreads), \ + (hipStream_t)(uintptr_t)(stream), __VA_ARGS__); \ + } while (0) + +#define R3D_ROPE2(thr, grid, stream, ...) \ + do { \ + if ((thr) == (int)kNarrow) { \ + if (gptj) R3D_ROPE_K(kNarrow, 1, grid, stream, __VA_ARGS__); \ + else R3D_ROPE_K(kNarrow, 0, grid, stream, __VA_ARGS__); \ + } else { \ + if (gptj) R3D_ROPE_K(kThreads, 1, grid, stream, __VA_ARGS__); \ + else R3D_ROPE_K(kThreads, 0, grid, stream, __VA_ARGS__); \ + } \ + } while (0) + +#define R3D_ROPE_K(THR, GPTJ, grid, stream, ...) \ + R3D_KLAUNCH(R3D_KNAME(rope_kernel), dim3((uint32_t)(grid)), dim3(THR), \ + (hipStream_t)(uintptr_t)(stream), __VA_ARGS__) + +/* A row count a dim3 can carry and a grid-strided loop cannot be asked to exceed. */ +static inline int row_count_ok(long long M) { return M > 0 && M <= 0x7fffffffLL; } + +static int rmsnorm_launch(long x, long w, long y, int M, int n, float eps, float wadd, float mult, + int x_ld, int y_ld, int wdt, int f32, long stream) { + if (!x || !y || (wdt != R3D_DT_N && !w)) return -1; + if (M <= 0 || n <= 0) return -2; + if (wdt != R3D_DT_N && wdt != R3D_DT_BF16 && wdt != R3D_DT_F32) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = f32 ? 0 : row_pair(y, n, x_ld, y_ld); + const uint16_t* xp = (const uint16_t*)(uintptr_t)x; + uint16_t* yp = (uint16_t*)(uintptr_t)y; + const void* wp = (const void*)(uintptr_t)w; +#define R3D_RMS(THR, WDT) \ + R3D_KLAUNCH(R3D_KNAME(rmsnorm_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, xp, wp, yp, (uint32_t)n, eps, wadd, mult, \ + (uint32_t)x_ld, (uint32_t)y_ld, pair) + if (wdt == R3D_DT_F32) { + if (thr == (int)kNarrow) R3D_RMS(kNarrow, R3D_DT_F32); else R3D_RMS(kThreads, R3D_DT_F32); + } else if (wdt == R3D_DT_BF16) { + if (thr == (int)kNarrow) R3D_RMS(kNarrow, R3D_DT_BF16); else R3D_RMS(kThreads, R3D_DT_BF16); + } else { + if (thr == (int)kNarrow) R3D_RMS(kNarrow, R3D_DT_N); else R3D_RMS(kThreads, R3D_DT_N); + } +#undef R3D_RMS + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The f32 leg: the same two passes over an f32 row, and a store that narrows nothing. */ +extern "C" int r3d_rmsnorm_f32(long x, long w, long y, int M, int n, float eps, float wadd, + float mult, int x_ld, int y_ld, int wdt, long stream) { + if (!x || !y || (wdt != R3D_DT_N && !w)) return -1; + if (M <= 0 || n <= 0) return -2; + if (wdt != R3D_DT_N && wdt != R3D_DT_BF16 && wdt != R3D_DT_F32) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; +#define R3D_RMSF(THR, WDT) \ + R3D_KLAUNCH(R3D_KNAME(rmsnorm_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)x, \ + (const void*)(uintptr_t)w, (uint16_t*)(uintptr_t)y, (uint32_t)n, eps, wadd, \ + mult, (uint32_t)x_ld, (uint32_t)y_ld, 0) + if (row_threads(n) == (int)kNarrow) { + if (wdt == R3D_DT_F32) R3D_RMSF(kNarrow, R3D_DT_F32); + else if (wdt == R3D_DT_BF16) R3D_RMSF(kNarrow, R3D_DT_BF16); + else R3D_RMSF(kNarrow, R3D_DT_N); + } else { + if (wdt == R3D_DT_F32) R3D_RMSF(kThreads, R3D_DT_F32); + else if (wdt == R3D_DT_BF16) R3D_RMSF(kThreads, R3D_DT_BF16); + else R3D_RMSF(kThreads, R3D_DT_N); + } +#undef R3D_RMSF + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The bf16 entry point, in terms of the same body. */ +extern "C" int r3d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, + float mult, int x_ld, int y_ld, int wdt, long stream) { + return rmsnorm_launch(x, w, y, M, n, eps, wadd, mult, x_ld, y_ld, wdt, 0, stream); +} + +/* The fused add + norm + E4M3 quantiser. `res` is the residual plane, INOUT, and 0 when the op has + * no residual; `ob` is the optional bf16 copy of exactly what was quantised. `group` is the + * quantiser's block and must divide n: a partial group needs the zero-padded store the standalone + * quantiser writes, and this row's band is a checkpoint whose block divides its hidden width. + * Pitches are in elements of their own operand; `s_ld` in scales, so a dense scale plane is n/group. + * 0, -1, -2, -3, -4. */ +extern "C" int r3d_rmsnorm_quant_fp8(long x, long res, long w, long q, long s, long ob, int M, + int n, int group, float eps, float wadd, int x_ld, int res_ld, + int ob_ld, int q_ld, int s_ld, int wdt, long stream) { + if (!x || !w || !q || !s) return -1; + if (M <= 0 || n <= 0) return -2; + if (group != 128 && group != 256 && group != 512) return -2; + if (n % group) return -2; + if (!x_ld) x_ld = n; + if (!res_ld) res_ld = n; + if (!ob_ld) ob_ld = n; + if (!q_ld) q_ld = n; + if (!s_ld) s_ld = n / group; + if (x_ld < n || res_ld < n || ob_ld < n || q_ld < n || s_ld < n / group) return -3; + const int thr = row_threads(n); +#define R3D_RQ(THR, GROUP, WDT) \ + R3D_KLAUNCH(R3D_KNAME(rmsnorm_quant_fp8_kernel), dim3((uint32_t)M), \ + dim3(THR), (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)x, \ + (uint16_t*)(uintptr_t)res, (const void*)(uintptr_t)w, \ + (uint8_t*)(uintptr_t)q, (float*)(uintptr_t)s, (uint16_t*)(uintptr_t)ob, \ + (uint32_t)n, eps, wadd, (uint32_t)x_ld, (uint32_t)res_ld, (uint32_t)ob_ld, \ + (uint32_t)q_ld, (uint32_t)s_ld) +#define R3D_RQ_G(THR, WDT) \ + do { \ + if (group == 128) R3D_RQ(THR, 128, WDT); \ + else if (group == 256) R3D_RQ(THR, 256, WDT); \ + else R3D_RQ(THR, 512, WDT); \ + } while (0) +#define R3D_RQ_W(THR) \ + do { \ + if (wdt == R3D_DT_F32) R3D_RQ_G(THR, R3D_DT_F32); \ + else R3D_RQ_G(THR, R3D_DT_BF16); \ + } while (0) + if (thr == (int)kNarrow) R3D_RQ_W(kNarrow); else R3D_RQ_W(kThreads); +#undef R3D_RQ_W +#undef R3D_RQ_G +#undef R3D_RQ + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_layernorm_bf16(long x, long w, long b, long y, int M, int n, float eps, + int x_ld, int y_ld, long stream) { + if (!x || !w || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = row_pair(y, n, x_ld, y_ld); + R3D_ROW2(layernorm_kernel, thr, M, stream, (const uint16_t*)(uintptr_t)x, + (const uint16_t*)(uintptr_t)w, (const uint16_t*)(uintptr_t)b, + (uint16_t*)(uintptr_t)y, (uint32_t)n, eps, (uint32_t)x_ld, (uint32_t)y_ld, pair); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The binary pair: one kernel over add/mul, bf16/f32 and the pair layout, with the broadcast + * expressed as b's row pitch (0 makes one row ride every row). */ +static int binary_launch(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, + float div, int bcast, int mul, int f32, long stream) { + if (!a || !b || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!(div != 0.0f) || !std::isfinite(div)) return -2; + if (!a_ld) a_ld = n; + if (!y_ld) y_ld = n; + if (!bcast) { + if (!b_ld) b_ld = n; + } else { + b_ld = 0; + } + if (a_ld < n || y_ld < n || (!bcast && b_ld < n)) return -3; + const int thr = row_threads(n); + const int pair = f32 ? 0 : row_pair(y, n, a_ld, y_ld) && (bcast || (b_ld & 1) == 0); +#define R3D_BIN(THR, MUL, PAIR, F32) \ + R3D_KLAUNCH(R3D_KNAME(binary_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)a, \ + (const uint16_t*)(uintptr_t)b, (uint16_t*)(uintptr_t)y, (uint32_t)n, \ + (uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, div) +#define R3D_BIN_M(THR) \ + do { \ + if (mul) { if (pair) R3D_BIN(THR, 1, 1, 0); else R3D_BIN(THR, 1, 0, 0); } \ + else { if (pair) R3D_BIN(THR, 0, 1, 0); else R3D_BIN(THR, 0, 0, 0); } \ + } while (0) +#define R3D_BIN_MF(THR) \ + do { \ + if (mul) R3D_BIN(THR, 1, 0, 1); else R3D_BIN(THR, 0, 0, 1); \ + } while (0) + if (f32) { if (thr == (int)kNarrow) R3D_BIN_MF(kNarrow); else R3D_BIN_MF(kThreads); } + else { if (thr == (int)kNarrow) R3D_BIN_M(kNarrow); else R3D_BIN_M(kThreads); } +#undef R3D_BIN_MF +#undef R3D_BIN_M +#undef R3D_BIN + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_add_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, + float div, int bcast, long stream) { + return binary_launch(a, b, y, M, n, a_ld, b_ld, y_ld, div, bcast, 0, 0, stream); +} + +extern "C" int r3d_add_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, + float div, int bcast, long stream) { + return binary_launch(a, b, y, M, n, a_ld, b_ld, y_ld, div, bcast, 0, 1, stream); +} + +extern "C" int r3d_mul_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, + int bcast, long stream) { + return binary_launch(a, b, y, M, n, a_ld, b_ld, y_ld, 1.0f, bcast, 1, 0, stream); +} + +extern "C" int r3d_mul_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, + int bcast, long stream) { + return binary_launch(a, b, y, M, n, a_ld, b_ld, y_ld, 1.0f, bcast, 1, 1, stream); +} + +/* The cast's dtype codes: every pair of the dtypes the library moves. The shim translates the + * tensor dtypes with r3d_dt_code and checks them here, so a call from a tool with an unlisted + * pair is refused rather than run over a switch's default. */ +static int cast_pair_ok(int from, int to) { + static const int kOk[] = { R3D_DT_BF16, R3D_DT_F16, R3D_DT_F32, R3D_DT_I32, R3D_DT_I64, + R3D_DT_U8, R3D_DT_I8 }; + int okf = 0, okt = 0; + for (int i = 0; i < (int)(sizeof kOk / sizeof kOk[0]); ++i) { + okf = okf || from == kOk[i]; + okt = okt || to == kOk[i]; + } + return okf && okt; +} + +extern "C" int r3d_cast(long x, long y, int M, int n, int x_ld, int y_ld, int from_dt, int to_dt, + long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!cast_pair_ok(from_dt, to_dt)) return -2; + const int fs = r3d_dt_size(from_dt), ts = r3d_dt_size(to_dt); + if (!fs || !ts) return -2; + /* The pitches are in elements of each operand's own dtype; 0 is dense. */ + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + R3D_ROW2(cast_kernel, thr, M, stream, (const void*)(uintptr_t)x, (void*)(uintptr_t)y, + (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, from_dt, to_dt, + int_pair(from_dt) && int_pair(to_dt) ? 1 : 0); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The unary activations: one launcher body, four template arguments. */ +static int unary_launch(long x, long y, int M, int n, int x_ld, int y_ld, int act, int f32, + long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = f32 ? 0 : row_pair(y, n, x_ld, y_ld); +#define R3D_UN(THR, ACT, PAIR, F32) \ + R3D_KLAUNCH(R3D_KNAME(unary_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)x, \ + (uint16_t*)(uintptr_t)y, (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld) +#define R3D_UN_A(THR) \ + do { \ + if (act == R3D_ACT_SILU) { if (pair) R3D_UN(THR, R3D_ACT_SILU, 1, 0); \ + else R3D_UN(THR, R3D_ACT_SILU, 0, 0); } \ + else if (act == R3D_ACT_GELU) { if (pair) R3D_UN(THR, R3D_ACT_GELU, 1, 0); \ + else R3D_UN(THR, R3D_ACT_GELU, 0, 0); } \ + else { if (pair) R3D_UN(THR, R3D_ACT_SIGMOID, 1, 0); \ + else R3D_UN(THR, R3D_ACT_SIGMOID, 0, 0); } \ + } while (0) +#define R3D_UN_AF(THR) \ + do { \ + if (act == R3D_ACT_SILU) R3D_UN(THR, R3D_ACT_SILU, 0, 1); \ + else if (act == R3D_ACT_GELU) R3D_UN(THR, R3D_ACT_GELU, 0, 1); \ + else R3D_UN(THR, R3D_ACT_SIGMOID, 0, 1); \ + } while (0) + if (f32) { if (thr == (int)kNarrow) R3D_UN_AF(kNarrow); else R3D_UN_AF(kThreads); } + else { if (thr == (int)kNarrow) R3D_UN_A(kNarrow); else R3D_UN_A(kThreads); } +#undef R3D_UN_AF +#undef R3D_UN_A +#undef R3D_UN + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_silu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + return unary_launch(x, y, M, n, x_ld, y_ld, R3D_ACT_SILU, 0, stream); +} + +extern "C" int r3d_gelu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + return unary_launch(x, y, M, n, x_ld, y_ld, R3D_ACT_GELU, 0, stream); +} + +extern "C" int r3d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + return unary_launch(x, y, M, n, x_ld, y_ld, R3D_ACT_SIGMOID, 0, stream); +} + +extern "C" int r3d_silu_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + return unary_launch(x, y, M, n, x_ld, y_ld, R3D_ACT_SILU, 1, stream); +} + +extern "C" int r3d_act_mul_bf16(long gate, long up, long y, int M, int n, int g_ld, int u_ld, + int y_ld, int act, long stream) { + if (!gate || !up || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (act != R3D_ACT_SILU && act != R3D_ACT_GELU && act != R3D_ACT_SIGMOID) return -2; + if (!g_ld) g_ld = n; + if (!u_ld) u_ld = n; + if (!y_ld) y_ld = n; + if (g_ld < n || u_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = row_pair(y, n, g_ld, y_ld) && (u_ld & 1) == 0; +#define R3D_AM(THR, ACT, PAIR) \ + R3D_KLAUNCH(R3D_KNAME(act_mul_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)gate, \ + (const uint16_t*)(uintptr_t)up, (uint16_t*)(uintptr_t)y, (uint32_t)n, \ + (uint32_t)g_ld, (uint32_t)u_ld, (uint32_t)y_ld) +#define R3D_AM_A(THR) \ + do { \ + if (act == R3D_ACT_SILU) { if (pair) R3D_AM(THR, R3D_ACT_SILU, 1); \ + else R3D_AM(THR, R3D_ACT_SILU, 0); } \ + else if (act == R3D_ACT_GELU) { if (pair) R3D_AM(THR, R3D_ACT_GELU, 1); \ + else R3D_AM(THR, R3D_ACT_GELU, 0); } \ + else { if (pair) R3D_AM(THR, R3D_ACT_SIGMOID, 1); \ + else R3D_AM(THR, R3D_ACT_SIGMOID, 0); } \ + } while (0) + if (thr == (int)kNarrow) R3D_AM_A(kNarrow); else R3D_AM_A(kThreads); +#undef R3D_AM_A +#undef R3D_AM + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* y = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate and the up share one plane, so one pitch + * carries both halves: `gu_ld` is the FUSED row's pitch (>= 2n), `y_ld` the output's. */ +extern "C" int r3d_silu_mul_bf16(long gate_up, long y, int M, int n, int gu_ld, int y_ld, + long stream) { + if (!gate_up || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!gu_ld) gu_ld = 2 * n; + if (!y_ld) y_ld = n; + if (gu_ld < 2 * n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = row_pair(y, n, gu_ld, y_ld); /* n even puts the up half on a 2-byte boundary */ +#define R3D_SM(THR, PAIR) \ + R3D_KLAUNCH(R3D_KNAME(silu_mul_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)gate_up, \ + (uint16_t*)(uintptr_t)y, (uint32_t)n, (uint32_t)gu_ld, (uint32_t)y_ld) + if (pair) { + if (thr == (int)kNarrow) R3D_SM(kNarrow, 1); else R3D_SM(kThreads, 1); + } else { + if (thr == (int)kNarrow) R3D_SM(kNarrow, 0); else R3D_SM(kThreads, 0); + } +#undef R3D_SM + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_softmax_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + R3D_ROW2(softmax_kernel, thr, M, stream, (const float*)(uintptr_t)x, (float*)(uintptr_t)y, + (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* scale's two legs: the scalar plane's dtype is `s_dt` (bf16 or f32), the row's dtype is the + * launcher's. A null `s` is -1: the shim refuses a scale with no plane, so a call that reaches + * here without one is a caller bug, not a scale of zero. */ +static int scale_launch(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, int f32, + long stream) { + if (!x || !s || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (s_dt != R3D_DT_BF16 && s_dt != R3D_DT_F32) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = f32 ? 0 : row_pair(y, n, x_ld, y_ld); +#define R3D_SC(THR, PAIR, F32) \ + R3D_KLAUNCH(R3D_KNAME(scale_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)x, \ + (const void*)(uintptr_t)s, (uint16_t*)(uintptr_t)y, (uint32_t)n, s_dt, \ + (uint32_t)x_ld, (uint32_t)y_ld) +#define R3D_SC_P(THR, F32) \ + do { \ + if (pair) R3D_SC(THR, 1, F32); else R3D_SC(THR, 0, F32); \ + } while (0) + if (f32) { if (thr == (int)kNarrow) R3D_SC_P(kNarrow, 1); else R3D_SC_P(kThreads, 1); } + else { if (thr == (int)kNarrow) R3D_SC_P(kNarrow, 0); else R3D_SC_P(kThreads, 0); } +#undef R3D_SC_P +#undef R3D_SC + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_scale_bf16(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, + long stream) { + return scale_launch(x, s, y, M, n, s_dt, x_ld, y_ld, 0, stream); +} + +extern "C" int r3d_scale_f32(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, + long stream) { + return scale_launch(x, s, y, M, n, s_dt, x_ld, y_ld, 1, stream); +} + +extern "C" int r3d_fill(long y, int M, int n, int y_ld, int dt, float v, long stream) { + if (!y) return -1; + if (M <= 0 || n <= 0) return -2; + if (r3d_dt_size(dt) == 0) return -2; + if (!y_ld) y_ld = n; + if (y_ld < n) return -3; + const int thr = row_threads(n); + R3D_ROW2(fill_kernel, thr, M, stream, (void*)(uintptr_t)y, (uint32_t)n, (uint32_t)y_ld, dt, v); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_head, int n_head_kv, + float theta, float scale, int mode, int rot, int qkv_ld, + long stream) { + if (!qkv || !pos) return -1; + if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv < 0) return -2; + if (rot <= 0) rot = head_dim; + if (rot > head_dim || (rot & 1)) return -3; + if (mode != R3D_ROPE_NEOX && mode != R3D_ROPE_GPTJ) return -3; + if (head_dim & 1) return -3; // the two halves of a head, evenly split + if (!(theta > 0.0f) || !std::isfinite(theta)) return -2; + if (!qkv_ld) qkv_ld = (n_head + 2 * n_head_kv) * head_dim; + if (qkv_ld < (n_head + 2 * n_head_kv) * head_dim) return -3; + /* rope is a per-head-of-64-pairs op: one wave covers a token's rope heads when the head is + * narrow, and 256 threads take the wide ones. */ + const int gptj = mode == R3D_ROPE_GPTJ; + const int thr = (n_head + n_head_kv) * (rot / 2) <= 256u ? (int)kNarrow : (int)kThreads; + R3D_ROPE2(thr, M, stream, (uint16_t*)(uintptr_t)qkv, (const int32_t*)(uintptr_t)pos, + (uint32_t)head_dim, (uint32_t)(n_head + n_head_kv), (uint32_t)rot, theta, scale, + (uint32_t)qkv_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_kv_store(long k, long v, long sm, long kv, int M, int head_dim, int n_head_kv, + int block_size, int kv_dt, float k_scale, float v_scale, int k_ld, + int v_ld, long long slot_max, long sb, long sh, long so, long sd, + long stream) { + if (!k || !v || !sm || !kv) return -1; + if (M <= 0 || head_dim <= 0 || n_head_kv <= 0 || block_size <= 0) return -2; + if (kv_dt != R3D_DT_BF16 && kv_dt != R3D_DT_F16 && kv_dt != R3D_DT_U8) return -2; + const int fp8 = kv_dt == R3D_DT_U8; + if (fp8 && !(k_scale > 0.0f && v_scale > 0.0f)) return -2; + const float k_inv = fp8 ? 1.0f / k_scale : 1.0f; + const float v_inv = fp8 ? 1.0f / v_scale : 1.0f; + if (!k_ld) k_ld = n_head_kv * head_dim; + if (!v_ld) v_ld = n_head_kv * head_dim; + if (k_ld < n_head_kv * head_dim || v_ld < n_head_kv * head_dim) return -3; + if (sb < 0 || sh < 0 || so < 0 || sd <= 0) return -3; + /* The cache's span, as r3d_shape_kv_store sizes it: M tokens need ceil(M/block_size) blocks, + * and the shape adds two so a step that resolves its slots before the next block is written + * has somewhere to put them. Keep the two formulas in step. */ + if (slot_max <= 0) + slot_max = (long long)((M + block_size - 1) / block_size + 2) * block_size; + const int thr = row_threads(n_head_kv * head_dim); + R3D_ROW2(kv_store_kernel, thr, M, stream, (const uint16_t*)(uintptr_t)k, + (const uint16_t*)(uintptr_t)v, (const int32_t*)(uintptr_t)sm, (void*)(uintptr_t)kv, + (uint32_t)head_dim, (uint32_t)n_head_kv, (uint32_t)block_size, kv_dt, k_inv, v_inv, + (uint32_t)k_ld, (uint32_t)v_ld, (int64_t)sb, (int64_t)sh, (int64_t)so, (int64_t)sd, + (int64_t)slot_max); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_embed_lookup(long ids, long wte, long x, int M, int n_embd, int n_vocab, + int vocab_offset, float wscale, float mult, int x_ld, int w_ld, + int dt, long stream) { + if (!ids || !wte || !x) return -1; + if (M <= 0 || n_embd <= 0 || n_vocab <= 0) return -2; + if (dt != R3D_DT_BF16 && dt != R3D_DT_F16 && dt != R3D_DT_F32 && dt != R3D_DT_U8) return -2; + if (!x_ld) x_ld = n_embd; + if (!w_ld) w_ld = n_embd; + if (x_ld < n_embd || w_ld < n_embd) return -3; + const int thr = row_threads(n_embd); + const int pair = (dt == R3D_DT_BF16) ? row_pair(x, n_embd, x_ld, x_ld) : 0; + R3D_ROW2(embed_lookup_kernel, thr, M, stream, (const int32_t*)(uintptr_t)ids, + (const void*)(uintptr_t)wte, (void*)(uintptr_t)x, (uint32_t)n_embd, (int32_t)n_vocab, + (int32_t)vocab_offset, wscale, mult, (uint32_t)x_ld, (int64_t)w_ld, dt, pair); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The row moves: the pitch is in elements and the element size in bytes, both off the dtype, so + * the kernel's row base is one multiply. */ +extern "C" int r3d_gather_rows(long x, long idx, long y, int M, int n, int x_ld, int y_ld, int dt, + long long src_rows, long stream) { + if (!x || !idx || !y) return -1; + if (M <= 0 || n <= 0) return -2; + const int es = r3d_dt_size(dt); + if (!es) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + R3D_ROW2(gather_rows_kernel, row_threads(n), M, stream, (const void*)(uintptr_t)x, + (const int32_t*)(uintptr_t)idx, (void*)(uintptr_t)y, (uint32_t)n, (uint32_t)x_ld, + (uint32_t)y_ld, dt, es, (int64_t)src_rows); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_scatter_rows(long v, long idx, long x, int M, int n, int v_ld, int x_ld, int dt, + long long dst_rows, long stream) { + if (!v || !idx || !x) return -1; + if (M <= 0 || n <= 0) return -2; + const int es = r3d_dt_size(dt); + if (!es) return -2; + if (!v_ld) v_ld = n; + if (!x_ld) x_ld = n; + if (v_ld < n || x_ld < n) return -3; + R3D_ROW2(scatter_rows_kernel, row_threads(n), M, stream, (const void*)(uintptr_t)v, + (const int32_t*)(uintptr_t)idx, (void*)(uintptr_t)x, (uint32_t)n, (uint32_t)v_ld, + (uint32_t)x_ld, dt, es, (int64_t)dst_rows); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== the plugin ABI entry points + * + * Unpacking RadArgs and deriving the pitches belongs to the kernel library (r3d_args.h). The + * kernels take raw pointers and one pitch per operand, so anything unpitched must be tight + * (spec §2.1). Before each launch a shim checks: + * + * * the dtype, off the operand: a row's `dtype` constraint is a necessary condition on the + * geometry, not a promise about the tensors, and an f32 operand read as bf16 is a value the + * geometry checks will not catch; + * * the row pitch, r3d_rows_pitch(): elements, or -1 (RAD_E_STRIDE) for a strided inner axis; + * * the row count, off the operand, never the `M` parameter: `M` is ranged, so the args carry + * the band's upper bound; + * * the parameters, with libref's defaults, and the forms the kernels cannot match -- refused + * with RAD_E_UNSUPPORTED so the row's constraints can state the band and a model that needs + * the refused form is not routed here at all. + * + * Every refusal goes through R3D_NO(), so a run with RAD_R3D_TRACE set says which line said no. + */ + +static inline int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; } +static inline int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; } +static inline int dt_i32(const RadTensor* t) { return r3d_is_i32(t) ? RAD_OK : RAD_E_DTYPE; } + +/* A bf16-or-f32 pair, so the two dtype legs of add/mul read as one test. */ +static inline int dt_same(const RadTensor* a, const RadTensor* b) { + return a && b && a->dtype == b->dtype ? RAD_OK : RAD_E_DTYPE; +} + +#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0) + +/* A launcher's return: 0 is RAD_OK, anything else is a device failure -- the arguments were the + * shim's to check, and it checked them. */ +static inline int r3d_launch_ok(int rc) { return rc == 0 ? RAD_OK : R3D_NO(RAD_E_DEVICE); } + +/* ------------------------------------------------------------------ rmsnorm */ + +enum { RMS_X = 0, RMS_W, RMS_Y }; + +extern "C" int r3d_rad_rmsnorm(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, RMS_X); + const RadTensor* w = r3d_opt(a, RMS_W); + const RadTensor* y = r3d_opt(a, RMS_Y); + if (!x || !y) return R3D_NO(RAD_E_INVAL); + /* The row's dtype band is bf16 or f32, and the two legs are the same two passes: an f32 + * checkpoint's residual stream normalizes without a store that narrows. */ + const bool f32 = r3d_is_f32(x) && r3d_is_f32(y); + if (!f32) { + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_bf16(y)); + } + + const float wadd = (float)r3d_getf(a, "wadd", 0.0); + const float mult = (float)r3d_getf(a, "mult", 1.0); + const float eps = (float)r3d_getf(a, "eps", 1e-6); + /* `wadd` without a gain is refused, as ref does: 1 + wadd of a gain that does not exist is a + * constant scale wearing a norm's name. */ + if (!w && wadd != 0.0f) return R3D_NO(RAD_E_INVAL); + /* The gain's dtype comes off the gain: bf16, f32, or none. */ + int wdt = R3D_DT_N; + if (w) { + if (r3d_is_bf16(w)) wdt = R3D_DT_BF16; + else if (r3d_is_f32(w)) wdt = R3D_DT_F32; + else return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(w)) return R3D_NO(RAD_E_STRIDE); + } + + const long long n = r3d_geti_or(a, "n", w ? r3d_dim(w, (int)w->rank - 1) + : r3d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, My = 0; + const long long x_ld = r3d_rows_pitch(x, n, &M); + const long long y_ld = r3d_rows_pitch(y, n, &My); + if (x_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || My < M) return R3D_NO(RAD_E_SHAPE); + if (w && r3d_numel(w) < n) return R3D_NO(RAD_E_SHAPE); + + const int rc = f32 + ? r3d_rmsnorm_f32(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)n, eps, wadd, mult, + (int)x_ld, (int)y_ld, wdt, (long)(uintptr_t)s) + : r3d_rmsnorm_bf16(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)n, eps, wadd, mult, + (int)x_ld, (int)y_ld, wdt, (long)(uintptr_t)s); + return r3d_launch_ok(rc); +} + +/* ------------------------------------------------------------------ rmsnorm_quant_fp8 + * The residual add, the norm and the E4M3 quantiser in one launch: {x, residual?, w, q, scale, + * out_bf16?} with {M, n, eps, group, dtype, wadd?}, libref's. The row's reason to exist is the + * traffic: the normalised row is written once as codes and one bf16 copy, not written as bf16 and + * read back by a separate quantiser. + */ +extern "C" int r3d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* res = r3d_opt(a, 1); + const RadTensor* w = r3d_opt(a, 2); + const RadTensor* q = r3d_opt(a, 3); + const RadTensor* sc = r3d_opt(a, 4); + const RadTensor* ob = r3d_opt(a, 5); + if (!x || !w || !q || !sc) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(x)); + /* The gain comes in the dtype the checkpoint stores it in -- bf16 or f32, read off the operand. + * The band's `dtype` is the activation's: a checkpoint that stores its gains as f32 is read as + * it is, and a shim that dtype-checks the weight against the activation band serves one + * checkpoint and refuses the next. The kernel's WDT leg is the plain rmsnorm's. */ + int wdt = R3D_DT_N; + if (r3d_is_bf16(w)) wdt = R3D_DT_BF16; + else if (r3d_is_f32(w)) wdt = R3D_DT_F32; + else return R3D_NO(RAD_E_DTYPE); + /* `residual` is validated below, where the flag that makes it read is read. `out_bf16` is + * checked because this kernel WRITES it, so it is required of the row that asks for it (the + * reference writes it when the operand is there) and absent when the slot carries no bytes. */ + if (r3d_has(ob)) R3D_NEED(dt_bf16(ob)); /* no bytes = the plan asked for no bf16 copy */ + if (r3d_dt_code(q->dtype) != R3D_DT_U8) return R3D_NO(RAD_E_DTYPE); // E4M3 codes + R3D_NEED(dt_f32(sc)); + + const long long n = r3d_geti_or(a, "n", w->rank ? r3d_dim(w, (int)w->rank - 1) : 0); + const long long group = r3d_geti_or(a, "group", 0); + if (n <= 0 || group <= 0) return R3D_NO(RAD_E_SHAPE); + /* A wave covers a group, four columns a lane per 128 columns, and a partial group is the + * standalone quantiser's zero-padded store. A checkpoint whose block divides its hidden width + * is the band this row is for. */ + if (group != 128 && group != 256 && group != 512) return R3D_NO(RAD_E_UNSUPPORTED); + if (n % group) return R3D_NO(RAD_E_UNSUPPORTED); + const float eps = (float)r3d_getf(a, "eps", 1e-6); + const float wadd = (float)r3d_getf(a, "wadd", 0.0); + /* The reference reads `residual` under `wadd` and nowhere else, and so do we -- checked here, + * after the flag, and REQUIRED by it. The engine hands the slot a tensor even when the band + * says wadd=0, in any dtype; a row that validates an operand the op will not read is a row + * that refuses a checkpoint. */ + if (wadd != 0.0f) { + if (!r3d_has(res)) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(res)); + } + + const long long ngrp = n / group; + long long M = 0, Mres = 0, Mob = 0, Mq = 0, Ms = 0; + const long long x_ld = r3d_rows_pitch(x, n, &M); + const long long q_ld = r3d_rows_pitch(q, n, &Mq); + const long long s_ld = r3d_rows_pitch(sc, ngrp, &Ms); + if (x_ld < 0 || q_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mq < M || Ms < M) return R3D_NO(RAD_E_SHAPE); + long long res_ld = 0, ob_ld = 0; + if (res) { res_ld = r3d_rows_pitch(res, n, &Mres); if (res_ld < 0 || Mres < M) + return Mres < 0 ? R3D_NO(RAD_E_STRIDE) : R3D_NO(RAD_E_SHAPE); } + if (ob) { ob_ld = r3d_rows_pitch(ob, n, &Mob); if (ob_ld < 0 || Mob < M) + return Mob < 0 ? R3D_NO(RAD_E_STRIDE) : R3D_NO(RAD_E_SHAPE); } + if (r3d_numel(w) < n) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_rmsnorm_quant_fp8( + r3d_addr(x), r3d_addr(res), r3d_addr(w), r3d_addr(q), r3d_addr(sc), r3d_addr(ob), (int)M, + (int)n, (int)group, eps, wadd, (int)x_ld, (int)res_ld, (int)ob_ld, (int)q_ld, (int)s_ld, + wdt, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ layernorm */ + +enum { LN_X = 0, LN_W, LN_B, LN_Y }; + +extern "C" int r3d_rad_layernorm(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, LN_X); + const RadTensor* w = r3d_opt(a, LN_W); + const RadTensor* b = r3d_opt(a, LN_B); + const RadTensor* y = r3d_opt(a, LN_Y); + if (!x || !w || !y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_bf16(w)); + R3D_NEED(dt_bf16(y)); + if (b) { + /* libref reads a bias in any float dtype; the kernel reads bf16 (the launcher has one + * dtype for gain and bias), so an f32 bias is refused, not read wrong. */ + if (!r3d_is_bf16(b)) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_bf16(b)); + } + if (!r3d_contig(w) || (b && !r3d_contig(b))) return R3D_NO(RAD_E_STRIDE); + + const long long n = r3d_geti_or(a, "n", r3d_dim(w, (int)w->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + const float eps = (float)r3d_getf(a, "eps", 1e-5); + long long M = 0, My = 0; + const long long x_ld = r3d_rows_pitch(x, n, &M); + const long long y_ld = r3d_rows_pitch(y, n, &My); + if (x_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || My < M) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(w) < n || (b && r3d_numel(b) < n)) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_layernorm_bf16(r3d_addr(x), r3d_addr(w), r3d_addr(b), r3d_addr(y), + (int)M, (int)n, eps, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ add / mul + * The broadcast rule is libref's, read off the operand: a `b` of exactly n elements against more + * than one row rides every row, and nothing else broadcasts. `div` is `add`'s only (mul's schema + * has no div key), and a zero, NaN or infinity is refused -- the reference refuses it too. */ +static int binary_shim(const RadArgs* a, RadStream s, int mul) { + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* B = r3d_opt(a, 1); + const RadTensor* Y = r3d_opt(a, 2); + if (!A || !B || !Y) return R3D_NO(RAD_E_INVAL); + const bool f32 = r3d_is_f32(Y); + if (f32) { + R3D_NEED(dt_f32(A)); + R3D_NEED(dt_f32(B)); + } else { + R3D_NEED(dt_bf16(A)); + R3D_NEED(dt_bf16(B)); + R3D_NEED(dt_bf16(Y)); + } + R3D_NEED(dt_same(A, Y)); + if (!mul) R3D_NEED(dt_same(A, B)); + + const long long n = r3d_geti_or(a, "n", r3d_numel(Y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + const float div = mul ? 1.0f : (float)r3d_getf(a, "div", 1.0); + if (!(div != 0.0f) || !std::isfinite(div)) return R3D_NO(RAD_E_INVAL); + + long long M = 0, Mb = 0; + const long long y_ld = r3d_rows_pitch(Y, n, &M); + const long long a_ld = r3d_rows_pitch(A, n, &Mb); + if (y_ld < 0 || a_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mb < M) return R3D_NO(RAD_E_SHAPE); + + const bool bcast = r3d_numel(B) == n && M > 1; + long long b_ld = 0; + if (!bcast) { + b_ld = r3d_rows_pitch(B, n, &Mb); + if (b_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (Mb < M) return R3D_NO(RAD_E_SHAPE); + } + + const int rc = mul + ? (f32 ? r3d_mul_f32(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, (int)a_ld, + (int)b_ld, (int)y_ld, bcast ? 1 : 0, (long)(uintptr_t)s) + : r3d_mul_bf16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, (int)a_ld, + (int)b_ld, (int)y_ld, bcast ? 1 : 0, (long)(uintptr_t)s)) + : (f32 ? r3d_add_f32(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, (int)a_ld, + (int)b_ld, (int)y_ld, div, bcast ? 1 : 0, (long)(uintptr_t)s) + : r3d_add_bf16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, (int)a_ld, + (int)b_ld, (int)y_ld, div, bcast ? 1 : 0, (long)(uintptr_t)s)); + return r3d_launch_ok(rc); +} + +extern "C" int r3d_rad_add(const RadArgs* a, RadStream s) { return binary_shim(a, s, 0); } +extern "C" int r3d_rad_mul(const RadArgs* a, RadStream s) { return binary_shim(a, s, 1); } + +/* ------------------------------------------------------------------ cast + * `from` and `to` are the selector's; the tensors' own dtypes are what the kernel moves. The + * whole op is flat, so one pitch per operand, and the row count is numel(y)/n with n the last + * dimension of y. */ +extern "C" int r3d_rad_cast(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* y = r3d_opt(a, 1); + if (!x || !y) return R3D_NO(RAD_E_INVAL); + const int from_dt = r3d_dt_code(x->dtype), to_dt = r3d_dt_code(y->dtype); + if (from_dt < 0 || to_dt < 0) return R3D_NO(RAD_E_DTYPE); + /* f16 has no e5m2 twin in this library, and the f16 <-> integer pairs have no caller: the + * codes the kernels move are bf16, f16, f32, i32, i64, E4M3 codes and i8. */ + static const int kOk[] = { R3D_DT_BF16, R3D_DT_F16, R3D_DT_F32, R3D_DT_I32, R3D_DT_I64, + R3D_DT_U8, R3D_DT_I8 }; + bool ok = false; + for (unsigned i = 0; i < sizeof kOk / sizeof kOk[0]; ++i) + ok = ok || (from_dt == kOk[i] && (to_dt == kOk[i] || to_dt == R3D_DT_F32 || + to_dt == R3D_DT_BF16 || to_dt == R3D_DT_I32 || + to_dt == R3D_DT_I64 || to_dt == R3D_DT_F16 || + to_dt == R3D_DT_U8 || to_dt == R3D_DT_I8)); + if (!ok) return R3D_NO(RAD_E_UNSUPPORTED); + + const long long n = r3d_geti_or(a, "n", r3d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx < M) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_cast(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + from_dt, to_dt, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ silu / gelu / sigmoid */ + +static int unary_shim(const RadArgs* a, RadStream s, int act) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* y = r3d_opt(a, 1); + if (!x || !y) return R3D_NO(RAD_E_INVAL); + const bool f32 = r3d_is_f32(x) && r3d_is_f32(y); + if (!f32) { + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_bf16(y)); + } + /* Only silu has an f32 leg in r3d.h (the vocoder's f32 branch is the one that asked for it); + * an f32 gelu or sigmoid is refused, not served by the bf16 kernel. */ + if (f32 && act != R3D_ACT_SILU) return R3D_NO(RAD_E_UNSUPPORTED); + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx < M) return R3D_NO(RAD_E_SHAPE); + + const int rc = f32 + ? r3d_silu_f32(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) + : (act == R3D_ACT_SILU + ? r3d_silu_bf16(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) + : act == R3D_ACT_GELU + ? r3d_gelu_bf16(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) + : r3d_sigmoid_bf16(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); + return r3d_launch_ok(rc); +} + +extern "C" int r3d_rad_silu(const RadArgs* a, RadStream s) { return unary_shim(a, s, R3D_ACT_SILU); } +extern "C" int r3d_rad_gelu(const RadArgs* a, RadStream s) { return unary_shim(a, s, R3D_ACT_GELU); } +extern "C" int r3d_rad_sigmoid(const RadArgs* a, RadStream s) { + return unary_shim(a, s, R3D_ACT_SIGMOID); +} + +/* ------------------------------------------------------------------ act_mul + * libref's kActs order is silu, gelu, gelu_tanh, sigmoid, quick_gelu; libr3d's rows serve silu, + * gelu and sigmoid, and the other two are refused with RAD_E_UNSUPPORTED so the row's constraints + * state which gated MLPs reach an RDNA3 card. */ +extern "C" int r3d_rad_act_mul(const RadArgs* a, RadStream s) { + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* B = r3d_opt(a, 1); + const RadTensor* Y = r3d_opt(a, 2); + if (!A || !B || !Y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(A)); + R3D_NEED(dt_bf16(B)); + R3D_NEED(dt_bf16(Y)); + + int act = -1; + if (const char* n = r3d_gets(a, "act")) { + if (!std::strcmp(n, "silu") || !std::strcmp(n, "swish")) act = R3D_ACT_SILU; + else if (!std::strcmp(n, "gelu")) act = R3D_ACT_GELU; + else if (!std::strcmp(n, "sigmoid")) act = R3D_ACT_SIGMOID; + else if (!std::strcmp(n, "gelu_tanh") || !std::strcmp(n, "quick_gelu")) + return R3D_NO(RAD_E_UNSUPPORTED); + else return R3D_NO(RAD_E_INVAL); + } else { + act = R3D_ACT_SILU; // libref's p_enum default: the gated MLP's activation + } + + const long long n = r3d_geti_or(a, "n", r3d_numel(Y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mg = 0, Mu = 0; + const long long y_ld = r3d_rows_pitch(Y, n, &M); + const long long g_ld = r3d_rows_pitch(A, n, &Mg); + const long long u_ld = r3d_rows_pitch(B, n, &Mu); + if (y_ld < 0 || g_ld < 0 || u_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mg < M || Mu < M) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_act_mul_bf16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, + (int)g_ld, (int)u_ld, (int)y_ld, act, + (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ silu_mul + * y[i] = silu(gate_up[i]) * gate_up[n + i]: libref's {gate_up, y} operands and its {M, n, dtype} + * schema. A distinct op from act_mul -- the llama MLP emits it, and act_mul takes two operands -- + * so a model asking for silu_mul is not served by the act_mul_silu row. + */ +extern "C" int r3d_rad_silu_mul(const RadArgs* a, RadStream s) { + const RadTensor* gu = r3d_opt(a, 0); + const RadTensor* y = r3d_opt(a, 1); + if (!gu || !y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(gu)); + R3D_NEED(dt_bf16(y)); + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mgu = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long gu_ld = r3d_rows_pitch(gu, 2 * n, &Mgu); /* the FUSED row is 2n wide */ + if (y_ld < 0 || gu_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mgu < M) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(gu) < M * 2 * n) return R3D_NO(RAD_E_SHAPE); // ref's own bound on the plane + + return r3d_launch_ok(r3d_silu_mul_bf16(r3d_addr(gu), r3d_addr(y), (int)M, (int)n, (int)gu_ld, + (int)y_ld, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ softmax + * f32, as ref spells it: the reference casts to f32, computes, and casts back, and the intermediate + * `e` is read back from an f32 plane. A bf16 y would round that intermediate and the kernel cannot + * match ref with ref's own arithmetic, so it is refused rather than served at a tolerance. */ +extern "C" int r3d_rad_softmax(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* y = r3d_opt(a, 1); + if (!x || !y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_f32(x)); + R3D_NEED(dt_f32(y)); + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx < M) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_softmax_f32(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ scale + * y = x * s. `s` is the op's [1] weight plane: the shim checks its dtype and that it has an + * element, and the kernel reads the value. The launcher cannot take the number by value, because + * reading a device plane on the host is a copy and a sync, and a row is neither. */ +extern "C" int r3d_rad_scale(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* sc = r3d_opt(a, 1); + const RadTensor* y = r3d_opt(a, 2); + if (!x || !sc || !y) return R3D_NO(RAD_E_INVAL); + const bool f32 = r3d_is_f32(x) && r3d_is_f32(y); + if (!f32) { + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_bf16(y)); + } + const int s_dt = r3d_is_f32(sc) ? R3D_DT_F32 : r3d_is_bf16(sc) ? R3D_DT_BF16 : -1; + if (s_dt < 0) return R3D_NO(RAD_E_DTYPE); + if (r3d_numel(sc) < 1) return R3D_NO(RAD_E_SHAPE); + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx < M) return R3D_NO(RAD_E_SHAPE); + + const int rc = f32 + ? r3d_scale_f32(r3d_addr(x), r3d_addr(sc), r3d_addr(y), (int)M, (int)n, s_dt, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s) + : r3d_scale_bf16(r3d_addr(x), r3d_addr(sc), r3d_addr(y), (int)M, (int)n, s_dt, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s); + return r3d_launch_ok(rc); +} + +/* ------------------------------------------------------------------ fill */ + +extern "C" int r3d_rad_fill(const RadArgs* a, RadStream s) { + const RadTensor* y = r3d_opt(a, 0); + if (!y) return R3D_NO(RAD_E_INVAL); + const int dt = r3d_dt_code(y->dtype); + if (dt < 0) return R3D_NO(RAD_E_DTYPE); + if (dt == R3D_DT_E5M2) return R3D_NO(RAD_E_UNSUPPORTED); // no e5m2 codec on this path + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + if (y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M)) return R3D_NO(RAD_E_SHAPE); + + const float v = (float)r3d_getf(a, "value", 0.0); + return r3d_launch_ok(r3d_fill(r3d_addr(y), (int)M, (int)n, (int)y_ld, dt, v, + (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ rope + * In place, so operand 0 is the row's INOUT: the shim checks it is writable (the role says it is; + * a null data is the row's bug, and is RAD_E_INVAL) and that head_dim and rot are even. + * + * What the shim refuses, and why: the multi-component modes (mrope, imrope, axial) need a + * [C, M] position plane and per-section ladders; the proportional ladder (`ladder=head`) pairs + * across the whole head; YaRN and Llama 3 rescale the ladder. Each changes the angles, not the + * arithmetic, and the kernel has the plain rotary -- so each is RAD_E_UNSUPPORTED, the row's + * constraints say so, and a model that needs one is not routed to this card's row. + */ +extern "C" int r3d_rad_rope(const RadArgs* a, RadStream s) { + const RadTensor* qkv = r3d_opt(a, 0); + const RadTensor* pos = r3d_opt(a, 1); + if (!qkv || !pos) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(qkv)); + R3D_NEED(dt_i32(pos)); + if (!r3d_contig(pos)) return R3D_NO(RAD_E_STRIDE); + if (pos->rank >= 2) return R3D_NO(RAD_E_UNSUPPORTED); // multi-component positions + + const long long head_dim = r3d_geti_or(a, "head_dim", 0); + const long long n_head = r3d_geti_or(a, "n_head", 0); + const long long n_head_kv = r3d_geti_or(a, "n_head_kv", 0); + if (head_dim <= 0 || n_head <= 0 || n_head_kv < 0) return R3D_NO(RAD_E_SHAPE); + long long rot = r3d_geti_or(a, "rotary_dim", head_dim); + if (rot <= 0) rot = head_dim; + if (rot > head_dim) return R3D_NO(RAD_E_SHAPE); + if ((head_dim & 1) || (rot & 1)) return R3D_NO(RAD_E_SHAPE); /* odd halves: a shape the kernel does not serve */ + + static const char* kModes[] = { "neox", "gptj", "mrope", "imrope", "axial" }; + int mode = -1; + if (const char* nm = r3d_gets(a, "mode")) { + for (int i = 0; i < 5; ++i) + if (!std::strcmp(nm, kModes[i])) { mode = i; break; } + } + if (mode < 0) return R3D_NO(RAD_E_UNSUPPORTED); // absent, or one of the three multi modes + if (mode > R3D_ROPE_GPTJ) return R3D_NO(RAD_E_UNSUPPORTED); + if (r3d_gets(a, "sections")) return R3D_NO(RAD_E_UNSUPPORTED); + if (r3d_getf(a, "yarn_factor", 0.0) != 0.0) return R3D_NO(RAD_E_UNSUPPORTED); + if (r3d_getf(a, "llama3_factor", 0.0) != 0.0) return R3D_NO(RAD_E_UNSUPPORTED); + if (const char* lad = r3d_gets(a, "ladder")) { + /* Absent and "rotary" are the ladder the kernel has: the base frequency divides by rot. */ + if (std::strcmp(lad, "rotary")) return R3D_NO(RAD_E_UNSUPPORTED); + } + + const float theta = (float)r3d_getf(a, "theta", 10000.0); + const float scale = (float)r3d_getf(a, "scale", 1.0); + + const long long width = (n_head + 2 * n_head_kv) * head_dim; + long long Mq = 0; + const long long qkv_ld = r3d_rows_pitch(qkv, width, &Mq); + if (qkv_ld < 0) return R3D_NO(RAD_E_STRIDE); + const long long Mp = r3d_numel(pos); + if (Mp <= 0 || Mq < Mp) return R3D_NO(RAD_E_SHAPE); + const long long M = Mp; // the positions drive the launch; a row past them is left alone + + return r3d_launch_ok(r3d_rope_bf16(r3d_addr(qkv), r3d_addr(pos), (int)M, (int)head_dim, + (int)n_head, (int)n_head_kv, theta, scale, mode, (int)rot, + (int)qkv_ld, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ kv_store + * The cache is INOUT: only the mapped slots are touched and every other slot must survive. Its + * strides are read off the operand (the reference's kv_view): a rank-4 cache carries them; the + * flat [blocks, kv_heads, block_size, 2*head_dim] form derives them. + * + * ref also refuses a slot naming a block past the cache (RAD_E_SHAPE), which the shim cannot do + * before the launch: the slots are in device memory. The bound travels as `slot_max`, the slot span + * of the cache the shapes hook sizes, and the kernel drops a slot at or past it -- a slot lost, + * not a step lost. + */ +extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream s) { + const RadTensor* k = r3d_opt(a, 0); + const RadTensor* v = r3d_opt(a, 1); + const RadTensor* sm = r3d_opt(a, 2); + const RadTensor* kv = r3d_opt(a, 3); + if (!k || !v || !sm || !kv) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(k)); + R3D_NEED(dt_bf16(v)); + R3D_NEED(dt_i32(sm)); + const int kv_dt = r3d_dt_code(kv->dtype); + if (kv_dt != R3D_DT_BF16 && kv_dt != R3D_DT_F16 && kv_dt != R3D_DT_U8) + return R3D_NO(RAD_E_DTYPE); + + const long long head_dim = r3d_geti_or(a, "head_dim", 0); + const long long n_head_kv = r3d_geti_or(a, "n_head_kv", 0); + const long long block_size = r3d_geti_or(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0); + if (head_dim <= 0 || n_head_kv <= 0 || block_size <= 0) return R3D_NO(RAD_E_SHAPE); + const float k_scale = (float)r3d_getf(a, "k_scale", 1.0); + const float v_scale = (float)r3d_getf(a, "v_scale", 1.0); + if (kv_dt == R3D_DT_U8 && !(k_scale > 0.0f && v_scale > 0.0f)) return R3D_NO(RAD_E_INVAL); + + long long sb = 0, sh = 0, so = 0, sd = 1; + if (kv->rank == 4) { + sb = r3d_stride(kv, 0); + sh = r3d_stride(kv, 1); + so = r3d_stride(kv, 2); + sd = r3d_stride(kv, 3); + if (sd != 1) return R3D_NO(RAD_E_UNSUPPORTED); // a strided cache element + if (r3d_dim(kv, 1) != n_head_kv || r3d_dim(kv, 2) != block_size) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(kv, 3) < 2 * head_dim) return R3D_NO(RAD_E_SHAPE); + } else { + so = 2 * head_dim; + sh = block_size * so; + sb = n_head_kv * sh; + } + + const long long width = n_head_kv * head_dim; + long long Mk = 0, Mv = 0; + const long long k_ld = r3d_rows_pitch(k, width, &Mk); + const long long v_ld = r3d_rows_pitch(v, width, &Mv); + if (k_ld < 0 || v_ld < 0) return R3D_NO(RAD_E_STRIDE); + const long long T = r3d_numel(sm); + if (T <= 0 || Mk < T || Mv < T) return R3D_NO(RAD_E_SHAPE); + if (!row_count_ok(T)) return R3D_NO(RAD_E_SHAPE); + + /* The cache's span, in slots: the pool's own plane, NOT this step's. A step that adopts a + * prefix writes its tail into the blocks the table names, and those sit at the allocator's + * GLOBAL indices -- a 4-token tail placed at block 3 is slots 48..51, past any bound built + * from T. A bound built from the step's own span is no bound for the tail's slots, so the + * pool's plane is the true bound: a slot at or past it names memory the cache does not have, + * and the kernel drops it there. */ + long long slot_max; + if (kv->rank == 4) { + slot_max = (long long)r3d_dim(kv, 0) * block_size; + } else { + long long el = 1; + for (int i = 0; i < kv->rank; ++i) el *= r3d_dim(kv, i); + slot_max = el / (2 * head_dim); + } + + if (std::getenv("RAD_R3D_TRACE")) /* the write side, spoken: where this step's KV lands. A + * tail that names slots of an adopted block writes over the + * shared prefix, and this line is the one that says so. */ + { + (void)hipDeviceSynchronize(); + int slots[8]; + if (hipMemcpy(slots, (const void*)(uintptr_t)r3d_addr(sm), 8 * sizeof(int), + hipMemcpyDeviceToHost) == hipSuccess) { + std::fprintf(stderr, "[r3d] kvstore: T=%lld kvbase=%p slots=", (long long)T, + (const void*)(uintptr_t)r3d_addr(kv)); + for (int c = 0; c < 8 && (long long)c < T; ++c) + std::fprintf(stderr, "%s%d", c ? " " : "", slots[c]); + std::fprintf(stderr, "\n"); + } + } + + return r3d_launch_ok(r3d_kv_store(r3d_addr(k), r3d_addr(v), r3d_addr(sm), r3d_addr(kv), (int)T, + (int)head_dim, (int)n_head_kv, (int)block_size, kv_dt, + k_scale, v_scale, (int)k_ld, (int)v_ld, slot_max, sb, sh, so, + sd, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ embed_lookup + * tokens are i32 (the engine's token ids), the table's dtype is the launcher's `dt`, and x is + * bf16 -- a table in any other float dtype, or an E4M3 table whose scale arrives as a tensor + * (embed_lookup_q's operand), is refused: one scale per gathered row is a device read the step + * path cannot do, which is why the op's schema carries `wscale` as a parameter. */ +extern "C" int r3d_rad_embed_lookup(const RadArgs* a, RadStream s) { + const RadTensor* tok = r3d_opt(a, 0); + const RadTensor* wte = r3d_opt(a, 1); + const RadTensor* x = r3d_opt(a, 2); + if (!tok || !wte || !x) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_i32(tok)); + R3D_NEED(dt_bf16(x)); + if (!r3d_contig(tok) || !r3d_contig(wte)) return R3D_NO(RAD_E_STRIDE); + const int dt = r3d_dt_code(wte->dtype); + if (dt != R3D_DT_BF16 && dt != R3D_DT_F16 && dt != R3D_DT_F32 && dt != R3D_DT_U8) + return R3D_NO(RAD_E_DTYPE); + if (dt != R3D_DT_BF16 && r3d_getf(a, "wscale", 1.0) == 1.0 && dt == R3D_DT_U8) + return R3D_NO(RAD_E_INVAL); // an E4M3 table with no scale stated is a bug, not a copy + + const long long n_embd = r3d_geti_or(a, "n_embd", r3d_dim(wte, (int)wte->rank - 1)); + const long long n_vocab = r3d_geti_or(a, "n_vocab", r3d_dim(wte, (int)wte->rank - 2)); + const long long voff = r3d_geti_or(a, "vocab_offset", 0); + if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(wte) < n_vocab * n_embd) return R3D_NO(RAD_E_SHAPE); + + long long Mx = 0; + const long long x_ld = r3d_rows_pitch(x, n_embd, &Mx); + if (x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(Mx) || r3d_numel(tok) < Mx) return R3D_NO(RAD_E_SHAPE); + const long long M = Mx; + + const float mult = (float)r3d_getf(a, "mult", 1.0); + const float wscale = (float)r3d_getf(a, "wscale", 1.0); + const long long w_ld = wte->rank >= 2 ? r3d_stride(wte, (int)wte->rank - 2) : n_embd; + + return r3d_launch_ok(r3d_embed_lookup(r3d_addr(tok), r3d_addr(wte), r3d_addr(x), (int)M, + (int)n_embd, (int)n_vocab, (int)voff, wscale, mult, + (int)x_ld, (int)w_ld, dt, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ gather_rows / scatter_rows */ + +extern "C" int r3d_rad_gather_rows(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* idx = r3d_opt(a, 1); + const RadTensor* y = r3d_opt(a, 2); + if (!x || !idx || !y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_i32(idx)); + const int dt = r3d_dt_code(x->dtype); + if (dt < 0) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_same(x, y)); + if (dt == R3D_DT_E5M2) return R3D_NO(RAD_E_UNSUPPORTED); + + const long long n = r3d_geti_or(a, "n", r3d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx <= 0 || r3d_numel(idx) < M) return R3D_NO(RAD_E_SHAPE); + + /* The source plane's row count, which the shim sees in the descriptor and the kernel cannot: + * an index at or past it is libref's refused step and takes the zero row here. */ + return r3d_launch_ok(r3d_gather_rows(r3d_addr(x), r3d_addr(idx), r3d_addr(y), (int)M, (int)n, + (int)x_ld, (int)y_ld, dt, Mx, (long)(uintptr_t)s)); +} + +extern "C" int r3d_rad_scatter_rows(const RadArgs* a, RadStream s) { + const RadTensor* v = r3d_opt(a, 0); + const RadTensor* idx = r3d_opt(a, 1); + const RadTensor* x = r3d_opt(a, 2); + if (!v || !idx || !x) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_i32(idx)); + const int dt = r3d_dt_code(v->dtype); + if (dt < 0) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_same(v, x)); + if (dt == R3D_DT_E5M2) return R3D_NO(RAD_E_UNSUPPORTED); + + const long long n = r3d_geti_or(a, "n", r3d_dim(v, (int)v->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long v_ld = r3d_rows_pitch(v, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (v_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx <= 0 || r3d_numel(idx) < M) return R3D_NO(RAD_E_SHAPE); + + /* The destination plane's row count, from the descriptor: an index at or past it writes past + * the plane, which is the one thing a scatter must not do, so the kernel drops the row. */ + return r3d_launch_ok(r3d_scatter_rows(r3d_addr(v), r3d_addr(idx), r3d_addr(x), (int)M, (int)n, + (int)v_ld, (int)x_ld, dt, Mx, (long)(uintptr_t)s)); +} diff --git a/libr3d/r3d_plugin.h b/libr3d/r3d_plugin.h new file mode 100644 index 00000000..4d265948 --- /dev/null +++ b/libr3d/r3d_plugin.h @@ -0,0 +1,289 @@ +/* r3d_plugin.h -- what libr3d's translation units share. + * + * The row table (r3d_rows.cpp) and the operand descriptions (r3d_shapes.cpp) are pure host C++ and + * include only this file and the ABI; the launch shims include r3d.h and so . + * The split lets the constraint table compile and be checked without ROCm, and is why every shim is + * declared here rather than beside its definition. + * + * Nothing in this header may include r3d.h. + */ +#ifndef RAD_R3D_PLUGIN_H +#define RAD_R3D_PLUGIN_H + +#include "r3d_args.h" + +/* ================================================================== the priority ladder + * + * The selector ranks candidate rows by an integer priority (spec §2.1); where two rows of one op + * can match a geometry, it decides which serves. Each group states the reason for its order. + * Values are spaced by ten so a row can be slipped between two without renumbering. + * + * libr3d ships one row per (op, dtype) pair far more often than libr4d does: on RDNA3 there is no + * matrix instruction whose fragment layout, tile shape or operand width a kernel has to design + * around, so the dot2 kernel that serves bf16 serves f16 with a template argument, and there is + * nothing to specialise a second row for. Where two rows of one op do exist, the reason is the + * geometry, and it is written next to the pair. + */ +enum { + /* The common case: this op, these dtypes, one row. Nothing competes with it. */ + R3D_PRIO_ONLY = 50, + + /* `attn_paged` is banded on q_len, and the decode row's bound (q_len <= 16) is a bucket + * boundary, not a partition: a speculative verify at 8 query tokens matches the prefill row + * too, and the decode kernel -- split-KV, one head group a workgroup, no query tile -- is the + * faster one there. Decode therefore outranks prefill, as it does in libr4d. */ + R3D_PRIO_ATTN_DECODE = 70, + R3D_PRIO_ATTN_PREFILL = 60, + + /* The skinny bf16 GEMM's band is M <= 16 and the tiled one's starts at M >= 16, so the two + * meet at exactly 16 rows and the skinny kernel wins there (it keeps the whole weight stream + * in flight with one wave a row and has no LDS staging to pay for). The overlap is deliberate: + * a caller that wants the tiled kernel at 16 rows asks with M=17, the same convention libr4d + * uses at its own m64/tiled boundary. */ + R3D_PRIO_GEMM_M16 = 60, + R3D_PRIO_GEMM_TILED = 40, + + /* The vocab is a GEMM whose N is the vocabulary: one row, M <= 16, split-K across the whole + * card. The tiled GEMM has no row for these N, so this priority only decides against a future + * tiled vocab row. */ + R3D_PRIO_VOCAB_M1 = 60, + + /* An fp8 weight row and an int8 weight row never compete: no dtype string reaches both, and a + * container's encoding picks which is legal. */ + R3D_PRIO_GEMM_FP8 = 60, + + /* The sampler stages are one row each, on one dtype (f32 logits), so there is nothing to rank. + * The name is here so a second row for a stage -- an i8 logits form, say -- has a ladder to + * join. */ + R3D_PRIO_SAMPLE = 50 +}; + +/* ================================================================== the dtype codes a C + * launcher takes + * + * The launchers in r3d.h take a dtype as an int, because a `__global__`'s dtype has to be a runtime + * value for the ops that are one kernel over several (cast, fill, dequant) and a compile-time one + * everywhere else. These are the codes; they are libr3d's own, not rad_types.h's RAD_DT_* (a + * launcher's argument list is a private contract between a shim and its kernel, and the kernel + * switch reads better over a dense 0..n than over the ABI's sparse enum). Every shim translates. */ +enum { + R3D_DT_BF16 = 0, + R3D_DT_F16 = 1, + R3D_DT_F32 = 2, + R3D_DT_I32 = 3, + R3D_DT_I64 = 4, + R3D_DT_U8 = 5, /* byte codes: fp8 e4m3, read with the codec */ + R3D_DT_I8 = 6, + R3D_DT_E5M2 = 7, + R3D_DT_N = 8 +}; + +/* A RadTensor's dtype to the code above, or -1 for one libr3d has no kernel for. */ +static inline int r3d_dt_code(uint32_t dt) { + switch (dt) { + case RAD_BF16: return R3D_DT_BF16; + case RAD_F16: return R3D_DT_F16; + case RAD_F32: return R3D_DT_F32; + case RAD_I32: + case RAD_U32: return R3D_DT_I32; + case RAD_I64: return R3D_DT_I64; + case RAD_F8E4M3: return R3D_DT_U8; + case RAD_F8E5M2: return R3D_DT_E5M2; + case RAD_I8: return R3D_DT_I8; + case RAD_U8: return R3D_DT_U8; + default: return -1; + } +} + +/* The bytes an element of that code occupies. */ +static inline int r3d_dt_size(int code) { + static const int kSize[R3D_DT_N] = { 2, 2, 4, 4, 8, 1, 1, 1 }; + return (code >= 0 && code < R3D_DT_N) ? kSize[code] : 0; +} + +/* The activation an `act` parameter names, as the kernels' template argument. */ +enum { R3D_ACT_SILU = 0, R3D_ACT_SIGMOID = 1, R3D_ACT_GELU = 2 }; + +/* rope's `mode`, same numbering as libref's kModes. libr3d's kernel implements neox and gptj; the + * rows' constraints say so, so a model that needs mrope is not routed here. */ +enum { R3D_ROPE_NEOX = 0, R3D_ROPE_GPTJ = 1 }; + +/* ================================================================== the row table's entry points + * + * Declared here so r3d_rows.cpp, which is host code built without ROCm, can name them; each is + * defined beside its kernel, in the unit named below, and is documented there. A shim is a + * `RadLaunchFn`: operands read with r3d_args.h, dtype from the tensor, row count from the operand. + * A shape hook is a `RadShapeFn`: the extent and content domain of one operand (r3d_shapes.cpp). + */ +extern "C" { + +/* --- r3d_model_bf16.hip --- */ +int r3d_rad_rmsnorm (const RadArgs* a, RadStream s); +int r3d_rad_layernorm (const RadArgs* a, RadStream s); +int r3d_rad_add (const RadArgs* a, RadStream s); +int r3d_rad_mul (const RadArgs* a, RadStream s); +int r3d_rad_cast (const RadArgs* a, RadStream s); +int r3d_rad_silu (const RadArgs* a, RadStream s); +int r3d_rad_gelu (const RadArgs* a, RadStream s); +int r3d_rad_sigmoid (const RadArgs* a, RadStream s); +int r3d_rad_act_mul (const RadArgs* a, RadStream s); +int r3d_rad_softmax (const RadArgs* a, RadStream s); +int r3d_rad_scale (const RadArgs* a, RadStream s); +int r3d_rad_fill (const RadArgs* a, RadStream s); +int r3d_rad_rope (const RadArgs* a, RadStream s); +int r3d_rad_kv_store (const RadArgs* a, RadStream s); +int r3d_rad_embed_lookup (const RadArgs* a, RadStream s); +int r3d_rad_gather_rows (const RadArgs* a, RadStream s); +int r3d_rad_scatter_rows (const RadArgs* a, RadStream s); + +/* --- r3d_quant_fp8.hip --- */ +int r3d_rad_quant_act_fp8 (const RadArgs* a, RadStream s); +int r3d_rad_quant_act_i8 (const RadArgs* a, RadStream s); +int r3d_rad_quant_act_i8g (const RadArgs* a, RadStream s); +int r3d_rad_gated_quant_fp8 (const RadArgs* a, RadStream s); +int r3d_rad_dequant (const RadArgs* a, RadStream s); + +/* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */ +int r3d_rad_gemm_nt_bf16_m16 (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_fp8 (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_i8 (const RadArgs* a, RadStream s); + +/* --- r3d_shapes.cpp --- */ +int r3d_shape_rmsnorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_layernorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_add (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_mul (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_act_mul (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_cast (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_silu (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gelu (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_sigmoid (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_softmax (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_scale (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_fill (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_rope (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_kv_store (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_embed_lookup (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gather_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_scatter_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_quant_act_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_quant_act_i8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_quant_act_i8g (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gated_quant_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_dequant (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gemm_nt (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gemm_nt_q (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); + +/* --- r3d_attn_paged_h128.hip, r3d_vocab_bf16.hip, r3d_sample_f32.hip --- */ +extern "C" int r3d_shape_silu_mul (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_attn_paged (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_gemm_nt_q_gated (const RadParam*, int, int, RadOpdDesc*); +/* The vocab projection at w2a8, decode. The layout hook is this library's scoped exception to + * "no layout hooks" (the other two are the fp8 weight's and the logits head's, below): it repacks + * nothing, it presents the container's `scale` and `zero` planes as the single joined `b_scale` + * operand the way rad_planes stores them, transcribed from + * ref_layout_gemm_q. Without it the plan has a placement with no reader. */ +extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadEncoding*, + const int* sel, const RadTensor* planes, int n_planes, + RadLayout*); +extern "C" int r3d_shape_dflash_select (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_row_topk (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_argmax (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_temp (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_topk (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_topp (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_minp (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_typical (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_xtc (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_pick (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_penalties (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_dry (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_ngram_ban (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_mask (const RadParam*, int, int, RadOpdDesc*); +extern "C" int r3d_shape_sample_logprobs (const RadParam*, int, int, RadOpdDesc*); + +/* --- r3d_sample_f32.hip: the draw spine (row_topk, argmax, temp, topk, pick, the four narrowings) + and r3d_model_bf16.hip's pre-filters (penalties, dry, ngram_ban, mask, logprobs) --- */ +int r3d_rad_gemm_nt_q_w2a8 (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_gated (const RadArgs* a, RadStream s); +int r3d_rad_dflash_select (const RadArgs* a, RadStream s); +int r3d_rad_row_topk (const RadArgs* a, RadStream s); +int r3d_rad_sample_argmax (const RadArgs* a, RadStream s); +int r3d_rad_sample_temp (const RadArgs* a, RadStream s); +int r3d_rad_sample_topk (const RadArgs* a, RadStream s); +int r3d_rad_sample_pick (const RadArgs* a, RadStream s); +int r3d_rad_sample_topp (const RadArgs* a, RadStream s); +int r3d_rad_sample_minp (const RadArgs* a, RadStream s); +int r3d_rad_sample_typical (const RadArgs* a, RadStream s); +int r3d_rad_sample_xtc (const RadArgs* a, RadStream s); +int r3d_rad_sample_penalties (const RadArgs* a, RadStream s); +int r3d_rad_sample_dry (const RadArgs* a, RadStream s); +int r3d_rad_sample_ngram_ban (const RadArgs* a, RadStream s); +int r3d_rad_sample_mask (const RadArgs* a, RadStream s); +int r3d_rad_sample_logprobs (const RadArgs* a, RadStream s); + +/* --- r3d_model_bf16.hip: the fused MLP activation and the fused norm-quantiser --- */ +/* The paged attention's two entry points, banded on q_len: the decode kernel is split-KV over the + * cache with one head group a workgroup, the prefill kernel stages a 16-token query tile. */ +int r3d_rad_attn_decode_h128 (const RadArgs* a, RadStream s); +int r3d_rad_attn_prefill_h128 (const RadArgs* a, RadStream s); + +/* --- r3d_vocab_bf16.hip: the vocabulary projection, both heights. The shape hook is a + * transcription of ref_logits_gemm_shape -- three plain tensors, nothing joined -- so the band the + * engine declares is the band kbench fills, which is the opposite of the w2a8 row's null hook: there + * the describable byte count is the trap, here it is the point. */ +/* --- r3d_gemm_fp8a8_tiled.hip: the quantised GEMM above the decode heights, and the reader for + * the container's fp8 weight: codes and per-128x128 scale as two planes behind `b_scale`. The + * reference's own gemm_nt_q hook answers nothing for this dtype -- ref_layout_gemm_q reads zp_grid, + * and zp_grid has no fp8a8 entry -- which is why the row carries its own. */ +int r3d_rad_gemm_nt_q_fp8_tiled (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_w2a8_tiled (const RadArgs* a, RadStream s); +extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*, + const int*, const RadTensor*, int, RadLayout*); + +/* --- r3d_gemm_mxfp4a8.hip: the OCP-MXFP4 weight against the fp8 activation, both heights. The + * weight is two plain u8 planes -- e2m1 codes [N, K/2] and the e8m0 scale [N, K/32] -- so the row + * reads them in place and carries no layout hook; the shape hook is its own because the weight's + * two planes are not the fp8 grid's E4M3 codes and block scale. */ +int r3d_rad_gemm_nt_q_mxfp4a8_m16 (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s); + +/* --- r3d_gemm_inta8.hip: the symmetric int4 and int8 weight grids at decode heights. The weight + * is signed codes (I4, two a byte, or I8, one a byte) against a plain f16 scale per (row, 128 of + * K) -- no zero point and no a_sum, so both planes are read in place and the rows carry no layout + * hook. */ +int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_w8a8_m16(const RadArgs* a, RadStream s); +int r3d_shape_gemm_nt_q_w4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gemm_nt_q_w8a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); + +/* The three writers that go with the three plane hooks, one per row, each delegating to + * rad_planes_relayout: the loader converts a quantised weight into the joined operand the plan names + * at load, and only the row that reads it can say how. See abi/rad_abi.h. */ +extern "C" int r3d_relayout_logits_head(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); +extern "C" int r3d_relayout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*, + const int*, const RadTensor*, int, void*, int64_t); +extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadEncoding*, + const int*, const RadTensor*, int, void*, int64_t); + +int r3d_rad_logits_gemm_bf16 (const RadArgs* a, RadStream s); +/* The head's reader: `output.weight` at a llama_dense_fp8 checkpoint is E4M3 codes and a bf16 scale + * per 128x128 block, stored as two container planes behind the one `lm_head` operand, and the mapped + * tier will not place a weight a loaded library cannot read in place. Transcribed from + * ref_layout_head (libref's own logits row carries that hook), with the statics it uses inlined + * beside it. It moves no byte: a round-trip through its relayout writer (above) reproduces the + * planes byte for byte, and that writer exists for the round-trip, not for a move. */ +extern "C" int r3d_layout_logits_head(const RadParam*, int, int, const RadEncoding*, + const int*, const RadTensor*, int, RadLayout*); +int r3d_rad_gemm_nt_bf16_tiled (const RadArgs* a, RadStream s); +int r3d_shape_logits_gemm_bf16 (const RadParam*, int, int, RadOpdDesc*); + +int r3d_rad_silu_mul (const RadArgs* a, RadStream s); +int r3d_rad_rmsnorm_quant_fp8 (const RadArgs* a, RadStream s); +int r3d_shape_rmsnorm_quant_fp8 (const RadParam*, int, int, RadOpdDesc*); + +} /* extern "C" */ + +#endif /* RAD_R3D_PLUGIN_H */ diff --git a/libr3d/r3d_quant_fp8.hip b/libr3d/r3d_quant_fp8.hip new file mode 100644 index 00000000..d953ee3c --- /dev/null +++ b/libr3d/r3d_quant_fp8.hip @@ -0,0 +1,929 @@ +/* r3d_quant_fp8.hip -- the activation quantisers and the dequantise that reads a container's own + * codes. + * + * The arithmetic is libref's, transcribed. The group core is `q8_group`: an amax over + * the group's consecutive columns, `sc = amax * (1.0f / top)` -- a MULTIPLY by the reciprocal, not a + * divide -- codes `v * (1/sc)` clamped to +-top and encoded by the codec, and scale 1 for an + * all-zero group, whose reciprocal would be an infinity. The five bodies are libref's + * quant_act_fp8, quant_act_i8, quant_act_i8g, gated_quant_fp8 and dequant, loop order and rounding + * points as written. The clamp is required and not defensive: `amax * (1/scale)` is + * 448 exactly and can round an ulp above once the reciprocal is rounded, and a code out of range + * encodes as NaN, which then spreads through every row that reads it. + * + * RDNA3 has no fp8 instruction (r3d_common.h), so both directions are the software codecs in + * r3d_codecs.h, which are bit-exact mirrors of rad_plugin.h's; the absmax is a butterfly + * (r3d_xor_max), which reproduces a `__shfl_xor` loop bit for bit, and a max is exact and + * order-free, so the bracketing is q8_group's ascending one whatever the lane mapping. + * + * No kernel here carries a layout hook, and the codes are the bytes their consumer reads, which is + * the reason a container converted on this card is readable anywhere. Four of the five planes are + * plain row-major with one f32 scale per (row, group), because a dot2 GEMM reads codes in the order + * they are stored. The fifth is the op whose NAME carries the order: libref stores quant_act_i8's + * codes in the int8 WMMA's step order (`i8_step_pos`, the middle two dwords of every 16-byte step + * exchanged) because that is what the w4a8, w8a8 and w2a8 GEMMs read, so this kernel stores them + * that way too and its n is a multiple of 16; quant_act_i8g is the row-major int8 plane, and it is + * the one this library's i8a8 GEMM consumes. The two are not interchangeable. + * + * The store address costs nothing either way: a lane owns FOUR CONSECUTIVE COLUMNS, so its codes are + * one dword, a wave's are 128 contiguous bytes, and a wave covers exactly one 128-column group; + * `i8_step_pos` preserves c % 4, so it permutes a wave's 128 bytes without splitting a lane. The + * launchers therefore refuse `n % 4` -- and quant_act_i8 `n % 16` -- and a ragged last group + * (n % group != 0) is written zero-padded: padding is a zero code and takes no part in the amax. + * + * Group widths: the rows ask for 128, the checkpoint's weight-scale block width, and the kernels + * also serve any other power of two from 4 to 512, so a selftest can drive a narrow group and a + * future row on a 64-wide grid needs no new kernel. A group is a power of two because the amax + * butterfly is over the lanes covering it, GROUP/4 of them. + */ + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; + +enum : uint32_t { + kColsPerLane = 4, /* one dword of codes a lane */ + kWaveCols = kWave * kColsPerLane /* 128: the columns a wave covers */ +}; + +/* The largest code each quantiser saturates at. E4M3 has no infinity, so 448 is the largest finite + * value, and the scale is a dequant multiplier like the checkpoint's weight_scale_inv: the GEMM + * multiplies the activation's scale by the weight's block scale and never divides. */ +constexpr float kTopE4M3 = 448.0f; +constexpr float kTopI8 = 127.0f; + +/* The floor quant_act_i8's amax is raised to before its DIVIDE by 127, where quant_act_fp8 + * multiplies by a reciprocal, so the two quantisers round one ulp apart here; that is libref's + * spelling and the GEMMs read the scale as it is. */ +constexpr float kI8Floor = 1e-8f; + +/* The LDS code-sum accumulator's width, in groups, as in libr4d's r4d_quant_act_i8. */ +enum : uint32_t { kI8MaxGroups = 256 }; + +/* A bf16 element of a row: a whole-register 16-bit load (r3d_common.h) widened by a shift. */ +__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(p + i)); +} + +/* q8_group's clamp, in q8_group's order and with q8_group's comparisons, at the codec's top -- 448 + * for E4M3, 127 for int8. fminf/fmaxf are NOT the same function here: they replace a NaN with the + * bound, and a NaN in an activation is a value the reference encodes as the format's NaN, not as + * +-top. */ +__device__ __forceinline__ float clamp_top(float c, float top) { + if (c > top) c = top; + if (c < -top) c = -top; + return c; +} + +/* The four codes a lane's four columns produce, in column order: byte 0 is column c0. */ +__device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) { + const uint32_t lo = e4m3x2_pack(clamp_top(v[0] * inv, kTopE4M3), clamp_top(v[1] * inv, kTopE4M3)); + const uint32_t hi = e4m3x2_pack(clamp_top(v[2] * inv, kTopE4M3), clamp_top(v[3] * inv, kTopE4M3)); + return lo | (hi << 16); +} + +/* The same four codes as int8, at the same rounding points: clamp to +-127, then the codec's + * round-to-nearest-even. quant_act_i8g's store; quant_act_i8's is the same bytes at a permuted + * address. */ +__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) { + const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8)); + const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8)); + const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8)); + const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8)); + return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); +} + +/* q8_group's scale from the group's amax: the reciprocal of `top` MULTIPLIED, not a divide -- the + * one place the two int8 quantisers and the fp8 one agree, and the reason the per-row + * quant_act_i8 spells its scale as a divide and is a separate body. */ +__device__ __forceinline__ float group_scale(float am, float top) { + return am > 0.0f ? am * (1.0f / top) : 1.0f; +} + +/* The map libref uses, verbatim: where a row's column c is stored in the step-ordered int8 plane. + * Bits 2 and 3 of c exchanged = the middle two dwords of every 16-byte step swapped, which is the + * order the int8 WMMA reads an A fragment. The map is its own inverse, and it preserves c % 4, so a + * lane's four columns stay contiguous and its store stays one dword. */ +__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) { + return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1); +} + +/* block_sum's twin for a maximum -- r3d_common.h has the sum. A max needs no order argument at all: + * it is exact, so the wave partials combine in any order -- but it is spelled the same way, so a + * reader sees one reduction shape in this library and not two. `lds` holds kWaves floats. */ +__device__ __forceinline__ float block_max(float v, float* lds) { + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + v = wave_max(v); + if (lane == 0) lds[wave] = v; + __syncthreads(); + float t = lds[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]); + return t; +} + +/* ================================================================== quant_act_fp8 + * + * Per-(row, group) symmetric E4M3 of an activation, over q8_group. One workgroup + * a row, a wave a group, a lane four columns -- libr4d's layout, because the reason for + * it (one dword a lane, 128 contiguous bytes a wave) is the store and not the instruction set. + * + * GROUP is the group's width. At 128 a wave covers one group and the amax is r3d_xor_max<32>. A + * narrower group is covered by GROUP/4 lanes of the wave and the butterfly is over those lanes, so + * one wave quantises 128/GROUP groups in a pass; a wider one is covered by one wave in sub-blocks + * of 128 whose maxima are fmaxf'd. All three are q8_group's bracketing. + * + * Rows are dim 0, so a rank-3 activation ([tokens, heads, width], a GDN block's out-projection + * input) is one row per token, as libref reads it: its consuming GEMM's K is heads*width, and one + * row per head would put scales on a grid that GEMM does not read. + */ +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel( + const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, + uint32_t ngrp, uint32_t x_ld, uint32_t s_ld) { + constexpr int kSub = GROUP >= (int)kWaveCols ? GROUP / (int)kWaveCols : 1; + constexpr int kPer = GROUP < (int)kWaveCols ? (int)kWaveCols / GROUP : 1; + constexpr int kLanes = GROUP < (int)kWaveCols ? (int)(GROUP / kColsPerLane) : (int)kWave; + static_assert(kLanes >= 1 && kLanes <= (int)kWave, "a group spans at most one wave"); + + const uint32_t row = blockIdx.x; + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + const uint16_t* __restrict__ xr = x + (size_t)row * x_ld; + uint8_t* __restrict__ qr = q + (size_t)row * n; + + const uint32_t nunit = (ngrp + kPer - 1) / kPer; + for (uint32_t u = wave; u < nunit; u += kWaves) { + const uint32_t g0 = u * kPer, cbase = g0 * GROUP; + float v[kSub][kColsPerLane]; + float am = 0.0f; +#pragma unroll + for (int sb = 0; sb < kSub; ++sb) { + const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane; +#pragma unroll + for (int j = 0; j < kColsPerLane; ++j) { + const uint32_t c = c0 + (uint32_t)j; + /* Past the row's end a lane contributes 0.0f, so padding is a zero code and takes + * no part in the amax. n is a multiple of 4, so a lane's four columns are all in + * the row or all outside it: the ragged edge never splits a lane. */ + v[sb][j] = c < n ? ld_bf(xr, c) : 0.0f; + } + float m = 0.0f; +#pragma unroll + for (int j = 0; j < kColsPerLane; ++j) m = fmaxf(m, fabsf(v[sb][j])); + am = fmaxf(am, r3d_xor_max(m)); + } + const float sc = group_scale(am, kTopE4M3); + /* The scale store is guarded by the group count, not just by the lane: a wave covers + * kPer = 128/GROUP groups and a row's group count is ceil(n/group), which is not a multiple + * of kPer when the last group is ragged. Unguarded, those lanes wrote one row past the + * scale row -- and on a ragged n, past the plane's end. */ + if ((lane & (kLanes - 1)) == 0) { + const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes; + if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc; + } + const float inv = 1.0f / sc; +#pragma unroll + for (int sb = 0; sb < kSub; ++sb) { + const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane; + if (c0 < n) *(uint32_t*)(qr + c0) = e4m3_codes4(v[sb], inv); + } + } +} + +/* ================================================================== quant_act_i8g + * + * The same group core at int8, q8_group called with top 127. One scale + * per (row, group), `sc = amax * (1.0f / 127)` -- the reciprocal MULTIPLIED, as in the fp8 path, so + * this is quant_act_fp8 with a different codec and not quant_act_i8 at a finer granularity -- codes + * clamp(v * (1/sc), +-127) to nearest even, stored ROW-MAJOR, and scale 1 for an all-zero group. + * + * The row-major store is the point of the op: libr3d's only int8 GEMM is the i8a8 one, and a dot2 + * GEMM reads a row in the order it is stored. The step-ordered plane belongs to quant_act_i8, whose + * consumers are libr4d's WMMA GEMMs, and the two are not interchangeable. + * + * Same lane mapping and same ragged rules as quant_act_fp8_kernel, so the two bodies read as one + * shape with the codec swapped. + */ +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8g_kernel( + const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, + uint32_t ngrp, uint32_t x_ld, uint32_t s_ld) { + constexpr int kSub = GROUP >= (int)kWaveCols ? GROUP / (int)kWaveCols : 1; + constexpr int kPer = GROUP < (int)kWaveCols ? (int)kWaveCols / GROUP : 1; + constexpr int kLanes = GROUP < (int)kWaveCols ? (int)(GROUP / kColsPerLane) : (int)kWave; + static_assert(kLanes >= 1 && kLanes <= (int)kWave, "a group spans at most one wave"); + + const uint32_t row = blockIdx.x; + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + const uint16_t* __restrict__ xr = x + (size_t)row * x_ld; + uint8_t* __restrict__ qr = q + (size_t)row * n; + + const uint32_t nunit = (ngrp + kPer - 1) / kPer; + for (uint32_t u = wave; u < nunit; u += kWaves) { + const uint32_t g0 = u * kPer, cbase = g0 * GROUP; + float v[kSub][kColsPerLane]; + float am = 0.0f; +#pragma unroll + for (int sb = 0; sb < kSub; ++sb) { + const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane; +#pragma unroll + for (int j = 0; j < kColsPerLane; ++j) { + const uint32_t c = c0 + (uint32_t)j; + v[sb][j] = c < n ? ld_bf(xr, c) : 0.0f; /* padding is a zero code, as above */ + } + float m = 0.0f; +#pragma unroll + for (int j = 0; j < kColsPerLane; ++j) m = fmaxf(m, fabsf(v[sb][j])); + am = fmaxf(am, r3d_xor_max(m)); + } + const float sc = group_scale(am, kTopI8); + if ((lane & (kLanes - 1)) == 0) { + const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes; + if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc; + } + const float inv = 1.0f / sc; +#pragma unroll + for (int sb = 0; sb < kSub; ++sb) { + const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane; + if (c0 < n) *(uint32_t*)(qr + c0) = i8_codes4(v[sb], inv); /* row-major */ + } + } +} + +} /* namespace */ + +/* x [M][n] bf16, `x_ld` elements a row (0 = n) + * q [M][n] E4M3, DENSE: the launcher takes no code pitch, so the plane is + * row-major with no hole in it, rounded up to 4 bytes for the padding + * s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group)) + * + * A launcher checks what a `__global__` cannot and issues one kernel: 0, -1 a null pointer, -2 a bad + * extent (including a group with no instantiation), -3 a pitch that does not describe the operand, + * -4 the HIP launch failed. It allocates nothing and synchronises on nothing. */ +extern "C" int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld, + int s_ld, long stream) { + if (!x || !q || !s) return -1; + if (M <= 0 || n <= 0) return -2; + if (n % (int)kColsPerLane) return -3; /* a lane owns four columns; see the kernel */ + if (group < 4 || group > 512 || (group & (group - 1))) return -2; + const int ngrp = (n + group - 1) / group; + if (!x_ld) x_ld = n; + if (!s_ld) s_ld = ngrp; + if (x_ld < n || s_ld < ngrp) return -3; + + const hipStream_t st = (hipStream_t)(uintptr_t)stream; + const dim3 grid((unsigned)M), block(kThreads); +#define R3D_QAF(G) \ + R3D_KLAUNCH(R3D_KNAME(quant_act_fp8_kernel), grid, block, st, (const uint16_t*)x, \ + (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)ngrp, (uint32_t)x_ld, \ + (uint32_t)s_ld) + switch (group) { + case 4: R3D_QAF(4); break; + case 8: R3D_QAF(8); break; + case 16: R3D_QAF(16); break; + case 32: R3D_QAF(32); break; + case 64: R3D_QAF(64); break; + case 128: R3D_QAF(128); break; + case 256: R3D_QAF(256); break; + case 512: R3D_QAF(512); break; + default: return -2; + } +#undef R3D_QAF + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +namespace { + +/* ================================================================== quant_act_i8 + * + * The activation of the w4a8, w8a8 and w2a8 GEMMs, ONE SCALE PER ROW, + * max(amax, 1e-8) / 127, codes x * (1/scale) rounded to nearest even by the int8 codec. + * + * The codes go out in libref's STEP ORDER, `i8_step_pos`: the middle two + * dwords of every 16-byte step exchanged, which is why this op's n is a multiple of 16 and not of + * 4. That order is what the op MEANS -- the w4a8, w8a8 and w2a8 GEMMs read the plane that way, and + * kbench compares the plane element by element -- so it is kept on a card that has no WMMA, and the + * row-major int8 plane is a separate op, quant_act_i8g below, which is the one this library's i8a8 + * GEMM consumes. The permutation is per-lane and preserves c % 4, so a lane's four codes stay + * contiguous and the store stays one dword; a wave's 128 bytes are a permutation of the same 128. + * + * One divergence from the reference's arithmetic, and it is inert: libref reduces a row with + * std::max and this with fmaxf. They agree on every input the op can see -- std::max(a, NaN) is a, so + * the reference's amax is never a NaN, and fmaxf drops the NaN the same way; an all-NaN row has amax + * 0 in both and scale 1e-8/127. + * + * ASUM, when present, also takes each row's code sums per `group` columns, group-major + * [n/group][Mpad] with Mpad = ceil(M/16)*16: an asymmetric weight grid needs sum_k a_k to subtract + * z_g * sum_k a_k from a group's dot product once instead of N times, and it reads whole 16-row + * tiles. The sums are integers, so the LDS accumulator's atomic adds are exact and their order is + * free. Rows M..Mpad-1 are not written; the caller zeroes them, as libref does. + */ +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel( + const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, + float* __restrict__ asum, uint32_t n, uint32_t group, uint32_t x_ld, uint32_t s_ld, + uint32_t mpad) { + __shared__ float red[kWaves]; + __shared__ int gs[kI8MaxGroups]; + + const uint32_t row = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)row * x_ld; + uint8_t* __restrict__ qr = q + (size_t)row * n; + const uint32_t ngrp = ASUM ? n / group : 0; + + float am = 0.0f; + for (uint32_t c = threadIdx.x * kColsPerLane; c < n; c += kThreads * kColsPerLane) { +#pragma unroll + for (int j = 0; j < kColsPerLane; ++j) { + const uint32_t cc = c + (uint32_t)j; + if (cc < n) am = fmaxf(am, fabsf(ld_bf(xr, cc))); + } + } + const float scale = fmaxf(block_max(am, red), kI8Floor) / kTopI8; + const float inv = 1.0f / scale; + if (threadIdx.x == 0) s[(size_t)row * s_ld] = scale; + if (ASUM) { + for (uint32_t g = threadIdx.x; g < ngrp; g += kThreads) gs[g] = 0; + __syncthreads(); /* the zeroing has to land before the atomics */ + } + + for (uint32_t c = threadIdx.x * kColsPerLane; c < n; c += kThreads * kColsPerLane) { + uint32_t w = 0; +#pragma unroll + for (int j = 0; j < kColsPerLane; ++j) { + const uint32_t cc = c + (uint32_t)j; + const int8_t code = (cc < n) ? f32_to_i8_rtne(ld_bf(xr, cc) * inv) : (int8_t)0; + w |= (uint32_t)(uint8_t)code << (8 * j); + /* n % group == 0 and group % 4 == 0, so a lane's four columns are in one group. The + * sum is over column order, and the map is its own inverse, so summing the codes of + * columns [gi*group, (gi+1)*group) here is libref reading qr[i8_step_pos(i)] -- + * same bytes, same groups. */ + if (ASUM && cc < n) atomicAdd(&gs[cc / group], (int)code); + } + *(uint32_t*)(qr + i8_step_pos(c)) = w; /* the step order, one dword a lane */ + } + if (ASUM) { + __syncthreads(); + for (uint32_t g = threadIdx.x; g < ngrp; g += kThreads) + asum[(size_t)g * mpad + row] = (float)gs[g]; + } +} + +} /* namespace */ + +/* x [M][n] bf16, `x_ld` elements a row (0 = n) + * q [M][n] i8, DENSE, in libref's STEP ORDER (i8_step_pos: bits 2 and 3 of the + * column exchanged), so n is a multiple of 16, not of 4 + * s [M] f32, ONE scale a row, written at element pitch `s_ld` (0 = 1). A + * plane with more room than rows is legal and filled in libref's flat + * order -- the row's scale at s[r], the tail the caller's -- because + * that is what libref does with whatever capacity it is handed, and a + * byte comparison of the tail then agrees. + * asum [n/group][Mpad] f32, optional, group-major, Mpad = ceil(M/16)*16 + * + * `group` sizes asum and is ignored without it, as libref ignores it: it is the width of the code + * sums, not the granularity of the scale, which is the whole row. */ +extern "C" int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n, int group, + int x_ld, int s_ld, long stream) { + if (!x || !q || !s) return -1; + if (M <= 0 || n <= 0) return -2; + if (n % 16) return -3; /* a whole 16-byte step; see i8_step_pos */ + uint32_t mpad = 0; + if (asum) { + if (group < (int)kColsPerLane || group % (int)kColsPerLane || n % group) return -2; + if (n / group > (int)kI8MaxGroups) return -2; + mpad = (uint32_t)((M + 15) / 16 * 16); + } else { + group = n; + } + if (!x_ld) x_ld = n; + if (!s_ld) s_ld = 1; + if (x_ld < n || s_ld < 1) return -3; + + const hipStream_t st = (hipStream_t)(uintptr_t)stream; + const dim3 grid((unsigned)M), block(kThreads); + if (asum) + R3D_KLAUNCH(R3D_KNAME(quant_act_i8_kernel), grid, block, st, (const uint16_t*)x, + (uint8_t*)q, (float*)s, (float*)asum, (uint32_t)n, (uint32_t)group, + (uint32_t)x_ld, (uint32_t)s_ld, mpad); + else + R3D_KLAUNCH(R3D_KNAME(quant_act_i8_kernel), grid, block, st, (const uint16_t*)x, + (uint8_t*)q, (float*)s, (float*)nullptr, (uint32_t)n, (uint32_t)group, + (uint32_t)x_ld, (uint32_t)s_ld, mpad); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* x [M][n] bf16, `x_ld` elements a row (0 = n) + * q [M][n] i8, DENSE and ROW-MAJOR: the plane this library's i8a8 GEMM reads + * s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group)) + * + * `group` is the scale's width and is clamped to n when absent, as libref clamps it: `group >= n` + * and `group` absent are both one scale a row. Codes clamp to +-127 before + * the codec, in q8_group's order. 0, -1, -2 a bad extent or an uninstantiated group, -3 a pitch + * that does not describe the operand, -4 the HIP launch failed. */ +extern "C" int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group, + long long x_ld, long long s_ld, long stream) { + if (!x || !q || !s) return -1; + if (M <= 0 || n <= 0) return -2; + if (n % (int)kColsPerLane) return -3; /* a lane owns four columns; see the kernel */ + if (group < 4 || group > 512 || (group & (group - 1))) return -2; + const int ngrp = (n + group - 1) / group; + if (!x_ld) x_ld = n; + if (!s_ld) s_ld = ngrp; + if (x_ld < n || s_ld < ngrp) return -3; + + const hipStream_t st = (hipStream_t)(uintptr_t)stream; + const dim3 grid((unsigned)M), block(kThreads); +#define R3D_QAI8G(G) \ + R3D_KLAUNCH(R3D_KNAME(quant_act_i8g_kernel), grid, block, st, (const uint16_t*)x, \ + (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)ngrp, (uint32_t)x_ld, \ + (uint32_t)s_ld) + switch (group) { + case 4: R3D_QAI8G(4); break; + case 8: R3D_QAI8G(8); break; + case 16: R3D_QAI8G(16); break; + case 32: R3D_QAI8G(32); break; + case 64: R3D_QAI8G(64); break; + case 128: R3D_QAI8G(128); break; + case 256: R3D_QAI8G(256); break; + case 512: R3D_QAI8G(512); break; + default: return -2; + } +#undef R3D_QAI8G + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +namespace { + +/* ================================================================== gated_quant_fp8 + * + * act(gate) * up, then quant_act_fp8's quantiser, in one pass. `gate_up` is + * [M, 2n], gate in the first n and up in the second, which is what a fused gate_up projection + * writes; the product is what gets quantised, and `out_bf16`, when bound, receives it. + * + * The product is narrowed to bf16 and read back before the absmax. That is the op and not an + * optimisation: the unfused pair writes a bf16 [M, n] tensor and quantises those bytes, so the + * codes are taken over the narrowed value and out_bf16 holds exactly the value they came from. + * Within the product the rounding points are libref's: sg = 1/(1+exp(-gate)) in f32, then + * (gate*sg) for silu -- MULTIPLIED, not divided, which is a different f32 -- then * up, then one + * bf16 narrowing. `expf` is the accurate form and not __expf (r3d_common.h); it is the one value in + * this unit the reference evaluates in double, so a code can move by one where the bf16 narrowing + * lands on a tie. Every other number here is bit-for-bit. + * + * No row reduction, so no first pass and no barrier: a wave a group, a lane four columns. + */ +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void gated_quant_fp8_kernel( + const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q, + float* __restrict__ s, uint32_t n, uint32_t ngrp, uint32_t s_ld) { + constexpr int kSub = GROUP >= (int)kWaveCols ? GROUP / (int)kWaveCols : 1; + constexpr int kPer = GROUP < (int)kWaveCols ? (int)kWaveCols / GROUP : 1; + constexpr int kLanes = GROUP < (int)kWaveCols ? (int)(GROUP / kColsPerLane) : (int)kWave; + + const uint32_t row = blockIdx.x; + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + const uint16_t* __restrict__ gr = gu + (size_t)row * (2 * n); + uint16_t* __restrict__ yr = y ? y + (size_t)row * n : nullptr; + uint8_t* __restrict__ qr = q + (size_t)row * n; + + const uint32_t nunit = (ngrp + kPer - 1) / kPer; + for (uint32_t u = wave; u < nunit; u += kWaves) { + const uint32_t g0 = u * kPer, cbase = g0 * GROUP; + float v[kSub][kColsPerLane]; + float am = 0.0f; +#pragma unroll + for (int sb = 0; sb < kSub; ++sb) { + const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane; +#pragma unroll + for (int j = 0; j < kColsPerLane; ++j) { + const uint32_t c = c0 + (uint32_t)j; + if (c < n) { + const float gt = ld_bf(gr, c); + const float up = ld_bf(gr, n + c); + const float sg = 1.0f / (1.0f + expf(-gt)); + const uint16_t h = f32_to_bf16((ACT == R3D_ACT_SILU ? gt * sg : sg) * up); + if (yr) yr[c] = h; + v[sb][j] = bf16_to_f32(h); + } else { + v[sb][j] = 0.0f; /* padding: see quant_act_fp8_kernel */ + } + } + float m = 0.0f; +#pragma unroll + for (int j = 0; j < kColsPerLane; ++j) m = fmaxf(m, fabsf(v[sb][j])); + am = fmaxf(am, r3d_xor_max(m)); + } + const float sc = group_scale(am, kTopE4M3); + if ((lane & (kLanes - 1)) == 0) { /* the ragged guard, as above */ + const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes; + if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc; + } + const float inv = 1.0f / sc; +#pragma unroll + for (int sb = 0; sb < kSub; ++sb) { + const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane; + if (c0 < n) *(uint32_t*)(qr + c0) = e4m3_codes4(v[sb], inv); + } + } +} + +} /* namespace */ + +/* gu [M][2n] bf16, gate first then up, DENSE (the launcher takes no pitch) + * y [M][n] bf16, the product, optional, dense + * q [M][n] E4M3, dense + * s [M][ceil(n/group)] f32, dense + * + * `act` is R3D_ACT_SILU (down_proj's input) or R3D_ACT_SIGMOID (a gated attention o_proj's). */ +extern "C" int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16, int M, int n, + int group, int act, long stream) { + if (!gate_up || !q || !s) return -1; + if (M <= 0 || n <= 0) return -2; + if (n % (int)kColsPerLane) return -3; + if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return -2; + if (group < 4 || group > 512 || (group & (group - 1))) return -2; + const int ngrp = (n + group - 1) / group; + + const hipStream_t st = (hipStream_t)(uintptr_t)stream; + const dim3 grid((unsigned)M), block(kThreads); +#define R3D_GQ(G, A) \ + R3D_KLAUNCH(R3D_KNAME(gated_quant_fp8_kernel), grid, block, st, (const uint16_t*)gate_up, \ + (uint16_t*)out_bf16, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)ngrp, \ + (uint32_t)ngrp) +#define R3D_GQ_ACT(A) \ + switch (group) { \ + case 4: R3D_GQ(4, A); break; \ + case 8: R3D_GQ(8, A); break; \ + case 16: R3D_GQ(16, A); break; \ + case 32: R3D_GQ(32, A); break; \ + case 64: R3D_GQ(64, A); break; \ + case 128: R3D_GQ(128, A); break; \ + case 256: R3D_GQ(256, A); break; \ + case 512: R3D_GQ(512, A); break; \ + default: return -2; \ + } + /* The gate is a template argument, so the multiply below is one instruction and not a branch in + * the inner loop; the switch is over the group widths, each with its own lane mapping. */ + if (act == R3D_ACT_SILU) { R3D_GQ_ACT(R3D_ACT_SILU); } + else { R3D_GQ_ACT(R3D_ACT_SIGMOID); } +#undef R3D_GQ_ACT +#undef R3D_GQ + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +namespace { + +/* ================================================================== dequant + * + * y = code * scale, the read of a container's own quantised weight. Elementwise, + * so there is no reduction and no order to match; the code decodes exactly (E4M3's four exponent + * bits and three mantissa bits are a subset of f16's, and of f32's; E5M2 is f16's top byte, + * rad_plugin.h; int8 is exact in f32), the product is one f32 multiply per element, and the + * store narrows it to bf16 -- the width every consumer of a dequantised weight on this card reads, + * which is why the launcher names the codes' dtype and not the output's. + * + * The scale stream is [M, ceil(n/group)] and the shim requires it to carry every group, so the + * clamp below never fires on a well-formed call; libref clamps a short stream's index to its last + * scale instead of reading off the end, and a kernel row refuses that geometry instead. + */ +template +__device__ __forceinline__ float code_value(uint8_t b) { + if (QDT == R3D_DT_U8) return e4m3_to_f32(b); + if (QDT == R3D_DT_E5M2) return f16_to_f32((uint16_t)b << 8); + return (float)(int8_t)b; +} + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void dequant_kernel( + const uint8_t* __restrict__ q, const float* __restrict__ s, uint16_t* __restrict__ y, + uint32_t n, uint32_t group, uint32_t ngrp, uint32_t s_ld, uint32_t y_ld) { + const uint32_t row = blockIdx.x; + const uint8_t* __restrict__ qr = q + (size_t)row * n; + const float* __restrict__ sr = s + (size_t)row * s_ld; + uint16_t* __restrict__ yr = y + (size_t)row * y_ld; + + for (uint32_t c = threadIdx.x * kColsPerLane; c < n; c += kThreads * kColsPerLane) { + const uint32_t gi = min(c / group, ngrp - 1u); + const float sc = ldg_f32(sr + gi); + /* n is a multiple of 4 and the plane is dense, so a lane's four codes are one dword. */ + const uint32_t w = ldg_u32((const uint32_t*)(qr + c)); + /* One 8-byte store a lane: bf16x2_rne is software RTNE, because gfx11 has no + * v_cvt_pk_bf16_f32 (r3d_common.h), and the narrowing is the store's single round. */ + uint32_t* yp = (uint32_t*)(yr + c); + yp[0] = bf16x2_rne(code_value((uint8_t)(w & 0xffu)) * sc, + code_value((uint8_t)(w >> 8)) * sc); + yp[1] = bf16x2_rne(code_value((uint8_t)(w >> 16)) * sc, + code_value((uint8_t)(w >> 24)) * sc); + } +} + +} /* namespace */ + +/* q [M][n] codes, DENSE: E4M3, E5M2 or i8, one byte apiece + * s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group)) + * y [M][n] bf16, `y_ld` elements a row (0 = n) + * + * `y` is bf16: the launcher describes the codes' dtype and not the output's, because a dequantised + * weight here is read by a bf16 dot2 GEMM, which is the same reason r3d.h gives this launcher one + * dtype argument. An f32 plane is r3d_cast's, which carries two. */ +extern "C" int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s_ld, + int y_ld, long stream) { + if (!q || !s || !y) return -1; + if (M <= 0 || n <= 0 || group < 1) return -2; + if (n % (int)kColsPerLane) return -3; + if (q_dt != R3D_DT_U8 && q_dt != R3D_DT_E5M2 && q_dt != R3D_DT_I8) return -2; + const int ngrp = (n + group - 1) / group; + if (!s_ld) s_ld = ngrp; + if (!y_ld) y_ld = n; + if (s_ld < ngrp || y_ld < n) return -3; + + const hipStream_t st = (hipStream_t)(uintptr_t)stream; + const dim3 grid((unsigned)M), block(kThreads); +#define R3D_DQ(D) \ + R3D_KLAUNCH(R3D_KNAME(dequant_kernel), grid, block, st, (const uint8_t*)q, (const float*)s, \ + (uint16_t*)y, (uint32_t)n, (uint32_t)group, (uint32_t)ngrp, (uint32_t)s_ld, \ + (uint32_t)y_ld) + switch (q_dt) { + case R3D_DT_U8: R3D_DQ(R3D_DT_U8); break; + case R3D_DT_E5M2: R3D_DQ(R3D_DT_E5M2); break; + case R3D_DT_I8: R3D_DQ(R3D_DT_I8); break; + default: return -2; + } +#undef R3D_DQ + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== the plugin ABI entry points + * + * Three things every shim here reads off the operands and not off the parameters: + * + * * the dtype. A row's `dtype` constraint is a necessary condition on the geometry, not a promise + * about the tensors, and an f32 activation read as bf16 is a value that passes every other + * check. + * * the row count. `M` is the band's upper bound, so the args carry a bound and the operand + * carries the call. + * * the pitch. r3d_rows_pitch() answers in elements, or -1 for an inner axis that is strided. + * + * The code planes are dense: none of the four launchers takes a code pitch, because a dot2 GEMM + * reads codes row-major and the engine hands them over in the order it stores them. A plane with a + * hole in it is a stride refusal and not a slow path. */ + +/* bf16 is the only activation width these kernels read. An f32 activation is r3d_cast's problem, + * which takes the dtypes as arguments; a quantiser with a dtype switch in its inner loop is the + * wrong shape for an op whose whole point is the store. */ +static inline int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; } +static inline int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; } +/* The codes' dtype picks the codec, so it is checked exactly and never as "some byte". */ +static inline int dt_e4m3(const RadTensor* t) { return r3d_is_e4m3(t) ? RAD_OK : RAD_E_DTYPE; } +static inline int dt_i8(const RadTensor* t) { return r3d_is_i8(t) ? RAD_OK : RAD_E_DTYPE; } + +#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0) + +/* A launcher checked the geometry and answered with a code; translate it to a RAD status. */ +static inline int r3d_launch_status(int e) { + switch (e) { + case 0: return RAD_OK; + case -1: return RAD_E_INVAL; + case -2: return RAD_E_SHAPE; + case -3: return RAD_E_STRIDE; + default: return RAD_E_DEVICE; + } +} + +/* The group must be a power of two from 4 to 512: the amax butterfly is over the lanes covering a + * group, GROUP/4 of them, and the kernels are instantiated for those widths. libref clamps + * `group <= 0 || group > n` to n, so "one scale a row" arrives as 0 and leaves as n; + * a width with no instantiation is refused and not rounded, because a rounded group would quantise + * on a grid the weight's scales are not on. */ +static inline int r3d_group_of(long long g, long long n) { + if (g <= 0 || g > n) g = n; + return (g >= 4 && g <= 512 && (g & (g - 1)) == 0) ? (int)g : 0; +} + +/* ------------------------------------------------------------------ quant_act_fp8 */ + +enum { QAF_X = 0, QAF_Q, QAF_S }; + +extern "C" int r3d_rad_quant_act_fp8(const RadArgs* a, RadStream stream) { + const RadTensor* x = r3d_opt(a, QAF_X); + const RadTensor* q = r3d_opt(a, QAF_Q); + const RadTensor* sc = r3d_opt(a, QAF_S); + if (!x || !q || !sc) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_e4m3(q)); + R3D_NEED(dt_f32(sc)); + + const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1)); + if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE); + const int group = r3d_group_of(r3d_geti_or(a, "group", R3D_ACT_GROUP), n); + if (!group) return R3D_NO(RAD_E_SHAPE); + const long long ngrp = (n + group - 1) / group; + + long long rows = 0, qrows = 0, srows = 0; + const long long x_ld = r3d_rows_pitch(x, n, &rows); + const long long q_ld = r3d_rows_pitch(q, n, &qrows); + const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows); + if (x_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE); + if (srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE); + if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN); + + return r3d_launch_status(r3d_quant_act_fp8(r3d_addr(x), r3d_addr(q), r3d_addr(sc), (int)rows, + (int)n, group, (int)x_ld, (int)s_ld, + (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ quant_act_i8 */ + +enum { QAI_X = 0, QAI_Q, QAI_S, QAI_ASUM }; + +extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) { + const RadTensor* x = r3d_opt(a, QAI_X); + const RadTensor* q = r3d_opt(a, QAI_Q); + const RadTensor* sc = r3d_opt(a, QAI_S); + const RadTensor* as = r3d_opt(a, QAI_ASUM); /* the asymmetric grid's code sums */ + if (!x || !q || !sc) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_i8(q)); + R3D_NEED(dt_f32(sc)); + if (r3d_has(as)) R3D_NEED(dt_f32(as)); /* a slot with no bytes is the operand being absent */ + + const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1)); + if (n <= 0 || n % 16) return R3D_NO(RAD_E_SHAPE); /* a whole 16-byte step: see i8_step_pos */ + + /* One scale a row: this op's scale granularity IS the row (the amax runs over the whole row, + * and the store is `stt(s, rowoff(s, r, 1), scale)`, a FLAT stream at element pitch 1), and + * libref lists `group` as the width of the row SUMS, not of the scale. A plane with more + * elements than rows is therefore accepted and filled in libref's order: the row's scale + * lands at s[r], the plane's first M elements, and the rest of it stays the caller's. That + * is exactly the plane the row's operand description gives -- + * [M, ceil(n/group)], quant_act_i8g's width, of which this op writes the first column -- and + * refusing it would be the shim tightening its own row past the reference: libref requires + * numel(s) >= rows and nothing more, and the bytes it never touches compare equal. */ + + long long rows = 0, qrows = 0, srows = 0; + const long long x_ld = r3d_rows_pitch(x, n, &rows); + const long long q_ld = r3d_rows_pitch(q, n, &qrows); + const long long s_ld = r3d_rows_pitch(sc, 1, &srows); + if (x_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE); + if (srows < rows || r3d_numel(sc) < rows) return R3D_NO(RAD_E_SHAPE); + if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN); + + /* `group` sizes asum only, and is not read without it. n % group == 0, because a sum is over + * whole columns of a row, and the LDS accumulator is 256 groups wide. */ + int group = 0; + if (as) { + group = (int)r3d_geti_or(a, "group", R3D_W8_GROUP); + if (group < (int)kColsPerLane || group % kColsPerLane || n % group) + return R3D_NO(RAD_E_SHAPE); + if (n / group > (long long)kI8MaxGroups) return R3D_NO(RAD_E_SHAPE); + if (!r3d_contig(as)) return R3D_NO(RAD_E_STRIDE); + const long long mpad = ((rows + 15) / 16) * 16; + if (r3d_numel(as) < (n / group) * mpad) return R3D_NO(RAD_E_SHAPE); + } + + return r3d_launch_status(r3d_quant_act_i8( + r3d_addr(x), r3d_addr(q), r3d_addr(sc), r3d_addr(as), (int)rows, (int)n, group, (int)x_ld, + (int)s_ld, (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ quant_act_i8g */ + +/* The int8 plane at group granularity, and the one this library's i8a8 GEMM reads. Operands are + * libref's oQuantFp8 shape -- {x, q, scale} -- with the int8 codes' dtype. */ +enum { QAG_X = 0, QAG_Q, QAG_S }; + +extern "C" int r3d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) { + const RadTensor* x = r3d_opt(a, QAG_X); + const RadTensor* q = r3d_opt(a, QAG_Q); + const RadTensor* sc = r3d_opt(a, QAG_S); + if (!x || !q || !sc) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_i8(q)); + R3D_NEED(dt_f32(sc)); + + const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1)); + if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE); + /* libref's clamp of `group`: absent, zero or wider than the row is one + * scale a row, so the default here is 0 and the clamp turns it into n. A width the kernels have + * no instantiation for is refused, not rounded to one. */ + const int group = r3d_group_of(r3d_geti_or(a, "group", 0), n); + if (!group) return R3D_NO(RAD_E_SHAPE); + const long long ngrp = (n + group - 1) / group; + + long long rows = 0, qrows = 0, srows = 0; + const long long x_ld = r3d_rows_pitch(x, n, &rows); + const long long q_ld = r3d_rows_pitch(q, n, &qrows); + const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows); + if (x_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE); + if (srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE); + if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN); + + return r3d_launch_status(r3d_quant_act_i8g(x->data, q->data, sc->data, (int)rows, (int)n, group, + x_ld, s_ld, (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ gated_quant_fp8 */ + +enum { GQT_GU = 0, GQT_Q, GQT_S, GQT_Y }; + +extern "C" int r3d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) { + const RadTensor* gu = r3d_opt(a, GQT_GU); + const RadTensor* q = r3d_opt(a, GQT_Q); + const RadTensor* sc = r3d_opt(a, GQT_S); + const RadTensor* y = r3d_opt(a, GQT_Y); /* the product, for a bf16 consumer */ + if (!gu || !q || !sc) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(gu)); + R3D_NEED(dt_e4m3(q)); + R3D_NEED(dt_f32(sc)); + if (r3d_has(y)) R3D_NEED(dt_bf16(y)); /* the same: an empty slot is no operand at all */ + + /* "silu" (down_proj's input) or "sigmoid" (a gated attention o_proj's), `mode` the integer + * spelling of the same choice, `act` winning where both are given. libref's `act` enumerates + * those two, so a gelu-gated feed-forward is not this row's: it asks for a gate the oracle has + * no definition for here. */ + const int act = r3d_act_code(a, "act", "mode", R3D_ACT_SILU); + if (act < 0) return R3D_NO(RAD_E_UNSUPPORTED); + + const long long n = r3d_geti_or(a, "n", r3d_dim(q, (int)q->rank - 1)); + if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE); + const int group = r3d_group_of(r3d_geti_or(a, "group", R3D_ACT_GROUP), n); + if (!group) return R3D_NO(RAD_E_SHAPE); + const long long ngrp = (n + group - 1) / group; + + /* The fused gate_up projection writes the plane dense, gate half first, [M, 2n] with no hole: a + * sliced gate is r3d_act_mul_bf16's, which takes the two pitches. */ + long long rows = 0, qrows = 0, srows = 0, yrows = 0; + const long long gu_ld = r3d_rows_pitch(gu, 2 * n, &rows); + const long long q_ld = r3d_rows_pitch(q, n, &qrows); + const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows); + const long long y_ld = y ? r3d_rows_pitch(y, n, &yrows) : n; + if (gu_ld < 0 || q_ld < 0 || s_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + if (gu_ld != 2 * n) return R3D_NO(RAD_E_SHAPE); + if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE); + if (s_ld != ngrp || srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE); + if (y && (y_ld != n || yrows < rows || r3d_numel(y) < rows * n)) return R3D_NO(RAD_E_SHAPE); + if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN); + + return r3d_launch_status(r3d_gated_quant_fp8( + r3d_addr(gu), r3d_addr(q), r3d_addr(sc), r3d_addr(y), (int)rows, (int)n, group, act, + (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ dequant */ + +enum { DQT_Q = 0, DQT_S, DQT_Y }; + +extern "C" int r3d_rad_dequant(const RadArgs* a, RadStream stream) { + const RadTensor* q = r3d_opt(a, DQT_Q); + const RadTensor* sc = r3d_opt(a, DQT_S); + const RadTensor* y = r3d_opt(a, DQT_Y); + if (!q || !sc || !y) return R3D_NO(RAD_E_INVAL); + /* The codes' dtype IS the encoding, so it is read off the tensor: E4M3 and E5M2 are one byte + * apiece and nothing in the bytes tells them apart. A plain u8 plane carries no encoding, so it + * is not accepted under the E4M3 code. */ + if (q->dtype == RAD_U8) return R3D_NO(RAD_E_DTYPE); + const int q_dt = r3d_dt_code(q->dtype); + if (q_dt != R3D_DT_U8 && q_dt != R3D_DT_E5M2 && q_dt != R3D_DT_I8) + return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_f32(sc)); + R3D_NEED(dt_bf16(y)); /* the launcher has no output dtype; see above */ + + const long long n = r3d_geti_or(a, "n", r3d_dim(y, (int)y->rank - 1)); + if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE); + + /* Rows come off `y`, as in ref_dequant: `y` is the plane the consumer reads. */ + long long rows = 0, qrows = 0, srows = 0; + const long long y_ld = r3d_rows_pitch(y, n, &rows); + const long long q_ld = r3d_rows_pitch(q, n, &qrows); + if (y_ld < 0 || q_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE); + + /* The scale stream's extent gives the group count and `group` each group's width, as libref + * reads them; with no `group`, the stream is taken as one scale per group of ceil(n/ngrp). */ + const long long ngrp_param = r3d_numel(sc) / rows > 0 ? r3d_numel(sc) / rows : 1; + long long group = r3d_geti_or(a, "group", 0); + if (group <= 0) group = (n + ngrp_param - 1) / ngrp_param; + if (group < 1 || group > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + const long long ngrp = (n + group - 1) / group; + const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows); + if (s_ld < 0 || srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE); + if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4) || !r3d_aligned(r3d_p(y), 8)) + return R3D_NO(RAD_E_ALIGN); + + return r3d_launch_status(r3d_dequant(r3d_addr(q), r3d_addr(sc), r3d_addr(y), (int)rows, (int)n, + (int)group, q_dt, (int)s_ld, (int)y_ld, + (long)(uintptr_t)stream)); +} diff --git a/libr3d/r3d_rows.cpp b/libr3d/r3d_rows.cpp new file mode 100644 index 00000000..50f586bc --- /dev/null +++ b/libr3d/r3d_rows.cpp @@ -0,0 +1,1839 @@ +/* r3d_rows.cpp -- what libr3d can compute, and for which geometry. + * + * One row per (kernel, band). A row is a `RadKernelInfo`: names, prose, the geometry it serves as + * constraints, the tuning axes, and the entry points that launch it. The engine reads this table at + * load, matches a requested op and geometry against it, and ranks the candidates by `priority`; it + * never calls a function in this file to do that, and it never looks at a kernel's name. Nothing in + * the engine, the graph, the containers or a test names libr3d's kernels: a card runs this library + * because the rows say they cover its ops, and it stops running them when they do not. + * + * ============================================================ the schema table + * + * The first plugin in hierarchy order to declare an op fixes its schema, and a plugin whose schema + * disagrees is refused at load, both plugins named (rad_abi.h, spec §2.3): arguments are positional, + * so two schemas for one op would make one call mean two things depending on which row won. libref + * declares the vocabulary in `docs/OPS.md`, so every schema below is libref's -- the same keys, the + * same types, the same requiredness, the same operand roles and optionality, in the same order. The + * prose is ours, because it states what *this* row computes; the loader's comparison + * covers the positional slots and not the documents. + * + * An op libr3d invents needs a schema here too, and libref's side of it: an op whose schema is + * declared only by a kernel plugin cannot be checked against a reference, and an op that exists in + * two kernels with two schemas breaks the rule above. That is why libr3d declares no new op: every + * row below implements an op libref declares. + * + * ============================================================ the constraint table + * + * A constraint is a necessary condition on the geometry (spec §2.1). "bf16 only" is not one: the + * dtype of an operand is a property of the call, and the shim reads the tensor. What goes here is + * what the *kernel* cannot do -- the divisibility its lane map assumes, the band its grid is sized + * for, the scheme its decoders implement -- and what the selector needs to choose between rows. + * A constraint the shim also checks costs nothing; a constraint the kernel does not actually + * enforce is a promise the tests will break. + * + * ============================================================ rows are positional + * + * `RadKernelInfo` is initialised positionally, as `rad_abi.h` requires: a field added anywhere but + * the end shifts every later initialiser, and `nullptr` converts to any function pointer, so part + * of the shift compiles. The order below is the struct's; the trailing slots a row does not use are + * left off, which aggregate initialisation zeroes. A row's entry points are, in order: init, fini, + * launch, scratch, layout, relayout, opd_shape, unrelayout, replaces. + * + * The only `layout` and `relayout` hooks in this table present the container's own planes as the + * joined operands they store -- the w2a8 row's `b_scale`, the fp8 weight's codes and scale, the + * logits head -- and repack nothing, so a container converted on this card keeps row-major codes + * against row-major scales. A dot2 GEMM reads a weight in the order it is stored; libr4d's fragment + * permutations are a WMMA fact, and RDNA3's tensor cores are not reachable from this toolchain + * (r3d_common.h has the measurements). + * + * Pure host C++: no r3d.h, no HIP, so this table compiles and can be read and tested without ROCm. + */ + +#include "r3d_plugin.h" + +#ifndef R3D_BUILD_TARGET +#define R3D_BUILD_TARGET "gfx1100 gfx1101 gfx1102 gfx1103 gfx1150 gfx1151" +#endif + +#include +#include + +#define ROW(a) (a), (int)(sizeof(a) / sizeof((a)[0])) +#define NELEM(a) ((int)(sizeof(a) / sizeof((a)[0]))) + +/* Parameter and constraint spellings, shared with libref's table. */ +#define P_INT(k) { (k), RAD_P_INT, RAD_REQUIRED } +#define P_INTO(k) { (k), RAD_P_INT, RAD_OPTIONAL } +#define P_INTD(k) { (k), RAD_P_INT, RAD_DERIVED } +#define P_STR(k) { (k), RAD_P_STR, RAD_REQUIRED } +#define P_STRO(k) { (k), RAD_P_STR, RAD_OPTIONAL } +#define P_F64(k) { (k), RAD_P_F64, RAD_REQUIRED } +#define P_F64O(k) { (k), RAD_P_F64, RAD_OPTIONAL } + +#define C_EQ(k, v) { (k), RAD_C_EQ, (long long)(v), nullptr } +#define C_LE(k, v) { (k), RAD_C_LE, (long long)(v), nullptr } +#define C_GE(k, v) { (k), RAD_C_GE, (long long)(v), nullptr } +#define C_DIV(k, v) { (k), RAD_C_DIV, (long long)(v), nullptr } +#define C_IN(k, s) { (k), RAD_C_IN, 0, (s) } + +/* A row with one implementation and nothing to measure. */ +#define NOTUNE nullptr, 0, nullptr + +#define SCHEMA(op, p, o, doc) { (op), ROW(p), ROW(o), (doc) } + +/* ================================================================== schemas + * + * Operand names are diagnostics only; roles and optionality are positional and must match. Where + * libref's array carries a name libr3d's reads differently (`b` for a gate, say) the names differ + * and the schema does not. + */ + +/* --- norms and elementwise --- */ +static const RadParamSpec pRmsNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), + P_F64O("wadd"), P_F64O("mult") }; +static const RadOperandSpec oRmsNorm[] = { { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 1 }, + { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pLayernorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; +static const RadOperandSpec oLayernorm[] = { { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "b", RAD_OPD_WEIGHT, 1 }, + { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") }; +static const RadParamSpec pMnDtype[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oBinary[] = { { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oUnary[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; + +static const RadParamSpec pCast[] = { P_INT("M"), P_INT("n"), P_STR("from"), P_STR("to") }; + +static const RadParamSpec pScale[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +/* `s` is a WEIGHT, which is what the reference declares and what the core acts on: a weight operand + * has its issue resolve a handle and wait on the mover, and a scale plane comes from the container + * or from a quantiser, not from a buffer the planner allocated for this step. Declaring it IN is + * not a cosmetic difference -- the loader compares roles positionally and refuses the library that + * disagrees, every row with it. */ +static const RadOperandSpec oScale[] = { { "x", RAD_OPD_IN, 0 }, { "s", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; +static const RadOperandSpec oFill[] = { { "y", RAD_OPD_OUT, 0 } }; + +/* --- the model's odds and ends --- */ +static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), + P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"), + P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"), + P_F64O("yarn_factor"), P_F64O("yarn_low"), + P_F64O("yarn_high"), P_F64O("yarn_magnitude"), + P_STRO("ladder"), P_F64O("llama3_factor"), + P_F64O("llama3_low"), P_F64O("llama3_high"), + P_F64O("llama3_orig") }; +static const RadOperandSpec oRope[] = { { "qkv", RAD_OPD_INOUT, 0 }, + { "positions", RAD_OPD_IN, 0 } }; + +static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"), + P_INT("block_size"), P_STR("kv_dtype"), + P_F64O("k_scale"), P_F64O("v_scale") }; +static const RadOperandSpec oKvStore[] = { { "k", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 0 }, + { "slot_mapping", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_INOUT, 0 } }; + +static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), + P_STR("dtype"), P_INTO("vocab_offset"), P_F64O("wscale"), + P_F64O("mult") }; +static const RadOperandSpec oEmbed[] = { { "tokens", RAD_OPD_IN, 0 }, + { "wte", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_OUT, 0 } }; + +static const RadOperandSpec oGather[] = { { "x", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oScatter[] = { { "v", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, + { "x", RAD_OPD_INOUT, 0 } }; + +/* --- quantisation --- */ +static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype") }; +static const RadOperandSpec oQuantFp8[] = { { "x", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oQuant[] = { { "x", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "asum", RAD_OPD_OUT, 1 } }; + +static const RadParamSpec pGatedQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), + P_STRO("act") }; +static const RadOperandSpec oGatedQuant[] = { { "gate_up", RAD_OPD_IN, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 } }; + +static const RadOperandSpec oDequant[] = { { "q", RAD_OPD_IN, 0 }, { "scale", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; + +/* --- gemm --- */ +static const RadParamSpec pGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_STR("dtype") }; +static const RadOperandSpec oGemm[] = { { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), + P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"), + P_INTO("split_n") }; +static const RadOperandSpec oGemmQ[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RAD_OPD_IN, 1 }, + { "b", RAD_OPD_WEIGHT, 0 }, + { "b_scale", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, { "a_sum", RAD_OPD_IN, 1 }, + { "b_ref", RAD_OPD_WEIGHT, 1 } }; + + +/* ================================================================== the vocab and the sampler + * + * The vocab and sampler bands, transcribed from libref. A schema is inert on its own -- the loader + * matches a row to a schema, and a row naming an entry point no unit defines is an undefined symbol + * that kills `dlopen` and takes every row in the library with it -- so `r3d_selftest`'s schema phase + * compares every declared schema against libref's, slot for slot, the moment the library loads, and + * a misspelled key is refused at load, not when a row first meets it. + * + * The sampler is a law, not a shape: the candidate set, the tie-break in the top-k, the order of the + * renormalisations and the seeded draw are all observable, and libref is the oracle for all of them. + */ + +/* The gated MLP's activation, as the llama-family graphs emit it: one fused [M, 2n] projection, the + * gate's half activated and multiplied by the other. `act_mul` is the same arithmetic over two + * operands; these are different ops, and an architecture emits one or the other. */ +static const RadOperandSpec oGateUp[] = { { "gate_up", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; + +/* Paged attention. `block_size` is RAD_DERIVED here (the container's cache geometry, admitted by a + * constraint that only refuses its absence), and `n_head`, `max_seqs`, `max_ctx` and `prefill_fp8` + * are on the list because a plugin's scratch hook sizes a split-KV buffer from them and both + * libraries must agree on the parameter list -- libref ignores them. */ +/* DFlash2's candidate walk: a draft block of `steps` proposals, `top_k` candidates at each step, + * rescored against the target's rank-d codebooks. `anchor_stride` is optional and defaults to 1; + * `hp` is the optional per-edge scaling of the predecessor's codebook row, and absent it is a plane + * of ones, which is what the reference computes. */ +/* The gated MLP band: one weight of N = 2n rows (gate first, then up), the GEMM, the gate and the + * output quantiser in one launch, so the [M, N] intermediate the unfused chain writes and re-reads + * never exists. `act` is a required string: an implementation compiles one gate, and an optional + * would let a row resolve for the gate it does not have. */ +static const RadParamSpec pGemmQGated[] = { P_INT("M"), P_INT("N"), P_INT("K"), + P_INT("group"), P_STR("dtype"), P_STR("act") }; +/* The vocabulary projection's schema, slot for slot with the reference's: the geometry is the head's + * (`n_vocab` x `n_embd`), the dtype is the activation's, and `logits` is f32 -- the op exists + * separately from gemm_nt for that reason, and the row that serves it narrows nothing. */ +static const RadParamSpec pLogits[] = { P_INT("M"), P_INT("n_vocab"), P_INT("n_embd"), + P_STR("dtype") }; +static const RadOperandSpec oLogits[] = { + { "x", RAD_OPD_IN, 0 }, { "lm_head", RAD_OPD_WEIGHT, 0 }, { "logits", RAD_OPD_OUT, 0 } }; + +static const RadOperandSpec oGemmQGated[] = { + { "a", RAD_OPD_IN, 0 }, { "a_scale", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_WEIGHT, 0 }, { "b_scale", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, +}; + +static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"), + P_INT("rank"), P_INT("n_vocab"), + P_INTO("anchor_stride"), P_STR("dtype") }; +static const RadOperandSpec oDflashSelect[] = { + { "cand", RAD_OPD_IN, 0 }, { "unary", RAD_OPD_IN, 0 }, + { "hp", RAD_OPD_IN, 1 }, { "anchor", RAD_OPD_IN, 0 }, + { "pred", RAD_OPD_WEIGHT, 0 },{ "succ", RAD_OPD_WEIGHT, 0 }, + { "tokens", RAD_OPD_OUT, 0 }, +}; + +static const RadParamSpec pAttnPaged[] = { + P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"), + P_INT("window"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), + P_INTO("n_head"), P_INTO("max_seqs"), P_INTO("prefill_fp8") +}; +static const RadOperandSpec oAttnPaged[] = { + { "q", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_IN, 0 }, { "block_table", RAD_OPD_IN, 0 }, + { "seqused", RAD_OPD_IN, 0 }, { "k_descale", RAD_OPD_IN, 1 }, { "v_descale", RAD_OPD_IN, 1 }, + { "cu_seqlens", RAD_OPD_IN, 1 }, { "out", RAD_OPD_OUT, 0 } +}; + +/* The row's top-R over a vocabulary slice, and the sampler's stages. The history stages write this + * rank's columns and read global ids, so they carry `vocab_off`; the narrowing stages work on the + * candidate set the top-k produced and need only its width. */ +static const RadParamSpec pRowTopk[] = { P_INT("M"), P_INT("N"), P_INT("R"), P_INTO("vocab_off"), + P_STR("dtype") }; +static const RadOperandSpec oRowTopk[] = { { "x", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_OUT, 0 }, + { "val", RAD_OPD_OUT, 0 }, + { "pairs", RAD_OPD_OUT, 1 } }; +static const RadParamSpec pMVocab[] = { P_INT("M"), P_INT("n_vocab") }; +static const RadParamSpec pMCand[] = { P_INT("M"), P_INT("n_cand") }; +static const RadParamSpec pPenal[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") }; +static const RadParamSpec pTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") }; +static const RadParamSpec pLogprobs[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), + P_INTO("vocab_off") }; +static const RadOperandSpec oTemp[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 } }; +static const RadOperandSpec oMask[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "bitmask", RAD_OPD_IN, 0 } }; +static const RadOperandSpec oPenalties[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "history", RAD_OPD_IN, 0 } }; +static const RadOperandSpec oDry[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "history", RAD_OPD_IN, 0 }, + { "breakers", RAD_OPD_IN, 1 } }; +static const RadOperandSpec oNgramBan[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "history", RAD_OPD_IN, 0 }, + { "ngram", RAD_OPD_IN, 0 }, + { "whitelist", RAD_OPD_IN, 1 } }; +static const RadOperandSpec oTopk[] = { { "logits", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "cand_idx", RAD_OPD_OUT, 0 }, + { "cand_val", RAD_OPD_OUT, 0 }, + { "pairs", RAD_OPD_OUT, 1 } }; +static const RadOperandSpec oArgmax[] = { { "logits", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "token", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oLogprobs[] = { { "logits", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "stats", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oNarrow[] = { { "cand_idx", RAD_OPD_INOUT, 0 }, + { "cand_val", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 } }; +static const RadOperandSpec oPick[] = { { "cand_idx", RAD_OPD_IN, 0 }, + { "cand_val", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "token", RAD_OPD_OUT, 0 } }; + + +/* The fused MLP activation and the fused norm-quantiser, both from the model unit. The first takes + * one [M, 2n] operand and produces [M, n]; the second is libref's, slot for slot, with `residual` + * INOUT because the sum it stores is the one the variance reads. */ +static const RadParamSpec pRmsQuantFp8[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), + P_STR("dtype"), P_F64O("wadd") }; +/* `residual` is optional because the op has a no-residual form, which is what the launcher's `res` + * pointer being 0 means; libref spells it INOUT_O and the loader compares the flag. */ +static const RadOperandSpec oRmsQuantFp8[] = { + { "x", RAD_OPD_IN, 0 }, { "residual", RAD_OPD_INOUT, 1 }, { "w", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "out_bf16", RAD_OPD_OUT, 1 } +}; + +static const RadOpSchema kSchemas[] = { + SCHEMA("rmsnorm", pRmsNorm, oRmsNorm, + "y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. `wadd` is GemmaRMSNorm's `1 +`, " + "added to the gain in f32; `mult` scales the normed row before its one rounding. No " + "gain operand at all means a gain of 1 and a `wadd` of 0."), + SCHEMA("layernorm", pLayernorm, oLayernorm, + "y = (x - mean) / sqrt(var + eps) * w + b, the mean and the variance taken in two " + "passes over the row."), + SCHEMA("add", pAdd, oBinary, + "y = a + b. `b` carrying exactly n elements against an output of M rows broadcasts " + "along rows, and nothing else broadcasts at all. With `div`, y = rd(rd(a + b) / div)."), + SCHEMA("mul", pMnDtype, oBinary, "y = a * b, with the same one broadcast rule as `add`."), + SCHEMA("act_mul", pActMul, oBinary, + "y = act(a) * b over two [M, n] operands, `act` naming silu, gelu (the exact erf form), " + "gelu_tanh, sigmoid or quick_gelu. The feed-forward's gated middle."), + SCHEMA("silu", pMnDtype, oUnary, "y = x * sigmoid(x)."), + SCHEMA("gelu", pMnDtype, oUnary, + "y = 0.5 * x * (1 + erf(x / sqrt(2))), the exact form; the tanh approximation is a " + "different op name."), + SCHEMA("sigmoid", pMnDtype, oUnary, "y = 1 / (1 + exp(-x))."), + SCHEMA("softmax", pMnDtype, oUnary, "Row-wise, f32, with the maximum subtracted."), + SCHEMA("cast", pCast, oUnary, + "y = x, from the dtype `from` to the dtype `to`, one rounding on the way. An integer " + "pair goes through without touching f32, so ids above 2^24 survive."), + SCHEMA("scale", pScale, oScale, + "y = x * s, `s` one element broadcast over the whole output. A row of scales is " + "`mul_weight`."), + SCHEMA("fill", pFill, oFill, "y = value over [M, n]. The output is the only operand."), + SCHEMA("rope", pRope, oRope, + "Rotary positions applied in place to a fused qkv row: q heads, then the key heads, the " + "value heads untouched. `mode` is neox, gptj, mrope, imrope or axial; the yarn, llama3 " + "and ladder parameters adjust the frequency ladder."), + SCHEMA("kv_store", pKvStore, oKvStore, + "K and V into a paged cache at slot_mapping's slots, converting to the cache's dtype. A " + "negative slot is skipped; the cache is [blocks, kv_heads, block_size, 2*head_dim]."), + SCHEMA("embed_lookup", pEmbed, oEmbed, + "x[r] = wte[tokens[r] - vocab_offset] * wscale * mult, the id global and the table " + "sharded by `vocab_offset`. An id outside the shard's range yields a zero row."), + SCHEMA("gather_rows", pMnDtype, oGather, "y[r] = x[idx[r]], rows of n elements."), + SCHEMA("scatter_rows", pMnDtype, oScatter, "x[idx[r]] = v[r], rows of n elements."), + SCHEMA("quant_act_fp8", pQuant, oQuantFp8, + "Symmetric per-(row, group) E4M3: scale = amax * (1/448) with the reciprocal " + "multiplied, not divided; an all-zero group gets scale 1 and the codes 0."), + SCHEMA("quant_act_i8", pQuant, oQuant, + "Symmetric int8 with ONE SCALE PER ROW, max(amax, 1e-8) / 127, codes round-to-nearest-" + "ties-to-even and saturating, stored in the STEP ORDER the int8 WMMA reads. `asum` takes " + "the group-major row sums the zero-pointed GEMMs reduce."), + SCHEMA("quant_act_i8g", pQuant, oQuantFp8, + "The same int8 code at `group` granularity: one f32 scale per (row, group), amax / 127, " + "1 for an all-zero group, codes row-major."), + SCHEMA("gated_quant_fp8", pGatedQuant, oGatedQuant, + "act(gate) * up over a fused [M, 2n] projection, quantised in the same pass: the codes " + "are taken over the rounded product, which `out_bf16` receives when present."), + SCHEMA("dequant", pQuant, oDequant, + "y = code * scale, the read of a container's own quantised weight: `group`-wide f32 " + "scales against E4M3, E5M2 or int8 codes."), + SCHEMA("gemm_nt", pGemm, oGemm, "y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate."), + SCHEMA("gemm_nt_q", pGemmQ, oGemmQ, + "The same product against a quantised weight. `dtype` names the scheme: fp8a16 a bf16 " + "activation against E4M3 codes, fp8a8 quant_act_fp8's codes and scales, i8a8 int8 on " + "both axes. `group` is the activation's scale width; `pb1` and `pb2` the weight's block, " + "which the container states. `a_sum` and `b_ref` are the row sums a zero-pointed form " + "reduces."), + + SCHEMA("rmsnorm_quant_fp8", pRmsQuantFp8, oRmsQuantFp8, + "RMS norm with an optional residual add, then the E4M3 quantiser, in one pass. The " + "residual add is STORED BEFORE THE VARIANCE READS IT, so the sum the norm is taken over " + "is the bf16 one and not the f32 one -- that is what makes this the `add` + `rmsnorm` " + "pair and not `rmsnorm_add`, which normalises the unrounded sum. `wadd` is added to every " + "gain in f32. `out_bf16` holds exactly the value the codes were taken over."), + + /* ---- the vocabulary and the sampler: schemas first, rows with their kernels ---- */ + SCHEMA("silu_mul", pMnDtype, oGateUp, + "y[i] = silu(gate_up[i]) * gate_up[n + i] over one fused [M, 2n] plane, the gate the " + "first half -- rad-convert's fusion order -- and the product of an activation that was " + "never narrowed. act_mul is the same arithmetic over two operands, narrowing first, " + "because the pair it replaces stored the activation."), + SCHEMA("attn_paged", pAttnPaged, oAttnPaged, + "Scaled dot-product attention over a paged KV cache: q [tokens, n_head, head_dim], the " + "cache [blocks, kv_heads, block_size, 2*head_dim], `block_table` a row's block list, " + "`seqused` its length. `gqa` is the head ratio; `causal` and `window` are the mask; " + "`scale` is 1/sqrt(head_dim) unless the graph says otherwise. k_descale and v_descale " + "come with an fp8 cache, cu_seqlens with a packed prefill."), + SCHEMA("row_topk", pRowTopk, oRowTopk, + "Exact per-row top-R, descending, ties to the lower column. `vocab_off` shifts every " + "column reported, so a rank's slice reports global ids; `pairs` is the [M, R, 2] plane an " + "all_gather moves, with id -1 for a slot the row could not fill."), + SCHEMA("sample_argmax", pMVocab, oArgmax, + "The most likely token of each row, the lowest id on a tie."), + SCHEMA("sample_temp", pMVocab, oTemp, + "logits / temperature, in place. The temperature is a row parameter, so a batch mixes " + "greedy and sampled rows."), + SCHEMA("sample_topk", pTopk, oTopk, + "The k most likely candidates a row: ids and values, descending, ties to the lower id. " + "`pairs` is the vocab-parallel form the merge reads after the all-gather."), + SCHEMA("sample_topp", pMCand, oNarrow, + "Narrow the candidate set to the smallest prefix whose probabilities reach p, in the " + "order the candidates arrive -- not in sorted order, which is a different set at a tie."), + SCHEMA("sample_minp", pMCand, oNarrow, + "Drop a candidate whose probability is under min_p times the best candidate's."), + SCHEMA("sample_typical", pMCand, oNarrow, + "Drop the candidates furthest from the set's entropy: keep those within `sigma` of the " + "mean surprise, the token set a reader would not have predicted least and most alike."), + SCHEMA("sample_xtc", pMCand, oNarrow, + "The exclusion-the-model-would-not-choose filter: drop every candidate above p, keeping " + "the last one standing when all of them are."), + SCHEMA("sample_pick", pMCand, oPick, + "The seeded inverse-CDF draw over the candidate set: the law the request's seed selects, " + "in the order the candidates arrive. A kernel that draws from the same distribution " + "differs from the reference on every token, and kbench reads that as a failure, because " + "for a sampler it is one."), + SCHEMA("sample_penalties", pPenal, oPenalties, + "Presence, frequency and repetition penalties in place, over the row's history, with the " + "DRY and penalty terms libref spells out."), + SCHEMA("sample_dry", pPenal, oDry, + "Distributed Repetition Penalty: a sequence of `last_n` that repeats a sequence of " + "`baseline` is penalised, growing with the length of the repeat. `breakers` marks the " + "positions that end a sequence and are never penalised."), + SCHEMA("sample_ngram_ban", pPenal, oNgramBan, + "Ban the n-grams of length `n` that the history shows inside `window`, to -inf. " + "`whitelist` exempts a set of ids from the ban."), + SCHEMA("sample_mask", pMVocab, oMask, + "The grammar's and the tool-caller's doing: set to -inf every id whose bit is clear in " + "the row's bitmask, addressed by the row's mask_row, which is -1 for a row with no " + "constraint and so shares a short plane."), + SCHEMA("sample_logprobs", pLogprobs, oLogprobs, + "The row's log-softmax statistics for the response: max, sum of exp, and the k best " + "(id, logit) pairs, in [M, 2 + 2k]."), + SCHEMA("logits_gemm", pLogits, oLogits, + "logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T. Separate from gemm_nt " + "because lm_head is its own access class and the sampler wants to fuse against it: the " + "head is the largest read in a decode step and the output is f32, which every sampler " + "stage downstream reads."), + SCHEMA("gemm_nt_q_gated", pGemmQGated, oGemmQGated, + "The gated MLP band in one launch: `b` is N = 2n rows, gate over up, the dot products are " + "narrowed to bf16 as the unfused pair would leave them, the gate is `gt * sigmoid(gt)`, the " + "product is narrowed, and the row is coded per group of `group` columns with the amax that " + "group's scale comes from. `out_bf16`, when asked for, is the narrowed gated tensor before " + "the coding."), + SCHEMA("dflash_select", pDflashSelect, oDflashSelect, + "DFlash2's greedy walk over a draft block: at each of `steps` steps the candidate with " + "the best `unary + pred[pid] . (hp * succ[cand])` is picked, and becomes the predecessor " + "of the next step. `cand`/`unary` have one row per (sequence, step); `anchor` is the " + "block's first predecessor, at `m * anchor_stride`."), +}; + +extern "C" int rad_kernel_schema_count(void) { + return (int)(sizeof(kSchemas) / sizeof(kSchemas[0])); +} +extern "C" const RadOpSchema* rad_kernel_schema_at(int i) { + if (i < 0 || i >= rad_kernel_schema_count()) return nullptr; + return &kSchemas[i]; +} + +/* ================================================================== tuning + * + * The axes a kernel is instantiated along, measured on this card (`rad-tune`, spec §15). Every row + * without a matrix instruction to size a tile against has few axes: what is left to measure is how + * the work is split across the card, and how the weight stream is read. + */ + +/* Split-K. 0 is not a point in the space, it is the kernel's own law: "the largest split legal at + * this K", because no fixed default is legal at every shape and an illegal default would make an + * untuned install fail rather than run slowly. */ +static const int64_t kSk[] = { 0, 1, 2, 4, 8, 16 }; +/* Waves per block. 8 is 256 threads, which is the largest block that keeps the register budget of + * a wave-per-N-tile kernel inside gfx11's 1024 VGPRs a SIMD at four waves. */ +static const int64_t kWv[] = { 1, 2, 4, 8 }; +/* Non-temporal weight streaming: a decode GEMM reads a weight once per token, so the L2 is a + * latency cache and not a reuse cache. RDNA3 has no transposed-load instruction, so this axis + * selects the plain 128-bit stream with the cache hints off -- a knob worth measuring, not an + * instruction. */ +static const int64_t kNt[] = { 0, 1 }; +/* No `kb` axis. Only a GEMM that stages a K slab through LDS has a slab width to measure, and + * the skinny rows stream the weight through registers; the axis joins the table with the tiled + * row. */ + +static const RadTunable tGemmM16[] = { + { "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" }, + { "wv", kWv, NELEM(kWv), 8, "waves per block" }, + { "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" }, +}; +/* No `wv` here. The quantised kernel's launcher takes a fixed block of eight waves -- its weight + * decode, sixteen codes a lane into eight dot2, is the whole of a wave's issue budget at any block + * size -- so an axis the tuner would sweep is an axis the kernel ignores, and a tunable that changes + * nothing is worse than none: it spends the tuner on a knob and teaches the reader that the table + * lies. The axis joins the row with a launcher that takes it. */ +static const RadTunable tGemmQ[] = { + { "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" }, + { "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" }, +}; + +/* Cross-axis legality, in one place so the tuner, the scratch hook and the launch agree. A split's + * slice must end on a k multiple the kernel's inner loop consumes: 8 elements for a bf16 dot2 pair + * group, and one whole scale group for a quantised weight, since a slice that ends mid-block cannot + * apply its block scale. */ +static int gemm_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_c) { + const long long K = rad_param_getdim(p, n_p, "K", 0); + const long long sk = rad_param_geti(c, n_c, "sk", 0); + const long long wv = rad_param_geti(c, n_c, "wv", 8); + if (K <= 0 || wv < 1 || wv > 8) return 0; + const long long unit = rad_param_getdim(p, n_p, "group", 0) > 0 + ? rad_param_getdim(p, n_p, "group", 0) + : 8; + return sk >= 0 && (sk == 0 || K % (sk * unit) == 0); +} + +/* The chosen point, read back. `TUNE` falls to the axis's default when the core appended nothing, + * so a checker with no tuned key runs what an untuned install runs. */ +static long long tune_i(const RadArgs* a, const RadTunable* t, int n, const char* key) { + if (a && a->p) + for (int i = 0; i < a->n_p; ++i) + if (a->p[i].key && !std::strcmp(a->p[i].key, key) && a->p[i].kind == RAD_P_INT) + return a->p[i].ival; + for (int i = 0; i < n; ++i) + if (!std::strcmp(t[i].key, key)) return t[i].deflt; + return 0; +} +#define TUNE(a, tab, key) ((int)tune_i((a), (tab), NELEM(tab), (key))) + +extern "C" void r3d_cfg_gemm(const RadArgs* a, R3dGemmCfg* out) { + out->wv = TUNE(a, tGemmM16, "wv"); + out->sk = TUNE(a, tGemmM16, "sk"); + out->kb = 0; + out->nt = TUNE(a, tGemmM16, "nt"); +} +extern "C" void r3d_cfg_split(const RadArgs* a, R3dSplitCfg* out) { + out->splits = TUNE(a, tGemmM16, "sk"); +} +extern "C" void r3d_cfg_topk(const RadArgs* a, R3dTopkCfg* out) { + out->rc = 0; + out->nch = 0; +} + +/* A split's partials are f32 over the output, plus one arrival counter per split. Sized at the + * band's bounds and the axis's widest split, because a scratch hook runs at declare, where the + * range may still be open: the buffer must hold any point the tuner can pick. */ +/* Split-KV's partials: one record of 128 accumulator floats plus the running max and sum -- 132 + * floats -- per (query row, head, slice). The shim takes the slice count from the bytes the engine + * offers and halves it until they fit, so this is the want, stated at the slice count the walk + * benefits from and capped at what these bands can carry: 15 MB at the decode band (1792 rows over + * 16 heads) and 17 MB at the prefill band. Attaching scratch makes the row non-concurrent, which is + * the ABI's rule (rad_kernel_concurrent is `scratch == nullptr`) and the price of the split. */ +static int64_t attn_scratch(const RadArgs* a) { + /* The size comes from the SHAPE, and a scratch hook runs at declare, where the engine has bound + * the operands' shapes and has no bytes to hand out yet -- `data` is null at declare for every + * tensor in the plan. A hook that requires bytes answers 0 for the whole run, the engine + * allocates an arena of 0 bytes, and the shim's split pass finds no partials to write. The + * sibling `gemm_scratch` sizes off `RadParam` dims for exactly this reason. */ + if (!a || a->n_t < 1 || a->t[0].rank == 0) return 0; + long long n_head = 0, head_dim = 0; + const int64_t nh = rad_args_geti(a, "n_head", &n_head) ? n_head : 0; + if (!rad_args_geti(a, "head_dim", &head_dim) || !head_dim || !nh) return 0; + const long long rows = rad_tensor_numel(&a->t[0]) / (nh * head_dim); + if (rows <= 0) return 0; + const long long want = rows * nh * 8 * 132 * (long long)sizeof(float); + const long long cap = 16LL << 20; + return want < cap ? want : cap; +} + +static int64_t gemm_scratch(const RadParam* p, int n_p) { + const long long M = rad_param_getdim(p, n_p, "M", 0), N = rad_param_getdim(p, n_p, "N", 0); + const long long sk = kSk[NELEM(kSk) - 1]; + if (M <= 0 || N <= 0) return 0; + return sk * M * N * 4 + sk * 64; +} + +/* ================================================================== constraints + * + * What the kernel cannot do, and what the selector needs. The divisibility in each is the lane map + * in the unit: a wave covering a bf16 row reads four elements a lane (two pairs), so a row of 4m + * elements needs no tail; where the kernel has a tail path the constraint says 2, not 4. + */ + +/* bf16 elementwise, norms and the GEMMs: rows of an even width, so a lane owns a pair. */ +static const RadConstraint cBf16Row[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; +static const RadConstraint cF32Row[] = { C_IN("dtype", "f32"), C_DIV("n", 2) }; +static const RadConstraint cNormBf16[] = { C_IN("dtype", "bf16"), C_DIV("n", 2), + C_GE("n", 2) }; +static const RadConstraint cNormF32[] = { C_IN("dtype", "f32"), C_DIV("n", 2), C_GE("n", 2) }; +static const RadConstraint cSoftmax[] = { C_IN("dtype", "f32"), C_GE("n", 2) }; + +/* A cast row is its pair of dtype names. */ +static const RadConstraint cCastBf16F32[] = { C_IN("from", "bf16"), C_IN("to", "f32"), + C_DIV("n", 2) }; +static const RadConstraint cCastF32Bf16[] = { C_IN("from", "f32"), C_IN("to", "bf16"), + C_DIV("n", 2) }; +static const RadConstraint cCastBf16[] = { C_IN("from", "bf16"), C_IN("to", "bf16"), + C_DIV("n", 2) }; +static const RadConstraint cCastF32[] = { C_IN("from", "f32"), C_IN("to", "f32"), + C_DIV("n", 2) }; +static const RadConstraint cCastI64F32[] = { C_IN("from", "i64"), C_IN("to", "f32"), + C_DIV("n", 2) }; +static const RadConstraint cCastI32I64[] = { C_IN("from", "i32"), C_IN("to", "i64"), + C_DIV("n", 2) }; +static const RadConstraint cCastI64I32[] = { C_IN("from", "i64"), C_IN("to", "i32"), + C_DIV("n", 2) }; + +/* act_mul names its activation, because a row for gelu and a row for silu are different template + * instantiations and a model asks for one of them. */ +static const RadConstraint cActSilu[] = { C_IN("act", "silu"), C_IN("dtype", "bf16"), + C_DIV("n", 2) }; +static const RadConstraint cActGelu[] = { C_IN("act", "gelu"), C_IN("dtype", "bf16"), + C_DIV("n", 2) }; +static const RadConstraint cActSigmoid[] = { C_IN("act", "sigmoid"), C_IN("dtype", "bf16"), + C_DIV("n", 2) }; + +/* A fill row is its dtype; the value is a parameter, and every dtype takes every value. */ +static const RadConstraint cFillBf16[] = { C_IN("dtype", "bf16") }; +static const RadConstraint cFillF32[] = { C_IN("dtype", "f32") }; +static const RadConstraint cFillI32[] = { C_IN("dtype", "i32") }; +static const RadConstraint cFillI64[] = { C_IN("dtype", "i64") }; + +/* rope: the two modes this kernel implements, and a rotary width that is a whole even head. The + * yarn, llama3 and ladder parameters are absent from these rows' bands, so a geometry carrying them + * is not routed here. */ +/* `rotary_dim` is optional on the op, and a constraint on a parameter a band does not carry does + * not hold -- the engine's rule, quoted in r3d_selftest.cpp's band-reachability phase -- so it + * cannot appear here: an architecture that rotates the whole head, which is every llama-family + * graph, emits a band without the parameter and would find no row. Its evenness is the shim's to + * refuse (RAD_E_SHAPE), and `rotary_dim` absent is head_dim, which is even by the constraint above. */ +static const RadConstraint cRope[] = { C_IN("mode", "neox gptj"), C_DIV("head_dim", 2) }; + +/* The cache's dtype is the row: a bf16 cache stores the value, an E4M3 cache encodes it with the + * store's scale. head_dim even because a lane writes a pair; block_size a multiple of 16 so a + * block's slice of a row is a whole number of lanes. */ +static const RadConstraint cKvBf16[] = { C_IN("kv_dtype", "bf16"), C_DIV("head_dim", 2), + C_DIV("block_size", 16) }; +static const RadConstraint cKvFp8[] = { C_IN("kv_dtype", "fp8_e4m3"), C_DIV("head_dim", 2), + C_DIV("block_size", 16) }; +static const RadConstraint cKvF16[] = { C_IN("kv_dtype", "f16"), C_DIV("head_dim", 2), + C_DIV("block_size", 16) }; + +static const RadConstraint cEmbed[] = { C_IN("dtype", "bf16"), C_DIV("n_embd", 2) }; + +/* The gather's and scatter's dtype, and a row wide enough for a lane to own a pair. */ +static const RadConstraint cGatherBf16[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; +static const RadConstraint cGatherF32[] = { C_IN("dtype", "f32"), C_DIV("n", 2) }; +static const RadConstraint cScatterBf16[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; + +/* The quantisers: the scale group is the checkpoint's block, 128, and a row wide enough that a + * wave's four-elements-a-lane store is whole. */ +static const RadConstraint cQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_FP8_BLOCK), + C_DIV("n", 4) }; +/* `quant_act_i8` is the per-row int8 whose codes the int8 WMMA reads, so its width is a whole + * 16-byte step, not a lane's four. `quant_act_i8g` is the per-group one whose codes are row-major, + * which is what a dot2 GEMM reads; it is the activation of this library's i8a8 row. */ +static const RadConstraint cQuantI8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_W8_GROUP), + C_DIV("n", 16) }; +static const RadConstraint cQuantI8g[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_W8_GROUP), + C_DIV("n", 4) }; +/* Not `C_IN("act", "silu sigmoid")`: `act` is optional on the op (a graph may carry libref's integer + * `mode` instead, and libref's own default is silu), and a band that states neither would resolve to + * nothing. The shim reads `act`, falls back to `mode`, then to silu, and refuses a gelu -- the + * activation whose kernel this unit does not carry -- with RAD_E_UNSUPPORTED. */ +static const RadConstraint cGateQuant[] = { C_IN("dtype", "bf16"), + C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", 4) }; +static const RadConstraint cDequantFp8[] = { C_IN("dtype", "fp8_e4m3"), + C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", 4) }; +static const RadConstraint cDequantE5[] = { C_IN("dtype", "fp8_e5m2"), + C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", 4) }; +static const RadConstraint cDequantI8[] = { C_IN("dtype", "i8"), C_EQ("group", R3D_W8_GROUP), + C_DIV("n", 4) }; + +/* The GEMMs. The skinny row's band is the decode and verify height: 16 rows, which is a speculative + * verify's ceiling with room to spare, and below the height where staging the activations through + * LDS starts to pay. K even, because the inner loop consumes pairs; N unconstrained, because a wave + * covering N tiles the tail. + * + * No upper bound on N: the vocabulary and the feed-forward widths are 11008, 14336, 128256 and + * whatever a given checkpoint's `intermediate_size` is, and a bound would refuse them. */ +static const RadConstraint cGemmM16[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 16), + C_DIV("K", 2), C_GE("N", 1) }; +/* The vocabulary projection. **No `dtype` constraint, and the reason is the engine's, not the + * kernel's**: the band this op is declared with carries the geometry (M, n_vocab, n_embd) and not a + * dtype key -- the head's dtype is a property of the weight, which is why libref's own logits row + * answers it with a `check_dtypes` hook and not with a constraint. A constraint on a key the + * geometry does not carry serves nobody: with `dtype in {bf16}` declared, the engine resolves a + * host kernel and no device one and refuses to start, so the dtype is refused where it is read, at + * the shim, naming the widening the kernel does. + * `n_embd` in 32-code chunks is the entry's own rule (K % 32), stated so a band outside it is + * refused at declare rather than at launch. `n_vocab`'s floor is the store's granularity: a row + * writes 16-byte runs, so a plane four ids wide is the narrowest it can read, and a band narrower + * than that -- a shard's padding, a 1-id test vocabulary -- is refused by the constraint and not by + * the launch. Above the floor the grid is vocab-wide at every M, so a 320-wide vocabulary and a + * 130560-wide one are the same kernel. */ +static const RadConstraint cLogitsGemm[] = { C_GE("M", 1), C_GE("n_vocab", 4), + C_DIV("n_embd", 32) }; +/* The tiled GEMM at prefill heights. M >= 17 is the complement of cGemmM16's M <= 16 by + * construction, so the two rows never compete for a band: the skinny shape (a wave a run of + * columns, the weight streamed past registers) is right up to 16 rows and wrong above it, and the + * 128x128 tile is the reverse. K % 32 is the tile's k-chunk and N >= 8 the bf16 store run, for the + * same reason cLogitsGemm states its floor: what the kernel cannot read is in the constraints. */ +/* The quantised GEMM above the decode heights. Here `dtype` IS the operand scheme -- gemm_q_shape + * switches on it -- so C_IN filters, which is the distinction from logits_gemm, where the band's + * dtype names the activation and C_IN filters nothing. M >= 17 is the complement of + * gemm_nt_q_fp8a8_m16's M <= 16 -- read from its constraint, not from its name: a higher floor + * would leave 17..64 unserved, and a 209-row batched decode is the shape a serving card spends + * most of its life in. The tile's k-chunk (32) divides the container's scale + * block (128), which is why `group` is an equality and `K` a divisibility. */ +static const RadConstraint cGemmQFP8Tiled[] = { C_IN("dtype", "fp8a8 fp8a8f32"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 17), + C_DIV("K", 128) }; +/* The OCP-MXFP4 rows: the weight is e2m1 with one e8m0 scale per 32 of K, the activation's + * scale per 128 -- both fixed by the format, so the `group` key carries no kernel-side meaning + * and the rows do not constrain it (the reference derives the planes from it). K dividing 128 + * carries the 32-block; the band split is the fp8a8 one, 16 at the ceiling and 17 at the floor, + * and the dtype carries the whole scheme. */ +static const RadConstraint cGemmQMxfp4a8M16[] = { C_IN("dtype", "mxfp4a8"), + C_GE("M", 1), + C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; +static const RadConstraint cGemmQMxfp4a8Tiled[] = { C_IN("dtype", "mxfp4a8"), + C_GE("M", 17), + C_DIV("K", 128) }; + +/* The symmetric int4 / int8 weight grids at decode heights: the block is the weight's scale + * group (128), and the band is the m16 one -- M > 16 is the tiled rows', and the 8-bit grid at + * prefill heights is declared out. */ +static const RadConstraint cGemmQW4A8M16[] = { C_IN("dtype", "w4a8"), + C_GE("M", 1), C_LE("M", 16), + C_DIV("K", 128), C_GE("N", 1) }; +static const RadConstraint cGemmQW8A8M16[] = { C_IN("dtype", "w8a8"), + C_GE("M", 1), C_LE("M", 16), + C_DIV("K", 128), C_GE("N", 1) }; + +static const RadConstraint cGemmNTTiled[] = { C_IN("dtype", "bf16"), C_GE("M", 17), C_DIV("K", 32), + C_GE("N", 8) }; +/* The quantised GEMM: the scheme names the row, the weight's block is the container's, and a split + * must land on a block boundary (gemm_tune_valid). */ +/* The block: `group` is required and every band names it, so the row states it. `pb1` and `pb2` are + * OPTIONAL, and a constraint on a key the band omits does not hold -- a model whose container + * declares the default block says nothing about pb1, and constraining it would make every one of + * that model's GEMM bands fall through to the reference and its host kernel -- 259 ops on one + * 2B model. The launcher defaults them to `group` (r3d_gemm_fp8a16_nt_m1.hip) and refuses a + * pb2 that is not the code group, which is the container's own invariant: the K block IS the code + * group, so a band naming pb2 unequal to group resolves to this row and is refused at launch. */ +static const RadConstraint cGemmQFp8a16[] = { C_IN("dtype", "fp8a16"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), + C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; +static const RadConstraint cGemmQFp8a8[] = { C_IN("dtype", "fp8a8"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), + C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; +/* The int8 GEMM's constraints are written ahead of its row: a row naming an entry point that is + * not in the library is an undefined symbol, and the plugin would fail to load, taking every other + * row with it. */ +static const RadConstraint cGemmQI8[] = { C_IN("dtype", "i8a8"), + C_EQ("group", R3D_W8_GROUP), C_GE("M", 1), + C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; + +/* ================================================================== the rows + * + * Declaration order is the tie-break within one priority, so rows that share an op are declared + * narrowest first. + */ +/* The constraints above are written ahead of the rows that use them, for the same reason the + * schemas are: the table reads as one document. A constraint array with no row is not an error, so + * the file builds; the comment above each says which row it serves. */ + +/* ================================================================== the fused-MLP rows + * + * The two rows the llama graphs ask for that the model unit serves. `silu_mul` constrains + * nothing but the dtype and an even `n`: `act` is not in this op's parameter list (it is the fused + * form of one fixed activation), and a constraint on a key the geometry lacks does not hold, so a + * row built on the act_mul constraints would resolve to no band at all. `rmsnorm_quant_fp8` states + * the group the kernel covers with a wave and requires it to divide `n`; the standalone quantiser's + * `n % 4` would admit a band this kernel refuses, and a row that resolves at declare and fails at + * launch is the shape of bug this file exists to prevent. + */ +static const RadConstraint cSiluMul[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; +static const RadConstraint cRmsQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_FP8_BLOCK), + C_DIV("n", R3D_FP8_BLOCK) }; + +/* The sampler's pre-filters constrain `n_vocab` and nothing else. The bands an architecture emits + * for these ops carry `n_vocab` and `M` (plus `vocab_off`, and `k` for logprobs) and no `dtype` + * key, so a row that constrained a dtype would constrain a key the geometry lacks and resolve to no + * band at all. The dtype is f32; the shims check it on the tensor, which is where a dtype belongs + * when the geometry does not name it. `k <= 64` is the depth of the logprobs kernel's pool, so the + * row serves exactly the bands its launcher accepts. + */ +static const RadConstraint cSampleF32[] = { C_GE("n_vocab", 1) }; +static const RadConstraint cSampleLogprobs[] = { C_GE("n_vocab", 1), C_GE("k", 1), C_LE("k", 64) }; + +/* The attention rows bind the two dtype keys, the head width the kernel's tile is built for, and + * the q_len bucket boundary the two kernels are split at. `gqa`, `window` and `causal` are left + * free: the kernel walks the mask for any gqa the shim accepts and any window, and a constraint on + * them would only exclude bands it serves. */ +static const RadConstraint cAttnBf16Decode[] = { C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), + C_EQ("head_dim", 128), C_LE("q_len", 16) }; +static const RadConstraint cAttnBf16Prefill[] = { C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), + C_EQ("head_dim", 128), C_GE("q_len", 17) }; +static const RadConstraint cAttnFp8Decode[] = { C_IN("q_dtype", "bf16"), + C_IN("kv_dtype", "fp8_e4m3"), + C_EQ("head_dim", 128), C_LE("q_len", 16) }; +static const RadConstraint cAttnFp8Prefill[] = { C_IN("q_dtype", "bf16"), + C_IN("kv_dtype", "fp8_e4m3"), + C_EQ("head_dim", 128), C_GE("q_len", 17) }; + +/* `row_topk` is banded on dtype, so it gets two rows; the candidate stages are banded on `n_cand`, + * whose ceiling is the kernel's: five f32 arrays of n_cand in LDS is 20 KiB of the 64 KiB, and a + * wider band is refused by the shim (RAD_E_SHAPE), so the row states the ceiling and resolves for + * exactly what it serves. The vocab stages carry `n_vocab` and no dtype key, and the logits are f32 + * by the shim's check on the tensor. + */ +static const RadConstraint cRowTopkBf16[] = { C_IN("dtype", "bf16"), C_GE("N", 1), C_GE("R", 1) }; +static const RadConstraint cRowTopkF32[] = { C_IN("dtype", "f32"), C_GE("N", 1), C_GE("R", 1) }; +static const RadConstraint cSampleCand[] = { C_GE("n_cand", 1), C_LE("n_cand", 1024) }; + +/* Every key the walk reads is required and in the band, so all of them are bound -- `top_k <= 256` + * is one lane a candidate. `anchor_stride` is deliberately NOT bound: it is optional, defaults to + * 1, and the kernel serves any value at or above 1, so a band that omits it must still resolve. */ +/* The block is one key for three things at once: the weight's K block, its row block and the + * quantiser's group. `act` is C_IN because it is a required string here, not the optional `mode` + * form. M <= 64 is the ceiling the launcher serves; 47 of MiniCPM5-2B's 48 bands are M=64. */ +/* The container's 2-bit vocab weights. `group` is one key for the weight's K block and the scale's + * block, as everywhere in this family; K must also be a multiple of the launcher's chunk + * (2048 / M-tile), which the launcher refuses and the row does not pretend to cover. */ +static const RadConstraint cGemmQW2A8[] = { C_IN("dtype", "w2a8"), C_EQ("group", R3D_FP8_BLOCK), + C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), + C_GE("N", 1) }; + +/* The packed-code grids at the heights gemm_nt_q_w2a8_m16 declines. The grid is the container's -- + * one scale and one zero per `group` of codes on a {1, group} plane -- so `group` is the block, and + * K divides by it because a staged 32-code chunk must sit inside one scale group. */ +static const RadConstraint cGemmQW2A8Tiled[] = { C_IN("dtype", "w2a8 w4a8_asym"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 17), + C_DIV("K", 128) }; + +static const RadConstraint cGemmGated[] = { C_IN("dtype", "fp8a8"), + C_IN("act", "silu sigmoid"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), + C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 2), + C_GE("N", 2) }; + +static const RadConstraint cDflashSelect[] = { C_IN("dtype", "bf16"), C_GE("M", 1), + C_GE("steps", 1), C_GE("top_k", 1), + C_LE("top_k", 256), C_GE("rank", 1), + C_GE("n_vocab", 1) }; + +static const RadKernelInfo kKernels[] = { +/* ------------------------------------------------------------------ r3d_model_bf16.hip + * + * One workgroup a row. The `shape` column states the geometry the grid is built for; the + * `computes` column states the arithmetic, in the order the kernel performs it. + */ +{ "rmsnorm_bf16", "rmsnorm", "norm", + "root-mean-square norm with a gain, two passes over the row", + "any n; a workgroup a row; the sum of squares accumulates in f32 and only the store narrows", + "bf16 x and y, bf16 or f32 gain, fp32 reduction", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cNormBf16), NOTUNE, + nullptr, nullptr, r3d_rad_rmsnorm, nullptr, nullptr, nullptr, + r3d_shape_rmsnorm }, + +{ "rmsnorm_f32", "rmsnorm", "norm", + "root-mean-square norm with a gain, two passes over the row", + "any n; a workgroup a row", + "f32 x, y and gain, fp32 reduction", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cNormF32), NOTUNE, + nullptr, nullptr, r3d_rad_rmsnorm, nullptr, nullptr, nullptr, + r3d_shape_rmsnorm }, + +{ "layernorm_bf16", "layernorm", "norm", + "layer norm with a gain and an optional bias, mean and variance in two passes", + "any n; a workgroup a row; both passes accumulate in f32", + "bf16 x, y, gain and bias, fp32 reduction", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cNormBf16), NOTUNE, + nullptr, nullptr, r3d_rad_layernorm, nullptr, nullptr, nullptr, + r3d_shape_layernorm }, + +{ "add_bf16", "add", "elem", + "a + b, with b's row broadcast and an optional divisor", + "any n; a workgroup a row; f32 arithmetic, one narrowing at the store", + "bf16 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_add, nullptr, nullptr, nullptr, + r3d_shape_add }, + +{ "add_f32", "add", "elem", + "a + b, with b's row broadcast and an optional divisor", + "any n; a workgroup a row", + "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r3d_rad_add, nullptr, nullptr, nullptr, + r3d_shape_add }, + +{ "mul_bf16", "mul", "elem", + "a * b, with b's row broadcast", + "any n; a workgroup a row", + "bf16 in and out, f32 product, one narrowing at the store", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_mul, nullptr, nullptr, nullptr, + r3d_shape_mul }, + +{ "mul_f32", "mul", "elem", + "a * b, with b's row broadcast", + "any n; a workgroup a row", + "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r3d_rad_mul, nullptr, nullptr, nullptr, + r3d_shape_mul }, + +/* The casts, one row per pair the engine issues. bf16 to f32 and back is the residual stream's + * width change; i64 to f32 is a position table read by a rotary; the integer pairs move token ids + * between planes and must not pass through f32, which loses the low bits above 2^24. */ +{ "cast_bf16_f32", "cast", "elem", "bf16 to f32, exact", "any n; a wave 128 elements", + "bf16 in, f32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastBf16F32), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_f32_bf16", "cast", "elem", "f32 to bf16, one rounding", "any n; a wave 128 elements", + "f32 in, bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastF32Bf16), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_bf16_bf16", "cast", "elem", "bf16 to bf16, a copy", "any n; a wave 128 elements", + "bf16 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastBf16), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_f32_f32", "cast", "elem", "f32 to f32, a copy", "any n; a wave 128 elements", + "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastF32), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_i64_f32", "cast", "elem", "i64 to f32", "any n; a wave 128 elements", + "i64 in, f32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastI64F32), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_i32_i64", "cast", "elem", "i32 to i64, exact", "any n; a wave 128 elements", + "i32 in, i64 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastI32I64), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_i64_i32", "cast", "elem", "i64 to i32, the ids' narrowing", "any n; a wave 128 elements", + "i64 in, i32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastI64I32), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "silu_bf16", "silu", "elem", "x * sigmoid(x), the sigmoid in f32", "any n; a wave 128 elements", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_silu, nullptr, nullptr, nullptr, r3d_shape_silu }, + +{ "silu_f32", "silu", "elem", "x * sigmoid(x)", "any n; a wave 128 elements", "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r3d_rad_silu, nullptr, nullptr, nullptr, r3d_shape_silu }, + +{ "gelu_bf16", "gelu", "elem", + "the exact erf GELU: 0.5 * x * (1 + erf(x / sqrt(2)))", + "any n; a wave 128 elements; erff, the accurate form, not the tanh approximation", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_gelu, nullptr, nullptr, nullptr, r3d_shape_gelu }, + +{ "sigmoid_bf16", "sigmoid", "elem", "1 / (1 + exp(-x))", "any n; a wave 128 elements", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_sigmoid, nullptr, nullptr, nullptr, r3d_shape_sigmoid }, + +{ "act_mul_silu_bf16", "act_mul", "elem", + "silu(gate) * up, the gated feed-forward's middle", + "any n; a workgroup a row; the gate is operand 0", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cActSilu), NOTUNE, + nullptr, nullptr, r3d_rad_act_mul, nullptr, nullptr, nullptr, r3d_shape_act_mul }, + +{ "act_mul_gelu_bf16", "act_mul", "elem", + "gelu(gate) * up, the exact erf form", + "any n; a workgroup a row", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cActGelu), NOTUNE, + nullptr, nullptr, r3d_rad_act_mul, nullptr, nullptr, nullptr, r3d_shape_act_mul }, + +{ "act_mul_sigmoid_bf16", "act_mul", "elem", "sigmoid(gate) * up", "any n; a workgroup a row", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cActSigmoid), NOTUNE, + nullptr, nullptr, r3d_rad_act_mul, nullptr, nullptr, nullptr, r3d_shape_act_mul }, + +{ "softmax_f32", "softmax", "elem", + "row softmax with the maximum subtracted, the denominator summed in ascending order", + "any n; a workgroup a row", + "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSoftmax), NOTUNE, + nullptr, nullptr, r3d_rad_softmax, nullptr, nullptr, nullptr, r3d_shape_softmax }, + +{ "scale_bf16", "scale", "elem", "x * s, one scalar over the whole output", + "any n; a wave 128 elements", "bf16 in and out, fp32 product", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_scale, nullptr, nullptr, nullptr, r3d_shape_scale }, + +{ "scale_f32", "scale", "elem", "x * s, one scalar over the whole output", + "any n; a wave 128 elements", "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r3d_rad_scale, nullptr, nullptr, nullptr, r3d_shape_scale }, + +{ "fill_bf16", "fill", "elem", "the value over [M, n]", "any n; a wave 128 elements", + "bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cFillBf16), NOTUNE, + nullptr, nullptr, r3d_rad_fill, nullptr, nullptr, nullptr, r3d_shape_fill }, + +{ "fill_f32", "fill", "elem", "the value over [M, n]", "any n; a wave 128 elements", "f32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cFillF32), NOTUNE, + nullptr, nullptr, r3d_rad_fill, nullptr, nullptr, nullptr, r3d_shape_fill }, + +{ "fill_i32", "fill", "elem", "the value over [M, n], the value as an integer", + "any n; a wave 128 elements", "i32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cFillI32), NOTUNE, + nullptr, nullptr, r3d_rad_fill, nullptr, nullptr, nullptr, r3d_shape_fill }, + +{ "fill_i64", "fill", "elem", "the value over [M, n], the value as an integer", + "any n; a wave 128 elements", "i64 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cFillI64), NOTUNE, + nullptr, nullptr, r3d_rad_fill, nullptr, nullptr, nullptr, r3d_shape_fill }, + +{ "rope_bf16", "rope", "attn", + "rotary positions applied in place to a fused qkv row, neox and gptj pair layouts", + "head_dim even; rotary_dim optional and even, defaulting to head_dim; a wave a head; the " + "angles from accurate powf and sincosf, the position divided by `scale`", + "bf16 qkv in place, i32 positions, fp32 angles", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRope), NOTUNE, + nullptr, nullptr, r3d_rad_rope, nullptr, nullptr, nullptr, r3d_shape_rope }, + +{ "kv_store_bf16", "kv_store", "attn", + "K and V into a paged cache at the slot mapping, bf16 to bf16", + "any head_dim and block size; a wave a (token, head) pair; a negative slot skipped", + "bf16 k and v, i32 slot mapping, bf16 cache", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cKvBf16), NOTUNE, + nullptr, nullptr, r3d_rad_kv_store, nullptr, nullptr, nullptr, r3d_shape_kv_store }, + +{ "kv_store_f16", "kv_store", "attn", + "K and V into a paged cache at the slot mapping, bf16 to f16", + "any head_dim and block size; a wave a (token, head) pair", + "bf16 k and v, i32 slot mapping, f16 cache", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cKvF16), NOTUNE, + nullptr, nullptr, r3d_rad_kv_store, nullptr, nullptr, nullptr, r3d_shape_kv_store }, + +{ "kv_store_fp8", "kv_store", "attn", + "K and V into a paged cache at the slot mapping, encoding E4M3 with the store's scale", + "any head_dim and block size; a wave a (token, head) pair; the scale divides before the encode", + "bf16 k and v, i32 slot mapping, fp8_e4m3 cache", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cKvFp8), NOTUNE, + nullptr, nullptr, r3d_rad_kv_store, nullptr, nullptr, nullptr, r3d_shape_kv_store }, + +{ "embed_lookup_bf16", "embed_lookup", "gemm", + "the codebook row an id names, scaled, with out-of-shard ids yielding a zero row", + "any n_embd; a workgroup a row of the table", + "bf16 table and output, i32 ids", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cEmbed), NOTUNE, + nullptr, nullptr, r3d_rad_embed_lookup, nullptr, nullptr, nullptr, r3d_shape_embed_lookup }, + +{ "gather_rows_bf16", "gather_rows", "elem", "y[r] = x[idx[r]]", + "any n; a workgroup a row", "bf16 rows, i32 indices", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGatherBf16), NOTUNE, + nullptr, nullptr, r3d_rad_gather_rows, nullptr, nullptr, nullptr, r3d_shape_gather_rows }, + +{ "gather_rows_f32", "gather_rows", "elem", "y[r] = x[idx[r]]", + "any n; a workgroup a row", "f32 rows, i32 indices", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGatherF32), NOTUNE, + nullptr, nullptr, r3d_rad_gather_rows, nullptr, nullptr, nullptr, r3d_shape_gather_rows }, + +{ "scatter_rows_bf16", "scatter_rows", "elem", "x[idx[r]] = v[r]", + "any n; a workgroup a row; distinct indices, so no two rows write one destination", + "bf16 rows, i32 indices", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cScatterBf16), NOTUNE, + nullptr, nullptr, r3d_rad_scatter_rows, nullptr, nullptr, nullptr, r3d_shape_scatter_rows }, + +/* ------------------------------------------------------------------ r3d_quant_fp8.hip + * + * Plain row-major code planes against one f32 scale per (row, group). No fragment permutation for + * the codes a dot2 GEMM reads: it reads them in the order they are stored, which is the whole + * reason a container converted on this card is readable by libref and by `rad-convert` on any other + * card. The one plane that keeps libref's permutation is `quant_act_i8`'s, whose order is part of + * what the op means -- see the row. + */ +{ "quant_act_fp8_bf16", "quant_act_fp8", "quant", + "symmetric per-(row, group) E4M3: scale = amax * (1/448), the codes the value times 1/scale", + "group 128; n a multiple of 4; a wave covers four columns a lane, so a group is a quarter-wipe", + "bf16 in, fp8_e4m3 codes, f32 scales", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cQuantFp8), NOTUNE, + nullptr, nullptr, r3d_rad_quant_act_fp8, nullptr, nullptr, nullptr, + r3d_shape_quant_act_fp8 }, + +/* The per-row int8, in libref's step order. The order is the op's, not the kernel's convenience: + * the codes are the WMMA A-fragment's, and the plane is what the oracle compares, so this row keeps + * the permutation and the kernel's store address carries it. libr3d's own int8 GEMM reads the + * row-major `quant_act_i8g` plane two rows below, which is the pairing libref's comment states; a + * gfx11 card has no consumer for the step-ordered plane and serves the op so an architecture that + * emits it resolves to a kernel here rather than to the reference. */ +{ "quant_act_i8_bf16", "quant_act_i8", "quant", + "symmetric int8 with one scale per row: scale = max(amax, 1e-8) / 127, ties to even, saturating", + "n a multiple of 16, a whole WMMA step; a wave a row of the row sums; the codes stored in the " + "step order, the middle two dwords of every 16 bytes exchanged", + "bf16 in, i8 codes, f32 scale per row and the group-major row sums", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cQuantI8), NOTUNE, + nullptr, nullptr, r3d_rad_quant_act_i8, nullptr, nullptr, nullptr, + r3d_shape_quant_act_i8 }, + +{ "quant_act_i8g_bf16", "quant_act_i8g", "quant", + "symmetric per-(row, group) int8: scale = amax / 127, 1 for an all-zero group, ties to even", + "group 128; n a multiple of 4; a wave covers four columns a lane, so a lane's codes are one " + "dword and a wave's are 128 contiguous bytes", + "bf16 in, i8 codes row-major, f32 scales", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cQuantI8g), NOTUNE, + nullptr, nullptr, r3d_rad_quant_act_i8g, nullptr, nullptr, nullptr, + r3d_shape_quant_act_i8g }, + +{ "gated_quant_fp8_bf16", "gated_quant_fp8", "quant", + "silu(gate) * up over a fused [M, 2n] projection, quantised in the same pass", + "group 128; n a multiple of 4; the product is rounded to bf16 before its amax, as every fused " + "implementation rounds it", + "bf16 gate_up in, fp8_e4m3 codes, f32 scales, optional bf16 product", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGateQuant), NOTUNE, + nullptr, nullptr, r3d_rad_gated_quant_fp8, nullptr, nullptr, nullptr, + r3d_shape_gated_quant_fp8 }, + +{ "dequant_fp8", "dequant", "quant", + "E4M3 code times its group's f32 scale", + "group 128; n a multiple of 4", + "fp8_e4m3 codes and f32 scales in, bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cDequantFp8), NOTUNE, + nullptr, nullptr, r3d_rad_dequant, nullptr, nullptr, nullptr, r3d_shape_dequant }, + +{ "dequant_e5m2", "dequant", "quant", + "E5M2 code times its group's f32 scale", + "group 128; n a multiple of 4", + "fp8_e5m2 codes and f32 scales in, bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cDequantE5), NOTUNE, + nullptr, nullptr, r3d_rad_dequant, nullptr, nullptr, nullptr, r3d_shape_dequant }, + +{ "dequant_i8", "dequant", "quant", + "int8 code times its group's f32 scale", + "group 128; n a multiple of 4", + "i8 codes and f32 scales in, bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cDequantI8), NOTUNE, + nullptr, nullptr, r3d_rad_dequant, nullptr, nullptr, nullptr, r3d_shape_dequant }, + +/* ------------------------------------------------------------------ r3d_gemm_bf16_nt_m16.hip + * + * The decode GEMM: M is 1 to 16, so a wave owns a run of N columns and streams the weight's rows + * past an activation kept in registers. There is no fragment layout to fill, which is why this + * kernel reads the checkpoint's rows in order. + */ +{ "gemm_nt_bf16_m16", "gemm_nt", "gemm", + "a[M,K] @ b[N,K]^T for the decode and verify heights, f32 accumulate, one narrowing at the store", + "M <= 16; a wave a run of N columns, one output element a lane, k ascending in pairs; split-K " + "over scratch with the partials reduced in split order; a ragged K runs the scalar tail at sk=1", + "bf16 a, b and y, fp32 accumulation; the pair is folded into the accumulator by one rounding, so " + "about 0.3% of a long-K output lands one bf16 store ulp from the reference's, and no output is " + "further. bf16 reaches the dot as f16, exact over f16's normal range, which every checkpoint's " + "weights and activations live inside", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_M16, + ROW(cGemmM16), tGemmM16, NELEM(tGemmM16), gemm_tune_valid, + nullptr, nullptr, r3d_rad_gemm_nt_bf16_m16, + [](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); }, + nullptr, nullptr, r3d_shape_gemm_nt }, + +/* ------------------------------------------------------------------ r3d_gemm_fp8a16_nt_m1.hip + * + * The same shape against a block-scaled weight. The codes are E4M3, widened to f16 exactly and + * accumulated by dot2; the block scale is applied once per 128-element slab, after the slab's + * products, which is where the reference applies it. + */ +{ "gemm_nt_q_fp8a16_m16", "gemm_nt_q", "gemm", + "a[M,K] @ b[N,K]^T against E4M3 codes with a scale per 128x128 block", + "M <= 16, K a multiple of the block, group = pb2 = 128 and pb1 the rows sharing a scale row; a " + "wave a run of N columns; the codes widened to f16 exactly and the block scale applied after each " + "slab; a split ends on a block boundary (gemm_tune_valid)", + "bf16 a, fp8_e4m3 b, f32 b_scale, bf16 y, fp32 accumulation; an f32 a, a bf16 scale plane, a " + "ragged last block and the zero-point planes a_sum and b_ref are refused, not approximated", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQFp8a16), tGemmQ, NELEM(tGemmQ), gemm_tune_valid, + nullptr, nullptr, r3d_rad_gemm_nt_q_fp8, + [](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); }, + nullptr, nullptr, r3d_shape_gemm_nt_q }, + +{ "gemm_nt_q_fp8a8_m16", "gemm_nt_q", "gemm", + "quant_act_fp8's codes and scales against E4M3 codes with a scale per 128x128 block", + "M <= 16, K a multiple of the block; both axes coded, so both scales apply", + "fp8_e4m3 a and b, f32 scales on both, bf16 y, fp32 accumulation", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQFp8a8), tGemmQ, NELEM(tGemmQ), gemm_tune_valid, + nullptr, nullptr, r3d_rad_gemm_nt_q_fp8, + [](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); }, + nullptr, nullptr, r3d_shape_gemm_nt_q }, + +{ "gemm_nt_q_mxfp4a8_m16", "gemm_nt_q", "gemm", + "fp8 a against OCP-MXFP4 weights: e2m1 codes, two a byte, with an e8m0 scale per 32 of K, the " + "block's partials scaled and summed in ascending k", + "M <= 16, K a multiple of 128; one wave a weight row, 64 codes a lane, the lane's two 32-blocks " + "scaled at the block boundary", + "fp8_e4m3 a with an f32 scale per (row, 128 of K), fp4_e2m1 codes with an e8m0 scale per (row, " + "32 of K) -- `b_ref`, the same exponent plane, is accepted and ignored, bf16 y, fp32 " + "accumulation; a reserved e8 (0, 255) is refused", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQMxfp4a8M16), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_mxfp4a8_m16, + nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_mxfp4a8 }, + +{ "gemm_nt_q_w4a8_m16", "gemm_nt_q", "gemm", + "the symmetric 4-bit weight grid at decode: signed int4 codes against int8 activations, the " + "group's integer sub-sum scaled once by the activation's row scale and the weight's group scale", + "M <= 16, K a multiple of 128; one wave a weight row, 64 codes a lane from two 16-byte loads, " + "the pair fold at the group boundary, the group terms scaled in the epilogue", + "I8 a in the step order with an f32 scale per row, I4 codes b (two a byte) with an f16 scale " + "per (row, 128 of K), bf16 y, fp32 accumulation; the sub-sums are exact integers under 2^24, " + "and the store is the only narrowing; no zero point, so no a_sum", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQW4A8M16), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_w4a8_m16, + nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_w4a8 }, + +{ "gemm_nt_q_w8a8_m16", "gemm_nt_q", "gemm", + "the symmetric 8-bit weight grid at decode: signed int8 codes against int8 activations, the " + "group's integer sub-sum scaled once by the activation's row scale and the weight's group scale", + "M <= 16, K a multiple of 128; one wave a weight row, 64 codes a lane from four 16-byte loads, " + "the pair fold at the group boundary, the group terms scaled in the epilogue", + "I8 a in the step order with an f32 scale per row, I8 codes b with an f16 scale per (row, 128 " + "of K), bf16 y, fp32 accumulation; the sub-sums are exact integers under 2^24, and the store is " + "the only narrowing; no zero point, so no a_sum; M > 16 is declared out", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQW8A8M16), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_w8a8_m16, + nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_w8a8 }, + + { "silu_mul_bf16", "silu_mul", "elem", + "silu(gate) * up over one fused gate_up plane, the gate the first half", + "any n; a workgroup a row; the activation is NOT narrowed before the product, as ref's is not " + "-- act_mul narrows it, over two operands, because the pair it replaces stored it", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSiluMul), NOTUNE, + nullptr, nullptr, r3d_rad_silu_mul, nullptr, nullptr, nullptr, r3d_shape_silu_mul }, + + { "rmsnorm_quant_fp8_bf16", "rmsnorm_quant_fp8", "quant", + "residual add, RMS norm and the E4M3 quantiser in one pass: a 5120-element bf16 plane a token " + "is written once and read once inside one kernel, where the pair writes it and reads it back", + "group 128 and a multiple of 128; a workgroup a row; the residual sum is stored before the " + "variance reads it, so the norm is over the bf16 sum, and the codes are taken over the bf16 " + "normalised value, which out_bf16 receives", + "bf16 x, residual, gain and optional out_bf16, fp8_e4m3 codes, f32 scales, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRmsQuantFp8), NOTUNE, + nullptr, nullptr, r3d_rad_rmsnorm_quant_fp8, nullptr, nullptr, nullptr, + r3d_shape_rmsnorm_quant_fp8 }, + + +/* ------------------------------------------------------------------ r3d_sample_pre_f32.hip + * + * The sampler's pre-filters: one workgroup a row over the logits plane. The history stages are + * sparse -- a row's history is a few hundred tokens against a vocabulary of 130560, so the + * reference's own shape, walk the window and not the row, is the fast shape too. + */ +{ "sample_penalties_f32", "sample_penalties", "sample", + "presence, frequency and repetition penalties from the row's history, in place", + "a workgroup a row; the count is taken from the token's FIRST occurrence forward, and the " + "repetition penalty is sign-dependent -- v > 0 divides, v < 0 multiplies -- as the reference has " + "it; a penalty of zero writes nothing", + "f32 logits, f32 params, i32 history; writes only inside the row's own n_vocab columns", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_penalties, nullptr, nullptr, nullptr, + r3d_shape_sample_penalties }, + +{ "sample_dry_f32", "sample_dry", "sample", + "the DRY penalty: a suffix of the history that repeats after a token penalises it, by its length", + "a workgroup a row; the longest repeat per token, capped at dry_allowed_length; the multiplier " + "grows by repeated multiply and stops at FLT_MAX/base, which is where an exponent would overflow; " + "one penalty per token, from its longest repeat, and the FIRST occurrence is the one written", + "f32 logits, f32 params, i32 history, u8 breakers; a breaker position ends a sequence and is " + "never penalised; a history no longer than dry_allowed_length penalises nothing", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_dry, nullptr, nullptr, nullptr, + r3d_shape_sample_dry }, + +{ "sample_ngram_ban_f32", "sample_ngram_ban", "sample", + "the n-grams the history shows inside the window are banned to -inf", + "a workgroup a row; the prefix compare over n-1 tokens, the ban landing on s[idx+n-1]; the " + "whitelist is removed from the banned set BEFORE the ban, so an exempt id survives; the window is " + "dry_penalty_last_n, and n = 0 bans nothing", + "f32 logits, f32 params, i32 history, i32 n-gram pairs, an optional i32 whitelist plane", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_ngram_ban, nullptr, nullptr, nullptr, + r3d_shape_sample_ngram_ban }, + +{ "sample_mask_f32", "sample_mask", "sample", + "the grammar's and the tool-caller's doing: every id whose bit is clear becomes -inf", + "a workgroup a row over 4080 words at this vocabulary; a word of all ones is skipped and the last " + "partial word honours n_vocab; a NEGATIVE mask_row skips the row, which is how an unconstrained " + "request ends up with no mask applied -- the descriptor calls the same thing " + "a shared row, and the body is the spec; the bound is the bitmask plane's own row count, not M, " + "so a row addressing the plane's second half is masked as the reference masks it", + "f32 logits, f32 params, i32 bitmask; a plane with fewer rows than the logits is refused " + "(RAD_E_SHAPE), the case the geometry never produces", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_mask, nullptr, nullptr, nullptr, + r3d_shape_sample_mask }, + +{ "sample_logprobs_f32", "sample_logprobs", "sample", + "the row's summary for the response: max, the sum of exp, and the k best (id, logit) pairs", + "one read of the logits plane where the reference reads it three (max, sum, k-list); the sum is " + "SUM exp(v - max) in DOUBLE, the reference's law, and a row's k-list is one insertion list in " + "registers, not an upper_bound per element; stats is [M][2 + 2k], and rows the flag leaves alone " + "are not written", + "f32 logits, f32 params, f32 stats; k <= 64 is the pool's depth and above it the shim refuses " + "(RAD_E_UNSUPPORTED); on a row that contains a NaN the reference's list freezes at the first k it " + "saw, because upper_bound over a NaN returns end and every later compare then fails -- this kernel " + "reports the row's true k-best, a divergence a plane has to be fed NaNs to reach", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleLogprobs), NOTUNE, + nullptr, nullptr, r3d_rad_sample_logprobs, nullptr, nullptr, nullptr, + r3d_shape_sample_logprobs }, + + +/* ------------------------------------------------------------------ r3d_attn_paged_h128.hip + * + * Paged attention, head_dim 128, banded on q_len. The two kernels share the block walk and differ + * in what a workgroup is: decode is one head group over 16 query rows with split-KV, prefill stages + * a 16-token query tile. The walk's block bounds are the WORKGROUP's -- a tile is staged once into + * LDS and every wave of the workgroup consumes it, and waves that narrowed the walk to their own + * query positions would stage different blocks over the same LDS, the last writer per 16-byte chunk + * winning. + */ +{ "attn_paged_bf16_decode", "attn_paged", "attn", + "paged attention over a bf16 cache: one head group a workgroup, 16-token tiles, split-KV", + "head_dim 128; q_len <= 16; two passes over the blocks -- scores are recomputed in the second so " + "the softmax sum accumulates ascending like the reference, and a masked key is never exponentiated; " + "the block bounds come from the workgroup's 16 rows, because the staged tile is shared", + "bf16 q and out, bf16 cache, i32 block_table and seqused; a descale on a bf16 cache is refused", + RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_DECODE, + ROW(cAttnBf16Decode), NOTUNE, + nullptr, nullptr, r3d_rad_attn_decode_h128, attn_scratch, nullptr, nullptr, + r3d_shape_attn_paged }, + +{ "attn_paged_bf16_prefill", "attn_paged", "attn", + "the same walk over a 16-token query tile, for a chunk that is wider than the decode bucket", + "head_dim 128; q_len >= 17; a workgroup is 4 waves over 16 query rows and one KV head; the tile's " + "idle lanes clamp to the last query row instead of reading past the q plane", + "bf16 q and out, bf16 cache, i32 block_table and seqused", + RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_PREFILL, + ROW(cAttnBf16Prefill), NOTUNE, + nullptr, nullptr, r3d_rad_attn_prefill_h128, attn_scratch, nullptr, nullptr, + r3d_shape_attn_paged }, + +{ "attn_paged_fp8_decode", "attn_paged", "attn", + "paged attention over an E4M3 cache, the descale riding the widening into the tile", + "head_dim 128; q_len <= 16; a 16-code chunk is the aligned 16-byte unit -- eight codes are 8 bytes " + "and a 16-byte load at a slot's odd half returns garbage; the descale " + "multiplies into the f16 tile, exact for a power-of-two scale inside f16's range", + "bf16 q and out, fp8_e4m3 cache, i32 block_table and seqused, f32 k_descale and v_descale " + "optional (absent is scale 1.0)", + RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_DECODE, + ROW(cAttnFp8Decode), NOTUNE, + nullptr, nullptr, r3d_rad_attn_decode_h128, attn_scratch, nullptr, nullptr, + r3d_shape_attn_paged }, + +{ "attn_paged_fp8_prefill", "attn_paged", "attn", + "the E4M3 cache over a 16-token query tile", + "head_dim 128; q_len >= 17; the same staged walk as the bf16 prefill, with the codes widened as " + "they land in the tile", + "bf16 q and out, fp8_e4m3 cache, i32 block_table and seqused, f32 descales optional (absent is " + "scale 1.0)", + RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_PREFILL, + ROW(cAttnFp8Prefill), NOTUNE, + nullptr, nullptr, r3d_rad_attn_prefill_h128, attn_scratch, nullptr, nullptr, + r3d_shape_attn_paged }, + + +/* ------------------------------------------------------------------ r3d_sample_f32.hip + * + * The sampler's spine: the row's top-R, and the stages that turn the top-R's candidate plane into + * one token. The candidate set is the contract between them -- `cand_val` carries LOGITS, so each + * narrowing stage takes its own softmax and the stages compose in any order; a dropped candidate is + * `cand_idx` -1 and `cand_val` -inf; the set is descending by value then ascending by id; and every + * stage leaves a greedy row byte-identical, because a greedy row's token is `sample_argmax`'s. + * `topk_next` is a sort by (-value, +column) wearing a loop -- the rule `v == *pv && i <= *pi` is + * "the next one in a run of equal values" -- so one pass keeping the best R returns the reference's + * R pairs, in its order, with its tie-breaks to the lower column. + */ +{ "row_topk_bf16", "row_topk", "moe", + "the row's top R, with the reference's tie-breaks, in one scan of the row", + "one pass keeps the best R in the reference's order, where the reference scans the row R times; " + "R beyond a pass's pool rescans with the chain's state carried, so the answer is the reference's " + "at any R and only the time grows; a slot a short row cannot fill is idx -1 and val -inf; a row " + "that opens with a NaN reports (0, NaN) R times, because the reference's seed takes the first " + "element it sees and nothing displaces a NaN", + "bf16 x, i32 idx [M,R], f32 val [M,R], an optional f32 pairs [M,R,2] (the id's bits and the value)", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRowTopkBf16), NOTUNE, + nullptr, nullptr, r3d_rad_row_topk, nullptr, nullptr, nullptr, r3d_shape_row_topk }, + +{ "row_topk_f32", "row_topk", "moe", + "the row's top R over an f32 plane, in one scan", + "the same one-pass insertion as the bf16 row; the band's router row costs the reference 7.0 GB of " + "scans and this kernel 468 MB, and at the band it is the sifts that cost, not the bytes: the f32 " + "plane moves half again the traffic for the same 23 ms", + "f32 x, i32 idx, f32 val, optional f32 pairs", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRowTopkF32), NOTUNE, + nullptr, nullptr, r3d_rad_row_topk, nullptr, nullptr, nullptr, r3d_shape_row_topk }, + +{ "sample_argmax_f32", "sample_argmax", "sample", + "the greedy token: the row's argmax, ties to the lower id", + "a workgroup a row; the max is a strict `>`, so a NaN is never adopted -- the reference's scan " + "keeps the first element it sees, which is why a row opening with a NaN yields token 0, and a row " + "of all -inf yields 0; the stage that reads no scalar at all, so a missing params operand is not " + "a refusal: the reference describes the operand and does not read it", + "f32 logits, i32 token [M]; the params plane is described, not read", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_argmax, nullptr, nullptr, nullptr, + r3d_shape_sample_argmax }, + +{ "sample_temp_f32", "sample_temp", "sample", + "temperature, in place: every logit multiplied by the reciprocal of temp", + "a workgroup a row; a row is skipped when temp is not positive or is exactly 1; the reciprocal is " + "formed ONCE, as the reference forms it, not a divide per element -- a divide per element is a " + "different f32, and the argmax after it is only bit-exact under the transcription", + "f32 logits INOUT, f32 params; the most expensive row in the slice at 11 ms a step, and the cost " + "is the plane: 1 GiB in and 1 GiB out for one multiply an element", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_temp, nullptr, nullptr, nullptr, + r3d_shape_sample_temp }, + +{ "sample_topk_f32", "sample_topk", "sample", + "the candidate set the rest of the sampler draws from, written whole every step", + "the set's width is the BUFFER's, not the row's: top_k 40 in a 1024-wide plane is 40 candidates " + "and 984 holes, and a stale candidate left in a hole is a token the pick can draw; the row's " + "top_k only narrows inside the width, and `<= 0` or a width above it takes the whole width, as " + "the reference clamps; cand_val carries the LOGIT, which is what lets the narrowing stages " + "compose in any order; a greedy row takes none", + "f32 logits, f32 params, i32 cand_idx [M,n_cand] (local columns), f32 cand_val, an optional i32 " + "pairs [M,2*n_cand] of (global id, logit bits) with 0xffffffff for a hole; n_cand <= 1024", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_topk, nullptr, nullptr, nullptr, + r3d_shape_sample_topk }, + +{ "sample_pick_f32", "sample_pick", "sample", + "the draw: one uniform over the candidate set's own softmax, in index order", + "splitmix64 over the seed and the position, the top 24 bits over 2^24, keyed by the pick's own " + "key; the exps are computed by the wave in parallel and the CDF accumulates on one lane in " + "candidate index order, because the order is the law -- parallel values, serial sums; an empty " + "set writes -1; a set whose mass falls below u falls back to the last candidate above -infinity, " + "which is why a masked tail is never the fallback", + "i32 cand_idx, f32 cand_val, f32 params (seed, pos), i32 token [M]; only token is written", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_pick, nullptr, nullptr, nullptr, + r3d_shape_sample_pick }, + +{ "sample_topp_f32", "sample_topp", "sample", + "nucleus: the shortest prefix whose cumulative probability reaches top_p", + "the stage takes its own softmax over the set (max by strict `>` over live candidates, then exp, " + "then the predicate), because the set carries logits; at least one candidate survives; it is a " + "PREFIX rule in the set's order, which is why the set's order is contract and why no stage sorts " + "it", + "i32 cand_idx INOUT, f32 cand_val INOUT, f32 params; off when top_p is out of range; a greedy row " + "and an all-holes row are left alone", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_topp, nullptr, nullptr, nullptr, + r3d_shape_sample_topp }, + +{ "sample_minp_f32", "sample_minp", "sample", + "min-p: drop what is below p times the best candidate's probability", + "the stage's own softmax again; the best always survives; a relative cut under the best, not a " + "prefix, so it composes with top-p in either order", + "i32 cand_idx INOUT, f32 cand_val INOUT, f32 params; off when min_p is out of range", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_minp, nullptr, nullptr, nullptr, + r3d_shape_sample_minp }, + +{ "sample_typical_f32", "sample_typical", "sample", + "locally typical: drop the candidates whose surprisal is furthest from the set's entropy", + "the set's entropy from the same exps, the kept mass overshooting p by design and not depending " + "on the order, ties kept -- a stage that sorted the set would genuinely disagree with the schema", + "i32 cand_idx INOUT, f32 cand_val INOUT, f32 params; off when typical_p is out of range", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_typical, nullptr, nullptr, nullptr, + r3d_shape_sample_typical }, + +{ "sample_xtc_f32", "sample_xtc", "sample", + "the exclusion of top candidates: a coin, then drop all but the least likely of the clearers", + "its own coin (the seed keyed by XTC) decides whether the stage fires at all; when it fires it " + "drops every candidate at or above the threshold EXCEPT the least likely of them, and does nothing " + "when fewer than two clear it -- a stage that dropped unconditionally would fire on 100% of steps", + "i32 cand_idx INOUT, f32 cand_val INOUT, f32 params; off when the probability or the threshold is " + "out of range", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_xtc, nullptr, nullptr, nullptr, + r3d_shape_sample_xtc }, + +/* ------------------------------------------------------------------ r3d_dflash_f32.hip + * + * The speculative decoder's accept step. It is a gather, not arithmetic: two 63.8 MiB codebooks, a + * walk gathering `M * steps * rank` elements, so the score's rank sum is one lane's serial chain -- + * there is nothing to hide the gather behind, and a tree would be a different sum for no gain. + */ +/* ------------------------------------------------------------------ r3d_gemm_nt_q_w2a8.hip + * + * `output.weight`: U2 codes, int8 activations, one f32 scale per activation ROW (ZP_I8_ROW), and a + * joined `b_scale` the container writes as two planes -- scale f16 and zero u8 -- behind one operand + * that only a layout hook can present. libref's shape hook declines the dtype for exactly that + * reason, so kbench has no case for the band: the row's opd_shape is null, which is the tool's + * named skip, and the joined plane is built with rad_planes_relayout, the same builder the driver + * uses. + * + * Exactness, measured and not assumed: `v_fdot2_f32_f16` carries ~22 bits of mantissa on integer + * operands, not 24, so an integer dot through it is inexact above 2^20 (71027 of 262144 sampled dots + * at bias 1024, worst |err| 0.125; 70115 and 0.015625 at bias 128). The bias is 128 because the + * error's ratio to the magnitude is ~2^-22 and shrinking the bias shrinks the tail. The result is + * that 0.1-0.2% of outputs land one bf16 ulp off the reference: rel_l2 5.0e-3 at the band, + * max_abs 9.8e-4, no non-finite anywhere. This row is NOT bit-exact by construction, and the dot + * probe in the unit is the check that states it. + * + * M <= 16 is decode. 46 of these per token, 135 GFLOP a token of CPU work that the host row puts on + * the card at 3.0-4.2 ms (66.8 MB of codes at the card's 22 GB/s is the floor; the warm-L2 run is + * 2.43 ms at 30 GB/s). + */ +{ "gemm_nt_q_w2a8_m16", "gemm_nt_q", "gemm", + "the vocab projection at decode: 2-bit codes, int8 activations, the zero removed with a_sum", + "a wave takes one weight row; lane l owns group l&15 and half of it, 64 codes to a 16-byte load, " + "the pair (l, l^16) folding the group in one shuffle; lanes 0..15 hold the per-group terms and " + "lane 0 sums the groups in ascending order in one accumulator, which is the reference's order. " + "The codes widen to f16 through a bias of 128, so the dot's integer answer comes back with " + "B*sum(a) on it and a_sum -- group-major, the reference's own 16-row pad -- removes it", + "U2 codes b, I8 activations a, f32 a_scale (one per row), the joined b_scale (f16 scale + u8 zero " + "as rad_planes stores them), f32 a_sum, bf16 y. fp8a8, fp8a16 and w4a8 take their own rows; a zero " + "plane stored sub-byte (U2/U4/U5) is refused, not approximated -- the bit-extract path is 10 lines " + "of rad_load_bits and is not written; M > 16 is refused, prefill's vocab is logits_gemm", + RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1, + ROW(cGemmQW2A8), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_w2a8, nullptr, + r3d_layout_gemm_nt_q_w2a8, r3d_relayout_gemm_nt_q_w2a8, nullptr }, + +{ "gemm_nt_q_w2a8_tiled", "gemm_nt_q", "gemm", + "the packed-code grids at the heights the skinny row declines: 2-bit and 4-bit codes, int8 " + "activations, the batched decode and the draft head of a 2-bit vocab projection", + "the same 128x128 tile as the fp8a8 arm, with the codes unpacked on the way into LDS -- 8 codes " + "from a 4-byte load at U2, 16 from a 16-byte load at U4 -- and the epilogue folding " + "(code - zero) * scale per staged element, so the dot runs over values and no a_sum term is " + "reduced: the zero comes off term by term, which is why Σ a(q-z) needs no Σ a here while the m16 " + "row needs it to lift the integer bias off its f16-as-int dot. The row's scale and zero are one " + "per ROW on a {1, group} plane, so the staging reads 128 scalars a chunk where the fp8a8 arm reads " + "one, at the row the grid puts it; issued one chunk ahead of the fold that consumes them, because " + "a scalar load with nothing to overlap it is the whole band (210.8 ms against 2.396 ms with the " + "answer hoisted, the same output bits). r3d_tiling.h's swizzle is shared, proven byte-identical", + "M <= 16 is gemm_nt_q_w2a8_m16's by its declared C_LE(\"M\", 16); fp8a8 and fp8a16 take their own " + "rows, and the fp8a8 arm refuses a band carrying a_sum at its own line -- a row that silently " + "ignores a band operand passes a checkpoint whose a_sum is garbage. A zero plane stored sub-byte " + "(U2/U4) is refused and named, not approximated: rad_load_bits is the ten-line fix and it is " + "written for the codes, not the zero. Measured, VRAM: M=64 N=130560 K=2048 w2a8 24.151 ms, 1417 " + "GFLOP/s, 3.7 GB/s useful against a 0.449 ms read floor of the 73.1 MB operand -- at kKC=32 a " + "staged chunk draws 8 bytes from a row of pitch 512, so the band moves 8x the bytes it uses and " + "the lever is a wider k-chunk, not more loads in flight (the codes lead measured 0.6%, " + "bit-identical)", + RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1, + ROW(cGemmQW2A8Tiled), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_w2a8_tiled, nullptr, + r3d_layout_gemm_q_fp8_weight, r3d_relayout_gemm_q_fp8_weight, r3d_shape_gemm_nt_q }, + +/* ------------------------------------------------------------------ r3d_gemm_fp8a8_gated.hip + * + * The gate couples column i to column n+i, so a lane owns both dots and the coupling costs no extra + * weight traffic; the block is one group by 256/group rows so the group's amax closes in-block, + * which is also why there is nothing to tune (the block shape is the quantiser's rule, not a knob) + * and why the row keeps its M ceiling in the prose. At the band's own numbers this is ~341 GFLOP/s + * at M=64 -- 0.7% of the card's fp8 peak, 46 of these per forward pass -- and it is still the row + * the model wants, because the alternative it replaces is the reference's host GEMM: the same 3.2 + * GFLOP per layer on the CPU, which is 135 GFLOP a token for this checkpoint. + */ +{ "gemm_nt_q_gated_fp8a8", "gemm_nt_q_gated", "gemm", + "the gated MLP band's GEMM, its gate and its output quantiser in one launch", + "a block is one 128-wide group by 256/group rows, so the group's amax closes in-block: wave max " + "then an LDS fold over the lanes that share a group. The gate couples column i to column n+i, so a " + "lane owns both dots and the coupling costs no extra weight traffic. No [M,N] bf16 intermediate " + "exists: the row is narrowed, gated and coded from registers, which is why there is no scratch and " + "no second pass. The narrowing matches the unfused chain -- both halves bf16 before the gate, the " + "activation NOT narrowed before the product, the product formed in f32 then narrowed -- so the " + "codes are the codes the chain would have written, byte for byte at the band", + "fp8_e4m3 a and b, f32 a_scale, bf16 b_scale (f32 accepted and equal bit for bit; fp8a8f32 is a " + "different dtype and takes no row here), f32 scale, E4M3 q, bf16 out_bf16 optional; f32 " + "accumulation with -ffp-contract=off; f16x4 dot pairing, the code widening exact. M > 64, N odd, K " + "% group != 0, group outside {32,64,128,256} or wider than n, sk > 1 and an absent act are refused, " + "not approximated", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmGated), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_gated, nullptr, nullptr, nullptr, + r3d_shape_gemm_nt_q_gated }, + +{ "dflash_select_bf16", "dflash_select", "draft", + "DFlash2's greedy walk over the candidate lattice, one lane a (sequence, candidate) pair", + "score[l][c] = unary[l][c] + SUM_r pred[pid(l)][r] * hp[l][r] * succ[cand[l][c]][r], the rank sum " + "ascending in r in f32 with ax[r] = pred * hp rounded to f32 BEFORE it meets succ, because the " + "reference writes it to a float array first; argmax strict `>` over c ascending, so the earliest " + "candidate wins a tie and a NaN never takes the lead; pid(0) is the anchor at m * anchor_stride " + "and pid(l) the walk's own previous pick, so the steps loop is serial with the two LDS round " + "trips its dependence requires; hp absent is a plane of ones; a predecessor outside the vocabulary " + "contributes zero and a candidate outside it is scored by unary alone, which is what makes a " + "shard's padding rows legal input", + "bf16 codebooks (pred, succ, optional hp) with contiguous rows, f32 unary, i32 cand, anchor and " + "tokens; pitched rows served on cand, unary, tokens and hp, a row stride INSIDE a codebook row " + "refused (RAD_E_STRIDE); top_k > 256 refused (RAD_E_UNSUPPORTED); a cand plane describing more " + "sequences than the band's M is refused, not truncated", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cDflashSelect), NOTUNE, + nullptr, nullptr, r3d_rad_dflash_select, nullptr, nullptr, nullptr, + r3d_shape_dflash_select }, + +/* ------------------------------------------------------------------ r3d_vocab_bf16.hip + * + * The head is the largest read in a decode step -- 510 MiB at this checkpoint's 130560 x 2048 -- and + * the sampler reads f32, which is why the store is typed rather than narrowed and why a prefill band + * writes 1.07 GB. Measured on the card: 3.29 ms a token at M=1 (163 GB/s of the head), 0.507 ms a + * token at M=16 (the head read once for sixteen rows), 269 ms for a 2048-token prefill at 4067 + * GFLOP/s. Against the reference's law the f32 plane is 1.77e-6 in rel_l2, which is ~30 f32 ulps at + * K=2048 and is the pair-dot folding two products into one rounding -- measured identical against + * the same law with the operands widened to f16 first, so the widening contributes nothing and the + * head's own bf16 quantisation (4.9e-4 an element) is 300x coarser than the row. + */ +{ "logits_gemm_bf16", "logits_gemm", "vocab", + "logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T, the head read once a token", + "M <= 16: a wave a run of vocabulary columns, one output element a lane, the head's rows streamed " + "past an activation kept in registers, no wave reduction. M > 16: 128x128 tiles through LDS, 8x8 " + "f32 accumulators a lane, the head staged with an 8-element swizzle, k ascending in 32-code " + "chunks. The grid is vocab-wide at every M, so there is no split-K and no scratch", + "bf16 x, f32 logits: every sampler stage reads f32, so the narrowing the schema does not ask for " + "is not performed, and a prefill band's output plane is M x n_vocab f32. The head arrives in the " + "form the container stores and the row reads both, chosen by the operand's header, not by a " + "parameter: bf16 rows in the order they are stored, or -- what this checkpoint's output.weight " + "actually is -- E4M3 codes with a bf16 scale per 128x128 block as two container planes, which the " + "row's layout hook presents as the one operand the plan says they are, moving no byte. E4M3 and " + "int8 widen to f16 exactly, so the fold into f16 is the only arithmetic the codes pay: 2.77e-04 " + "from the reference's exact law, one f16 rounding, 250x finer than the code's own quantum. A head " + "with a zero plane is w2a8's grid and is refused at the shim's own line; so is a scale block that " + "is not 128x128, which is gemm_nt_q's grid", + RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1, + ROW(cLogitsGemm), NOTUNE, + nullptr, nullptr, r3d_rad_logits_gemm_bf16, nullptr, + r3d_layout_logits_head, r3d_relayout_logits_head, r3d_shape_logits_gemm_bf16 }, + +/* ------------------------------------------------------------------ r3d_gemm_fp8a8_tiled.hip + * + * The prefill projection: this checkpoint declares 176 of these a forward pass (44 of qkv, 44 of + * the gated MLP's 12288 columns, 44 of o, 44 of the 2048-wide one, three of the drafter at + * K=10240), and the reference does their 135 GFLOP a token in a host loop. + * Measured at the graph's own bands, weights in VRAM: 28.171 ms at N=12288 K=2048 (3659 GFLOP/s), + * 14.699 at N=2048 K=6144, 5.911 at N=2560, 4.381 at N=2048 K=2048, 29.798 at N=2048 K=10240 -- + * 27 to 36% of the card's dense f16 peak against a byte floor of 0.051 to 0.257 ms. These are the + * first bands in this library where the dot, not the wire, is the limit, and it is the reason the + * E4M3 decoder is a table: at the tile's densities the decode ALU is on the critical path. + */ +{ "gemm_nt_q_fp8a8_tiled", "gemm_nt_q", "gemm", + "y[M,N] = a[M,K] @ dequant(b)^T at prefill heights, the group sub-sum from the raw codes and one " + "scale per group, which is the reference's law and the reason the codes are never pre-scaled", + "128x128 tiles through LDS, 64 f32 accumulators a lane, k in 32-code chunks, the family's 8-element " + "XOR swizzle on the staged rows; both sides decode through the block's 512-byte E4M3->f16 table " + "and leave staging as f16 with their scale folded in -- a_scale per staged row, b_scale one scalar " + "per tile, because the tile's 128 columns are exactly the scale plane's row extent and 32 divides " + "128. One accumulator, no per-group partials, 237 VGPRs and no spill", + "E4M3 codes both sides, f32 a_scale per (row, group of 128), bf16 b_scale per 128x128 block -- the " + "container's own block; a {1,group} scale block is w2a8's grid and is refused, as is a zero plane " + "and an a_sum, fp8a8 being symmetric. y bf16 with one narrowing at the store, and at a bf16 output " + "the store's ulp (3.9e-3) is the binding floor, not the fold's (9.8e-4 of the quadrature scale): " + "83% of outputs are bit-exact, 99.93% land within the fold plus one store ulp, none beyond. The " + "fold is v_mul_f16, never f16x2_pack, which rounds toward zero and flushes subnormals", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQFP8Tiled), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_fp8_tiled, nullptr, + r3d_layout_gemm_q_fp8_weight, r3d_relayout_gemm_q_fp8_weight, r3d_shape_gemm_nt_q }, + +{ "gemm_nt_q_mxfp4a8_tiled", "gemm_nt_q", "gemm", + "y[M,N] = a[M,K] @ dequant(b)^T at prefill heights, the weight in OCP MXFP4: e2m1 codes, two a " + "byte, one e8m0 scale per 32 of K; the 32-block partial scales at the block boundary and the " + "blocks sum in ascending k", + "128x128 tiles through LDS, 64 f32 accumulators a lane for the block partials and 64 more for the " + "running sum, k in 32-code chunks -- one OCP 32-block a chunk -- the family's 8-element XOR " + "swizzle on the staged rows; the codes unpack to e4m3 through eight fixed magnitude bytes and " + "decode through the block's 512-byte table, a_scale folded per staged row, the e8 read at " + "staging and held in registers for the flush", + "E4M3 a with an f32 scale per (row, 128 of K), fp4_e2m1 codes with an e8m0 scale per (row, 32 " + "of K) -- `b_ref`, the same exponent plane, is accepted and ignored, bf16 y, fp32 accumulation. " + "The e2m1 magnitude is exact in e4m3, the code products are " + "exact in f16, the 32-block partial scales by a power of two in f32, and the store is the only " + "narrowing; a reserved e8 (0, 255) is refused", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_TILED, + ROW(cGemmQMxfp4a8Tiled), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_mxfp4a8_tiled, nullptr, + nullptr, nullptr, r3d_shape_gemm_nt_q_mxfp4a8 }, + +/* The same tiling on gemm_nt's operands, the prefill projection the reference runs on the host: at + * M=2048 this checkpoint's q/k/v/o and the MLP's up/down are 135 GFLOP a token of f32-accumulating + * bf16, and the reference does them on the CPU. The exactness is the m16 row's, because it is the + * same dot. */ +{ "gemm_nt_bf16_tiled", "gemm_nt", "gemm", + "a[M,K] @ b[N,K]^T at prefill heights, f32 accumulate, one narrowing at the store", + "128x128 tiles through LDS, 8x8 f32 accumulators a lane, k ascending in 32-code chunks, the " + "partials closed in the tile; M <= 16 stays with gemm_nt_bf16_m16, whose wave-per-run-of-columns " + "shape is the right one there -- the two rows' M ranges are complements, so neither competes for " + "the other's band", + "bf16 a, b and y, fp32 accumulation; the pair is folded into the accumulator by one rounding, so " + "about 0.3% of a long-K output lands one bf16 store ulp from the reference's, and no output is " + "further. 99.93% bit-exact measured at the 512-column twin, 100% within two ulps", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_TILED, + ROW(cGemmNTTiled), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_bf16_tiled, nullptr, + nullptr, nullptr, r3d_shape_gemm_nt }, + +}; + +/* ================================================================== the exports + * + * The two every plugin must export, the four that make a kernel library, and `rad_kernel_concurrent`. + * + * libr3d exports no `rad_kernel_chain`: chaining replaces the queue's ordering bit between two + * dependent launches with a spin in the kernel, and it pays where a wave is idle during that spin. + * Nothing here is built as a chained form, so the answer would be 0 for every row; the symbol is + * left out, which is the same answer with one less thing to keep in step (ABI, + * `rad_kernel_chain`: "without the symbol, or with 0, the engine never asks"). + * + * It exports no `rad_kernel_collective` either: there is no second rank in this plugin's world. The + * cards that run these rows are single-GPU cards, and an all-reduce over the PCIe x1 slot most of + * them sit in is slower than sending the bytes through the host. + */ +extern "C" int rad_kernel_count(void) { + return (int)(sizeof(kKernels) / sizeof(kKernels[0])); +} +extern "C" const RadKernelInfo* rad_kernel_at(int i) { + if (i < 0 || i >= rad_kernel_count()) return nullptr; + return &kKernels[i]; +} + +/* Which rows touch nothing but their operands and the scratch they were handed. + * + * The elementwise, norm, quant, cast, rope, cache and gather rows do: one launch, one pass, no + * state between launches, so two of them may run at once and the engine can start a row before an + * independent earlier one finishes. + * + * The GEMM rows do not, and the reason is the scratch, not the kernel. The scratch arena belongs to + * the op instance, so two layers' decode GEMMs launched at the same time share it: a split-K row's + * partials and arrival counters from the two launches would land on each other. With sk = 1 a GEMM + * launch has no partials and is safe, but the promise is per row and the axis is chosen per + * geometry, so the row states the worst case. When split-K is off on a given card (a tuned point of + * sk = 1 for every shape), the loss is one overlap the engine would have taken. + */ +extern "C" int rad_kernel_concurrent(int i) { + const RadKernelInfo* k = rad_kernel_at(i); + if (!k) return 0; + return k->scratch == nullptr; +} + +static const RadPluginInfo kInfo = { + RAD_PLUGIN_KERNEL, + "libr3d", + "0.1.0", + "the RDNA3 (gfx11) kernel library: the elementwise, norm, rope, cache and embedding rows, fp8 " + "and int8 activation quantisation with its dequant and gated forms, and the skinny bf16 and " + "fp8a16 GEMMs, every one of them through v_dot2acc_f32_f16 because RDNA3 has no matrix " + "instruction a compiler will emit", + /* The architectures this build's code objects run on, spelled as `RadDeviceProps::arch`. The + * loader compares a device's arch against these words and warns once when the code object it + * picked names a card this list does not (`target_covers`), so the string has to be the build's + * real targets rather than an author's guess at them. + * RAD_GPU_TARGETS reaches this source as a compile definition from CMakeLists.txt; the fallback + * is the whole family, which is what a build that did not say is claiming. */ + R3D_BUILD_TARGET, +}; + +extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } +extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } diff --git a/libr3d/r3d_sample_f32.hip b/libr3d/r3d_sample_f32.hip new file mode 100644 index 00000000..a9e2cda1 --- /dev/null +++ b/libr3d/r3d_sample_f32.hip @@ -0,0 +1,1314 @@ +/* r3d_sample_f32.hip -- the sampler: the two full-vocabulary reductions, the candidate set, the + * seeded draw and the four narrowing stages. + * + * The arithmetic is libref's, transcribed -- the reference's sampler is the law and the ORDER of + * its passes is the point. `abi/rad_sample.h` is the wire format: every scalar (`temp`, `top_k`, + * `top_p`, `min_p`, `typical_p`, `xtc_*`, `seed`, `pos`, the flags, the history window) is DATA, one + * 96-byte row per sampled position, because a parameter is geometry and frozen at declare, and two + * rows of one batch with different top_p must resolve to one kernel. `param_rows` below is that + * check, and it is the dtype check libref states: the plane is 32-bit words, and a 16-bit view + * passes a byte-count test and then misreads every row. + * + * ============================== what has to agree, and with what ============================== + * + * The draws must REPRODUCE, so the summation order is transcription and not performance: + * + * - A MAX is order-free and every max here is a strict `>`, which is also how NaN is kept out: + * libref's `if (v > mx) mx = v` over -infinity never adopts a NaN, and the butterfly merges with + * the same strict comparison, so a NaN in a row of logits cannot become the max anywhere. + * - A SUM of f32 is not order-free. libref's `sum` (the pick, the narrowing stages) runs + * over the candidates in INDEX order, and the CDF scan below it accumulates in index order too. + * So the exps are computed in parallel -- each is a separate value, order-free -- and the + * accumulation is serial on one lane, in index order, exactly as written. That is the whole + * design of the candidate kernels: parallel values, serial sums. + * - The draw is specified in the ABI, not left to a library: splitmix64 over + * `seed * 0x9E3779B97F4A7C15 + pos`, top 24 bits over 2^24. Integer arithmetic, so it is the + * same number here as on the host. Independent draws at one position are independent streams: + * the pick XORs the seed with RAD_SAMPLE_KEY_PICK (0), XTC's firing coin with RAD_SAMPLE_KEY_XTC. + * - `ref_exp`/`ref_log` are `(float)std::exp((double)x)` and `(float)std::log((double)x)`, and + * they are transcribed as double calls rounded once to f32. There is no fp8-style hardware + * shortcut to take: an f32 exp2 (`v_exp_f32`) is a couple of ulps away, and a `u < cum` + * comparison sitting on an ulp boundary changes the drawn token, which is a fixture failure even + * when the distribution is right. Consumer RDNA3 fp64 is 1:64, so this is the slow path and the + * candidate set is where it shows: it costs time, not agreement. The device's + * `(float)exp((double)x)` and `(float)log((double)x)` are bit-identical to glibc's over + * a million points in [-100, 100] (0 of 2^20 differ), while `expf` differs from the host's + * `expf` in 5.7% of them by 1 ulp -- the double call is not only the law, it is the only one + * of the two that reproduces the recording. + * + * This is where the law is affordable, and it is why this file and the attention unit differ. Here + * the widest softmax is the candidate set: 1024 exponentials a row, 2 per lane, and the whole op is + * half a millisecond a step at the band. Attention at the prefill band is 17 M exponentials a layer + * on the same 1:64 fp64, and there the law cannot be paid, so that unit ships a 0.5-ulp polynomial + * and says so. A sampler that draws a different token than the recording is wrong at any speed, so + * this unit keeps the double call and the switch stays off. + * + * ============================== the top-k, and why it is one pass ============================== + * + * libref selects with `topk_next`: R scans of the row, each taking the largest + * value strictly below the last pick, ties to the LOWER column. Read as a whole that is a sort by + * (-value, +column), and the rule `v == *pv && i <= *pi` is exactly "the next one within a run of + * equal values" -- so one pass that keeps the best R by that order produces the same R pairs, in the + * same order, with the same tie-breaks. At the band's row (N=130560, R=16, bf16, M=1792) the + * reference scans the row sixteen times: 7.0 GB of traffic. This file scans it once: 468 MB. + * + * At the band (M=1792, N=130560, R=16) the one pass is 22.0 ms bf16, 22.4 ms f32, i.e. 21 GB/s and + * 42 GB/s: the same time for half the bytes, so the pass is not bound by the plane, it is bound by + * the accepted inserts (~55 sifts a lane at 510 elements a lane, POOL steps each). The traffic is 15x + * lower than the reference's and the headroom is in the insert, not in the load; a lane that filtered + * against a block-wide threshold instead of its own tail would take ~5 sifts a lane and land near the + * 2 ms the bandwidth floor allows. The number is stated so it is not read as the memory system's + * answer. + * + * One pass needs a per-lane list, and a list costs comparisons, so it is 64 deep and the merge keeps + * the best 64 of two lists: a lane's test against its 64th best is ONE comparison for almost every + * element (only ~12% of a row's elements clear it at 510 elements a lane), and the deep comparisons + * happen only for the elements that enter. Sixty-four covers R=16, the selftest's 64-wide candidate + * set, and every top_k a request asks for in practice. Deeper is not free and is not silent: + * `r3d_sample_topk` and `r3d_row_topk` take ceil(k/64) passes when the row asks for more, and each + * pass is one more read of the row. That is the reference's own chain, so the answer is the same one + * at any k; only the time is the reference's. + * + * The chain's QUIRK is transcribed too, because kbench compares the plane. `topk_next` seeds its + * scan with `best_i < 0 ||`, so the first element it examines becomes the best even when it is a + * NaN, and after that `v > best_v` is false for everything: a row whose FIRST logit is NaN yields R + * identical (NaN, 0) slots, not a hole. To reproduce that the 64-deep pool is re-scanned by ONE lane + * in ascending column order with the literal chain -- the pool provably contains every element the + * chain can ever pick (a pick is in the global top-64, so it is in its own lane's top-64), and the + * chain's comparisons are only exact when the scan order is the row's. + * + * ============================== shape ============================== + * + * One block a row everywhere: at the band a row of 130560 f32 is 510 KiB and M is 2048, so the whole + * plane is 1 GiB and these are the memory-bound kernels of the library -- argmax and top-k each read + * 1 GiB, temp reads and writes 2 GiB. A row of the candidate set is 1024 f32 and the work is the + * transcendentals, so the same shape costs nothing and buys the serial order for free. The candidate + * stages keep their probabilities in LDS (2 * 1024 floats), which is what makes typical's O(n^2) + * distance scan affordable. + * + * Single rank. `vocab_off` is read where libref reads it (`row_topk`'s reported ids, `sample_topk`'s + * `pairs` plane) and the pair planes are written as the shape hooks describe them, because kbench + * fills and compares them. There is no all-gather here and no merge kernel: `sample_merge_topk` is + * declined by libref's own shape hook and rank 0 has nothing to merge. + */ + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +/* ================================================================== shared device helpers */ +namespace { + +constexpr uint32_t kThreads = 256; /* 8 waves */ +constexpr uint32_t kWave = 32; +constexpr uint32_t kWaves = kThreads / kWave; + +/* The candidate pool's depth, and the widest candidate set the narrowing stages carry in LDS. + * 1024 candidates is the engine's declared buffer width; two f32 arrays of it is 8 KiB of 64 KiB. */ +constexpr int kPool = 64; +constexpr int kCandMax = 1024; + +/* The double call and the single rounding to f32 ARE the law: libref's oracle + * is glibc's double exp and log, and the f32 result of a double-accurate implementation agrees with + * it for every input but a double-rounding tie. */ +/* The two transcendentals, and the A/B switch. The law is libref's `(float)std::exp((double)x)`, + * and on this card the device's double `exp`/`log` are BIT-IDENTICAL to glibc's (0 of 2^20 points + * in [-100, 100] differ, both functions), so the law is reproducible here and the draw is the + * recording's. `expf` is not: it moves 5.7% of inputs by 1 ulp relative to the host's, which is + * under a bit-exact fixture. -DR3D_EXP_F32 swaps both for the f32 hardware path, so the cost of the + * law can be measured in kbench; nothing in the shipped build uses it, and the flips it causes are + * reported with it. */ +#ifdef R3D_EXP_F32 +__device__ __forceinline__ float ref_exp(float x) { return expf(x); } +__device__ __forceinline__ float ref_log(float x) { return logf(x); } +#else +__device__ __forceinline__ float ref_exp(float x) { return (float)exp((double)x); } +__device__ __forceinline__ float ref_log(float x) { return (float)log((double)x); } +#endif + +/* abi/rad_sample.h's draw, verbatim: splitmix64 over (seed * golden + pos), top 24 bits as a float + * in [0, 1) -- exactly f32's mantissa, so no double anywhere. */ +__device__ __forceinline__ uint64_t splitmix64(uint64_t z) { + z += 0x9E3779B97F4A7C15ull; + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); +} +__device__ __forceinline__ float uniform01(uint64_t seed, uint64_t pos) { + const uint64_t z = splitmix64(seed * 0x9E3779B97F4A7C15ull + pos); + return (float)(uint32_t)(z >> 40) * (1.0f / 16777216.0f); +} + +/* The params row, as the kernels see it. 96 bytes, a multiple of 8, so row m is 8-byte aligned in a + * plane of words and the u64 seed and pos load as one instruction. */ +struct Params { + const RadSampleParams* p; + __device__ __forceinline__ const RadSampleParams& operator[](uint32_t m) const { + return p[m]; + } +}; + +/* A block-wide maximum with a strict `>`, which is the comparison libref writes and the reason a NaN + * is never the max: a wave butterfly, then the wave partials. `lds` holds kWaves floats. */ +__device__ __forceinline__ float block_max(float v, float* lds) { + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + v = wave_max(v); /* a butterfly of fmaxf: drops a NaN */ + if (lane == 0) lds[wave] = v; + __syncthreads(); + float t = lds[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]); + return t; +} + +/* ------------------------------------------------------------------ sample_argmax + * + * The law: the largest logit, ties to the LOWER column, because greedy and top-1 have to + * agree. The scan's rule is `bi < 0 || v > best`: strict, so the first of a run wins, and a NaN is + * never adopted -- except as the row's very first element, which the seed of the scan adopts. The + * parallel form is the same total order: take the right candidate only when it is strictly better + * (larger, or equal with a lower column), which is associative, so the butterfly and the serial scan + * agree, and a NaN in `best` is never displaced by anything. + */ +struct Best { float v; uint32_t i; }; + +/* The scan's law, made associative. `best_take(a, b)` keeps `a` unless `b` is strictly better -- + * larger, or equal with a lower column -- and `b.i == kNone` is "nothing examined yet". The + * reference's serial scan seeds with `bi < 0 ||` and then moves only on a strict `>`, which is the + * same total order, so a butterfly of this and a scan of that agree on every input. */ +__device__ __forceinline__ Best best_take(Best a, Best b) { + const bool better = (b.v > a.v) || (b.v == a.v && b.i < a.i); + return (b.i != 0xffffffffu && better) ? b : a; +} + +/* A max with a strict `>` over the block, NaN dropped: `fmaxf` is the drop, and libref's + * `if (v > mx) mx = v` from -infinity never adopts a NaN either. */ +__device__ __forceinline__ float block_max_strict(float v, float* lds) { + return block_max(v != v ? -INFINITY : v, lds); +} + +__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_argmax_kernel( + const float* __restrict__ lg, int32_t* __restrict__ tok, uint32_t n, uint32_t lg_ld) { + __shared__ float red[kWaves]; + __shared__ uint32_t redi[kWaves]; + + const uint32_t row = blockIdx.x; + const float* __restrict__ lr = lg + (size_t)row * lg_ld; + + /* Non-NaN values only, lowest column winning a tie. */ + Best b{ -INFINITY, 0xffffffffu }; + for (uint32_t c = threadIdx.x; c < n; c += kThreads) { + const float v = ldg_f32(lr + c); + if (v != v) continue; + if (b.i == 0xffffffffu || v > b.v) { b.v = v; b.i = c; } + } +#define R3D_BEST_XOR(M) \ + { \ + const Best o{ r3d_xor_lane(b.v), r3d_xor_lane_u32(b.i) }; \ + b = best_take(b, o); \ + } + R3D_BEST_XOR(16) + R3D_BEST_XOR(8) + R3D_BEST_XOR(4) + R3D_BEST_XOR(2) + R3D_BEST_XOR(1) +#undef R3D_BEST_XOR + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + if (lane == 0) { red[wave] = b.v; redi[wave] = b.i; } + __syncthreads(); + if (threadIdx.x == 0) { + Best t{ red[0], redi[0] }; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) t = best_take(t, Best{ red[w], redi[w] }); + /* topk_next's seed, and nothing else: the first element the reference examines becomes its + * best even when it is a NaN, and no finite value can displace a NaN afterwards, so a row + * that opens with a NaN reports column 0. Every other NaN the scan walks past. */ + const float x0 = ldg_f32(lr); + tok[row] = (int32_t)(x0 != x0 ? 0u : t.i); + } +} + +/* ------------------------------------------------------------------ sample_temp + * + * The law: `inv = 1/t` computed once per row, then every logit multiplied -- by the + * reciprocal, not divided, and only when the row is sampled at all: `!(t > 0) || t == 1` leaves the + * row exactly as it was, bit for bit, which is what makes temp 1.0 and temp 0.0 (greedy) no-ops the + * kernel has to keep. The write is in place: logits are an INOUT operand. + */ +__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_temp_kernel( + float* __restrict__ lg, const RadSampleParams* __restrict__ pr, uint32_t n, uint32_t lg_ld) { + const uint32_t row = blockIdx.x; + const float t = pr[row].temp; + if (!(t > 0.0f) || t == 1.0f) return; + const float inv = 1.0f / t; + float* __restrict__ lr = lg + (size_t)row * lg_ld; + for (uint32_t c = threadIdx.x; c < n; c += kThreads) { + const float v = ldg_f32(lr + c); + lr[c] = v * inv; + } +} + +} /* namespace */ + +/* lg [M][n_vocab] f32, INOUT for temp, read-only for argmax; `lg_ld` elements a row (0 = n) + * tok [M] i32 + * params [M] 24 words a row; argmax does not read it, and libref's shape hook describes + * it anyway, so the operand is there and unchecked, as libref leaves it. + * + * 0, -1 null, -2 bad extent, -3 pitch that does not describe the operand, -4 the HIP launch failed. + * No allocation, no synchronisation. */ +extern "C" int r3d_sample_argmax(long lg, long tok, int M, int n_vocab, long long lg_ld, + long stream) { + if (!lg || !tok) return -1; + if (M <= 0 || n_vocab <= 0) return -2; + if (!lg_ld) lg_ld = n_vocab; + if (lg_ld < n_vocab) return -3; + if (M > 0x7fffffff || n_vocab > 0x7fffffff) return -2; + + const dim3 grid((unsigned)M), block(kThreads); + R3D_KLAUNCH(R3D_KNAME(sample_argmax_kernel), grid, block, (hipStream_t)(uintptr_t)stream, + (const float*)lg, (int32_t*)tok, (uint32_t)n_vocab, (uint32_t)lg_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_sample_temp(long lg, long params, int M, int n_vocab, long long lg_ld, + long stream) { + if (!lg || !params) return -1; + if (M <= 0 || n_vocab <= 0) return -2; + if (!lg_ld) lg_ld = n_vocab; + if (lg_ld < n_vocab) return -3; + if (M > 0x7fffffff || n_vocab > 0x7fffffff) return -2; + + const dim3 grid((unsigned)M), block(kThreads); + R3D_KLAUNCH(R3D_KNAME(sample_temp_kernel), grid, block, (hipStream_t)(uintptr_t)stream, + (float*)lg, (const RadSampleParams*)params, (uint32_t)n_vocab, (uint32_t)lg_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== the top-k pool + * + * One lane's share of a row, kept as the 64 best by (value descending, column ascending) -- the + * order `topk_next` walks. Two rules make it one pass and make it exact: + * + * - the order is a STRICT total order, so a merge of two such lists is a merge of two sorted + * lists and keeps the first 64 of the union, which is what the reference's R scans converge on; + * - the list lives in registers, so insertion is a 64-step sift with STATIC indices (compare, and + * swap when the newcomer is better) and never a dynamic index, which would spill the array to + * private memory. The sift costs 64 compares per INSERTED element, and elements are inserted + * only after a single compare against the lane's 64th best -- about one element in eight at the + * band's 510 columns a lane -- so the amortised cost is a few comparisons a column. + * + * Slots the row never filled hold (-INFINITY, 0xffffffff): lower than any real value, and higher + * than any real column, so a real -infinity logit (a masked one) beats a pad and the extraction + * stops at the first pad. + */ +namespace { + +constexpr uint32_t kPadCol = 0xffffffffu; + +/* The pool's order, strict: larger value wins, equal value goes to the lower column. */ +__device__ __forceinline__ bool pool_better(float av, uint32_t ai, float bv, uint32_t bi) { + return av > bv || (av == bv && ai < bi); +} + +/* Insert (v, i) into a lane's register list. POOL is the list depth, which is the width of a pass: + * the sift is POOL steps and the merges are POOL-wide. The band asks for 16 (a router's top_k) and + * a candidate set for 64; carrying 64 through a router row costs four times the sift and returns + * the same 16 pairs. + * + * `pv`/`pi` carry the pick chain: an element at or above the last pick has been picked already, and + * within a run of equal values only columns after the last pick are still candidates -- + * `topk_next`'s two skips, in its order. */ +template +__device__ __forceinline__ void pool_insert(float v, uint32_t i, float pv, uint32_t pi, + float* lv, uint32_t* li) { + if (v != v) return; /* the scan walks past a NaN (its first element is + handled by the caller, as the reference's is) */ + if (v > pv) return; /* picked on an earlier pass */ + if (v == pv && i <= pi) return; /* the last pick, or one before it */ + if (!pool_better(v, i, lv[POOL - 1], li[POOL - 1])) return; /* the fast path: one compare */ + + float cv = v; + uint32_t ci = i; +#pragma unroll + for (int j = 0; j < POOL; ++j) { /* the sift: every index a compile-time constant */ + if (pool_better(cv, ci, lv[j], li[j])) { + const float tv = lv[j]; const uint32_t ti = li[j]; + lv[j] = cv; li[j] = ci; cv = tv; ci = ti; + } + } +} + +/* The best 64 of the union of two lists, in the pool's order. + * + * A[j] and B[j] are descending, so C[j] = the better of A[j] and B[kPool-1-j] is a bitonic sequence + * that already contains the top 64 of the union, and a bitonic sort of 64 in registers is six + * passes of 32 compare-exchanges with static strides -- no dynamic index, no spill, 448 compares. + * Both lanes of a shuffle pair compute the same result, which is what makes a butterfly of this + * operation a wave reduction. */ +template +__device__ __forceinline__ void pool_merge(const float* av, const uint32_t* ai, + const float* bv, const uint32_t* bi, + float* ov, uint32_t* oi) { +#define R3D_POOL_GET(X, J) \ + const float x##v = r3d_xor_lane(X[0]); (void)x##v +#pragma unroll + for (int j = 0; j < POOL; ++j) { + const int r = POOL - 1 - j; + if (pool_better(av[j], ai[j], bv[r], bi[r])) { ov[j] = av[j]; oi[j] = ai[j]; } + else { ov[j] = bv[r]; oi[j] = bi[r]; } + } +#undef R3D_POOL_GET +#pragma unroll + for (int k = POOL; k > 1; k >>= 1) { +#pragma unroll + for (int h = k / 2; h > 0; h >>= 1) { +#pragma unroll + for (int j = 0; j < POOL; ++j) { + const int o = j ^ h; + if (o <= j) continue; + /* Descending everywhere: the whole array is one descending run, so the direction of + * every compare-exchange is "the larger value to the lower index". */ + if (pool_better(ov[o], oi[o], ov[j], oi[j])) { + const float tv = ov[j]; const uint32_t ti = oi[j]; + ov[j] = ov[o]; oi[j] = oi[o]; ov[o] = tv; oi[o] = ti; + } + } + } + } +} + +/* One lane's pass over its columns of a row. STEP is 1 (scalar) or 4 (a vector load a step); LD + * reads one column. */ +template +__device__ __forceinline__ void pool_scan(const void* __restrict__ x, uint32_t n, uint32_t x_ld, + float pv, uint32_t pi, float* lv, uint32_t* li) { + const uint32_t tid = threadIdx.x; + if (XDT == 0) { /* bf16: four columns a 64-bit load */ + const uint16_t* __restrict__ p = (const uint16_t*)x + (size_t)blockIdx.x * x_ld; + if (STEP == 4) { + const uint32_t nw = n / 4; + for (uint32_t w = tid; w < nw; w += kThreads) { + const uint2 u = *(const uint2*)(p + (size_t)w * 4); + const uint32_t lo = u.x, hi = u.y; + pool_insert(bf16_to_f32((uint16_t)(lo & 0xffffu)), 4 * w + 0, pv, pi, lv, li); + pool_insert(bf16_to_f32((uint16_t)(lo >> 16)), 4 * w + 1, pv, pi, lv, li); + pool_insert(bf16_to_f32((uint16_t)(hi & 0xffffu)), 4 * w + 2, pv, pi, lv, li); + pool_insert(bf16_to_f32((uint16_t)(hi >> 16)), 4 * w + 3, pv, pi, lv, li); + } + for (uint32_t c = nw * 4 + tid; c < n; c += kThreads) /* the row's odd tail, once */ + pool_insert(bf16_to_f32((uint16_t)ldg_u16(p + c)), c, pv, pi, lv, li); + } else { + for (uint32_t c = tid; c < n; c += kThreads) + pool_insert(bf16_to_f32((uint16_t)ldg_u16(p + c)), c, pv, pi, lv, li); + } + } else { /* f32: four columns a 128-bit load */ + const float* __restrict__ p = (const float*)x + (size_t)blockIdx.x * x_ld; + if (STEP == 4) { + const uint32_t nw = n / 4; + for (uint32_t w = tid; w < nw; w += kThreads) { + const float4 v = *(const float4*)(p + (size_t)w * 4); + pool_insert(v.x, 4 * w + 0, pv, pi, lv, li); + pool_insert(v.y, 4 * w + 1, pv, pi, lv, li); + pool_insert(v.z, 4 * w + 2, pv, pi, lv, li); + pool_insert(v.w, 4 * w + 3, pv, pi, lv, li); + } + for (uint32_t c = nw * 4 + tid; c < n; c += kThreads) + pool_insert(ldg_f32(p + c), c, pv, pi, lv, li); + } else { + for (uint32_t c = tid; c < n; c += kThreads) + pool_insert(ldg_f32(p + c), c, pv, pi, lv, li); + } + } +} + +/* One pass over the row: every lane's list, a wave butterfly of merges, the eight wave lists in + * LDS, and the block's 64 best in LDS at [kWaves*kPool, ...). Returns how many are real (pads + * stop it). */ +/* The block's 64 best are left in LDS at [kWaves*kPool, ...): the extraction that follows walks + * them with a runtime index, and a runtime index into a register array is a spill. */ +template +__device__ __forceinline__ uint32_t pool_pass(const void* __restrict__ x, uint32_t n, + uint32_t x_ld, int xdt, int vec, + float pv, uint32_t pi, + float* lds_v, uint32_t* lds_i) { + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + float lv[POOL], bv[POOL], cv[POOL]; + uint32_t li[POOL], bi[POOL], ci[POOL]; +#pragma unroll + for (int j = 0; j < POOL; ++j) { lv[j] = -INFINITY; li[j] = kPadCol; } + + if (vec) { + if (xdt == 0) pool_scan<0, 4, POOL>(x, n, x_ld, pv, pi, lv, li); + else pool_scan<1, 4, POOL>(x, n, x_ld, pv, pi, lv, li); + } else { + if (xdt == 0) pool_scan<0, 1, POOL>(x, n, x_ld, pv, pi, lv, li); + else pool_scan<1, 1, POOL>(x, n, x_ld, pv, pi, lv, li); + } + +#define R3D_POOL_XOR(J) \ + { \ + _Pragma("unroll") for (int q = 0; q < POOL; ++q) { \ + bv[q] = r3d_xor_lane(lv[q]); bi[q] = r3d_xor_lane_u32(li[q]); \ + } \ + pool_merge(lv, li, bv, bi, cv, ci); \ + _Pragma("unroll") for (int q = 0; q < POOL; ++q) { lv[q] = cv[q]; li[q] = ci[q]; } \ + } + R3D_POOL_XOR(16) + R3D_POOL_XOR(8) + R3D_POOL_XOR(4) + R3D_POOL_XOR(2) + R3D_POOL_XOR(1) +#undef R3D_POOL_XOR + + if (lane == 0) { +#pragma unroll + for (int j = 0; j < POOL; ++j) { lds_v[wave * POOL + j] = lv[j]; lds_i[wave * POOL + j] = li[j]; } + } + __syncthreads(); + + uint32_t nout = 0; + if (threadIdx.x == 0) { /* the eight lists, merged with cursors */ + uint32_t cur[kWaves]; +#pragma unroll + for (int w = 0; w < kWaves; ++w) cur[w] = 0; + for (int j = 0; j < POOL; ++j) { + float bv = -INFINITY; uint32_t bi = kPadCol; int bw = -1; + for (int w = 0; w < kWaves; ++w) { + const uint32_t idx = (uint32_t)w * POOL + cur[w]; + const float v = lds_v[idx]; const uint32_t i = lds_i[idx]; + if (i == kPadCol) continue; + if (bw < 0 || pool_better(v, i, bv, bi)) { bv = v; bi = i; bw = w; } + } + if (bw < 0) break; + lds_v[kWaves * POOL + j] = bv; lds_i[kWaves * POOL + j] = bi; + cur[bw]++; nout = (uint32_t)j + 1; + } + } + __syncthreads(); + return nout; +} + +/* The pool, in LDS: the eight wave lists, then the block's. */ +} /* namespace */ + +/* ================================================================== row_topk + * + * The law: exact per-row top-R, descending, ties to the lower column, with `vocab_off` + * added to every reported id and the optional [M, R, 2] pair plane an all-gather moves (an int32 id + * in the first f32 slot, the value in the second, id -1 for a slot the row could not fill). + * + * The reference calls `topk_next` R times, a full scan each time; the pool above produces the same + * R pairs from one scan, because the pool's order IS the chain's order. A row that wants more than + * 64 costs ceil(R/64) scans and carries the chain's state across them, so the answer is the same at + * any R and only the time is the reference's. + */ +namespace { + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(4) void row_topk_kernel( + const void* __restrict__ x, int32_t* __restrict__ idx, float* __restrict__ val, + float* __restrict__ pairs, uint32_t n, uint32_t k, int vec, int32_t vocab_off, + uint32_t x_ld, uint32_t idx_ld, uint32_t val_ld, uint32_t pairs_ld) { + __shared__ float lds_v[kWaves * kPool + kPool]; + __shared__ uint32_t lds_i[kWaves * kPool + kPool]; + __shared__ float st[4]; + __shared__ uint32_t s2[2]; + + const uint32_t row = blockIdx.x; + float* __restrict__ vr = val + (size_t)row * val_ld; + int32_t* __restrict__ ir = idx + (size_t)row * idx_ld; + float* __restrict__ pr = pairs ? pairs + (size_t)row * pairs_ld : nullptr; + + /* topk_next's seed of the scan: the first element it looks at becomes the best even as a NaN, + * and nothing displaces a NaN, so a row that opens with one reports (0, NaN) in every slot. + * Stated once, here, rather than buried in the pool's comparisons. */ + if (threadIdx.x == 0) + st[0] = XDT == 0 ? bf16_to_f32((uint16_t)ldg_u16((const uint16_t*)x + (size_t)row * x_ld)) + : ldg_f32((const float*)x + (size_t)row * x_ld); + __syncthreads(); + if (st[0] != st[0] && threadIdx.x == 0) { + for (uint32_t r = 0; r < k; ++r) { + ir[r] = (int32_t)vocab_off; + vr[r] = st[0]; + if (pr) { + int32_t bits = (int32_t)vocab_off; + float v = st[0]; + __builtin_memcpy(&pr[2 * r], &bits, 4); + pr[2 * r + 1] = v; + } + } + return; + } + + float pv = INFINITY; + uint32_t pi = 0xffffffffu; + uint32_t done = 0; + constexpr uint32_t kBlk = kWaves * POOL; /* where pool_pass leaves the block's list */ + while (done < k) { + __syncthreads(); + const uint32_t nout = pool_pass(x, n, x_ld, XDT, vec, pv, pi, lds_v, lds_i); + if (threadIdx.x == 0) { + /* Only the first `nout` entries of the block list were written this pass; what sits past + * them is last pass's list, so the count, not the pad sentinel, bounds the copy. */ + const uint32_t room = (k - done < POOL) ? k - done : (uint32_t)POOL; + const uint32_t take = nout < room ? nout : room; + uint32_t j = 0; + for (; j < take; ++j) { + const uint32_t col = lds_i[kBlk + j]; + if (col == kPadCol) break; + const float v = lds_v[kBlk + j]; + const int32_t id = (int32_t)(col + (uint32_t)vocab_off); + ir[done + j] = id; + vr[done + j] = v; + if (pr) { __builtin_memcpy(&pr[2 * (done + j)], &id, 4); pr[2 * (done + j) + 1] = v; } + pv = v; pi = col; + } + for (; j < room; ++j) { /* holes to the end of the window */ + ir[done + j] = -1; + vr[done + j] = -INFINITY; + if (pr) { + const int32_t h = -1; + const float hinf = -INFINITY; + __builtin_memcpy(&pr[2 * (done + j)], &h, 4); + pr[2 * (done + j) + 1] = hinf; + } + } + st[1] = pv; + s2[0] = pi; + s2[1] = nout == 0 ? k : done + take; + } + __syncthreads(); +#ifdef R3D_POOL_TRACE + if (threadIdx.x == 0) + printf(" [pool] n=%u done=%u nout=%u take=%u pv=%g pi=%u -> pv=%g pi=%u done=%u\n", + n, done, nout, (uint32_t)0, pv, pi, st[1], s2[0], s2[1]); +#endif + pv = st[1]; pi = s2[0]; done = s2[1]; + } +} + +/* One row's top_k: the request's, clamped to the buffer, whole width when absent, none when the row + * is greedy (its token is sample_argmax's, and a stage that wrote it candidates would be a bug the + * pick cannot see). */ +__device__ __forceinline__ uint32_t row_k(const RadSampleParams& sp, uint32_t n_cand) { + if (sp.flags & RAD_SP_GREEDY) return 0; + const int32_t k = sp.top_k; + if (k <= 0 || (uint32_t)k > n_cand) return n_cand; + return (uint32_t)k; +} + +} /* namespace */ + +/* x [M][N] bf16 (x_dt 0) or f32 (x_dt 1), `x_ld` elements a row (0 = N) + * idx [M][R] i32, the column plus `vocab_off`, -1 for a slot the row could not fill + * val [M][R] f32, -infinity with the hole + * pairs [M][2R] f32, optional: (int32 id bits, value) as the all-gather moves it + * + * 0, -1, -2 a bad extent, -3 a pitch that does not describe the operand, -4 the launch failed. */ +extern "C" int r3d_row_topk(long x, long idx, long val, long pairs, int M, int N, int R, int x_dt, + long long x_ld, long long idx_ld, long long val_ld, long long pairs_ld, + int vocab_off, long stream) { + if (!x || !idx || !val) return -1; + if (M <= 0 || N <= 0 || R <= 0) return -2; + if (x_dt != 0 && x_dt != 1) return -2; + if (!x_ld) x_ld = N; + if (!idx_ld) idx_ld = R; + if (!val_ld) val_ld = R; + if (!pairs_ld) pairs_ld = 2 * R; + if (x_ld < N || idx_ld < R || val_ld < R || (pairs && pairs_ld < 2 * R)) return -3; + if (M > 0x7fffffff || N > 0x7fffffff || R > 0x7fffffff) return -2; + + /* The vector load needs a row start that is 16 bytes (f32) or 8 bytes (bf16) aligned. Any pitch + * that is a multiple of 4 elements does it for every row; the base is the caller's to align and + * is checked here, so a slice handed in at an odd column takes the scalar path and is right. */ + const int es = x_dt == 0 ? 2 : 4; + const int vec = (x_ld % 4 == 0) && ((x % (4 * (long long)es)) == 0); + + const dim3 grid((unsigned)M), block(kThreads); + + /* The list depth is the pass width: R 16 (a router's top_k, the band's row) sifts 16 deep, a + * wide candidate set 64. Beyond 64 the row is scanned again, so the depth buys passes, not + * per-element work. */ + const int pool = R <= 16 ? 16 : (R <= 32 ? 32 : 64); +#define R3D_RTK(XDT, POOL) \ + R3D_KLAUNCH(R3D_KNAME(row_topk_kernel), grid, block, \ + (hipStream_t)(uintptr_t)stream, (const void*)x, (int32_t*)idx, (float*)val, \ + (float*)pairs, (uint32_t)N, (uint32_t)R, vec, (int32_t)vocab_off, \ + (uint32_t)x_ld, (uint32_t)idx_ld, (uint32_t)val_ld, (uint32_t)pairs_ld) + if (x_dt == 0) { + if (pool == 16) { R3D_RTK(0, 16); } + else if (pool == 32) { R3D_RTK(0, 32); } + else { R3D_RTK(0, 64); } + } else { + if (pool == 16) { R3D_RTK(1, 16); } + else if (pool == 32) { R3D_RTK(1, 32); } + else { R3D_RTK(1, 64); } + } +#undef R3D_RTK + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== sample_topk + * + * The law: the row's top_k largest logits into the fixed-width candidate set, descending, + * ties to the lower token id, with `cand_idx` -1 and `cand_val` -infinity for a hole. Two things + * here are not in row_topk: the width is the BUFFER's (a declare-time bound), the row's top_k only + * narrows within it -- top_k 40 in a 1024-wide buffer is 40 candidates and 984 holes -- and a greedy + * row takes none, because its token is sample_argmax's and the pick must not overwrite it. + * + * `cand_val` carries LOGITS, not probabilities: every narrowing stage takes its own softmax over the + * set, which is what lets the stages compose in any order. + */ +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel( + const float* __restrict__ lg, const RadSampleParams* __restrict__ pr, int32_t* __restrict__ ci, + float* __restrict__ cv, int32_t* __restrict__ pairs, uint32_t n_vocab, uint32_t n_cand, int vec, + int32_t vocab_off, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pairs_ld) { + __shared__ float lds_v[kWaves * kPool + kPool]; + __shared__ uint32_t lds_i[kWaves * kPool + kPool]; + __shared__ float st[4]; + __shared__ uint32_t s2[2]; + + const uint32_t row = blockIdx.x; + const uint32_t k = row_k(pr[row], n_cand); + int32_t* __restrict__ ir = ci + (size_t)row * ci_ld; + float* __restrict__ vr = cv + (size_t)row * cv_ld; + int32_t* __restrict__ pp = pairs ? pairs + (size_t)row * pairs_ld : nullptr; + + /* The whole buffer is written every step: a hole is a value the later stages test for, and a + * stale candidate from the previous step would be drawn. */ + auto hole = [&](uint32_t r) { + ir[r] = -1; + vr[r] = -INFINITY; + if (pp) { pp[2 * r] = (int32_t)0xffffffffu; pp[2 * r + 1] = (int32_t)0xff800000; } + }; + + const float x0 = ldg_f32(lg + (size_t)row * lg_ld); + if (x0 != x0) { /* topk_next's seed, as in row_topk */ + for (uint32_t r = 0; r < n_cand; ++r) { + if (r >= k) { hole(r); continue; } + ir[r] = vocab_off; + vr[r] = x0; + if (pp) { pp[2 * r] = vocab_off; pp[2 * r + 1] = *(const int32_t*)&x0; } + } + return; + } + + float pv = INFINITY; + uint32_t pi = 0xffffffffu; + uint32_t done = 0; + constexpr uint32_t kBlk = kWaves * POOL; + while (done < k) { + __syncthreads(); + const uint32_t nout = pool_pass(lg, n_vocab, lg_ld, 1, vec, pv, pi, lds_v, lds_i); + if (threadIdx.x == 0) { + /* Only the first `nout` entries of the block list were written this pass; what sits past + * them is last pass's list, so the count, not the pad sentinel, bounds the copy. */ + const uint32_t room = (k - done < POOL) ? k - done : (uint32_t)POOL; + const uint32_t take = nout < room ? nout : room; + uint32_t j = 0; + for (; j < take; ++j) { + const uint32_t col = lds_i[kBlk + j]; + if (col == kPadCol) break; + const float v = lds_v[kBlk + j]; + const int32_t id = (int32_t)(col + (uint32_t)vocab_off); + ir[done + j] = (int32_t)col; /* cand_idx is LOCAL: it indexes this row of logits */ + vr[done + j] = v; + if (pp) { pp[2 * (done + j)] = id; pp[2 * (done + j) + 1] = *(const int32_t*)&v; } + pv = v; pi = col; + } + for (; j < room; ++j) hole(done + j); /* holes to the end of the window */ + s2[0] = pi; + s2[1] = nout == 0 ? k : done + take; + st[1] = pv; + } + __syncthreads(); + pv = st[1]; pi = s2[0]; done = s2[1]; + } + for (uint32_t r = done + threadIdx.x; r < n_cand; r += kThreads) hole(r); +} + +/* lg [M][n_vocab] f32; `lg_ld` a row (0 = n_vocab) + * params [M] 24 words a row + * ci [M][n_cand] i32, LOCAL columns, -1 for a hole + * cv [M][n_cand] f32, the LOGIT, -infinity with the hole + * pairs [M][2*n_cand] i32, optional: (global id, logit bits), 0xffffffff for a hole + * + * The candidate width is ci's last dimension, as libref takes it; the row's top_k only narrows + * inside it. 0, -1, -2, -3, -4. */ +extern "C" int r3d_sample_topk(long lg, long params, long ci, long cv, long pairs, int M, + int n_vocab, int n_cand, long long lg_ld, long long ci_ld, + long long cv_ld, long long pairs_ld, int vocab_off, long stream) { + if (!lg || !params || !ci || !cv) return -1; + if (M <= 0 || n_vocab <= 0 || n_cand <= 0 || n_cand > kCandMax) return -2; + if (!lg_ld) lg_ld = n_vocab; + if (!ci_ld) ci_ld = n_cand; + if (!cv_ld) cv_ld = n_cand; + if (!pairs_ld) pairs_ld = 2 * n_cand; + if (lg_ld < n_vocab || ci_ld < n_cand || cv_ld < n_cand || (pairs && pairs_ld < 2 * n_cand)) + return -3; + if (M > 0x7fffffff || n_vocab > 0x7fffffff) return -2; + const int vec = (lg_ld % 4 == 0) && ((lg % 16) == 0); + + const dim3 grid((unsigned)M), block(kThreads); + const int pool = n_cand <= 16 ? 16 : (n_cand <= 32 ? 32 : 64); +#define R3D_STK(POOL) \ + R3D_KLAUNCH(R3D_KNAME(sample_topk_kernel), grid, block, \ + (hipStream_t)(uintptr_t)stream, (const float*)lg, \ + (const RadSampleParams*)params, (int32_t*)ci, (float*)cv, (int32_t*)pairs, \ + (uint32_t)n_vocab, (uint32_t)n_cand, vec, (int32_t)vocab_off, \ + (uint32_t)lg_ld, (uint32_t)ci_ld, (uint32_t)cv_ld, (uint32_t)pairs_ld) + if (pool == 16) { R3D_STK(16); } + else if (pool == 32) { R3D_STK(32); } + else { R3D_STK(64); } +#undef R3D_STK + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== the narrowing stages and the draw + * + * One block a row of the candidate set, the row in LDS (five arrays of n_cand f32 at the band's + * 1024 is 20 KiB of the 64 KiB), and the division of labour the arithmetic asks for: + * + * - the max is a butterfly of strict `>`: libref's `if (v > mx) mx = v` from -infinity, so a + * candidate at -infinity (a hole, or a grammar-masked token at the set's tail) is never the max + * and a NaN never is; + * - exp(v - mx) is one value per candidate, so the wave computes them all, in parallel, into LDS; + * - every SUM that follows is libref's loop, in index order, on lane 0. The normaliser, the top-p + * prefix, the entropy and the inverse-CDF scan are all order-sensitive f32 accumulations, and + * the draw is decided by the last of them. A parallel prefix sum would round differently, and a + * draw that rounds differently is a different token: this is the law, so the loop stays serial. + * It is 1024 adds, half a microsecond; the transcendentals it waits on are the cost, and they + * are already out of the loop. + * + * A greedy row is left alone by every stage, as the reference leaves it, which is the same rule + * that keeps its token the argmax's. + */ +namespace { + +enum { ST_TOPP = 0, ST_MINP = 1, ST_TYPICAL = 2, ST_XTC = 3, ST_PICK = 4 }; + +__device__ __forceinline__ void cand_load(uint32_t n_cand, const int32_t* __restrict__ ir, + const float* __restrict__ vr, int32_t* __restrict__ ci, + float* __restrict__ cv) { + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + ci[i] = ir[i]; + cv[i] = vr[i]; + } +} + +__device__ __forceinline__ void cand_write(uint32_t n_cand, int32_t* __restrict__ ir, + float* __restrict__ vr, const int32_t* __restrict__ ci, + const float* __restrict__ cv) { + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + ir[i] = ci[i]; + vr[i] = cv[i]; + } +} + +/* exp(v[i] - mx) for every live candidate, in parallel. A dropped candidate gets 0, which is what + * the reference's loops contribute for it (they skip it, and a 0 is inert in every sum below). */ +__device__ __forceinline__ void cand_exp(uint32_t n_cand, const int32_t* __restrict__ ci, + const float* __restrict__ cv, float mx, + float* __restrict__ ev) { + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + ev[i] = (ci[i] >= 0) ? ref_exp(cv[i] - mx) : 0.0f; +} + +__device__ __forceinline__ float lane0_sum(uint32_t n_cand, const float* __restrict__ ev, + uint32_t* out) { + if (threadIdx.x == 0) { + float sum = 0.0f; + for (uint32_t i = 0; i < n_cand; ++i) sum += ev[i]; + out[0] = (uint32_t)(uintptr_t)0; + ((float*)out)[0] = sum; + } + __syncthreads(); + return ((float*)out)[0]; +} + +/* A minimum to match, for typical's cut: the smallest qualifying distance. */ +__device__ __forceinline__ float block_min(float v, float* lds) { + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; +#define R3D_MIN_XOR(M) v = fminf(v, r3d_xor_lane(v)) + R3D_MIN_XOR(16); R3D_MIN_XOR(8); R3D_MIN_XOR(4); R3D_MIN_XOR(2); R3D_MIN_XOR(1); +#undef R3D_MIN_XOR + if (lane == 0) lds[wave] = v; + __syncthreads(); + float t = lds[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) t = fminf(t, lds[w]); + return t; +} + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel( + int32_t* __restrict__ ci_p, float* __restrict__ cv_p, const RadSampleParams* __restrict__ pr, + int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) { + __shared__ int32_t s_ci[kCandMax]; + __shared__ float s_cv[kCandMax]; + __shared__ float s_ev[kCandMax]; + __shared__ float s_q[kCandMax]; + __shared__ float s_d[kCandMax]; + __shared__ float red[kWaves]; + __shared__ float st[4]; + __shared__ uint32_t su[4]; + + const uint32_t row = blockIdx.x; + const RadSampleParams& sp = pr[row]; + if (sp.flags & RAD_SP_GREEDY) return; /* the row's token is the argmax's, untouched */ + + int32_t* __restrict__ ir = ci_p + (size_t)row * ci_ld; + float* __restrict__ vr = cv_p + (size_t)row * cv_ld; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { s_ci[i] = ir[i]; s_cv[i] = vr[i]; } + __syncthreads(); + + /* mx over live candidates with a strict `>` from -infinity: a hole, a masked tail at -infinity + * and a NaN are all excluded, exactly as the reference's loop excludes them. */ + float mine = -INFINITY; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + if (s_ci[i] >= 0 && s_cv[i] > mine) mine = s_cv[i]; + const float mx = block_max(mine, red); + if (mx == -INFINITY) { + if (STAGE == ST_PICK && threadIdx.x == 0) tok[row] = -1; + return; /* an empty row: nothing to narrow, nothing to draw */ + } + + if (STAGE == ST_MINP) { + const float p = sp.min_p; + if (!(p > 0.0f)) return; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + if (s_ci[i] < 0) continue; + const float v = s_cv[i]; + if (v == mx) continue; /* the max always survives */ + if (ref_exp(v - mx) < p) { s_ci[i] = -1; s_cv[i] = -INFINITY; } + } + } else { + float inv = 0.0f; + /* exp(v - mx) for every live candidate, in parallel, in place in LDS. */ + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + s_ev[i] = (s_ci[i] >= 0) ? ref_exp(s_cv[i] - mx) : 0.0f; + __syncthreads(); + if (threadIdx.x == 0) { /* the normaliser: libref's loop, index order */ + float sum = 0.0f; + for (uint32_t i = 0; i < n_cand; ++i) sum += s_ev[i]; + st[0] = sum > 0.0f ? 1.0f / sum : 0.0f; + } + __syncthreads(); + inv = st[0]; + + if (STAGE == ST_TOPP) { + const float p = sp.top_p; + if (!(p < 1.0f) || !(p > 0.0f)) return; + if (threadIdx.x == 0) { /* the shortest prefix reaching p, at least one */ + float cum = 0.0f; + bool done = false; + for (uint32_t i = 0; i < n_cand; ++i) { + if (s_ci[i] < 0) continue; + if (done) { s_ci[i] = -1; s_cv[i] = -INFINITY; continue; } + cum += s_ev[i] * inv; + if (cum >= p) done = true; + } + } + __syncthreads(); + } else if (STAGE == ST_XTC) { + const float pq = sp.xtc_probability, th = sp.xtc_threshold; + if (!(pq > 0.0f) || !(th > 0.0f)) return; + if (threadIdx.x == 0) + su[1] = uniform01(sp.seed ^ RAD_SAMPLE_KEY_XTC, sp.pos) >= pq ? 1u : 0u; + __syncthreads(); + if (su[1]) return; /* the coin says leave the set alone this step */ + float cnt = 0.0f, last = -1.0f; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + if (s_ci[i] < 0) continue; + if (s_ev[i] * inv >= th) { cnt += 1.0f; last = (float)i; } + } + /* Count and last are a sum and a maximum: both order-free, which is why this stage needs + * no serial loop. Candidates above the threshold are re-tested below, from the same + * values in `s_ev`. */ + const float n_above = block_sum(cnt, red); + const float hi = block_max(last, red); + if (n_above < 2.0f) return; /* needs two to exclude all but the least likely */ + const int32_t keep = (int32_t)hi; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + if (s_ci[i] < 0 || (int32_t)i == keep) continue; + if (s_ev[i] * inv >= th) { s_ci[i] = -1; s_cv[i] = -INFINITY; } + } + __syncthreads(); + } else if (STAGE == ST_TYPICAL) { /* typical: the pick must not fall through here, + * it needs s_ev to still hold the exponentials */ + const float p = sp.typical_p; + if (!(p < 1.0f) || !(p > 0.0f)) return; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + s_q[i] = (s_ci[i] >= 0) ? s_ev[i] * inv : 0.0f; + __syncthreads(); + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + s_ev[i] = (s_q[i] > 0.0f) ? ref_log(s_q[i]) : 0.0f; /* log(q) once, used twice */ + __syncthreads(); + if (threadIdx.x == 0) { /* the entropy, in index order */ + float H = 0.0f; + for (uint32_t i = 0; i < n_cand; ++i) + if (s_q[i] > 0.0f) H -= s_q[i] * s_ev[i]; + st[1] = H; + } + __syncthreads(); + const float H = st[1]; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + s_d[i] = (s_q[i] > 0.0f) ? fabsf(-s_ev[i] - H) : 0.0f; + __syncthreads(); + /* The smallest distance whose mass reaches p. A lane owns one candidate's distance and + * sums the mass at or below it in index order; ties are kept, so the set may overshoot + * p and does not depend on the candidate order. */ + float cut = INFINITY; + for (uint32_t c = threadIdx.x; c < n_cand; c += kThreads) { + if (!(s_q[c] > 0.0f)) continue; + float mass = 0.0f; + for (uint32_t i = 0; i < n_cand; ++i) + if (s_q[i] > 0.0f && s_d[i] <= s_d[c]) mass += s_q[i]; + if (mass >= p && s_d[c] < cut) cut = s_d[c]; + } + const float cuth = block_min(cut, red); + if (cuth == INFINITY) return; /* no qualifying band: the reference leaves it be */ + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + if (s_ci[i] < 0) continue; + if (!(s_q[i] > 0.0f) || s_d[i] > cuth) { s_ci[i] = -1; s_cv[i] = -INFINITY; } + } + __syncthreads(); + } + + if (STAGE == ST_PICK) { + if (threadIdx.x == 0) { /* the inverse CDF, in candidate order */ + const float u = uniform01(sp.seed ^ RAD_SAMPLE_KEY_PICK, sp.pos); + float cum = 0.0f; + int32_t chosen = -1, last = -1; + for (uint32_t i = 0; i < n_cand; ++i) { + const int32_t id = s_ci[i]; + if (id < 0) continue; + const float v = s_cv[i]; + if (v > -INFINITY) last = id; /* a masked tail is never the fallback */ + cum += s_ev[i] * inv; + if (u < cum) { chosen = id; break; } + } + tok[row] = chosen >= 0 ? chosen : last; + } + return; /* the draw writes no candidate plane */ + } + } + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { ir[i] = s_ci[i]; vr[i] = s_cv[i]; } +} + +} /* namespace */ + +/* ci [M][n_cand] i32, INOUT: -1 marks a dropped candidate + * cv [M][n_cand] f32, INOUT: the LOGIT, -infinity with a drop + * params [M] 24 words a row -- the stage's own scalar, the seed and the pos + * + * The set is not re-sorted: it arrives descending from sample_topk and the stages skip holes. A + * greedy row is left exactly as it was. 0, -1, -2, -3, -4. */ +namespace { +template +int narrow_launch(long ci, long cv, long params, int M, int n_cand, long long ci_ld, + long long cv_ld, long stream, long tok) { + if (!ci || !cv || !params) return -1; + if (M <= 0 || n_cand <= 0 || n_cand > kCandMax) return -2; + if (!ci_ld) ci_ld = n_cand; + if (!cv_ld) cv_ld = n_cand; + if (ci_ld < n_cand || cv_ld < n_cand) return -3; + if (M > 0x7fffffff || n_cand > 0x7fffffff) return -2; + + const dim3 grid((unsigned)M), block(kThreads); + R3D_KLAUNCH(R3D_KNAME(narrow_kernel), grid, block, (hipStream_t)(uintptr_t)stream, + (int32_t*)ci, (float*)cv, (const RadSampleParams*)params, (int32_t*)tok, + (uint32_t)n_cand, (uint32_t)ci_ld, (uint32_t)cv_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} +} /* namespace */ + +extern "C" int r3d_sample_topp(long ci, long cv, long params, int M, int n_cand, long long ci_ld, + long long cv_ld, long stream) { + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, 0); +} +extern "C" int r3d_sample_minp(long ci, long cv, long params, int M, int n_cand, long long ci_ld, + long long cv_ld, long stream) { + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, 0); +} +extern "C" int r3d_sample_typical(long ci, long cv, long params, int M, int n_cand, + long long ci_ld, long long cv_ld, long stream) { + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, 0); +} +extern "C" int r3d_sample_xtc(long ci, long cv, long params, int M, int n_cand, long long ci_ld, + long long cv_ld, long stream) { + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, 0); +} + +/* The inverse-CDF draw over the candidate set: the splitmix64 uniform at (seed ^ PICK, pos), the + * normaliser and the accumulation in candidate order, and the fallback to the last candidate above + * -infinity when the f32 probabilities sum to less than u. Writes `token` only. */ +extern "C" int r3d_sample_pick(long ci, long cv, long params, long tok, int M, int n_cand, + long long ci_ld, long long cv_ld, long stream) { + if (!tok) return -1; + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, tok); +} + +/* ================================================================== the plugin ABI + * + * Nine shims, one per op. What a row's dtype is, the tensor says; what a row's geometry is, the + * operand says; `M` is the band's ceiling and never the row count, which is numel(x)/n_vocab. The + * params plane is checked the way libref checks it -- a 32-bit dtype and enough bytes for M rows -- + * and contiguous, because the kernels index it flat, as libref does. + */ + +#define R3D_NEED(expr) do { const int r3d_s = (expr); if (r3d_s) return R3D_NO(r3d_s); } while (0) + +/* A launcher checked the geometry and answered with a code; translate it to a RAD status. */ +static inline int r3d_launch_status(int e) { + switch (e) { + case 0: return RAD_OK; + case -1: return RAD_E_INVAL; + case -2: return RAD_E_SHAPE; + case -3: return RAD_E_STRIDE; + default: return RAD_E_DEVICE; + } +} + +static inline int sp_is_word(const RadTensor* t) { + return t && (t->dtype == RAD_U32 || t->dtype == RAD_I32 || t->dtype == RAD_F32); +} + +/* param_rows: the params operand is a byte blob of [M, 24] words. The dtype test + * is not decoration -- a 16-bit view of the plane passes a byte-count check and then misreads every + * row, so a stage would sample with the top half of one row's temp and the bottom of the next. */ +static inline int params_ok(const RadTensor* t, long long M) { + if (!t || !t->data) return RAD_E_INVAL; + if (!sp_is_word(t)) return RAD_E_DTYPE; + if (r3d_numel(t) * 4 < M * (long long)sizeof(RadSampleParams)) return RAD_E_SHAPE; + if (!r3d_contig(t)) return RAD_E_STRIDE; + if (!r3d_aligned(r3d_p(t), 8)) return RAD_E_ALIGN; /* the seed and pos are 8-byte fields */ + return RAD_OK; +} + +static inline int logits_ok(const RadTensor* t) { + if (!t || !t->data) return RAD_E_INVAL; + if (!r3d_is_f32(t)) return RAD_E_DTYPE; + if (!r3d_aligned(r3d_p(t), 4)) return RAD_E_ALIGN; + return RAD_OK; +} + +/* ------------------------------------------------------------------ row_topk */ + +enum { RTK_X = 0, RTK_IDX, RTK_VAL, RTK_PAIRS }; + +extern "C" int r3d_rad_row_topk(const RadArgs* a, RadStream stream) { + const RadTensor* x = r3d_opt(a, RTK_X); + const RadTensor* idx = r3d_opt(a, RTK_IDX); + const RadTensor* val = r3d_opt(a, RTK_VAL); + const RadTensor* pr = r3d_opt(a, RTK_PAIRS); + if (!x || !x->data || !idx || !idx->data || !val || !val->data) return R3D_NO(RAD_E_INVAL); + const int xdt = r3d_is_bf16(x) ? 0 : (r3d_is_f32(x) ? 1 : -1); + if (xdt < 0) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_i32(idx)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(val)) return R3D_NO(RAD_E_DTYPE); + if (pr && pr->data && !r3d_is_f32(pr)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_aligned(r3d_p(x), 4) || !r3d_aligned(r3d_p(idx), 4) || !r3d_aligned(r3d_p(val), 4)) + return R3D_NO(RAD_E_ALIGN); + + const long long N = r3d_geti_or(a, "N", r3d_dim(x, (int)x->rank - 1)); + const long long R = r3d_geti_or(a, "R", 1); + if (N <= 0 || R <= 0) return R3D_NO(RAD_E_SHAPE); + long long rows = 0, irows = 0, vrows = 0, prows = 0; + const long long x_ld = r3d_rows_pitch(x, N, &rows); + const long long idx_ld = r3d_rows_pitch(idx, R, &irows); + const long long val_ld = r3d_rows_pitch(val, R, &vrows); + if (x_ld < 0 || idx_ld < 0 || val_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || N > 0x7fffffffLL || R > 0x7fffffffLL) + return R3D_NO(RAD_E_SHAPE); + if (irows < rows || vrows < rows) return R3D_NO(RAD_E_SHAPE); + long long pairs = 0, pairs_ld = 0; + if (pr && pr->data) { + pairs_ld = r3d_rows_pitch(pr, 2 * R, &prows); + if (pairs_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (prows < rows || r3d_numel(pr) < rows * 2 * R) return R3D_NO(RAD_E_SHAPE); + pairs = r3d_addr(pr); + } + return r3d_launch_status(r3d_row_topk(r3d_addr(x), r3d_addr(idx), r3d_addr(val), pairs, + (int)rows, (int)N, (int)R, xdt, x_ld, idx_ld, val_ld, + pairs_ld, (int)r3d_geti_or(a, "vocab_off", 0), + (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ argmax and temp */ + +enum { ARG_LG = 0, ARG_PARAMS, ARG_TOK }; + +extern "C" int r3d_rad_sample_argmax(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, ARG_LG); + const RadTensor* pr = r3d_opt(a, ARG_PARAMS); + const RadTensor* tk = r3d_opt(a, ARG_TOK); + R3D_NEED(logits_ok(lg)); + if (!tk || !tk->data) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_i32(tk)) return R3D_NO(RAD_E_DTYPE); + const long long n_vocab = r3d_geti_or(a, "n_vocab", r3d_dim(lg, (int)lg->rank - 1)); + if (n_vocab <= 0) return R3D_NO(RAD_E_SHAPE); + long long rows = 0; + const long long lg_ld = r3d_rows_pitch(lg, n_vocab, &rows); + if (lg_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n_vocab > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(tk) < rows) return R3D_NO(RAD_E_SHAPE); + if (!r3d_contig(tk) || !r3d_aligned(r3d_p(tk), 4)) return R3D_NO(RAD_E_SHAPE); + /* The kernel reads no scalar from the params plane, so a missing one is not a refusal: argmax is + * the row every greedy request needs, and libref describes the operand without reading it. */ + if (pr && pr->data) R3D_NEED(params_ok(pr, rows)); + return r3d_launch_status(r3d_sample_argmax(r3d_addr(lg), r3d_addr(tk), (int)rows, (int)n_vocab, + lg_ld, (long)(uintptr_t)stream)); +} + +extern "C" int r3d_rad_sample_temp(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, ARG_LG); + const RadTensor* pr = r3d_opt(a, ARG_PARAMS); + R3D_NEED(logits_ok(lg)); + const long long n_vocab = r3d_geti_or(a, "n_vocab", r3d_dim(lg, (int)lg->rank - 1)); + if (n_vocab <= 0) return R3D_NO(RAD_E_SHAPE); + long long rows = 0; + const long long lg_ld = r3d_rows_pitch(lg, n_vocab, &rows); + if (lg_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n_vocab > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + R3D_NEED(params_ok(pr, rows)); + return r3d_launch_status(r3d_sample_temp(r3d_addr(lg), r3d_addr(pr), (int)rows, (int)n_vocab, + lg_ld, (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ sample_topk */ + +enum { TK_LG = 0, TK_PARAMS, TK_CI, TK_CV, TK_PAIRS }; + +extern "C" int r3d_rad_sample_topk(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, TK_LG); + const RadTensor* pr = r3d_opt(a, TK_PARAMS); + const RadTensor* ci = r3d_opt(a, TK_CI); + const RadTensor* cv = r3d_opt(a, TK_CV); + const RadTensor* pp = r3d_opt(a, TK_PAIRS); + R3D_NEED(logits_ok(lg)); + if (!ci || !ci->data || !cv || !cv->data) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_i32(ci)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(cv)) return R3D_NO(RAD_E_DTYPE); + if (pp && pp->data && !r3d_is_i32(pp)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_aligned(r3d_p(ci), 4) || !r3d_aligned(r3d_p(cv), 4)) return R3D_NO(RAD_E_ALIGN); + + const long long n_vocab = r3d_geti_or(a, "n_vocab", r3d_dim(lg, (int)lg->rank - 1)); + /* The width is the buffer's, the declare-time bound: the row's top_k narrows inside it. */ + const long long n_cand = r3d_dim(ci, (int)ci->rank - 1); + if (n_vocab <= 0 || n_cand <= 0 || n_cand > kCandMax) return R3D_NO(RAD_E_SHAPE); + long long rows = 0, cirows = 0, cvrows = 0, prows = 0; + const long long lg_ld = r3d_rows_pitch(lg, n_vocab, &rows); + const long long ci_ld = r3d_rows_pitch(ci, n_cand, &cirows); + const long long cv_ld = r3d_rows_pitch(cv, n_cand, &cvrows); + if (lg_ld < 0 || ci_ld < 0 || cv_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n_vocab > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + if (cirows < rows || cvrows < rows || r3d_numel(cv) < rows * n_cand) return R3D_NO(RAD_E_SHAPE); + R3D_NEED(params_ok(pr, rows)); + long long pairs = 0, pairs_ld = 0; + if (pp && pp->data) { + pairs_ld = r3d_rows_pitch(pp, 2 * n_cand, &prows); + if (pairs_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (prows < rows || r3d_numel(pp) < rows * 2 * n_cand) return R3D_NO(RAD_E_SHAPE); + pairs = r3d_addr(pp); + } + return r3d_launch_status(r3d_sample_topk(r3d_addr(lg), r3d_addr(pr), r3d_addr(ci), r3d_addr(cv), + pairs, (int)rows, (int)n_vocab, (int)n_cand, lg_ld, + ci_ld, cv_ld, pairs_ld, + (int)r3d_geti_or(a, "vocab_off", 0), + (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ the narrowing stages and the draw */ + +enum { NW_CI = 0, NW_CV, NW_PARAMS, NW_TOK }; + +struct CandRow { + long long n_cand, rows, ci_ld, cv_ld; +}; + +static inline int cand_row_ok(const RadArgs* a, const RadTensor* ci, const RadTensor* cv, + const RadTensor* pr, long long* M_hint, CandRow* g) { + if (!ci || !ci->data || !cv || !cv->data) return RAD_E_INVAL; + if (!r3d_is_i32(ci)) return RAD_E_DTYPE; + if (!r3d_is_f32(cv)) return RAD_E_DTYPE; + if (!r3d_aligned(r3d_p(ci), 4) || !r3d_aligned(r3d_p(cv), 4)) return RAD_E_ALIGN; + const long long n_cand = r3d_geti_or(a, "n_cand", r3d_dim(ci, (int)ci->rank - 1)); + if (n_cand <= 0 || n_cand > kCandMax) return RAD_E_SHAPE; + long long cirows = 0, cvrows = 0; + const long long ci_ld = r3d_rows_pitch(ci, n_cand, &cirows); + const long long cv_ld = r3d_rows_pitch(cv, n_cand, &cvrows); + if (ci_ld < 0 || cv_ld < 0) return RAD_E_STRIDE; + /* The step's rows are the operand's row count. The band key `M` is the plan's ceiling, never a + * source of row count: the plane decides the rows, and `M` is checked only as the upper bound + * the plan promised not to exceed. Preferring the key over the plane would refuse a step that + * fits the band. */ + const long long rows = cirows; + if (rows <= 0 || rows > 0x7fffffffLL) { r3d_trace_desc("ci", ci); + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] sample: %lld candidate rows, n_cand %lld\n", rows, n_cand); + return RAD_E_SHAPE; } + if (M_hint && *M_hint > 0 && rows > *M_hint) { r3d_trace_desc("ci", ci); + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] sample: %lld rows in a band that declared M <= %lld\n", + rows, *M_hint); + return RAD_E_SHAPE; } + if (cvrows < rows) { r3d_trace_desc("cv", cv); + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] sample: cv has %lld rows, ci has %lld\n", cvrows, rows); + return RAD_E_SHAPE; } + if (r3d_numel(cv) < rows * n_cand) return RAD_E_SHAPE; + const int s = params_ok(pr, rows); + if (s) return s; + g->n_cand = n_cand; g->rows = rows; g->ci_ld = ci_ld; g->cv_ld = cv_ld; + return RAD_OK; +} + +static int narrow_shim(const RadArgs* a, RadStream stream, + int (*launch)(long, long, long, int, int, long long, long long, long)) { + const RadTensor* ci = r3d_opt(a, NW_CI); + const RadTensor* cv = r3d_opt(a, NW_CV); + const RadTensor* pr = r3d_opt(a, NW_PARAMS); + CandRow g{}; + long long M_hint = r3d_geti_or(a, "M", 0); + const int s = cand_row_ok(a, ci, cv, pr, &M_hint, &g); + if (s) return R3D_NO(s); + return r3d_launch_status(launch(r3d_addr(ci), r3d_addr(cv), r3d_addr(pr), (int)g.rows, + (int)g.n_cand, g.ci_ld, g.cv_ld, (long)(uintptr_t)stream)); +} + +extern "C" int r3d_rad_sample_topp(const RadArgs* a, RadStream s) { + return narrow_shim(a, s, r3d_sample_topp); +} +extern "C" int r3d_rad_sample_minp(const RadArgs* a, RadStream s) { + return narrow_shim(a, s, r3d_sample_minp); +} +extern "C" int r3d_rad_sample_typical(const RadArgs* a, RadStream s) { + return narrow_shim(a, s, r3d_sample_typical); +} +extern "C" int r3d_rad_sample_xtc(const RadArgs* a, RadStream s) { + return narrow_shim(a, s, r3d_sample_xtc); +} + +extern "C" int r3d_rad_sample_pick(const RadArgs* a, RadStream stream) { + const RadTensor* ci = r3d_opt(a, NW_CI); + const RadTensor* cv = r3d_opt(a, NW_CV); + const RadTensor* pr = r3d_opt(a, NW_PARAMS); + const RadTensor* tk = r3d_opt(a, NW_TOK); + if (!tk || !tk->data) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_i32(tk)) return R3D_NO(RAD_E_DTYPE); + CandRow g{}; + long long M_hint = r3d_geti_or(a, "M", 0); + const int s = cand_row_ok(a, ci, cv, pr, &M_hint, &g); + if (s) return R3D_NO(s); + if (r3d_numel(tk) < g.rows) return R3D_NO(RAD_E_SHAPE); + if (!r3d_contig(tk) || !r3d_aligned(r3d_p(tk), 4)) return R3D_NO(RAD_E_SHAPE); + return r3d_launch_status(r3d_sample_pick(r3d_addr(ci), r3d_addr(cv), r3d_addr(pr), r3d_addr(tk), + (int)g.rows, (int)g.n_cand, g.ci_ld, g.cv_ld, + (long)(uintptr_t)stream)); +} diff --git a/libr3d/r3d_sample_pre_f32.hip b/libr3d/r3d_sample_pre_f32.hip new file mode 100644 index 00000000..41e46231 --- /dev/null +++ b/libr3d/r3d_sample_pre_f32.hip @@ -0,0 +1,932 @@ +/* r3d_sample_pre_f32.hip -- the sampler's pre-filters: the five stages that edit the logits row + * before the candidate set is built. `sample_logprobs`, `sample_penalties`, `sample_dry`, + * `sample_ngram_ban` and `sample_mask`; the draw spine -- argmax, temp, top-k, the narrowings and + * the pick -- is `r3d_sample_f32.hip`, and the only things shared are statics. + * + * The arithmetic is libref's, transcribed: the reference's sampler is the law, and + * `abi/rad_sample.h` is the wire format for every scalar, one 96-byte row per sampled position. The order of the + * arithmetic is transcription where the order can be seen, and there is a lot of it here: the + * penalties law (sign-dependent repetition, the count times the frequency, presence once per + * distinct token, all of it at the token's FIRST occurrence in the window), DRY's longest-suffix + * repeat per continuation token with its repeated-multiplication penalty, the n-gram ban's + * windowed prefix search and its whitelist exemption, and the mask's bit-per-token rule. + * + * ============================== what each stage reads, and why the shapes differ ============== + * + * The row is 130560 f32 at the band and there are 2048 of them: the logits plane is 1.02 GiB and + * one pass over it is ~3.6 ms on this card (RX 7600, 16 CUs). That number sorts the five into two + * shapes, and the shape is decided by how many of the row's columns the stage touches -- which is + * what the reference touches, not what it could: + * + * HISTORY STAGES -- penalties, dry, ngram_ban. A row's window is 64 tokens, so a row has at most + * 64 columns to touch. libref touches exactly those, and so does this file: one block a row of 64 + * threads, each position a thread, the window read straight from L2 (4096 integer reads a row, + * which is why the quadratic scans are free and why there is no LDS copy of the history). These + * kernels move kilobytes a row. Micro-optimising the scans would be optimising the part that is + * not the cost. + * + * ROW STAGES -- mask, logprobs. A mask writes every disallowed column of the row and logprobs + * summarises every column of it, so these read and write the plane and are the bandwidth rows of + * the unit: 256 threads a row, a thread a run of columns, so each lane's traffic is one + * contiguous segment. + * + * `sample_logprobs` is where the pass count is the whole argument. libref reads the row three + * times -- a max, then a sum of `exp(v - max)`, then a third scan to insert every element into a + * k-list -- so at the band it reads 3.06 GiB where one pass reads 1.02. One pass cannot know the + * row's max before it has seen the row, so each lane keeps a running max and a running DOUBLE sum + * of `exp(v - its own max)`, rescaling its sum when its max rises (one double multiply per rise, + * a handful per lane), and the butterfly merges pairs of (max, sum) by + * + * m = max(a, b); sum = a.sum * exp(a.mx - m) + b.sum * exp(b.mx - m) + * + * which is the reference's sum shifted by a constant per lane. Each term is the reference's term + * to a fraction of an f64 ulp, the merged sum lands on the reference's to ~1e-15 relative, and the + * stored value is f32 -- 6e-8 is the granularity of what the plane holds, so the rescaling is + * below the store's own rounding. The lane shuffles carry the max (32-bit) and the k-list (one + * 8-byte pattern an entry at a time); the sum is merged in LDS, by wave and then across waves, and + * the reason is in sample_logprobs_kernel's comment: a double can cross lanes soundly only by + * moving bits, never by value. `r3d_lanes_check` at the end of the file is the control that keeps + * that true, and `r3d_selftest.cpp` runs it. The `exp` + * is `exp(double)`, the reference's own width: libref's sum adds double exps and the row is the + * logit distribution, so this is the file's one fp64-heavy kernel and it is the slow path by law, + * not by oversight -- consumer RDNA3 is 1:64 on doubles. At the band (M=2048, + * n_vocab=130560, k=21) the plane's one read is 3.6 ms at 266 GiB/s, a read that also sums + * `exp(double)` is 30.4 ms, this kernel is 38.9 ms, and libref's three reads of that plane are + * 2.988 GiB against this kernel's 0.996. + * + * The k-list is per lane too, k deep, kept in the reference's order -- descending by value, ties + * to the LOWER column, which is `topk_next`'s total order and the narrowing stages' -- and merged + * pairwise in the same butterfly, so the block's list is the reference's list. `k` at the band is + * 21; the pool is 64 deep, and a request above that is refused rather than silently truncated. + * + * ============================== agreement, and where this file declines ============================== + * + * Maxima are strict `>` with the max as the first argument, which is `std::max`'s law and is how a + * NaN is kept out of the row's max: a NaN never compares greater, so it is never adopted, at the + * first element or anywhere later. A NaN in the sum propagates, because the reference's + * `exp(NaN - mx)` is NaN and it is added. + * + * A row whose parameters turn the stage off is left bit for bit as it was -- the flag test is the + * reference's, and for penalties the identity test (rep 1, freq 0, pres 0) is too. + * + * Declines, all of them RAD_E_UNSUPPORTED from the shim and none of them reachable from a row that + * carries the constraints its rows do: a history plane wider than 2^31/8 columns is not a plane; + * `k` above 64 for logprobs (the pool's depth, and far above any k the engine requests); and for + * ngram_ban a `whitelist` plane, which the kernel implements -- the whitelist is exempted before + * the -inf writes, as the reference removes it from the banned set -- so the only decline is the + * `ngram` plane's dtype and the mask and whitelist's, which must be 32-bit words. + */ + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +#include + +/* ================================================================== shared helpers (statics) + * + * The headers are frozen, so a unit that needs a helper carries its own copy and keeps it static: a + * non-static one collides at link with the same helper in another unit and takes the library down. + */ +namespace { + +constexpr uint32_t kThreads = 256; /* 8 waves: the row stages */ +constexpr uint32_t kPre = 64; /* 2 waves: the history stages, a position a thread */ +constexpr uint32_t kWave = 32; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr int kKMax = 64; /* the k-list pool's depth, per lane */ + +/* The row's summary accumulates `exp` in DOUBLE, because that is where the reference's sum lives. + * The width is a switch, because the width is the cost: at the band the double exp is 30 ms of the + * kernel's 38 ms against a 3.7 ms plane read, and an f32 exp widened to double -- + * `expf`, terms accurate to an f32 ulp, summed in double -- lands the row's sum on the reference's + * to ~1e-10 relative against a stored f32 granularity of 6e-8. Define R3D_LP_EXP_F32 to build the + * fast exp; the default is the reference's arithmetic. */ +#ifdef R3D_LP_EXP_F32 +__device__ __forceinline__ double dexp(double x) { return (double)expf((float)x); } +#else +__device__ __forceinline__ double dexp(double x) { return exp(x); } +#endif + +/* A whole-register load of an index plane: the history, the n-gram pair, the bitmask words. */ +__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) { + return (int32_t)ldg_u32((const uint32_t*)p); +} +__device__ __forceinline__ uint32_t ldg_u8(const uint8_t* p) { return *(const uint8_t*)p; } + +/* Lane partners of the accumulator's pieces. */ +template +__device__ __forceinline__ int32_t xor_i32(int32_t v) { + return (int32_t)r3d_xor_lane_u32((uint32_t)v); +} +/* There is no 64-bit lane shuffle here on purpose: see sample_logprobs_kernel. */ + +/* The law, verbatim. The window both history stages read, clamped to the row's own row + * of the plane; `last_n` 0 disables the stage, a negative keeps the whole span, a positive keeps + * its TAIL. The window law IS the history law: the window, and the rule that a token is penalised + * at its first occurrence in it. */ +__device__ __forceinline__ bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax, + int64_t* ho_out, int64_t* hl_out) { + if (last_n == 0) return false; + int64_t hl = sp.hist_len; + int64_t ho = sp.hist_off < 0 ? 0 : sp.hist_off; + if (ho > hmax) ho = hmax; + if (hl > hmax - ho) hl = hmax - ho; + if (last_n > 0 && hl > last_n) { + ho += hl - last_n; + hl = last_n; + } + *ho_out = ho; + *hl_out = hl; + return hl > 0; +} + +/* The law, verbatim, including the stop short of overflow: repeated multiplication, so + * every implementation lands on the same float. */ +__device__ __forceinline__ float dry_penalty(float multiplier, float base, int64_t e) { + float pen = multiplier; + if (base == 1.0f) return pen; + const float lim = FLT_MAX / base; + for (int64_t i = 0; i < e; ++i) { + if (pen > lim) break; + pen *= base; + } + return pen; +} + +/* The k-list's order: descending by value, ties to the lower column. `above(x, y)` is "x comes + * first", the reference's comparator and `topk_next`'s chain. */ +struct Cand { float v; int32_t i; }; +__device__ __forceinline__ bool above(Cand x, Cand y) { + return x.v > y.v || (x.v == y.v && x.i < y.i); +} + +/* ================================================================== sample_logprobs + * + * The law. The row's summary: its max, the sum of exp(v - max) in double, and the k + * largest as (id, logit) pairs descending, ids as floats with `vocab_off` added, an unfilled slot + * id -1 and logit -infinity. Rows without RAD_SP_LOGPROBS are not written at all. + * + * One pass over the row, per the file's header: the max, the sum and the k-list are three + * independent accumulations of the same read, and the sum is rescaled into the row's final max at + * the merge, which is a per-lane shift of the reference's terms. + */ +struct Acc { + float mx; + double sum; + Cand c[kKMax]; + int n; +}; + +/* A lane's running state over its own elements. A new maximum rescales the sum it has so far; the + * reference never rescales (it knows the max up front) and the rescale is the price of the read. */ +__device__ __forceinline__ void acc_push(Acc& a, int k, uint32_t col, float v) { + if (v > a.mx) { + if (a.mx != -INFINITY) a.sum *= dexp((double)a.mx - (double)v); + a.mx = v; + } + a.sum += dexp((double)v - (double)a.mx); + /* The reference's insertion: an element that is not above the k-th is dropped, and the insert + * point is the first slot the element beats (with a NaN, no slot, so the tail: insert, then the + * pop leaves the list exactly as it was). */ + if (a.n == k && !above(Cand{ v, (int32_t)col }, a.c[a.n - 1])) return; + int pos = 0; + while (pos < a.n && !above(Cand{ v, (int32_t)col }, a.c[pos])) ++pos; + if (pos >= k) return; + for (int j = (a.n < k ? a.n : k - 1); j > pos; --j) a.c[j] = a.c[j - 1]; + a.c[pos] = Cand{ v, (int32_t)col }; + if (a.n < k) ++a.n; +} + +/* The butterfly's merge of two lanes' states: the max is strict, the sum is the two shifted sums, + * and the lists merge on the same order. Ties in the merge (two equal values at equal columns + * cannot happen -- the column is the lane's -- and a NaN is not above anything, so a NaN list + * entry stays in the lane that read it). */ +__device__ __forceinline__ Acc acc_merge(const Acc& a, const Acc& b, int k) { + Acc r; + r.mx = a.mx > b.mx ? a.mx : b.mx; + r.sum = (a.mx == -INFINITY ? 0.0 : a.sum * dexp((double)a.mx - (double)r.mx)) + + (b.mx == -INFINITY ? 0.0 : b.sum * dexp((double)b.mx - (double)r.mx)); + int i = 0, j = 0; + r.n = 0; + while (r.n < k && (i < a.n || j < b.n)) { + const bool take_b = (i >= a.n) || (j < b.n && above(b.c[j], a.c[i])); + r.c[r.n++] = take_b ? b.c[j++] : a.c[i++]; + } + return r; +} + +template +__global__ __launch_bounds__(THR) void sample_logprobs_kernel( + const float* __restrict__ lg, const RadSampleParams* __restrict__ pr, + float* __restrict__ st, uint32_t n, uint32_t k, uint32_t lg_ld, uint32_t st_ld, + int32_t voff) { + const uint32_t row = blockIdx.x; + if (!(pr[row].flags & RAD_SP_LOGPROBS)) return; + + Acc a; + a.mx = -INFINITY; + a.sum = 0.0; + a.n = 0; + const float* __restrict__ lr = lg + (size_t)row * lg_ld; + for (uint32_t c = threadIdx.x; c < n; c += THR) acc_push(a, (int)k, c, ldg_f32(lr + c)); + + /* The k-list and the max meet their partners in the wave's 32-bit lane shuffles, five rounds. + * + * The participation mask of a 64-bit shuffle on this ROCm is an `unsigned long long`, and on + * wave32 it is `0xFFFFFFFFull`: `~0ull` names lanes 32..63, which a wave of 32 does not have. + * `r3d_lanes_check` at the end of this file is the control that proves the lane helpers, and + * `r3d_selftest.cpp` runs it and checks every lane of every wave. + * + * The SUM does not go through a lane shuffle: it meets its partners in LDS, the machinery + * `block_sum` already trusts. A double can cross lanes soundly -- lanes_check_kernel below is + * exact in all 256 lanes of all 8 waves for three forms of it -- but only by moving the value's + * *bits*, never by value: a cast to an integer type converts by value, so + * + * d += (double)r3d_xor_lane_u64((unsigned long long)d); + * + * truncates the partner's term to its integer part, and a wave of fractions then sums to 1, the + * largest term's integer part -- a 40% loss of the row's mass at the band's width, the shape a + * hardware fault takes. The k-list, whose entries are bit patterns by construction (a float's + * pattern and an int in one 8-byte value), crosses lanes as that pattern in one shuffle; the sum, + * which is a number, does not cross lanes at all. */ +#define R3D_ACC_XOR(M) \ + { \ + Acc b; \ + b.mx = r3d_xor_lane(a.mx); \ + b.n = xor_i32((int32_t)a.n); \ + for (int j = 0; j < k; ++j) { \ + /* One list entry is one 8-byte value -- a float's pattern and a column -- and it + * crosses lanes as that pattern, in one shuffle. Assembling it from the two halves on + * the far side would need each half shuffled and then reassembled by value, which is + * the shape that turns a bit pattern into a number. */ \ + const unsigned long long packed = \ + (unsigned long long)__float_as_uint(a.c[j].v) | \ + ((unsigned long long)(uint32_t)a.c[j].i << 32); \ + const unsigned long long got = __shfl_xor_sync(0xFFFFFFFFull, packed, M); \ + b.c[j] = Cand{ __uint_as_float((uint32_t)got), (int32_t)(uint32_t)(got >> 32) }; \ + } \ + b.sum = 0.0; \ + const float mx = a.mx > b.mx ? a.mx : b.mx; /* no lane's max is a NaN: a NaN is never \ + adopted by the strict test above */ \ + a = acc_merge(a, b, (int)k); \ + a.mx = mx; \ + } + R3D_ACC_XOR(16) + R3D_ACC_XOR(8) + R3D_ACC_XOR(4) + R3D_ACC_XOR(2) + R3D_ACC_XOR(1) +#undef R3D_ACC_XOR + + /* The wave's sum, in LDS: the wave's max first, then every lane's sum shifted into it, in lane + * order. An empty lane (a row narrower than the block) has max -infinity and sum 0 and + * contributes nothing, which is the reference's own arithmetic on an empty span. */ + __shared__ float s_mx[kThreads]; + __shared__ double s_sum[kThreads]; + __shared__ float w_mx[kWaves]; + __shared__ double w_sum[kWaves]; + __shared__ int w_n[kWaves]; + __shared__ Cand w_c[kWaves][kKMax]; + s_mx[threadIdx.x] = a.mx; + s_sum[threadIdx.x] = a.sum; + __syncthreads(); + + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + if (lane == 0) { + const uint32_t b = wave * kWave; + float m = s_mx[b]; + for (uint32_t l = 1; l < kWave; ++l) + if (s_mx[b + l] > m) m = s_mx[b + l]; + double s = 0.0; + for (uint32_t l = 0; l < kWave; ++l) + s += s_mx[b + l] == -INFINITY ? 0.0 + : s_sum[b + l] * dexp((double)s_mx[b + l] - (double)m); + w_mx[wave] = m; + w_sum[wave] = s; + w_n[wave] = a.n; + for (int j = 0; j < k; ++j) w_c[wave][j] = a.c[j]; + } + __syncthreads(); + if (threadIdx.x != 0) return; + /* The eight wave partials, in wave order: the row's max, the row's sum, the row's k-list. */ + float m = w_mx[0]; + double s = w_sum[0]; + int n_list = w_n[0]; + Cand list[kKMax]; + for (int j = 0; j < k; ++j) list[j] = w_c[0][j]; + for (uint32_t w = 1; w < kWaves; ++w) { + const float mm = w_mx[w] > m ? w_mx[w] : m; + s = (m == -INFINITY ? 0.0 : s * dexp((double)m - (double)mm)) + + (w_mx[w] == -INFINITY ? 0.0 : w_sum[w] * dexp((double)w_mx[w] - (double)mm)); + m = mm; + Acc x, y; + x.mx = m; x.sum = 0.0; x.n = n_list; + for (int j = 0; j < k; ++j) x.c[j] = list[j]; + y.mx = w_mx[w]; y.sum = 0.0; y.n = w_n[w]; + for (int j = 0; j < k; ++j) y.c[j] = w_c[w][j]; + const Acc t = acc_merge(x, y, (int)k); + n_list = t.n; + for (int j = 0; j < k; ++j) list[j] = t.c[j]; + } + + float* __restrict__ sr = st + (size_t)row * st_ld; + sr[0] = m; + sr[1] = (float)s; + for (uint32_t j = 0; j < k; ++j) { + const bool have_j = j < (uint32_t)n_list; + sr[2 + 2 * j] = have_j ? (float)(list[j].i + voff) : -1.0f; + sr[3 + 2 * j] = have_j ? list[j].v : -INFINITY; + } +} + +/* ================================================================== sample_penalties + * + * The law. llama.cpp's ordering, at the token's first occurrence in the window: + * + * repetition logit = logit > 0 ? logit / rep : logit * rep + * frequency logit -= count * freq + * presence logit -= pres + * + * The repetition penalty is sign-dependent because dividing a negative logit would raise it. The + * count carries the multiplicity, which is why the update runs once per distinct token, and the + * scan for it is the reference's own: walk the window from the front, stop at an earlier + * occurrence, count the ones from here on. + * + * Columns are global ids less `vocab_off`, so a token on another rank's shard is skipped here and + * penalised there. Each distinct token is one column and one thread, so the writes cannot race. + */ +__global__ __launch_bounds__(kPre) void sample_penalties_kernel( + float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist, + uint32_t n, uint32_t lg_ld, uint32_t hmax, int32_t voff) { + const uint32_t row = blockIdx.x; + const RadSampleParams& sp = pr[row]; + if (!(sp.flags & RAD_SP_PENALTY)) return; + const float rep = sp.rep_penalty, freq = sp.freq_penalty, pres = sp.pres_penalty; + if (rep == 1.0f && freq == 0.0f && pres == 0.0f) return; + + int64_t ho = 0, hl = 0; + if (!hist_window(sp, sp.penalty_last_n, (int64_t)hmax, &ho, &hl)) return; + + const int32_t* __restrict__ hr = hist + (size_t)row * hmax + ho; + float* __restrict__ lr = lg + (size_t)row * lg_ld; + for (uint32_t i = threadIdx.x; i < (uint32_t)hl; i += kPre) { + const int32_t tok = ldg_i32(hr + i); + const int64_t col = (int64_t)tok - voff; + if (tok < 0 || col < 0 || col >= n) continue; + bool first = true; + int64_t count = 0; + for (int64_t j = 0; j < hl; ++j) { + if (ldg_i32(hr + j) != tok) continue; + if (j < (int64_t)i) { first = false; break; } + ++count; + } + if (!first) continue; + float v = lr[col]; + v = v > 0.0f ? v / rep : v * rep; + v -= (float)count * freq; + v -= pres; + lr[col] = v; + } +} + +/* ================================================================== sample_dry + * + * The law, DRY's rule (llama.cpp's llama_sampler_dry_apply): for every earlier position + * j, n_j is how long a suffix of the window also ends at j, capped at the breaker limit; the token + * at j+1 would extend that repeat and is penalised by multiplier * base^(n - allowed), once, by the + * LONGEST repeat it follows. A token that is itself a whole-sequence breaker is never penalised, + * and only lengths at or above `allowed` count. + * + * A thread a position, the window read from L2. The map the reference keeps is here a maximum over + * the threads that share a token, applied by the thread holding the token's first occurrence, so + * one column is written once. + */ +__global__ __launch_bounds__(kPre) void sample_dry_kernel( + float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist, + const uint8_t* __restrict__ brk, uint32_t n, uint32_t lg_ld, uint32_t hmax, int32_t voff) { + const uint32_t row = blockIdx.x; + const RadSampleParams& sp = pr[row]; + if (!(sp.flags & RAD_SP_DRY) || !(sp.dry_multiplier > 0.0f)) return; + const int64_t allowed = sp.dry_allowed_length > 0 ? sp.dry_allowed_length : 2; + + int64_t ho = 0, hl = 0; + if (!hist_window(sp, sp.dry_penalty_last_n, (int64_t)hmax, &ho, &hl)) return; + if (hl <= allowed) return; + const int64_t cap = sp.dry_rep_limit > 0 && sp.dry_rep_limit < hl ? sp.dry_rep_limit : hl; + if (cap < allowed) return; + + const int32_t* __restrict__ hr = hist + (size_t)row * hmax + ho; + const uint8_t* __restrict__ br = brk ? brk + (size_t)row * hmax + ho : nullptr; + float* __restrict__ lr = lg + (size_t)row * lg_ld; + const auto tok_at = [&](int64_t i) { return ldg_i32(hr + i); }; + const auto exempt = [&](int64_t i) { return br && ldg_u8(br + i) != 0u; }; + const float base = sp.dry_base > 0.0f ? sp.dry_base : 1.75f; + + for (uint32_t j = threadIdx.x; j + 1u < (uint32_t)hl; j += kPre) { + const int64_t lim = ((int64_t)j + 1 < cap) ? (int64_t)j + 1 : cap; + int64_t m = 0; + while (m < lim && tok_at(j - m) == tok_at(hl - 1 - m)) ++m; + if (m < allowed || exempt((int64_t)j + 1)) continue; + const int32_t tok = tok_at((int64_t)j + 1); + const int64_t col = (int64_t)tok - voff; + if (tok < 0 || col < 0 || col >= n) continue; + /* The longest repeat any position attributes to this token, and the first thread that + * carries it pays for it. Equal tokens at equal lengths: the lowest j, so one writer. */ + int64_t longest = m; + bool first = true; + for (int64_t q = 0; q + 1 < hl; ++q) { + if (tok_at(q + 1) != tok) continue; + const int64_t limq = (q + 1 < cap) ? q + 1 : cap; + int64_t mq = 0; + while (mq < limq && tok_at(q - mq) == tok_at(hl - 1 - mq)) ++mq; + if (mq < allowed || exempt(q + 1)) continue; + if (mq > longest) longest = mq; + if (q < (int64_t)j) { first = false; break; } + } + if (!first) continue; + const float v = lr[col]; + lr[col] = v - dry_penalty(sp.dry_multiplier, base, longest - allowed); + } +} + +/* ================================================================== sample_ngram_ban + * + * The law, the windowed no-repeat-ngram ban. With the row's window s[0, hl): + * + * search_start = max(0, hl - w); search_end = hl - n + 1; prefix = s[hl - n + 1, hl) + * for idx in [search_start, search_end): s[idx, idx + n - 1) == prefix => ban s[idx + n - 1] + * + * The window is on the START index, so the n-gram that straddles the window's edge is searched. A + * banned token's logit becomes -infinity, and the whitelist is removed from the banned set before + * any -inf is written, so a whitelisted column is never touched. n == 1 bans every token in the + * window, the prefix being empty. A row whose n is 0 is left bit for bit as it was. + * + * A thread a search index. Several indices can ban the same token; the write is the same -infinity + * from every one of them, so the race writes one value. + */ +__global__ __launch_bounds__(kPre) void sample_ngram_ban_kernel( + float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist, + const int32_t* __restrict__ ngram, const int32_t* __restrict__ wl, uint32_t n, uint32_t lg_ld, + uint32_t hmax, uint32_t words, int32_t voff) { + const uint32_t row = blockIdx.x; + const RadSampleParams& sp = pr[row]; + const int32_t* __restrict__ nr = ngram + (size_t)row * 2; + const int64_t nn = ldg_i32(nr); + const int64_t win_req = ldg_i32(nr + 1); + if (nn <= 0) return; + + int64_t ho = 0, hl = 0; + if (!hist_window(sp, -1, (int64_t)hmax, &ho, &hl)) return; /* the whole staged span */ + if (hl < nn) return; + const int64_t win = (win_req > 0 && win_req < hl) ? win_req : hl; + const int64_t search_start = hl - win; + const int64_t search_end = hl - nn + 1; + if (search_end <= search_start) return; + + const int32_t* __restrict__ hr = hist + (size_t)row * hmax + ho; + const int32_t* __restrict__ wr = wl ? wl + (size_t)row * words : nullptr; + float* __restrict__ lr = lg + (size_t)row * lg_ld; + const auto tok_at = [&](int64_t i) { return ldg_i32(hr + i); }; + const auto exempt = [&](int64_t col) { + if (!wr) return false; + const uint32_t word = (uint32_t)ldg_i32(wr + col / 32); + return ((word >> (uint32_t)(col % 32)) & 1u) != 0u; + }; + const int64_t plen = nn - 1, p0 = hl - plen; + + for (uint32_t idx = search_start + threadIdx.x; idx < (uint32_t)search_end; idx += kPre) { + bool match = true; + for (int64_t j = 0; j < plen; ++j) { + if (tok_at((int64_t)idx + j) != tok_at(p0 + j)) { match = false; break; } + } + if (!match) continue; + const int32_t tok = tok_at((int64_t)idx + plen); + const int64_t col = (int64_t)tok - voff; + if (tok < 0 || col < 0 || col >= n) continue; + if (exempt(col)) continue; + lr[col] = -INFINITY; + } +} + +/* ================================================================== sample_mask + * + * The law. A set bit means allowed; an unset column's logit becomes -infinity. This is + * the dense row stage: a row of 130560 columns and a bitmask of 4080 words, so a thread takes a + * word and the 32 columns under it, which is one contiguous 128-byte segment a lane. A word that + * is all ones is skipped whole, and a word that is all zeros is a run of eight 16-byte stores; + * either way the row is written in the order the plane is laid out. + * + * `mask_row` is the row's own row of the bitmask plane, and the reference skips a row index + * outside the plane, -1 included (the shape hook caps `idx_max` at M so a fixture draws a real + * row); the shim bounds the plane to at least M rows, which is the same test at the geometry the + * op's descriptor describes. + */ +__global__ __launch_bounds__(kThreads) void sample_mask_kernel( + float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ bm, + uint32_t n, uint32_t lg_ld, uint32_t words, uint32_t mask_rows) { + const uint32_t row = blockIdx.x; + const RadSampleParams& sp = pr[row]; + if (!(sp.flags & RAD_SP_MASK)) return; + const int64_t mrow = sp.mask_row; + if (mrow < 0 || (uint64_t)mrow >= mask_rows) return; + + const int32_t* __restrict__ br = bm + (size_t)mrow * words; + float* __restrict__ lr = lg + (size_t)row * lg_ld; + for (uint32_t w = threadIdx.x; w < words; w += kThreads) { + const uint32_t bits = (uint32_t)ldg_i32(br + w); + if (bits == 0xffffffffu) continue; /* nothing banned in these 32 */ + const uint32_t c0 = 32u * w; + const uint32_t cnt = n - c0 < 32u ? n - c0 : 32u; /* the row's last word is partial */ + if (bits == 0u) { + for (uint32_t c = 0; c < cnt; ++c) lr[c0 + c] = -INFINITY; + continue; + } + for (uint32_t c = 0; c < cnt; ++c) + if (((bits >> c) & 1u) == 0u) lr[c0 + c] = -INFINITY; + } +} + +/* ------------------------------------------------------------------ shim helpers */ + +static inline int sp_is_word(const RadTensor* t) { + return t && (t->dtype == RAD_U32 || t->dtype == RAD_I32 || t->dtype == RAD_F32); +} + +/* The params plane: [M, 24] words. The dtype test is not decoration -- a 16-bit view of the plane + * passes a byte-count check and then misreads every row, sampling with the top half of one row's + * temp and the bottom of the next. */ +static inline int params_ok(const RadTensor* t, long long M) { + if (!t || !t->data) return RAD_E_INVAL; + if (!sp_is_word(t)) return RAD_E_DTYPE; + if (r3d_numel(t) * 4 < M * (long long)sizeof(RadSampleParams)) return RAD_E_SHAPE; + if (!r3d_contig(t)) return RAD_E_STRIDE; + if (!r3d_aligned(r3d_p(t), 8)) return RAD_E_ALIGN; /* seed and pos are 8-byte fields */ + return RAD_OK; +} + +static inline int logits_ok(const RadTensor* t) { + if (!t || !t->data) return RAD_E_INVAL; + if (!r3d_is_f32(t)) return RAD_E_DTYPE; + if (!r3d_aligned(r3d_p(t), 4)) return RAD_E_ALIGN; + return RAD_OK; +} + +/* The history plane: i32 [M, max_hist], contiguous, its width the reference's `hmax`. */ +static inline int hist_ok(const RadTensor* t, long long M, long long* hmax) { + if (!t || !t->data) return RAD_E_INVAL; + if (!r3d_is_i32(t)) return RAD_E_DTYPE; + if (!r3d_contig(t)) return RAD_E_STRIDE; + if (!r3d_aligned(r3d_p(t), 4)) return RAD_E_ALIGN; + const long long w = r3d_numel(t) / M; + if (w <= 0 || w > 0x7fffffffLL) return RAD_E_SHAPE; + *hmax = w; + return RAD_OK; +} + +static inline int r3d_launch_status(int rc) { + if (rc == 0) return RAD_OK; + switch (rc) { + case -1: return RAD_E_INVAL; + case -2: return RAD_E_SHAPE; + case -3: return RAD_E_STRIDE; + default: return RAD_E_DEVICE; + } +} + +/* The logits row count, from the plane and never from the band's M. */ +static inline int logits_rows(const RadArgs* a, const RadTensor* lg, long long* n_vocab, + long long* rows, long long* lg_ld) { + /* The reference reads the width off the band, falling back to the plane's last dimension, and + * a rank-1 plane has no last dimension to read: the width is absent, which is E_SHAPE. */ + *n_vocab = r3d_geti_or(a, "n_vocab", + lg->rank >= 2 ? r3d_dim(lg, (int)lg->rank - 1) : 0); + if (*n_vocab <= 0 || *n_vocab > 0x7fffffffLL) return RAD_E_SHAPE; + *lg_ld = r3d_rows_pitch(lg, *n_vocab, rows); + if (*lg_ld < 0) return RAD_E_STRIDE; + if (*rows <= 0 || *rows > 0x7fffffffLL) return RAD_E_SHAPE; + return RAD_OK; +} + +} /* namespace */ + +#define R3D_NEED(x) \ + do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0) + +/* ================================================================== launchers + * + * lg [M][n_vocab] f32, INOUT for the four editing stages, read-only for logprobs + * params [M] 24 words a row, the per-row scalars + * hist [M][max_hist] i32, global token ids, `hist_off`/`hist_len` windowing it + * stats [M][2 + 2k] f32 + * bitmask [rows][(n_vocab+31)/32] i32, a set bit meaning allowed + * + * 0, -1 null, -2 bad extent, -3 pitch, -4 the HIP launch failed. No allocation, no synchronisation. + */ + +extern "C" int r3d_sample_logprobs(long lg, long params, long stats, int M, int n_vocab, int k, + long long lg_ld, long long stats_ld, int vocab_off, + long stream) { + if (!lg || !params || !stats) return -1; + if (M <= 0 || n_vocab <= 0 || k <= 0) return -2; + if (k > kKMax) return -2; + if (!lg_ld) lg_ld = n_vocab; + if (!stats_ld) stats_ld = 2 + 2 * (long long)k; + if (lg_ld < n_vocab || stats_ld < 2 + 2 * (long long)k) return -3; + R3D_KLAUNCH(R3D_KNAME(sample_logprobs_kernel), dim3((uint32_t)M), dim3(kThreads), + (hipStream_t)(uintptr_t)stream, (const float*)(uintptr_t)lg, + (const RadSampleParams*)(uintptr_t)params, (float*)(uintptr_t)stats, + (uint32_t)n_vocab, (uint32_t)k, (uint32_t)lg_ld, (uint32_t)stats_ld, + (int32_t)vocab_off); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_sample_penalties(long lg, long params, long hist, int M, int n_vocab, + long long lg_ld, long long hist_ld, int vocab_off, + long stream) { + if (!lg || !params || !hist) return -1; + if (M <= 0 || n_vocab <= 0) return -2; + if (!lg_ld) lg_ld = n_vocab; + if (!hist_ld) return -2; /* the window is clamped to the plane's width */ + if (lg_ld < n_vocab || hist_ld <= 0) return -3; + R3D_KLAUNCH(R3D_KNAME(sample_penalties_kernel), dim3((uint32_t)M), dim3(kPre), + (hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg, + (const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)hist, + (uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hist_ld, (int32_t)vocab_off); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_sample_dry(long lg, long params, long hist, long breakers, int M, int n_vocab, + long long lg_ld, long long hist_ld, int vocab_off, long stream) { + if (!lg || !params || !hist) return -1; + if (M <= 0 || n_vocab <= 0) return -2; + if (!lg_ld) lg_ld = n_vocab; + if (!hist_ld) return -2; + if (lg_ld < n_vocab || hist_ld <= 0) return -3; + R3D_KLAUNCH(R3D_KNAME(sample_dry_kernel), dim3((uint32_t)M), dim3(kPre), + (hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg, + (const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)hist, + (const uint8_t*)(uintptr_t)breakers, (uint32_t)n_vocab, (uint32_t)lg_ld, + (uint32_t)hist_ld, (int32_t)vocab_off); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_sample_ngram_ban(long lg, long params, long hist, long ngram, long whitelist, + int M, int n_vocab, long long lg_ld, long long hist_ld, + int vocab_off, long stream) { + if (!lg || !params || !hist || !ngram) return -1; + if (M <= 0 || n_vocab <= 0) return -2; + if (!lg_ld) lg_ld = n_vocab; + if (!hist_ld) return -2; + if (lg_ld < n_vocab || hist_ld <= 0) return -3; + const uint32_t words = (uint32_t)((n_vocab + 31) / 32); + R3D_KLAUNCH(R3D_KNAME(sample_ngram_ban_kernel), dim3((uint32_t)M), dim3(kPre), + (hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg, + (const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)hist, + (const int32_t*)(uintptr_t)ngram, (const int32_t*)(uintptr_t)whitelist, + (uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hist_ld, words, (int32_t)vocab_off); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_sample_mask(long lg, long params, long bitmask, int M, int n_vocab, + long long lg_ld, int mask_rows, long stream) { + if (!lg || !params || !bitmask) return -1; + if (M <= 0 || n_vocab <= 0) return -2; + if (!lg_ld) lg_ld = n_vocab; + if (lg_ld < n_vocab) return -3; + if (mask_rows < M) return -3; /* a plane that cannot address row M-1 is not that plane */ + const uint32_t words = (uint32_t)((n_vocab + 31) / 32); + /* mask_rows is the bitmask plane's own row count, which is what the reference compares + * mask_row against, and the shim reads it off the operand. It is M at the geometry the shape + * hook draws and the engine builds, and larger when a caller hands a plane of its own, in which + * case a row addressing past M is masked, as the reference masks it. The grid stays M: rows + * past the logits plane's row count have no logits to mask. */ + R3D_KLAUNCH(R3D_KNAME(sample_mask_kernel), dim3((uint32_t)M), dim3(kThreads), + (hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg, + (const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)bitmask, + (uint32_t)n_vocab, (uint32_t)lg_ld, words, (uint32_t)mask_rows); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== shims + * + * libref's operand lists: {logits, params, history[, breakers]} for the history stages, + * {logits, params, ngram, whitelist?} for the ban, {logits, params, bitmask} for the mask and + * {logits, params, stats} for logprobs. M is the logits plane's row count. + */ + +extern "C" int r3d_rad_sample_logprobs(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, 0); + const RadTensor* pr = r3d_opt(a, 1); + const RadTensor* st = r3d_opt(a, 2); + R3D_NEED(logits_ok(lg)); + const long long k = r3d_geti_or(a, "k", 0); + if (k <= 0) return R3D_NO(RAD_E_SHAPE); + /* The pool is 64 deep per lane, which is above every k the engine requests. A row carrying + * C_LE("k", 64) is what keeps a request above it out of the band. */ + if (k > kKMax) return R3D_NO(RAD_E_UNSUPPORTED); + long long n_vocab = 0, rows = 0, lg_ld = 0; + R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld)); + R3D_NEED(params_ok(pr, rows)); + if (!st || !st->data) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_f32(st)) return R3D_NO(RAD_E_DTYPE); + long long srows = 0; + const long long st_ld = r3d_rows_pitch(st, 2 + 2 * k, &srows); + if (st_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (srows < rows) return R3D_NO(RAD_E_SHAPE); + return r3d_launch_status(r3d_sample_logprobs( + r3d_addr(lg), r3d_addr(pr), r3d_addr(st), (int)rows, (int)n_vocab, (int)k, lg_ld, st_ld, + (int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream)); +} + +extern "C" int r3d_rad_sample_penalties(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, 0); + const RadTensor* pr = r3d_opt(a, 1); + const RadTensor* hi = r3d_opt(a, 2); + R3D_NEED(logits_ok(lg)); + long long n_vocab = 0, rows = 0, lg_ld = 0; + R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld)); + R3D_NEED(params_ok(pr, rows)); + long long hmax = 0; + R3D_NEED(hist_ok(hi, rows, &hmax)); + return r3d_launch_status(r3d_sample_penalties( + r3d_addr(lg), r3d_addr(pr), r3d_addr(hi), (int)rows, (int)n_vocab, lg_ld, hmax, + (int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream)); +} + +extern "C" int r3d_rad_sample_dry(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, 0); + const RadTensor* pr = r3d_opt(a, 1); + const RadTensor* hi = r3d_opt(a, 2); + const RadTensor* brk = r3d_opt(a, 3); + R3D_NEED(logits_ok(lg)); + long long n_vocab = 0, rows = 0, lg_ld = 0; + R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld)); + R3D_NEED(params_ok(pr, rows)); + long long hmax = 0; + R3D_NEED(hist_ok(hi, rows, &hmax)); + long long baddr = 0; + if (brk && brk->data) { + /* One byte a history position, the exemption matching the history position for position. */ + if (!r3d_is_u8(brk)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(brk)) return R3D_NO(RAD_E_STRIDE); + if (r3d_numel(brk) < rows * hmax) return R3D_NO(RAD_E_SHAPE); + baddr = r3d_addr(brk); + } + return r3d_launch_status(r3d_sample_dry( + r3d_addr(lg), r3d_addr(pr), r3d_addr(hi), baddr, (int)rows, (int)n_vocab, lg_ld, hmax, + (int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream)); +} + +extern "C" int r3d_rad_sample_ngram_ban(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, 0); + const RadTensor* pr = r3d_opt(a, 1); + const RadTensor* hi = r3d_opt(a, 2); + const RadTensor* ng = r3d_opt(a, 3); + const RadTensor* wl = r3d_opt(a, 4); + R3D_NEED(logits_ok(lg)); + long long n_vocab = 0, rows = 0, lg_ld = 0; + R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld)); + R3D_NEED(params_ok(pr, rows)); + long long hmax = 0; + R3D_NEED(hist_ok(hi, rows, &hmax)); + if (!ng || !ng->data) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_i32(ng)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(ng) || r3d_numel(ng) < 2 * rows) return R3D_NO(RAD_E_SHAPE); + const long long words = (n_vocab + 31) / 32; + long long waddr = 0; + if (wl && wl->data) { + if (wl->dtype != RAD_I32 && wl->dtype != RAD_U32) return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(wl)) return R3D_NO(RAD_E_STRIDE); + if (r3d_numel(wl) < rows * words) return R3D_NO(RAD_E_SHAPE); + waddr = r3d_addr(wl); + } + return r3d_launch_status(r3d_sample_ngram_ban( + r3d_addr(lg), r3d_addr(pr), r3d_addr(hi), r3d_addr(ng), waddr, (int)rows, (int)n_vocab, + lg_ld, hmax, (int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream)); +} + +extern "C" int r3d_rad_sample_mask(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, 0); + const RadTensor* pr = r3d_opt(a, 1); + const RadTensor* bm = r3d_opt(a, 2); + R3D_NEED(logits_ok(lg)); + long long n_vocab = 0, rows = 0, lg_ld = 0; + R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld)); + R3D_NEED(params_ok(pr, rows)); + if (!bm || !bm->data) return R3D_NO(RAD_E_INVAL); + if (bm->dtype != RAD_I32 && bm->dtype != RAD_U32) return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(bm)) return R3D_NO(RAD_E_STRIDE); + const long long words = (n_vocab + 31) / 32; + if (words <= 0 || r3d_numel(bm) < rows * words) return R3D_NO(RAD_E_SHAPE); + /* The plane's own row count is the bound the reference tests, and the plane may be longer than + * the logits: a caller that hands a plane of its own gets its rows. */ + const long long mask_rows = r3d_numel(bm) / words; + return r3d_launch_status(r3d_sample_mask(r3d_addr(lg), r3d_addr(pr), r3d_addr(bm), (int)rows, + (int)n_vocab, lg_ld, (int)mask_rows, + (long)(uintptr_t)stream)); +} + +/* ================================================================== the lane helpers, proved + * + * Every wave-sum in libr3d is a butterfly over lane shuffles, and the arithmetic that rides on a + * lane shuffle is invisible to a codec sweep: a helper that hands back a stale half of a 64-bit + * value reads as a few percent of a perplexity, in a model nobody suspects. This file + * has one of the shapes in it -- the logprobs k-list crosses lanes as 8-byte values -- so it also + * carries the control that checks the helpers, on the card, one entry per lane per wave. + * + * On this box (gfx1102, -O2 and -O3, wave32) the control is exact in **all 256 lanes of all 8 + * waves**: seeds at wave-local lanes 6, 9, 19 and 25, five butterfly rounds, and every form of the + * 64-bit exchange -- `r3d_xor_lane_u64` (two 32-bit shuffles of the halves), the same shape written + * as a `__shfl_xor_sync` per half, and one shuffle of the 64-bit value -- with the lane's value + * derived from `threadIdx.x`, loaded from a plane, and accumulated in a grid-stride loop. + * `r3d_xor_lane_u64` is sound; the form it must not be written in converts by value: + * + * d += (double)r3d_xor_lane_u64((unsigned long long)d); // WRONG + * + * `(unsigned long long)d` converts a double to an integer **by value** and `(double)` converts back + * by value, so the partner's term arrives truncated to its integer part. A wave of fractions then + * sums to 1 -- the largest term's integer part -- a 40% loss of the row's mass at the band's width, + * and a loss that vanishes when the terms are integers: an integer survives the round trip. Nothing + * about the lane shuffle is involved, and a codec sweep cannot see it, because the expression is not + * a codec. The correct form moves bits, not values (`bits_of` / `d_from_bits` below), which is what + * the k-list's shuffle does. + * + * The two traps of this shape are the whole content of the warning: summing a + * float's IEEE pattern as an integer, and converting a float's pattern to a value. The control + * catches both, in both directions, on the card, in every lane. + */ +__device__ __forceinline__ double d_from_bits(unsigned long long b) { + double d; + __builtin_memcpy(&d, &b, sizeof d); + return d; +} +__device__ __forceinline__ unsigned long long bits_of(double d) { + unsigned long long b; + __builtin_memcpy(&b, &d, sizeof b); + return b; +} + +__global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ out) { + /* kThreads and kWave are this file's anonymous-namespace names and are ambiguous out here, so + * the control spells its own geometry. */ + constexpr uint32_t kLWave = 32, kLBlock = 256; + /* Seeds at wave-local lanes 6, 9, 19, 25: a wave with four non-zero lanes and an expected sum + * of 0.08945 + 1 + 0.5971 + 0.9768, in the butterfly's own order. Every wave carries them, so + * every wave is checked. */ + const uint32_t lane = threadIdx.x & (kLWave - 1); + const double seed = (lane == 6) ? 0.08945 : (lane == 9) ? 1.0 : (lane == 19) ? 0.5971 + : (lane == 25) ? 0.9768 : 0.0; + __shared__ double s_d[kLBlock]; + __shared__ float s_f[kLBlock]; + s_d[threadIdx.x] = seed; + s_f[threadIdx.x] = (float)seed; + __syncthreads(); + + /* Form 0: the 32-bit butterfly every wave-sum in the library is built from, over a value read + * out of LDS so it is a memory operand and not a constant. */ + float f = s_f[threadIdx.x]; + f += r3d_xor_lane<16>(f); + f += r3d_xor_lane<8>(f); + f += r3d_xor_lane<4>(f); + f += r3d_xor_lane<2>(f); + f += r3d_xor_lane<1>(f); + out[0 * kLBlock + threadIdx.x] = (double)f; + + /* Form 1: the halves form over a value derived from the lane index. The pattern goes to the + * helper and back through bits_of/d_from_bits: a cast between double and an integer type + * converts the value, which is what this control guards against. */ + double d = seed; +#define R3D_L64(N) d += d_from_bits(r3d_xor_lane_u64(bits_of(d))); + R3D_L64(16) R3D_L64(8) R3D_L64(4) R3D_L64(2) R3D_L64(1) +#undef R3D_L64 + out[1 * kLBlock + threadIdx.x] = d; + + /* Form 2: the same halves form over a value loaded from LDS, the shape an accumulator has. */ + d = s_d[threadIdx.x]; +#define R3D_L64B(N) d += d_from_bits(r3d_xor_lane_u64(bits_of(d))); + R3D_L64B(16) R3D_L64B(8) R3D_L64B(4) R3D_L64B(2) R3D_L64B(1) +#undef R3D_L64B + out[2 * kLBlock + threadIdx.x] = d; + + /* Form 3: one shuffle of the 64-bit pattern, the form this file's k-list uses. The mask is + * 0xFFFFFFFFull, the 32 lanes a wave32 wave has. */ + d = s_d[threadIdx.x]; +#define R3D_S64(N) d += d_from_bits(__shfl_xor_sync(0xFFFFFFFFull, bits_of(d), N)); + R3D_S64(16) R3D_S64(8) R3D_S64(4) R3D_S64(2) R3D_S64(1) +#undef R3D_S64 + out[3 * kLBlock + threadIdx.x] = d; +} + +/* Four forms x 256 lanes of doubles (8 KiB, which the caller owns: this launcher allocates nothing, + * as every launcher in this file does). 0, -1 null, -4 the launch failed. r3d_selftest.cpp dlsyms + * this by name and compares every lane against a host emulation of the same five rounds. */ +extern "C" int r3d_lanes_check(long out, long stream) { + if (!out) return -1; + R3D_KLAUNCH(R3D_KNAME(lanes_check_kernel), dim3(1), dim3(256), + (hipStream_t)(uintptr_t)stream, (double*)(uintptr_t)out); + return hipGetLastError() == hipSuccess ? 0 : -4; +} diff --git a/libr3d/r3d_selftest.cpp b/libr3d/r3d_selftest.cpp new file mode 100644 index 00000000..6f07d827 --- /dev/null +++ b/libr3d/r3d_selftest.cpp @@ -0,0 +1,1321 @@ +/* r3d_selftest -- dump the libr3d row table, cross-check it, and prove every row links and runs. + * + * A transcription error in a constraint table stays invisible until a model silently picks the + * wrong kernel, and a codec one bit out on a subnormal shows up as a percentage of a perplexity. So + * the table is printed in full and checked against itself: + * + * - every row's `op` has a schema declared by this plugin, or nothing can select it; + * - every constraint key is a declared parameter of that op. libr3d's constraints and libref's + * schemas are one vocabulary, and a key renamed in only one place yields a row that matches + * nothing; + * - names are unique, launches exist, an init has a fini, a tunable's default is one of its + * values (the loader refuses a plugin whose default it cannot launch, and it is better to hear + * it here), and no row carries a `layout`, `relayout` or `unrelayout` hook: libr3d repacks + * nothing (r3d_rows.cpp explains why, and a hook appearing means a container format only this + * plugin can read has crept in); + * - every `opd_shape` describes as many operands as its schema declares, for a spread of + * geometries, with positive extents. + * + * The codecs are checked against the ABI's own host versions in `rad_plugin.h` over every bit + * pattern where the domain is small and a sweep where it is not: bf16 and f16 over all 65536, E4M3 + * over all 256 codes and the encoder over the saturating, subnormal, signed-zero and NaN cases, + * int8 against `rad_round_even_sat` over every tie in its band. This is the check `rad-kbench` + * cannot do: it compares whole ops, so a codec's disagreement appears as a diffuse percentage. + * libr3d's codecs are software -- RDNA3 has no fp8 conversion instruction, and its bf16 packing is + * `v_perm` and not `v_cvt_pk_bf16_f32` -- so they are the plugin's own arithmetic and belong to the + * tests. + * + * Then, on a device, every launch is called with a minimal valid input built from the row's own + * `opd_shape`, and every output plane is read back and checked to be finite. That catches the class + * of bug a table check cannot: a null operand the shim does not test, a stride read from the wrong + * axis, an operand index off by one, an undefined symbol, a kernel that writes where it should not. + * + * The numerical oracle is `rad-kbench`, which replays `kernels.rkb` against libref; this program + * does not duplicate it. What it adds is that the rows are reachable at all -- on this card, from + * this .so, with the geometry their constraints state. + * + * The plugin is dlopened rather than linked, so an undefined symbol in the .so is caught too. + * + * One child process per row. A bad pointer handed to a kernel is a GPU page fault, which ROCr + * reports by printing a line and aborting the process. In one process the first bad row would end + * the run, and with stdout block-buffered down a pipe the fault line can land next to the wrong + * row. So the parent runs the static phase and then re-execs itself once per row with + * `--case `; a child killed by a signal is a FAIL naming the signal, and the run continues. + * posix_spawn rather than fork, because the parent already has the HIP runtime's threads up and + * only exec resets them. + * + * `--case ` is also the reproducer: it runs one row, alone, in the foreground. + */ + +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r3d_codecs.h" +#include "rad_planes.h" /* the joined scale+zero plane, for the row no shape hook can describe */ +#include "r3d_plugin.h" /* the entry points, for the shape hooks that precede their rows */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* posix_spawn's environment; declared here rather than relying on unistd.h's _GNU_SOURCE guard. */ +extern char** environ; + +#ifdef RAD_HAVE_HIP +#include +#endif + +#define NELEM(a) ((int)(sizeof(a) / sizeof((a)[0]))) +static int g_fail = 0; +static void* g_h = nullptr; /* the plugin, opened by main */ +static int g_skip = 0; +static const char* g_case = nullptr; +static const char* g_plugin = nullptr; + +/* The plugin's table, reached through the symbols dlopened in main. The program is not linked + * against libr3d: an undefined symbol in the .so must be this program's failure, not its own + * failure to build. */ +static int (*P_count)(void) = nullptr; +static const RadKernelInfo* (*P_at)(int) = nullptr; +static int (*P_scount)(void) = nullptr; +static const RadOpSchema* (*P_sat)(int) = nullptr; + +static int rows() { return P_count ? P_count() : 0; } +static const RadKernelInfo* row_at(int i) { return P_at ? P_at(i) : nullptr; } +static int schemas() { return P_scount ? P_scount() : 0; } +static const RadOpSchema* schema_at(int i) { return P_sat ? P_sat(i) : nullptr; } + +/* The loader's messages are built with a printf into a string; so are these, so a failure reads + * like the line the engine would have printed. */ +static std::string fmt(const char* f, ...) { + va_list ap; + va_start(ap, f); + char buf[512]; + std::vsnprintf(buf, sizeof buf, f, ap); + va_end(ap); + return std::string(buf); +} + +static void say(const char* tag, const char* fmt, va_list ap) { + std::printf(" %s ", tag); + std::vprintf(fmt, ap); + std::printf("\n"); +} +static void ok(const char* fmt, ...) { + va_list ap; va_start(ap, fmt); say("ok ", fmt, ap); va_end(ap); +} +static void fail(const char* fmt, ...) { + va_list ap; va_start(ap, fmt); say("FAIL", fmt, ap); va_end(ap); ++g_fail; +} +static void skip(const char* fmt, ...) { + va_list ap; va_start(ap, fmt); say("skip", fmt, ap); va_end(ap); ++g_skip; +} + +static const RadOpSchema* find_schema(const char* op) { + if (!op) return nullptr; + for (int i = 0; i < schemas(); ++i) { + const RadOpSchema* s = schema_at(i); + if (s && s->op && !std::strcmp(s->op, op)) return s; + } + return nullptr; +} + +static const RadParamSpec* find_param(const RadOpSchema* s, const char* key) { + if (!s || !key) return nullptr; + for (int i = 0; i < s->n_params; ++i) + if (s->params[i].key && !std::strcmp(s->params[i].key, key)) return &s->params[i]; + return nullptr; +} + +/* ================================================================== the table's own checks + * + * Every check here has a failure mode behind it: a constraint on a key the schema does not declare + * (the row matches nothing, silently, and the model falls back to a reference kernel), a tunable + * default outside its axis (the loader refuses the whole plugin), a row whose `op` is spelled for + * another op's schema (one call meaning two things), a description whose operand count disagrees + * with its schema (every case for that op skipped, forever). + */ +static void check_table() { + const int n = rows(); + std::printf("== rows: %d, schemas: %d\n", n, schemas()); + + for (int i = 0; i < n; ++i) { + const RadKernelInfo* k = row_at(i); + if (!k) { fail("row %d is null", i); continue; } + std::printf("%-26s %-18s %-6s %s\n", k->name ? k->name : "(null)", + k->op ? k->op : "(null)", k->family ? k->family : "-", + k->priority >= 0 ? "" : "no priority"); + + if (!k->name || !*k->name) fail("row %d has no name", i); + else + for (int j = i + 1; j < n; ++j) { + const RadKernelInfo* o = row_at(j); + if (o && o->name && !std::strcmp(o->name, k->name)) + fail("row '%s' is declared twice", k->name); + } + if (!k->launch) fail("row '%s' has no launch", k->name); + if (k->init && !k->fini) fail("row '%s' inits without a fini", k->name); + if (k->domain != RAD_DOMAIN_DEVICE) fail("row '%s' is not a device row", k->name); + /* No row repacks a weight: the kernel reads the container's stored order, which is the rule that + * stops a plugin quietly demanding its own format. The exception is a class with a name list, and + * the class is the container's quantised weight: codes and scales stored as planes behind one + * operand, which the mapped tier will not place unless a loaded library can read them in place. + * Three rows, one per grid the container uses -- w2a8's {1,group} with a zero, the fp8a8 GEMM's + * {128,128} without, and the lm_head's same form -- each transcribed from the reference's own hook, + * including the case the reference answers nothing for (ref_layout_gemm_q reads zp_grid, and zp_grid + * has no fp8a8 entry). What carries the rule is the pair: every one of these names has a `layout` + * **and** a `relayout`, no row anywhere has an `unrelayout`, and a hook that names a joined layout + * without the writer that produces it is the failure the engine prints at load. A fifth name is a + * rule change, and it should fail here. */ + const bool joined = 0 == std::strcmp(k->name, "gemm_nt_q_w2a8_m16") + || 0 == std::strcmp(k->name, "logits_gemm_bf16") + || 0 == std::strcmp(k->name, "gemm_nt_q_fp8a8_tiled") + || 0 == std::strcmp(k->name, "gemm_nt_q_w2a8_tiled"); + /* The query and the writer come as a pair, and the pair is the rule: a row with a hook must + * supply the relayout that produces the form the hook names (abi/rad_abi.h -- a query + * answering RAD_OK is a promise the loader keeps on the row's word), and no row may carry an + * unrelayout, because nothing in this library invents a format a tool would need to invert. + * A hook with a null writer is the failure the engine reports at load -- `could not produce + * 'output.weight' (rad.planes) from fp8_e4m3*bf16[128x128]: unsupported` -- and a relayout + * without a hook is a row repacking a weight nobody asked to have repacked. */ + if ((k->layout && !joined) || (k->layout && !k->relayout) || (k->relayout && !joined) + || (k->relayout && !k->layout) || k->unrelayout) + fail("row '%s' declares a layout hook; libr3d stores weights in order", k->name); + if (!k->computes || !*k->computes || !k->shape || !*k->shape || !k->dtypes || + !*k->dtypes) + fail("row '%s' is missing prose", k->name); + + const RadOpSchema* s = find_schema(k->op); + if (!s) { fail("row '%s' implements '%s', which no schema declares", k->name, k->op); } + else { + for (int c = 0; c < k->n_constraints; ++c) { + const RadConstraint& x = k->constraints[c]; + const RadParamSpec* p = find_param(s, x.key); + if (!p) { + fail("row '%s' constrains '%s', not a parameter of '%s'", k->name, + x.key ? x.key : "(null)", k->op); + continue; + } + /* The selector compares a string constraint against a string parameter and an + * integer one against an integer. A mismatch matches nothing. */ + if (x.op == RAD_C_IN && p->type != RAD_P_STR) + fail("row '%s' matches '%s' with a string list on a non-string parameter", + k->name, x.key); + if (x.op == RAD_C_EQ && p->type == RAD_P_STR && !x.sval) + fail("row '%s' equals the string parameter '%s' with no string", k->name, + x.key); + if (x.op == RAD_C_IN && p->type == RAD_P_STR && x.sval) { + /* The band must name at least one value, and no value may be empty. */ + int words = 0; + for (const char* q = x.sval; *q; ++q) + if (*q == ' ') ++words; + if (!words && !*x.sval) fail("row '%s' constrains '%s' to nothing", k->name, + x.key); + } + if (x.op == RAD_C_DIV && x.ival <= 0) + fail("row '%s' constrains '%s' to divide by %lld", k->name, x.key, + (long long)x.ival); + } + } + + for (int t = 0; t < k->n_tunables; ++t) { + const RadTunable& a = k->tunables[t]; + if (!a.key || a.n_values <= 0 || !a.values) { + fail("row '%s' axis %d is empty", k->name, t); + continue; + } + bool has_default = false; + for (int v = 0; v < a.n_values; ++v) { + if (v && a.values[v] <= a.values[v - 1]) + fail("row '%s' axis '%s' values are not ascending", k->name, a.key); + if (a.values[v] == a.deflt) has_default = true; + } + if (!has_default) + fail("row '%s' axis '%s' defaults to %lld, which is not one of its values", + k->name, a.key, (long long)a.deflt); + if (!a.doc || !*a.doc) fail("row '%s' axis '%s' has no description", k->name, a.key); + } + } +} + +/* ================================================================== the reference library + * + * The loader refuses a plugin whose schema for an op differs from the one the first declarer fixed + * (core/plugin/loader.cpp, `schema_same`), and it refuses the *whole* .so, every row with it. The + * comparison is positional and narrow: parameter count, each parameter's key, type and + * requiredness; operand count, each operand's role and optionality. Operand names and doc strings + * are free, because arguments are positional and names are for diagnostics. + * + * So a schema copied from libref with one operand's role mistyped is a plugin that loads in + * r3d_selftest -- which does not open libref -- and disappears from the engine, with one line in a + * log most people never read. This check is the loader's own comparison, run here, naming the op + * and the slot. + */ +static void check_reference_schemas() { + std::printf("== schemas against the reference\n"); + + /* The reference library beside the plugin under test, the way the engine's home holds them. */ + std::string path(g_plugin); + const size_t slash = path.find_last_of('/'); + path = (slash == std::string::npos ? std::string() : path.substr(0, slash + 1)) + "libref.so"; + void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) { skip("no reference library at %s (%s)", path.c_str(), dlerror()); return; } + auto rc = (int (*)(void))dlsym(h, "rad_kernel_schema_count"); + auto ra = (const RadOpSchema* (*)(int))dlsym(h, "rad_kernel_schema_at"); + if (!rc || !ra) { skip("%s declares no schemas", path.c_str()); return; } + + static const char* kRole[] = { "in", "out", "inout", "weight", "wtab" }; + auto role_name = [](int r) { return (r >= 0 && r <= 4) ? kRole[r] : "?"; }; + int mismatches = 0, compared = 0; + for (int i = 0; i < schemas(); ++i) { + const RadOpSchema* mine = schema_at(i); + if (!mine || !mine->op) continue; + const RadOpSchema* theirs = nullptr; + for (int j = 0; j < rc() && !theirs; ++j) { + const RadOpSchema* o = ra(j); + if (o && o->op && !std::strcmp(o->op, mine->op)) theirs = o; + } + if (!theirs) { + /* Not a refusal: an op the reference does not serve is an op with nothing to agree + * with, and it is the reason libr3d's rows for a chain libref has no oracle for are + * checked by the selftest's own arithmetic instead. */ + skip("'%s' has no schema in the reference, so nothing to compare against", mine->op); + continue; + } + ++compared; + std::string diff; + if (mine->n_params != theirs->n_params) { + diff = fmt("%d parameters vs %d", mine->n_params, theirs->n_params); + } else { + for (int q = 0; q < mine->n_params && diff.empty(); ++q) { + const RadParamSpec& x = mine->params[q]; + const RadParamSpec& y = theirs->params[q]; + if (!x.key || std::strcmp(x.key, y.key ? y.key : "")) + diff = fmt("parameter %d is '%s' vs '%s'", q, x.key ? x.key : "(null)", + y.key ? y.key : "(null)"); + else if (x.type != y.type) + diff = fmt("parameter '%s' is %s vs %s", x.key, + x.type == RAD_P_STR ? "a string" : "an int", + y.type == RAD_P_STR ? "a string" : "an int"); + else if (x.required != y.required) + diff = fmt("parameter '%s' is %s in the reference", x.key, + y.required ? "required" : "optional"); + else if (x.role != y.role) + diff = fmt("parameter '%s' has core role %d vs %d", x.key, x.role, y.role); + } + if (diff.empty() && mine->n_operands != theirs->n_operands) + diff = fmt("%d operands vs %d", mine->n_operands, theirs->n_operands); + for (int q = 0; q < mine->n_operands && diff.empty(); ++q) { + const RadOperandSpec& x = mine->operands[q]; + const RadOperandSpec& y = theirs->operands[q]; + /* The name is free; the role and the optionality are the contract. */ + if (x.role != y.role) + diff = fmt("operand %d ('%s' / '%s') has a different role: %s vs %s", q, + x.name ? x.name : "?", y.name ? y.name : "?", + role_name(x.role), role_name(y.role)); + else if (x.optional != y.optional) + diff = fmt("operand %d ('%s') is %s in the reference", q, + x.name ? x.name : "?", y.optional ? "optional" : "required"); + } + } + if (!diff.empty()) { + fail("'%s' has two schemas: the reference fixed it, libr3d disagrees (%s)", mine->op, + diff.c_str()); + ++mismatches; + } + } + if (!mismatches) + ok("%d of %d schemas match the reference, slot for slot%s", compared, schemas(), + schemas() == compared ? "" : " (the rest the reference does not declare)"); + dlclose(h); +} + +/* ================================================================== band reachability + * + * A row is chosen by matching its constraints against a band's geometry, and the engine's rule + * (core/util/rad_util.cpp, constraint_holds) is that a constraint on a key the geometry lacks does + * not hold, in its own words "a row constraining an optional parameter serves only callers that + * state it, and others get a row without it". The bands an architecture emits carry the parameters + * its graph set, and nothing else, so a row that constrains an optional parameter is a row narrowed + * to the graphs that spell that parameter out. + * + * Nothing in kbench shows this: a fixture case names every parameter the op declares, so the + * constraint is tested against a geometry that has it. A server shows all of it, at startup, as + * "N device band(s) resolved to no kernel" and a model that will not start. So the check is here: + * a constraint on an optional parameter is not an error -- it is how a row says "I serve the form + * that states the parameter" -- but it is a decision, and a row whose author did not make it is a + * row that will silently not serve. + */ +static void check_band_reach() { + std::printf("== band reachability\n"); + std::string path(g_plugin); + const size_t slash = path.find_last_of('/'); + path = (slash == std::string::npos ? std::string() : path.substr(0, slash + 1)) + "libref.so"; + void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) { skip("no reference library at %s", path.c_str()); return; } + auto rc = (int (*)(void))dlsym(h, "rad_kernel_schema_count"); + auto ra = (const RadOpSchema* (*)(int))dlsym(h, "rad_kernel_schema_at"); + if (!rc || !ra) { skip("%s declares no schemas", path.c_str()); return; } + + int narrowed = 0, checked = 0; + for (int i = 0; i < rows(); ++i) { + const RadKernelInfo* k = row_at(i); + if (!k || !k->op) continue; + const RadOpSchema* s = nullptr; + for (int j = 0; j < rc() && !s; ++j) { + const RadOpSchema* o = ra(j); + if (o && o->op && !std::strcmp(o->op, k->op)) s = o; + } + if (!s) continue; /* the table phase already failed this row */ + for (int ci = 0; ci < k->n_constraints; ++ci) { + const RadConstraint& c = k->constraints[ci]; + if (!c.key) continue; + ++checked; + const RadParamSpec* sp = nullptr; + for (int q = 0; q < s->n_params && !sp; ++q) + if (s->params[q].key && !std::strcmp(s->params[q].key, c.key)) sp = &s->params[q]; + if (sp && !sp->required) { + ok("row '%s' constrains '%s', optional on '%s': a band that leaves it out does not " + "resolve to this row", k->name, c.key, k->op); + ++narrowed; + } + } + } + if (!narrowed) ok("%d constraint(s) over %d rows, every one on a parameter a band always " + "carries", checked, rows()); + dlclose(h); +} + +/* ================================================================== the operand descriptions + * + * Against the schemas, for one geometry per op taken from the widths a model really has: 4096 + * hidden, 128 head, 11008 intermediate, 128256 vocabulary. A description that returns a count the + * schema disagrees with, a rank of zero, or an extent of zero is a bug in the description or in the + * schema; rad-kbench reports it as a skipped case for every geometry, which is how a broken hook + * hides for years. + */ +static void check_shapes() { + /* RadParam is { key, kind, ival, ihi, sval, dval }. */ +#define PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } +#define PF(k, v) { (k), RAD_P_F64, 0, 0, nullptr, (double)(v) } +#define PS(k, v) { (k), RAD_P_STR, 0, 0, (v), 0.0 } + struct Geom { const char* op; std::vector p; }; + const std::vector g = { + { "rmsnorm", { PI("M", 8), PI("n", 4096), PF("eps", 1e-5), PS("dtype", "bf16") } }, + { "layernorm", { PI("M", 8), PI("n", 4096), PF("eps", 1e-5), PS("dtype", "bf16") } }, + { "add", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "mul", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "act_mul", { PI("M", 8), PI("n", 11008), PS("act", "silu"), PS("dtype", "bf16") } }, + { "silu", { PI("M", 8), PI("n", 11008), PS("dtype", "bf16") } }, + { "gelu", { PI("M", 8), PI("n", 11008), PS("dtype", "bf16") } }, + { "sigmoid", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "softmax", { PI("M", 8), PI("n", 4096), PS("dtype", "f32") } }, + { "cast", { PI("M", 8), PI("n", 4096), PS("from", "bf16"), PS("to", "f32") } }, + { "scale", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "fill", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16"), PF("value", 0.0) } }, + { "rope", { PI("M", 8), PI("head_dim", 128), PI("n_head", 32), PI("n_head_kv", 8), + PF("theta", 500000.0), PF("scale", 1.0), PS("mode", "neox") } }, + { "kv_store", { PI("M", 8), PI("head_dim", 128), PI("n_head_kv", 8), PI("block_size", 32), + PS("kv_dtype", "bf16") } }, + { "embed_lookup", { PI("M", 8), PI("n_embd", 4096), PI("n_vocab", 128256), + PS("dtype", "bf16") } }, + { "gather_rows", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "scatter_rows", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "quant_act_fp8", { PI("M", 8), PI("n", 4096), PI("group", 128), PS("dtype", "bf16") } }, + { "quant_act_i8", { PI("M", 8), PI("n", 4096), PI("group", 128), PS("dtype", "bf16") } }, + { "quant_act_i8g", { PI("M", 8), PI("n", 4096), PI("group", 128), PS("dtype", "bf16") } }, + { "gated_quant_fp8", { PI("M", 8), PI("n", 11008), PI("group", 128), PS("dtype", "bf16"), + PS("act", "silu") } }, + { "dequant", { PI("M", 11008), PI("n", 4096), PI("group", 128), + PS("dtype", "fp8_e4m3") } }, + { "rmsnorm_quant_fp8", { PI("M", 1792), PI("n", 5120), PI("eps", 1e-5), PI("group", 128), + PS("dtype", "bf16") } }, + { "gemm_nt", { PI("M", 8), PI("N", 11008), PI("K", 4096), PS("dtype", "bf16") } }, + { "gemm_nt_q", { PI("M", 8), PI("N", 11008), PI("K", 4096), PI("group", 128), + PS("dtype", "fp8a16"), PI("pb1", 128), PI("pb2", 128) } }, + /* The rest are the bands MiniCPM5-2B asks for, in /home/sysadmin/libr3d/bands.txt: the + * model's own widths, not invented ones. The vocab is 130560, the MLP is 6144 wide, the + * head is 128 with 16 heads over 2 KV heads at 16-token blocks. */ + { "silu_mul", { PI("M", 1792), PI("n", 6144), PS("dtype", "bf16") } }, + { "attn_paged", { PI("q_len", 2048), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), + PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), + PS("kv_dtype", "bf16"), PI("n_head", 16), PI("max_ctx", 4096), + PI("max_seqs", 256) } }, + { "attn_paged", { PI("q_len", 7), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), + PI("causal", 0), PI("window", 0), PS("q_dtype", "bf16"), + PS("kv_dtype", "fp8_e4m3"), PI("n_head", 16), PI("max_ctx", 4096), + PI("max_seqs", 256) } }, + /* The decode band with the context deeper than the query chunk: the walk has to cover keys + * that precede the chunk, which is the only thing in the op a q_len-sized cache cannot + * show. The second is the geometry that found the tile-sharing bug -- a window that starts + * mid-block, over an fp8 cache. */ + { "attn_paged", { PI("q_len", 7), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), + PI("causal", 0), PI("window", 0), PS("q_dtype", "bf16"), + PS("kv_dtype", "bf16"), PI("n_head", 16), PI("ctx", 4096), + PI("max_ctx", 4096) } }, + { "attn_paged", { PI("q_len", 7), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), + PI("causal", 1), PI("window", 37), PS("q_dtype", "bf16"), + PS("kv_dtype", "fp8_e4m3"), PI("n_head", 16), PI("ctx", 512), + PI("max_ctx", 4096) } }, + /* The 27B's sliding-window band, in the shape the fixture draws it: the shape hook describes + * the descales as ABSENT, so this is the case where an fp8 cache has no scale plane and the + * reference reads 1.0. It is the geometry kbench caught a refusal on. */ + { "attn_paged", { PI("q_len", 1), PI("head_dim", 128), PI("gqa", 4), PI("block_size", 16), + PI("causal", 0), PI("window", 2048), PS("q_dtype", "bf16"), + PS("kv_dtype", "fp8_e4m3"), PI("n_head", 32), PI("max_seqs", 8), + PI("max_ctx", 262144) } }, + { "row_topk", { PI("M", 1792), PI("N", 130560), PI("R", 16), PS("dtype", "bf16") } }, + { "sample_argmax", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_temp", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_topk", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_topp", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_minp", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_typical", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_xtc", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_pick", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_penalties", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_dry", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_ngram_ban", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_mask", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_logprobs", { PI("M", 2048), PI("n_vocab", 130560), PI("k", 21) } }, + /* The speculative decoder's band, as MiniCPM5-2B declares it: a 7-token draft block, 16 + * candidates a step, a rank-256 codebook over a 130560-token vocabulary, anchors strided 7 + * apart. The two codebooks are 63.8 MiB each, which is what the op really is. */ + { "dflash_select", { PI("M", 256), PI("steps", 7), PI("top_k", 16), PI("rank", 256), + PI("n_vocab", 130560), PI("anchor_stride", 7), PS("dtype", "bf16") } }, + }; +#undef PI +#undef PF +#undef PS + + /* The descriptions of the ops whose kernels have not landed: the schemas and the hooks are in + * the library, checked the moment it loads, so a transcription typo is found here and not on the + * day the row lands and kbench skips its cases -- "describes an output differently" is one line + * in a report, and a row nobody exercises is a row nobody tested. */ + /* By symbol name, dlsym'd from the plugin: this program links nothing from the library under + * test -- that is the point of dlopening it -- so a hook is a name and a pointer out of the + * handle, exactly as the rows are. */ + static const struct { const char* op; const char* sym; } kHooks[] = { + { "silu_mul", "r3d_shape_silu_mul" }, { "attn_paged", "r3d_shape_attn_paged" }, + { "row_topk", "r3d_shape_row_topk" }, { "sample_argmax", "r3d_shape_sample_argmax" }, + { "sample_temp", "r3d_shape_sample_temp" }, { "sample_topk", "r3d_shape_sample_topk" }, + { "sample_topp", "r3d_shape_sample_topp" }, { "sample_minp", "r3d_shape_sample_minp" }, + { "sample_typical", "r3d_shape_sample_typical" }, + { "sample_xtc", "r3d_shape_sample_xtc" }, { "sample_pick", "r3d_shape_sample_pick" }, + { "sample_penalties", "r3d_shape_sample_penalties" }, + { "sample_dry", "r3d_shape_sample_dry" }, { "sample_ngram_ban", "r3d_shape_sample_ngram_ban" }, + { "sample_mask", "r3d_shape_sample_mask" }, { "sample_logprobs", "r3d_shape_sample_logprobs" }, + }; + + for (const Geom& gm : g) { + const RadOpSchema* s = find_schema(gm.op); + if (!s) { fail("the geometry for '%s' has no schema", gm.op); continue; } + const RadKernelInfo* row = nullptr; + RadShapeFn hook = nullptr; + for (int i = 0; i < rows() && !row; ++i) { + const RadKernelInfo* k = row_at(i); + if (k && k->op && !std::strcmp(k->op, gm.op) && k->opd_shape) row = k; + } + if (row) hook = row->opd_shape; + for (size_t q = 0; q < NELEM(kHooks) && !hook; ++q) + if (!std::strcmp(kHooks[q].op, gm.op)) + hook = (int (*)(const RadParam*, int, int, RadOpdDesc*))dlsym(g_h, kHooks[q].sym); + if (!hook) { skip("no operand description for '%s' -- no row and no hook", gm.op); + continue; } + if (!row) std::printf(" -- '%s': the hook, ahead of its kernel\n", gm.op); + + bool bad = false; + for (int o = 0; o < s->n_operands && !bad; ++o) { + RadOpdDesc d{}; + const int st = hook(gm.p.data(), (int)gm.p.size(), o, &d); + if (st == RAD_E_UNSUPPORTED) { skip("'%s': the description declines this geometry", + gm.op); bad = true; break; } + if (st != RAD_OK) { fail("'%s' operand %d: the description returns %d", gm.op, o, st); + bad = true; break; } + if (d.flags & RAD_OPD_F_ABSENT) { + if (!s->operands[o].optional) + { fail("'%s' operand %d is required and described absent", gm.op, o); bad = true; } + continue; + } + if (d.rank == 0 || d.rank > RAD_MAX_RANK) + { fail("'%s' operand %d has rank %u", gm.op, o, d.rank); bad = true; break; } + for (uint32_t r = 0; r < d.rank && !bad; ++r) + if (d.shape[r] <= 0) + { fail("'%s' operand %d extent %u is %lld", gm.op, o, r, + (long long)d.shape[r]); bad = true; } + if (rad_dtype_bits(d.dtype) <= 0) + { fail("'%s' operand %d has an unparseable dtype", gm.op, o); bad = true; } + } + if (!bad) ok("'%s' described over %d operands", gm.op, s->n_operands); + } +} + +/* ================================================================== the codecs + * + * Against the ABI's host implementations. Exactness is the claim, and it is the claim because the + * widenings are exact (seven mantissa bits into ten, four exponent and three mantissa bits into + * five and ten) and the encoders are mirrors of `rad_plugin.h`, line for line. + */ +/* Two floats are the same when their bits are: `a == b` is false for two NaNs, and a codec that + * quiet a NaN the same way the ABI's does is a codec that agrees. */ +static bool same_float(float a, float b) { + return bits_of(a) == bits_of(b); +} + +/* ================================================================== the codecs + * + * Against the ABI's host implementations. Exactness is the claim, and it is the claim because the + * widenings are exact (seven mantissa bits into ten, four exponent and three mantissa bits into + * five and ten) and the encoders are mirrors of `rad_plugin.h`, line for line. + */ +static void check_codecs() { + std::printf("== codecs\n"); + + /* bf16: every one of the 65536 patterns, both directions. */ + int bad = 0; + for (uint32_t u = 0; u < 0x10000 && !bad; ++u) { + const uint16_t b = (uint16_t)u; + if (!same_float(bf16_to_f32(b), rad_bf16_to_f32(b))) { ++bad; break; } + /* Encoder against encoder: a NaN's payload is quieted on the way out by both, so a + * round-trip to the original pattern is not the claim. */ + if (f32_to_bf16(bf16_to_f32(b)) != rad_f32_to_bf16(rad_bf16_to_f32(b))) { ++bad; break; } + } + if (bad) fail("bf16: the codecs disagree with rad_plugin.h"); + else ok("bf16: 65536 patterns, decode and encode, match rad_plugin.h bit for bit"); + + /* f16: the same, subnormals included -- the narrowing keeps them, which the ABI's codec does + * and a naive shift-and-round does not. */ + bad = 0; + for (uint32_t u = 0; u < 0x10000 && !bad; ++u) { + const uint16_t h = (uint16_t)u; + const float f = f16_to_f32(h); + if (!same_float(f, rad_f16_to_f32(h))) { ++bad; break; } + if (f32_to_f16(f) != rad_f32_to_f16(rad_f16_to_f32(h))) { ++bad; break; } + } + if (bad) fail("f16: the codecs disagree with rad_plugin.h"); + else ok("f16: 65536 patterns, both directions, match rad_plugin.h (subnormals included)"); + + /* A bf16 pair widened to an f16 pair, in one register, exactly -- the reason the dot2 path is + * sound. Exact over f16's normal range [2^-14, 65504], as r3d_codecs.h states, and the sweep is + * over the patterns in it. Outside, the widening is not exact and is not claimed to be: above + * 65504 it saturates, and below 2^-14 an f16 subnormal's grid is coarser than bf16's, so the + * packing instruction truncates toward zero. Those patterns are counted and named in the + * message, because the number of them -- and the fact that they are the format's range, not a + * bug -- is the thing a reader needs. */ + bad = 0; + int inside = 0, outside = 0; + for (uint32_t u = 0; u < 0x10000 && !bad; ++u) { + const uint16_t b = (uint16_t)u; + const float v = bf16_to_f32(b); + const float av = v < 0.0f ? -v : v; + if (!(av >= 6.103515625e-05f && av <= 65504.0f)) { ++outside; continue; } /* f16 normals */ + ++inside; + const uint32_t w = ((uint32_t)(uint16_t)(b ^ 0x8000u) << 16) | b; + const uint32_t p = bf16x2_to_f16x2(w); + if (!same_float(f16_to_f32((uint16_t)(p & 0xFFFFu)), v) || + !same_float(f16_to_f32((uint16_t)(p >> 16)), -v)) { ++bad; break; } + } + if (bad) fail("bf16x2 -> f16x2 is not exact over f16's normal range"); + else ok("bf16 -> f16 exact over the %d patterns in f16's normal range (the other %d saturate " + "or truncate as the format says they must)", inside, outside); + + /* E4M3, both directions, over every code. The widening to f16 is exact for every code: e4m3 has + * four exponent and three mantissa bits, f16 five and ten, and 448 is well inside f16. */ + bad = 0; + for (uint32_t c = 0; c < 256 && !bad; ++c) { + if (!same_float(e4m3_to_f32((uint8_t)c), rad_fp8e4m3_to_f32((uint8_t)c))) { ++bad; break; } + if ((c & 0x7Fu) == 0x7Fu) continue; /* the code's one NaN */ + if (f32_to_e4m3(e4m3_to_f32((uint8_t)c)) != (uint8_t)c) { ++bad; break; } + const uint32_t p = e4m3x2_to_f16x2((c << 8) | c); + const float want = e4m3_to_f32((uint8_t)c); + if (!same_float(f16_to_f32((uint16_t)(p & 0xFFFFu)), want) || + !same_float(f16_to_f32((uint16_t)(p >> 16)), want)) { ++bad; break; } + } + if (bad) fail("e4m3: the codecs disagree with rad_plugin.h, or the widening is not exact"); + else ok("e4m3: 256 codes both ways, and the f16 widening exact, match rad_plugin.h"); + + /* The encoder over the cases that break a naive one: saturation at 448, the subnormals below + * 2^-6, the sign of zero, NaN, and the values a scale lands on. */ + bad = 0; + const float sweep[] = { 0.0f, -0.0f, 1.0f / 512, 1.0f / 1024, 1.0f / 6, 0.33f, 1.0f, 1.7f, + 2.0f, 3.0f, 447.0f, 448.0f, 449.0f, 1024.0f, 1e30f, -1e30f, + 1.0f / 0.0f, -1.0f / 0.0f, 0.0f / 0.0f, 1.0f / 448, 5.0f / 448, + 448.0f * 1.0000001f, 447.99f, -0.0f - 0.0f }; + int sbad = 0; + for (float v : sweep) + if (f32_to_e4m3(v) != rad_f32_to_fp8e4m3(v)) ++sbad; + if (sbad) fail("e4m3: %d of %d sweep values disagree with rad_plugin.h", sbad, + (int)(sizeof(sweep) / sizeof(sweep[0]))); + else ok("e4m3 encoder: saturating, subnormal, signed-zero and NaN cases match rad_plugin.h"); + (void)bad; + + /* int8: round to nearest, ties to even, saturating, over every tie and past the band. */ + bad = 0; + for (int i = -600; i <= 600 && !bad; ++i) + for (int f = 0; f < 4; ++f) { + const float v = (float)i + 0.25f * (float)f; + if (f32_to_i8_rtne(v) != (int8_t)rad_round_even_sat(v, -128.0, 127.0)) { ++bad; break; } + } + if (bad) fail("int8: the encoder disagrees with rad_round_even_sat"); + else ok("int8 encoder: 4804 values, every tie in the band, match rad_round_even_sat"); + + /* dot2's order. The device instruction folds the products with guard bits, so the host path is + * the reference's arithmetic and this checks only that the pairs are read low-then-high: the + * GEMMs' accumulation order is checked by rad-kbench against libref. */ + float acc = 0.0f; + const uint32_t a = f16x2_pack(1.5f, -2.5f), b = f16x2_pack(4.0f, 4.0f); + acc = dot2_f16x2(a, b, acc); + if (acc != 1.5f * 4.0f + -2.5f * 4.0f) fail("dot2: the pair is not read low-then-high"); + else ok("dot2: the pair is read low-then-high, into the accumulator it is handed"); + + /* The bf16 store a kernel's epilogue uses: two values, one dword, round to nearest even, the + * high half in the high half. A `v_perm` picking the wrong bytes shows up here and not in a + * kernel's output, where a swapped pair looks like a plausible tensor. */ + bad = 0; + for (int i = -500; i < 500 && !bad; ++i) { + const float lo = (float)i * 0.001f, hi = (float)i * -0.002f; + const uint32_t w = bf16x2_rne(lo, hi); + if (!same_float(bf16w_lo(w), rad_bf16_to_f32(rad_f32_to_bf16(lo))) || + !same_float(bf16w_hi(w), rad_bf16_to_f32(rad_f32_to_bf16(hi)))) { ++bad; break; } + } + if (bad) fail("bf16x2_rne: the pair is not (low, high) as rad_f32_to_bf16 rounds it"); + else ok("bf16x2_rne: a pair packs as rad_f32_to_bf16 rounds it, low half low"); +} + +/* ================================================================== a row, run + * + * Buffers from the row's own `opd_shape`, filled per the fill code the description carries, the + * launch called, the outputs read back and checked to be finite. + */ +enum { MAX_OPD = 24 }; + +struct Case { + RadTensor t[MAX_OPD]; + RadParam p[32]; + std::vector dev; + std::vector host; /* pinned operands: read on the host, read by the kernel too */ + std::vector words; /* the strings out.sval points into; reserved in make_params */ + int n_p = 0; +}; + +/* ================================================================== the lane helpers, on the card + * + * Every wave-sum in the library is five rounds of a butterfly over lane shuffles, and the + * arithmetic that rides on a shuffle is invisible to a codec sweep: `d += (double)f((unsigned long + * long)d)` moves a *value* where a bit pattern is wanted, and a wave of fractions then sums to 1 -- + * which is a bug this file's own predecessor shipped, in the logprobs sum, and which showed up as + * 40% of a row's probability mass missing at one shape. So the card runs the butterflies through + * `r3d_lanes_check` (r3d_sample_pre_f32.hip) and every lane of every wave is compared with a host + * emulation of the same five rounds, in the same order. + */ +static void check_lanes() { + std::printf("== lane helpers\n"); + auto run = (int (*)(long, long))dlsym(g_h, "r3d_lanes_check"); + if (!run) { skip("r3d_lanes_check is not in this plugin"); return; } +#ifndef RAD_HAVE_HIP + skip("built without HIP: the lane helpers are not checked"); + return; +#else + enum { NF = 4, NT = 256, NW = 32 }; + auto seed = [](int l) { + return l == 6 ? 0.08945 : l == 9 ? 1.0 : l == 19 ? 0.5971 : l == 25 ? 0.9768 : 0.0; + }; + /* The butterfly the kernel runs, emulated: five rounds, lane l meeting lane l^N. */ + double wd[NW]; + float wf[NW]; + for (int l = 0; l < NW; ++l) { wd[l] = seed(l); wf[l] = (float)seed(l); } + for (int N = NW / 2; N >= 1; N >>= 1) { + double t[NW]; + float u[NW]; + for (int l = 0; l < NW; ++l) { t[l] = wd[l ^ N]; u[l] = wf[l ^ N]; } + for (int l = 0; l < NW; ++l) { wd[l] += t[l]; wf[l] += u[l]; } + } + static const char* names[NF] = { + "f32 butterfly, the shape every wave_sum is", + "f64 halves (r3d_xor_lane_u64), lane-derived", + "f64 halves (r3d_xor_lane_u64), loaded from LDS", + "f64 one 64-bit __shfl_xor_sync, loaded from LDS", + }; + double* d = nullptr; + const size_t bytes = (size_t)NF * NT * sizeof(double); + if (hipMalloc(&d, bytes) != hipSuccess) { skip("no device for the lane helpers"); return; } + if (hipMemset(d, 0, bytes) != hipSuccess) { fail("could not clear the lane helper's plane"); + (void)hipFree(d); return; } + if (run((long)(uintptr_t)d, 0) != 0) { + fail("r3d_lanes_check refused to launch"); + (void)hipFree(d); + return; + } + if (hipDeviceSynchronize() != hipSuccess) { + fail("the lane helper kernel faulted"); + (void)hipFree(d); + return; + } + std::vector out((size_t)NF * NT, 0.0); + if (hipMemcpy(out.data(), d, bytes, hipMemcpyDeviceToHost) != hipSuccess) { + fail("reading the lane helper's plane back failed"); + (void)hipFree(d); + return; + } + (void)hipFree(d); + for (int f = 0; f < NF; ++f) { + int bad = 0, first = -1; + for (int i = 0; i < NT; ++i) { + const double w = (f == 0) ? (double)wf[i % NW] : wd[i % NW]; + uint64_t a, b; + std::memcpy(&a, &out[(size_t)f * NT + i], 8); + std::memcpy(&b, &w, 8); + if (a != b) { ++bad; if (first < 0) first = i; } + } + if (!bad) { + ok("%s: %d lanes over %d waves, every one exact (wave sums to %.6f)", names[f], NT, + NT / NW, wd[0]); + continue; + } + const double w = (f == 0) ? (double)wf[first % NW] : wd[first % NW]; + fail("%s: %d of %d lanes disagree; first is lane %d of wave %d: %.17g, want %.17g", + names[f], bad, NT, first % NW, first / NW, out[(size_t)f * NT + first], w); + } +#endif +} + +static size_t dt_bytes(uint32_t dt) { + const int bits = rad_dtype_bits(dt); + return bits > 0 ? (size_t)((bits + 7) / 8) : 1; +} + +static uint32_t xorshift(uint32_t& s) { + s ^= s << 13; s ^= s >> 17; s ^= s << 5; + return s; +} + +/* Fill a host plane per its description. "Normals" is a sum of four uniforms: a kernel's + * arithmetic is exercised by any value that is not a special case, and the special cases are what + * the hand-written cases and rad-kbench's sweeps are for. */ +static void fill_plane(const RadOpdDesc& d, uint8_t* p, size_t nel, uint32_t seed) { + uint32_t s = seed ? seed : 1u; + const size_t nbyte = d.dtype == RAD_U2 ? nel / 4 + : (d.dtype == RAD_U4 || d.dtype == RAD_I4 || d.dtype == RAD_FP4E2M1) ? nel / 2 + : nel * dt_bytes(d.dtype); + std::memset(p, 0, nbyte); + if (d.fill == RAD_FILL_INDEX) { + const long long mx = d.idx_const >= 0 ? d.idx_const + : (d.idx_max > 0 ? d.idx_max : (long long)nel); + for (size_t i = 0; i < nel; ++i) { + const long long v = d.idx_const >= 0 + ? d.idx_const + : (long long)(xorshift(s) % (uint32_t)(mx > 0 ? mx : 1)); + if (dt_bytes(d.dtype) >= 8) *(int64_t*)(p + i * dt_bytes(d.dtype)) = v; + else if (dt_bytes(d.dtype) == 4) *(int32_t*)(p + i * 4) = (int32_t)v; + else p[i] = (uint8_t)v; + } + return; + } + if (d.dtype == RAD_I4) { + /* Two signed codes a byte, the low nibble first: both grids' -7..7 draw, stored in + * two's complement, which is the low four bits. */ + for (size_t j = 0; j < nel / 2; ++j) { + double v0 = ((double)xorshift(s) / 4294967296.0) * 2.0 - 1.0; + double v1 = ((double)xorshift(s) / 4294967296.0) * 2.0 - 1.0; + const int c0 = (int)(v0 * 7.0); + const int c1 = (int)(v1 * 7.0); + p[j] = (uint8_t)(((uint32_t)c0 & 0xFu) | (((uint32_t)c1 & 0xFu) << 4)); + } + return; + } + if (d.dtype == RAD_FP4E2M1) { + /* Two e2m1 codes a byte, drawn independently: all 16 values, so the unpack's magnitude + * and sign paths are both exercised. */ + for (size_t j = 0; j < nel / 2; ++j) { + const uint8_t lo = (uint8_t)(xorshift(s) & 0xFu); + const uint8_t hi = (uint8_t)(xorshift(s) & 0xFu); + p[j] = (uint8_t)(lo | (hi << 4)); + } + return; + } + for (size_t i = 0; i < nel; ++i) { + double v = 0.0; + for (int k = 0; k < 4; ++k) v += (double)xorshift(s) / 4294967296.0; + v = v / 4.0 * 2.0 - 1.0; /* [-1, 1) */ + if (d.fill == RAD_FILL_SIGMOID) v = 0.05 + 0.9 * (v * 0.5 + 0.5); + switch (d.dtype) { + case RAD_F32: *(float*)(p + i * 4) = (float)v; break; + case RAD_BF16: *(uint16_t*)(p + i * 2) = f32_to_bf16((float)v); break; + case RAD_F16: *(uint16_t*)(p + i * 2) = f32_to_f16((float)v); break; + case RAD_F8E4M3: p[i] = f32_to_e4m3((float)v); break; + case RAD_I8: *(int8_t*)(p + i) = (int8_t)(v * 100.0); break; + case RAD_U8: p[i] = (uint8_t)(v * 100.0 + 128.0); break; + case RAD_I32: + case RAD_U32: *(int32_t*)(p + i * 4) = (int32_t)(v * 1000.0); break; + case RAD_I64: *(int64_t*)(p + i * 8) = (int64_t)(v * 1000.0); break; + default: break; + } + } +} + +/* The geometry a row is run at: the band's bounds where the row constrains them, the widths a + * model has elsewhere. Reading the row's own constraints is what makes this a test of the + * constraint table and not of a geometry the table happens to admit. */ +static void make_params(Case& c, const RadKernelInfo* k, const RadOpSchema* s) { + c.words.reserve(32); /* more parameters than any op declares, so no string ever moves */ + for (int q = 0; q < s->n_params && c.n_p < 32; ++q) { + const RadParamSpec& sp = s->params[q]; + /* Only the parameters the geometry has to carry. The engine passes the graph's parameters + * with their ranges collapsed, and an optional parameter the graph did not set is simply + * not in the list: the kernel's own default is then the one libref's `p_*` default is. A + * selftest that filled every optional slot with a value would be testing a geometry no + * graph produces -- and for rope, whose optional `sections` string switches the position + * plane to one row per component, it would be testing a mode the row's constraints + * exclude. Constrained parameters are always passed: the constraint states the row's band, + * so its value is the row's own claim. */ + bool constrained = false; + for (int ci = 0; ci < k->n_constraints && !constrained; ++ci) + if (k->constraints[ci].key && sp.key && !std::strcmp(k->constraints[ci].key, sp.key)) + constrained = true; + if (!sp.required && !constrained) continue; + RadParam out{}; + out.key = sp.key; + out.kind = sp.type; + out.ival = 8; + out.dval = 1.0; + out.sval = "bf16"; + if (sp.key && !std::strcmp(sp.key, "eps")) out.dval = 1e-5; + if (sp.key && !std::strcmp(sp.key, "theta")) out.dval = 500000.0; + if (sp.key && !std::strcmp(sp.key, "head_dim")) out.ival = 128; + if (sp.key && !std::strcmp(sp.key, "n_head")) out.ival = 8; + if (sp.key && !std::strcmp(sp.key, "n_head_kv")) out.ival = 8; + if (sp.key && !std::strcmp(sp.key, "block_size")) out.ival = 32; + if (sp.key && !std::strcmp(sp.key, "gqa")) out.ival = 1; + if (sp.key && !std::strcmp(sp.key, "q_len")) out.ival = 1; + if (sp.key && !std::strcmp(sp.key, "causal")) out.ival = 1; + if (sp.key && !std::strcmp(sp.key, "window")) out.ival = -1; + if (sp.key && !std::strcmp(sp.key, "n")) out.ival = 4096; + if (sp.key && !std::strcmp(sp.key, "N")) out.ival = 11008; + if (sp.key && !std::strcmp(sp.key, "K")) out.ival = 4096; + if (sp.key && !std::strcmp(sp.key, "n_embd")) out.ival = 4096; + if (sp.key && !std::strcmp(sp.key, "n_vocab")) out.ival = 128256; + if (sp.key && !std::strcmp(sp.key, "group")) out.ival = 128; + if (sp.key && !std::strcmp(sp.key, "pb1")) out.ival = 128; + if (sp.key && !std::strcmp(sp.key, "pb2")) out.ival = 128; + if (sp.key && !std::strcmp(sp.key, "from")) out.sval = "bf16"; + if (sp.key && !std::strcmp(sp.key, "to")) out.sval = "f32"; + if (sp.key && !std::strcmp(sp.key, "act")) out.sval = "silu"; + /* A constraint's own value wins: it is the band the row is compiled for, and C_IN spells + * the whole list. A list takes its first word. */ + for (int ci = 0; ci < k->n_constraints; ++ci) { + const RadConstraint& x = k->constraints[ci]; + if (!x.key || !sp.key || std::strcmp(x.key, sp.key)) continue; + if (x.op == RAD_C_EQ && sp.type == RAD_P_STR && x.sval) out.sval = x.sval; + if ((x.op == RAD_C_EQ || x.op == RAD_C_GE) && sp.type == RAD_P_INT) out.ival = x.ival; + if (x.op == RAD_C_IN && sp.type == RAD_P_STR && x.sval && x.sval[0]) { + /* The band's first word. The words outlive the parameter list, so they live in a + * vector that is reserved once: a string built per constraint and pointed at from + * out.sval is a pointer to storage the next constraint reuses, and a row with two + * string constraints reads the second one's value into the first's key. */ + c.words.emplace_back(x.sval); + std::string& w = c.words.back(); + const size_t sp0 = w.find(' '); + if (sp0 != std::string::npos) w.resize(sp0); + out.sval = w.c_str(); + } + } + c.p[c.n_p++] = out; + } +} + +/* ------------------------------------------------------------------ a row with no shape hook + * + * `gemm_q_shape` declines w2a8 for a good reason: the container stores the weight's scale and zero + * as two planes behind the one `b_scale` operand, and a RadOpdDesc names one dtype and one extent + * set, so it cannot describe that. A hook that named only the byte count would have the tool fill a + * container header with random bytes, and the kernel's correct refusal would be reported as a bug. + * So the row's `opd_shape` is null, kbench names the skip, and this is the row's coverage: the band + * MiniCPM5-2B asks for, with the joined plane built by rad_planes_relayout exactly as + * r3d_gemm_nt_q_w2a8_driver.cpp builds it, so the card test and the driver cannot drift apart. */ +static int build_w2a8(Case& c, const RadOpSchema* s) { +#define W_PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } +#define W_PS(k, v) { (k), RAD_P_STR, 0, 0, (v), 0.0 } + const long long M = 16, N = 130560, K = 2048, group = 128, G = K / group; + if (s->n_operands != 7) { fail("w2a8: the schema has %d operands, not 7", s->n_operands); return 1; } + c.n_p = 0; /* the band, not the constraint table's minimums */ + const RadParam pp[] = { W_PI("M", M), W_PI("N", N), W_PI("K", K), W_PI("group", group), + W_PS("dtype", "w2a8") }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + RadEncoding e; + std::memset(&e, 0, sizeof e); + rad_enc_copy_str(e.scheme, "affine"); + e.n_planes = 3; + rad_enc_copy_str(e.plane[0].role, "codes"); + e.plane[0].dtype = RAD_U2; e.plane[0].kind = RAD_PLANE_TILED; + e.plane[0].block[0] = 1; e.plane[0].block[1] = 1; + rad_enc_copy_str(e.plane[1].role, "scale"); + e.plane[1].dtype = RAD_F16; e.plane[1].kind = RAD_PLANE_TILED; + e.plane[1].block[0] = 1; e.plane[1].block[1] = group; + rad_enc_copy_str(e.plane[2].role, "zero"); + e.plane[2].dtype = RAD_U8; e.plane[2].kind = RAD_PLANE_TILED; + e.plane[2].block[0] = 1; e.plane[2].block[1] = group; + const int sel[2] = { 1, 2 }; + + std::vector sc((size_t)N * G), ze((size_t)N * G); + uint32_t st = 0x1234567u; + for (size_t i = 0; i < sc.size(); ++i) { + st = st * 1664525u + 1013904223u; + sc[i] = f32_to_f16(0.001f + 0.002f * (float)((st >> 8) & 0xffffu) / 65536.0f); + ze[i] = (uint8_t)((st >> 16) & 3u); + } + RadTensor ps[2] = {}; /* zero-initialised: rad_planes_plan reads every field */ + const long long pd[2][2] = { { N, G }, { N, G } }; + const uint32_t pdt[2] = { RAD_F16, RAD_U8 }; + void* pdat[2] = { sc.data(), ze.data() }; + for (int i = 0; i < 2; ++i) { + ps[i].data = pdat[i]; ps[i].dtype = pdt[i]; ps[i].rank = 2; + ps[i].shape[0] = pd[i][0]; ps[i].shape[1] = pd[i][1]; + ps[i].stride[1] = 1; ps[i].stride[0] = pd[i][1]; + } + RadPlanesEntry en[RAD_ENC_MAX_PLANES]; + const long long jb = rad_planes_plan(&e, sel, ps, 2, en); + if (jb <= 0) { fail("w2a8: rad_planes_plan refused the joined scale+zero"); return 1; } + std::vector jbytes((size_t)jb, 0); + if (rad_planes_relayout(&e, sel, ps, 2, jbytes.data(), jb) != RAD_OK) { + fail("w2a8: rad_planes_relayout refused"); return 1; + } + + /* Slots in the schema's order: a, a_scale, b, b_scale (the joined blob), y, a_sum. y is the + * output and it is pre-filled with a bf16 NaN: a kernel that never launches leaves its status + * RAD_OK behind and the caller's bytes in the plane, and a plane of the caller's own zeros is + * finite, so only a NaN fill says the row ran. */ + /* Schema order: a, a_scale (optional), b, b_scale, y, a_sum (optional), b_ref (an absent + * weight: a null tensor is what an omitted optional means to the shim). */ + struct Slot { long long rows, cols; uint32_t dt; int nan; } q[7] = { + { M, K, RAD_I8, 0 }, { M, 1, RAD_F32, 0 }, { N, K, RAD_U2, 0 }, + { jb, 1, RAD_U8, 0 }, { M, N, RAD_BF16, 1 }, { G, 16, RAD_F32, 0 }, { 0, 0, RAD_F32, 0 } }; + for (int o = 0; o < 7; ++o) { + if (o == 6) { c.t[o] = RadTensor{}; continue; } + size_t bytes = o == 3 ? (size_t)jb + : q[o].dt == RAD_U2 ? (size_t)(q[o].rows * q[o].cols) / 4 + : (size_t)(q[o].rows * q[o].cols) * dt_bytes(q[o].dt); + std::vector h(bytes, 0); + if (o == 3) std::memcpy(h.data(), jbytes.data(), bytes); /* the blob, not a random fill */ + else for (size_t i = 0; i < bytes; ++i) { + st = st * 1664525u + 1013904223u; + h[i] = (uint8_t)(st >> 13); + } + if (o == 1 || o == 5) { /* scales and sums: small and positive */ + float* f = (float*)h.data(); + const size_t n = bytes / 4; + for (size_t i = 0; i < n; ++i) f[i] = 0.001f + 0.01f * (float)((st = st * 1664525u + + 1013904223u) >> 8 & 0xffffu) / 65536.0f; + } + if (q[o].nan) { + uint16_t* b16 = (uint16_t*)h.data(); + for (size_t i = 0; i < bytes / 2; ++i) b16[i] = 0x7fc0u; + } + /* The joined operand stays on the host: the shim reads its header where it lies, which is + * the mapped tier the engine puts a joined weight on, and a device pointer there is a null + * header and a refused geometry. The driver hands it over the same way. The allocation is + * left standing -- this process is short-lived and one blob per run. */ + void* d = nullptr; + if (o == 3) { + /* Pinned host memory, the mapped tier's shape: the shim reads this operand's header on + * the host, the kernel reads the same bytes as a device pointer, and plain malloc is + * not device-addressable -- it faults with 700. hipHostMalloc is valid on both sides, + * which is what the engine's container mapping gives a joined weight. */ + if (hipHostMalloc(&d, bytes, 0) != hipSuccess) { fail("w2a8: hipHostMalloc(%zu) failed", bytes); return 1; } + c.dev.push_back(d); + c.host.push_back(d); + std::memcpy(d, h.data(), bytes); + } else { + if (hipMalloc(&d, bytes) != hipSuccess) { fail("w2a8: hipMalloc(%zu) failed", bytes); return 1; } + c.dev.push_back(d); + if (hipMemcpy(d, h.data(), bytes, hipMemcpyHostToDevice) != hipSuccess) { + fail("w2a8: hipMemcpy in failed"); return 1; + } + } + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = q[o].dt; + t.rank = (o == 3) ? 1 : 2; + t.shape[0] = q[o].rows; t.shape[1] = q[o].cols; + t.stride[1] = 1; t.stride[0] = q[o].cols; + if (o == 3) { t.shape[0] = jb; t.shape[1] = 0; t.stride[0] = 1; } + } + return 0; +#undef W_PI +#undef W_PS +} + +static int run_row(int i) { + const RadKernelInfo* k = row_at(i); + if (!k) return 1; + std::printf("== %s (%s)\n", k->name, k->op); +#ifndef RAD_HAVE_HIP + (void)i; + skip("built without the HIP runtime: no device run"); + return 0; +#else + /* No card is not a failure: the static phase above is a third of what this program checks, and + * a build machine, a container and the CI job that builds the plugin all run it without one. */ + int ndev = 0; + if (hipGetDeviceCount(&ndev) != hipSuccess || ndev == 0) { + skip("no device visible"); + return 0; + } + const int hand = k->opd_shape ? 0 + : (0 == std::strcmp(k->name, "gemm_nt_q_w2a8_m16")) ? 1 : 2; + if (hand == 2) { skip("no operand description, so no buffers to build"); return 0; } + const RadOpSchema* s = find_schema(k->op); + if (!s) { fail("no schema for '%s'", k->op); return 1; } + + Case c; + make_params(c, k, s); + RadArgs a{}; + a.p = c.p; + a.n_p = c.n_p; + + if (hand) { if (build_w2a8(c, s)) return 1; goto launched; } + for (int o = 0; o < s->n_operands && o < MAX_OPD; ++o) { + RadOpdDesc d{}; + const int st = k->opd_shape(c.p, c.n_p, o, &d); + if (st != RAD_OK) { skip("operand %d: the description declines this geometry (%d)", o, st); + return 0; } + RadTensor t{}; + if (d.flags & RAD_OPD_F_ABSENT) { c.t[o] = t; continue; } + long long nel = 1; + for (uint32_t r = 0; r < d.rank; ++r) nel *= d.shape[r]; + t.dtype = d.dtype; + t.rank = d.rank; + for (uint32_t r = 0; r < d.rank; ++r) t.shape[r] = d.shape[r]; + /* Sub-byte dtypes count elements, not bytes: fp4_e2m1 packs two a byte. */ + const size_t bytes = d.dtype == RAD_U2 ? (size_t)(nel / 4) + : (d.dtype == RAD_U4 || d.dtype == RAD_I4 || d.dtype == RAD_FP4E2M1) + ? (size_t)(nel / 2) + : (size_t)nel * dt_bytes(d.dtype); + std::vector h(bytes ? bytes : 1); + fill_plane(d, h.data(), (size_t)nel, 0x9E3779B9u + (uint32_t)o * 7919u); + /* Standing to-do, measured and not shipped: filling every OUT plane with the dtype's NaN -- + * which is what says a row that returns RAD_OK without launching has left the caller's bytes + * in the plane, the failure the attention unit's third bug is -- works for 66 of the 68 rows + * and, in the forked child, kills `quant_act_i8_bf16` and `sample_logprobs_f32` on signal 11 + * while both run clean in-process (`--case`), and both write planes the reference pads. It + * is the right check, it needs the padded-plane story finished, and the hand-built geometry + * below already does it for the row whose coverage is this file. */ + void* p = nullptr; + if (hipMalloc(&p, bytes) != hipSuccess) { fail("hipMalloc(%zu) failed", bytes); return 1; } + c.dev.push_back(p); + if (hipMemcpy(p, h.data(), bytes, hipMemcpyHostToDevice) != hipSuccess) { + fail("hipMemcpy in failed"); return 1; + } + t.data = p; + long long acc = 1; + for (int r = (int)t.rank - 1; r >= 0; --r) { t.stride[r] = acc; acc *= t.shape[r]; } + c.t[o] = t; + } +launched: + a.t = c.t; + a.n_t = s->n_operands; + + /* The scratch the row asked for, at this geometry, if it asks for any. */ + void* scratch = nullptr; + if (k->scratch) { + const int64_t bytes = k->scratch(&a); + if (bytes > 0 && hipMalloc(&scratch, (size_t)bytes) == hipSuccess) { + (void)hipMemset(scratch, 0, (size_t)bytes); + a.scratch = scratch; + a.scratch_bytes = bytes; + } else if (bytes > 0) { + fail("the row wants %lld scratch bytes and none could be allocated", + (long long)bytes); + return 1; + } + } + + const int rc = k->launch(&a, nullptr); + const hipError_t le = hipGetLastError(); + const int sync = (int)hipDeviceSynchronize(); + int ret = 0; + if (rc == RAD_E_UNSUPPORTED || rc == RAD_E_INVAL || rc == RAD_E_SHAPE || + rc == RAD_E_DTYPE) { + skip("the shim declines this geometry (%d)", rc); + } else if (rc != RAD_OK) { + fail("launch returned %d", rc); + /* The band, spelled out: a shim's mapped code says what kind of answer it gave, not what + * it was given, and the difference between a launch that failed and a geometry nobody + * intended is in the numbers. */ + for (int i = 0; i < c.n_p; ++i) + if (c.p[i].kind == RAD_P_STR) + std::printf(" param %s = %s\n", c.p[i].key, c.p[i].sval ? c.p[i].sval : "(null)"); + else + std::printf(" param %s = %lld\n", c.p[i].key, c.p[i].ival); + for (int o = 0; o < s->n_operands; ++o) { + const RadTensor& t = c.t[o]; + std::printf(" operand %d '%s' dt=%u rank=%u data=%p", o, s->operands[o].name, + t.dtype, t.rank, t.data); + for (uint32_t r = 0; r < t.rank; ++r) std::printf(" %lld/%lld", t.shape[r], t.stride[r]); + std::printf("\n"); + } + ret = 1; + } else if (le != hipSuccess || sync != hipSuccess) { + fail("the kernel faulted (last error %d, sync %d)", (int)le, sync); + ret = 1; + } else { + int outs = 0; + for (int o = 0; o < s->n_operands && !ret; ++o) { + if (s->operands[o].role == RAD_OPD_IN) continue; + const RadTensor& t = c.t[o]; + if (!t.data) continue; + /* A joined plane lives where the mapped tier puts it: pinned host bytes the shim reads + * on the host and the kernel reads over PCIe. It is not a device buffer, so there is + * nothing to copy back, and its contents are the container's, not the row's work. */ + if (std::find(c.host.begin(), c.host.end(), t.data) != c.host.end()) continue; + ++outs; + long long nel = 1; + for (uint32_t r = 0; r < t.rank; ++r) nel *= t.shape[r]; + /* Sub-byte planes are counted in codes, not bytes: a U2 tensor of 267M codes is + * 66.8 MB on the card, and asking the runtime for 267 MB of it is an out-of-range + * copy, not a large one. */ + const size_t bytes = t.dtype == RAD_U2 ? (size_t)(nel / 4) + : (t.dtype == RAD_U4 || t.dtype == RAD_I4 || t.dtype == RAD_FP4E2M1) + ? (size_t)(nel / 2) + : (size_t)nel * dt_bytes(t.dtype); + std::vector h(bytes); + if (hipMemcpy(h.data(), t.data, bytes, hipMemcpyDeviceToHost) != hipSuccess) { + fail("hipMemcpy out failed: operand %d ('%s'), %zu bytes", o, s->operands[o].name, + bytes); ret = 1; break; + } + int nan = 0, big = 0; + for (long long e = 0; e < nel; ++e) { + float v; + switch (t.dtype) { + case RAD_F32: v = *(const float*)(h.data() + e * 4); break; + case RAD_BF16: v = bf16_to_f32(*(const uint16_t*)(h.data() + e * 2)); break; + case RAD_F16: v = f16_to_f32(*(const uint16_t*)(h.data() + e * 2)); break; + case RAD_F8E4M3: v = e4m3_to_f32(h.data()[e]); break; + default: continue; + } + if (v != v) ++nan; + else if (!(v > -1e31f && v < 1e31f)) ++big; + } + /* An infinity is the sampler's contract, not a broken number: a dropped candidate is + * `cand_idx` -1 and `cand_val` -inf, a narrowing stage drops by writing -inf, the mask + * and the ban write -inf into the logits, and a slot row_topk cannot fill is -inf. A + * NaN is nobody's contract, so it stays a failure everywhere. */ + const bool sentinel = (k->family && 0 == std::strcmp(k->family, "sample")) || + (k->op && 0 == std::strcmp(k->op, "row_topk")); + /* Two planes carry the reference's grid rather than the row's work: `asum`, the int8 + * activation's row sums padded to a 16-row grid, and `stats`, the quantiser's per-group + * statistics. The row writes the rows it was given and leaves the pad, and with outputs + * pre-filled NaN the pad is NaN by construction. Named planes only -- NaN anywhere else + * is exactly the silent no-op the fill exists to find. */ + const bool padded = s->operands[o].name && + (0 == std::strcmp(s->operands[o].name, "asum") || + 0 == std::strcmp(s->operands[o].name, "stats")); + if (nan && padded) { + ok("ran, %d output plane%s read back with %d pad NaN of %lld on '%s' (the " + "reference's grid, not the row's work)", outs, outs == 1 ? "" : "s", nan, nan == 1 + ? "" : "s", nel, s->operands[o].name); + } else if (nan) { fail("operand %d ('%s'): %d NaN of %lld", o, s->operands[o].name, nan, + nel); ret = 1; } + else if (big && !sentinel) { + fail("operand %d ('%s'): %d non-finite of %lld", o, s->operands[o].name, big, nel); + ret = 1; + } else if (big) { + ok("ran, %d output plane%s read back with %d sentinel%s of %lld on '%s' (the " + "contract's -inf)", outs, outs == 1 ? "" : "s", big, big == 1 ? "" : "s", nel, + s->operands[o].name); + } + } + if (!ret) ok("ran, %d output plane%s read back finite", outs, outs == 1 ? "" : "s"); + } + + if (scratch) (void)hipFree(scratch); + for (void* p : c.dev) (void)hipFree(p); + return ret; +#endif +} + +/* ================================================================== main */ +int main(int argc, char** argv) { + /* A row that dies takes the line it was printing with it, and knowing which row died is the + * whole point of the census: stdout is unbuffered, so the last line is the last thing that + * worked. Redirecting the output to a file is exactly when the buffering would hide it. */ + std::setvbuf(stdout, nullptr, _IONBF, 0); + const char* path = nullptr; + for (int i = 1; i < argc; ++i) { + if (!std::strcmp(argv[i], "--case") && i + 1 < argc) g_case = argv[++i]; + else if (!std::strcmp(argv[i], "--help")) { + std::printf("usage: r3d_selftest /libr3d.so [--case ]\n"); + return 0; + } else if (!path) path = argv[i]; + } + if (!path) { std::fprintf(stderr, "r3d_selftest: no plugin given\n"); return 2; } + g_plugin = path; + + /* dlopen, not link: an undefined symbol in the .so must be this program's failure. */ + void* h = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (!h) { std::fprintf(stderr, "r3d_selftest: %s\n", dlerror()); return 2; } + g_h = h; + P_count = (int (*)(void))dlsym(h, "rad_kernel_count"); + P_at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at"); + P_scount = (int (*)(void))dlsym(h, "rad_kernel_schema_count"); + P_sat = (const RadOpSchema* (*)(int))dlsym(h, "rad_kernel_schema_at"); + if (!P_count || !P_at || !P_scount || !P_sat) { + std::fprintf(stderr, "r3d_selftest: %s is not a kernel plugin\n", path); + return 2; + } + + if (!g_case) { + check_codecs(); + check_lanes(); + check_table(); + check_reference_schemas(); + check_band_reach(); + check_shapes(); + + const int n = rows(); + int passed = 0, failed = 0; + for (int i = 0; i < n; ++i) { + const RadKernelInfo* k = row_at(i); + if (!k || !k->name) continue; + std::vector argv2 = { argv[0], const_cast(path), + const_cast("--case"), + const_cast(k->name), nullptr }; + pid_t pid = 0; + if (posix_spawn(&pid, argv[0], nullptr, nullptr, argv2.data(), environ) != 0) { + fail("could not spawn a child for '%s': %s", k->name, std::strerror(errno)); + ++failed; + continue; + } + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {} + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) == 0) ++passed; else ++failed; + } else if (WIFSIGNALED(status)) { + std::printf(" FAIL %s died on signal %d\n", k->name, WTERMSIG(status)); + ++failed; + } + } + std::printf("== %d rows ran clean, %d failed, %d skipped by the shims\n", passed, failed, + g_skip); + dlclose(h); + return (failed || g_fail) ? 1 : 0; + } + + for (int i = 0; i < rows(); ++i) { + const RadKernelInfo* k = row_at(i); + if (k && k->name && !std::strcmp(k->name, g_case)) return run_row(i); + } + std::printf(" FAIL no row named '%s'\n", g_case); + return 1; +} diff --git a/libr3d/r3d_shapes.cpp b/libr3d/r3d_shapes.cpp new file mode 100644 index 00000000..4ce8ca37 --- /dev/null +++ b/libr3d/r3d_shapes.cpp @@ -0,0 +1,836 @@ +/* r3d_shapes.cpp -- the extent and content domain of each operand of an op at a geometry. + * + * This is libr3d's side of the `RadShapeFn` hook: the component that reads an operand is the one + * that knows its extent. The hand-written table in `tools/` describes the ops it was written + * against; a row that exists only here is invisible to it, and a tool that cannot size an operand + * cannot call the op cold. So correctness checks, benchmarks and the coverage census reach these + * rows through this hook. + * + * The authority for every extent is the shim, not the prose or the row table. Each `r3d_rad_*` + * entry point unpacks `RadArgs.t[i]` into extents and pitches; if a shim passes `x->shape[1]` as + * `n`, that is what the operand is. Each group names its unit, and a change to a shim's contract + * must be mirrored here. + * + * Content matters as much as size. A token id gathers a row of a codebook, a KV slot indexes + * n_blocks * block_size positions, a block-table entry indexes n_blocks. Drawn from the wrong + * range, such an operand tests the kernel's out-of-range handling instead of its arithmetic, and a + * scatter whose indices collide is a race the parallel rerun rightly reports as a failure. + * `RAD_FILL_INDEX` with an explicit `idx_max` states each range, and `RAD_OPD_F_IDX_UNIQUE` marks + * the scatters that need distinct destinations. + * + * ============================================================ rows with no description + * + * A decline is a real answer: the caller skips and counts the case, where an invented extent + * yields a meaningless pass. These rows carry a null `opd_shape`: + * + * gemm_nt_q at a quantised `a` whose scale plane the row does not name + * Not present in libr3d: both quantised rows state their activation dtype in `dtype`, so + * `a` is bf16 against an fp8 weight (fp8a16) or i8 against an i8 weight (i8a8), and both are + * described below. The case is listed here because it is the one libr4d declines, and a + * reader comparing the two files will look for the difference. + * + * rope at a multi-component mode + * mrope, imrope and axial take one position per component, component-major, and the + * component count comes from the `sections` string. libr3d's kernel implements neox and gptj + * and its row's constraints say so, so a geometry with `sections` set is never routed here. + * + * No tuned axis is read here: this plugin's axes (split counts, wave counts, the streaming mode) + * change how a kernel walks its operands, not their extents. An axis that did would be read from + * `p`, where the core appends the chosen point. + * + * Pure host code (no r3d.h, no HIP), like r3d_rows.cpp, so the tables compile and can be read + * without ROCm. + */ + +#include +#include + +#include "r3d_plugin.h" + +namespace { + +/* ==================================================================== building a description + * + * Each op builds its whole operand list in schema order and hands out the one asked for, so the + * count can be checked by eye against the schema in r3d_rows.cpp (the tool also checks it against + * `RadOpSchema::n_operands`). + */ + +/* A plain operand of up to four extents. A trailing 0 ends the shape; zero is never a legal + * extent (`pick` refuses one), so it cannot be mistaken for a real one. */ +RadOpdDesc opd(uint32_t dt, int64_t d0, int64_t d1 = 0, int64_t d2 = 0, int64_t d3 = 0) { + RadOpdDesc d{}; + d.dtype = dt; + d.fill = RAD_FILL_NORMAL; + /* -1 is "draw"; set explicitly though the caller pre-initialises it. */ + d.idx_const = -1; + const int64_t e[4] = { d0, d1, d2, d3 }; + for (int i = 0; i < 4 && e[i] != 0; ++i) d.shape[d.rank++] = e[i]; + return d; +} + +/* An index operand. `idx_max` is the exclusive upper bound of the draw; 0 means the previous + * operand's leading extent (the ABI default, right for a gather from the operand before it). + * `konst >= 0` fills every element with that value. Always i32: every index libr3d reads is signed + * 32-bit. */ +RadOpdDesc opd_idx(int64_t d0, int64_t idx_max, int64_t konst = -1, uint32_t flags = 0, + int64_t d1 = 0) { + RadOpdDesc d = opd((uint32_t)RAD_I32, d0, d1); + d.fill = RAD_FILL_INDEX; + d.idx_max = idx_max; + d.idx_const = konst; + d.flags = flags; + return d; +} + +/* An optional operand this description does not pass. One entry per schema operand is still + * emitted, so absence needs a spelling; to the ABI it means a null RadTensor. */ +RadOpdDesc opd_none() { + RadOpdDesc d{}; + d.idx_const = -1; + d.flags = RAD_OPD_F_ABSENT; + return d; +} + +/* Restricts the fill to (0, 1); `RAD_FILL_SIGMOID` is the ABI's only such draw. A scale plane drawn + * from a normal is as likely to be negative as positive, and a negative descale inverts the sign of + * an entire quantised block. */ +RadOpdDesc in_unit(RadOpdDesc d) { d.fill = RAD_FILL_SIGMOID; return d; } + +/* Hands out operand `operand` of a list after checking the whole list, so a geometry missing a + * parameter declines every operand rather than describing a few and declining the rest. A + * non-positive extent means a needed parameter was absent or zero: RAD_E_UNSUPPORTED, not + * RAD_E_SHAPE, which would read as a tool bug. An index outside the list is a bug here or in the + * schema, reported as RAD_E_SHAPE. */ +int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) { + if (!out || !list || n <= 0) return RAD_E_INVAL; + for (int i = 0; i < n; ++i) { + if (list[i].flags & RAD_OPD_F_ABSENT) continue; + if (list[i].rank == 0 || list[i].rank > RAD_MAX_RANK) return RAD_E_UNSUPPORTED; + for (uint32_t d = 0; d < list[i].rank; ++d) + if (list[i].shape[d] <= 0) return RAD_E_UNSUPPORTED; + } + if (operand < 0 || operand >= n) return RAD_E_SHAPE; + *out = list[operand]; + return RAD_OK; +} + +#define R3D_PICK(list) return pick(out, operand, (list), (int)(sizeof(list) / sizeof((list)[0]))) + +/* ==================================================================== parameters + * + * `M` and the other ranged parameters read as the band's bound, not any one step's row count (as + * in every shim here): buffers must hold the whole band the kernel was selected for. + * + * Not r3d_pgeti_or(): that reads RAD_P_INT only, which suits a launch (every range has collapsed + * by then), but this hook can see ranges still open. rad_param_getdim (ABI, shared with libr4d) + * reads a RAD_P_RANGE as its high bound. + */ +int64_t gi(const RadParam* p, int n_p, const char* k, int64_t dflt) { + return rad_param_getdim(p, n_p, k, dflt); +} + +const char* gs(const RadParam* p, int n_p, const char* k) { + return rad_param_gets(p, n_p, k, nullptr); +} + +/* The activation dtype, from `dtype` and its attention spellings; bf16 when the geometry names + * none. A quantisation-scheme string ("fp8a16", "w8a16") is not a dtype and lands on bf16, which + * is what the quantised rows use it to mean: the scheme picks the weight's dtype, the row states + * the activation's. */ +uint32_t act_dt(const RadParam* p, int n_p) { + const char* s = gs(p, n_p, "dtype"); + if (!s) s = gs(p, n_p, "q_dtype"); + const uint32_t dt = rad_dtype_parse(s); + return dt == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : dt; +} + +/* The scale-stream group count, matching the quantisers' launches: `group` <= 0 or wider than the + * row is one scale per row, otherwise ceil(n / group). */ +int64_t scale_groups(int64_t n, int64_t group) { + int64_t g = group; + if (g <= 0 || g > n) g = n; + return g > 0 ? (n + g - 1) / g : 0; +} + +/* ==================================================================== elementwise and norms + * r3d_model_bf16.hip + */ + +} /* namespace */ + +extern "C" { + +/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. The gain is described at its full width; the + * form with no gain at all is a hand case, since a null optional operand is not a fill domain. */ +int r3d_shape_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n), opd(D, n), opd(D, M, n) }; /* x, w, y */ + R3D_PICK(list); +} + +/* The two-pass form. `b` is optional and passed: the biased form covers strictly more code, and a + * null optional operand is not a fill domain a tool can draw. */ +int r3d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n), opd(D, n), opd(D, n), opd(D, M, n) }; /* x,w,b,y */ + R3D_PICK(list); +} + +/* add / mul share a schema and a description. `b` is described at full extent; the row-broadcast + * form is not described, since a buffer of n elements against M rows cannot be told from a shape + * bug by a tool that sizes by shape alone. */ +static int binary_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd(D, M, n) }; /* a, b, y */ + return pick(out, operand, list, 3); +} + +int r3d_shape_add(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return binary_shape(p, n_p, operand, out); +} +int r3d_shape_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return binary_shape(p, n_p, operand, out); +} + +/* y = act(gate) * up over two [M, n] operands. The fused [M, 2n] form is the one the model + * issues; describing it here would be a second spelling of a geometry the row's `n` is about, so + * the two halves are described as the kernel sees them. */ +int r3d_shape_act_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return binary_shape(p, n_p, operand, out); +} + +/* x -> y, one dtype to another. Operand dtypes come from `from` and `to`; an unparseable spelling + * falls back to f32, the widest it could mean. */ +int r3d_shape_cast(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + uint32_t from = rad_dtype_parse(gs(p, n_p, "from")); + uint32_t to = rad_dtype_parse(gs(p, n_p, "to")); + if (from == (uint32_t)RAD_DT_INVALID) from = (uint32_t)RAD_F32; + if (to == (uint32_t)RAD_DT_INVALID) to = (uint32_t)RAD_F32; + const RadOpdDesc list[] = { opd(from, M, n), opd(to, M, n) }; /* x, y */ + R3D_PICK(list); +} + +/* The unary activations and softmax: x and y at the same extent. */ +static int unary_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n) }; /* x, y */ + return pick(out, operand, list, 2); +} + +int r3d_shape_silu(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return unary_shape(p, n_p, operand, out); +} +int r3d_shape_gelu(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return unary_shape(p, n_p, operand, out); +} +int r3d_shape_sigmoid(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return unary_shape(p, n_p, operand, out); +} +int r3d_shape_softmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return unary_shape(p, n_p, operand, out); +} + +/* y = x * s. `s` is one element, broadcast over everything; a row of them would be a different op. */ +int r3d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n), opd(D, 1), opd(D, M, n) }; /* x, s, y */ + R3D_PICK(list); +} + +/* y = value. The only operand is the output, so a case's whole content is the kernel's. */ +int r3d_shape_fill(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n) }; + R3D_PICK(list); +} + +/* ==================================================================== the model's odds and ends + * r3d_model_bf16.hip + */ + +/* In-place rotary over a fused qkv row: n_head q heads, then n_head_kv each of k and v. The + * positions are drawn over the row count, which for a single step is its own positions; a step + * crossing a context boundary is a hand case, since a fill cannot spell "contiguous from an + * arbitrary start". */ +int r3d_shape_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + const int64_t nh = gi(p, n_p, "n_head", 0); + const int64_t nkv = gi(p, n_p, "n_head_kv", nh); + if (M <= 0 || hd <= 0 || nh <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { + opd((uint32_t)RAD_BF16, M, (nh + 2 * nkv) * hd), /* qkv, INOUT */ + opd_idx(M, 0) /* positions */ + }; + R3D_PICK(list); +} + +/* K and V into a paged cache. Two blocks of slack over the tokens, so the slot mapping is not a + * dense prefix and the block index matters. Only the cache takes `kv_dtype`: k and v are bf16 + * activations whatever the cache stores. */ +int r3d_shape_kv_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + const int64_t kvh = gi(p, n_p, "n_head_kv", 0); + const int64_t bs = gi(p, n_p, "block_size", 0); + if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0) return RAD_E_UNSUPPORTED; + const int64_t nb = (M + bs - 1) / bs + 2; + const uint32_t kv = rad_dtype_parse(gs(p, n_p, "kv_dtype")); + const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : kv; + const RadOpdDesc list[] = { + opd((uint32_t)RAD_BF16, M, kvh, hd), /* k */ + opd((uint32_t)RAD_BF16, M, kvh, hd), /* v */ + opd_idx(M, nb * bs, -1, RAD_OPD_F_IDX_UNIQUE), /* slot_mapping */ + opd(KV, nb, kvh, bs, 2 * hd) /* kv_cache, INOUT */ + }; + R3D_PICK(list); +} + +/* x[r] = wte[ids[r] - vocab_offset]. Ids are global, so the draw's bound is `vocab_offset + n_vocab`: + * under a shard the draw crosses the slice boundary and exercises the zero-row path. */ +int r3d_shape_embed_lookup(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t ne = gi(p, n_p, "n_embd", 0); + const int64_t nv = gi(p, n_p, "n_vocab", 0); + const int64_t vo = gi(p, n_p, "vocab_offset", 0); + if (M <= 0 || ne <= 0 || nv <= 0 || vo < 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const RadOpdDesc list[] = { + opd_idx(M, vo + nv), /* tokens */ + opd(D, nv, ne), /* wte */ + opd(D, M, ne) /* x */ + }; + R3D_PICK(list); +} + +/* The source is 4x the gathered height so the gather is not the identity, which would pass while + * broken; `idx` draws over those 4M rows. */ +int r3d_shape_gather_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, 4 * M, n), opd_idx(M, 0), opd(D, M, n) }; /* x, idx, y */ + R3D_PICK(list); +} + +/* Onto exactly M rows a scatter is a permutation, which a kernel ignoring `idx` could pass, so the + * destination is 4x the scattered height and unnamed rows must come back unchanged. The indices are + * distinct: two rows drawing one destination is a race. */ +int r3d_shape_scatter_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { + opd(D, M, n), opd_idx(M, 4 * M, -1, RAD_OPD_F_IDX_UNIQUE), opd(D, 4 * M, n) + }; /* v, idx, x (INOUT) */ + R3D_PICK(list); +} + +/* ================================================================== quantisation + * r3d_quant_fp8.hip + */ + +/* Codes row-major at [M, n], one f32 scale per (row, `group` of n). `dtype` names the input; the + * output's dtype is in the op name. */ +int r3d_shape_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const RadOpdDesc list[] = { + opd(D, M, n), opd((uint32_t)RAD_F8E4M3, M, n), opd((uint32_t)RAD_F32, M, ng) + }; /* x, q, scale */ + R3D_PICK(list); +} + +/* The int8 twin, with the optional row-sum plane beside it. `asum` is described whenever `group` + * divides n, so a case checks the row sums as well; it is group-major, the layout libref's + * quant_act_i8 writes. */ +/* The per-row int8: one scale per row, in a [M, 1] plane (the reference writes it at pitch 1, so a + * plane with more room is legal and this states the tightest one), and the optional `asum` described + * whenever `group` divides n, so a case exercises the row sums too. `q` is in the step order -- + * described by its extent, because a description states a plane's size and content domain, not a + * permutation; the row's `shape` prose names the order. */ +int r3d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), g = gi(p, n_p, "group", 0); + const RadOpdDesc list[] = { + opd(D, M, n), + opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, 1), + (g > 0 && n % g == 0) ? opd((uint32_t)RAD_F32, n / g, (M + 15) / 16 * 16) : opd_none() + }; /* x, q, scale, asum */ + R3D_PICK(list); +} + +/* The per-group int8, the activation the i8a8 GEMM reads: the fp8 quantiser's extents at int8 codes + * and a 127 denominator. */ +int r3d_shape_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const RadOpdDesc list[] = { + opd(D, M, n), opd((uint32_t)RAD_I8, M, n), opd((uint32_t)RAD_F32, M, ng) + }; /* x, q, scale */ + R3D_PICK(list); +} + +/* The gated form: gate_up is [M, 2n] with the gate first, and what is quantised is + * act(gate) * up over n columns. */ +int r3d_shape_gated_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const RadOpdDesc list[] = { + opd(D, M, 2 * n), + opd((uint32_t)RAD_F8E4M3, M, n), + opd((uint32_t)RAD_F32, M, ng), + opd((uint32_t)RAD_BF16, M, n) + }; /* gate_up, q, scale, out_bf16 */ + R3D_PICK(list); +} + +/* y = code * scale. `dtype` names the code: E4M3 and E5M2 are the checkpoint's fp8, i8 the int8 + * twin. The scale is a dequant multiplier, so its draw is restricted to (0, 1) -- a normal draw is + * as likely to be negative, and a negative scale inverts a whole block. */ +int r3d_shape_dequant(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t g = gi(p, n_p, "group", 0); + const uint32_t qd = rad_dtype_parse(gs(p, n_p, "dtype")); + const uint32_t Q = qd == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_I8 : qd; + const RadOpdDesc list[] = { + opd(Q, M, n), in_unit(opd((uint32_t)RAD_F32, M, scale_groups(n, g))), + opd((uint32_t)RAD_BF16, M, n) + }; /* q, scale, y */ + R3D_PICK(list); +} + +/* ================================================================== gemm + * r3d_gemm_bf16_nt_m16.hip, r3d_gemm_bf16_nt_tiled.hip, r3d_gemm_fp8a16_nt_m1.hip + */ + +/* y[M,N] = a[M,K] @ b[N,K]^T. Both operands are k-contiguous, which is what the transposed spelling + * in the op's name means and why neither is described as [K, N]. */ +int r3d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); + const RadOpdDesc list[] = { opd(D, M, K), opd(D, N, K), opd(D, M, N) }; /* a, b, y */ + R3D_PICK(list); +} + +/* The vocabulary projection, transcribed from ref_logits_gemm_shape: x [M, n_embd] and the head + * [n_vocab, n_embd] in the activation's dtype, the logits in f32 -- the dtype the schema states, not + * the one a GEMM would narrow to, because every sampler stage downstream reads f32 and a prefill + * band's plane is 1.07 GB of it at M=2048. The reference's own logits row answers a placement + * question (`ref_layout_head`: where the head lives) and so carries a layout hook; this row has + * nothing to place, it reads the head where it is stored, which is why the hook it declares is the + * shape and nothing else. A hook is the right thing to write *because* all three operands are + * describable: the extents the hook names are the ones that get filled, which is the opposite of + * the joined w2a8 plane, where a describable byte count is a container header waiting to be filled + * with random bytes. */ +int r3d_shape_logits_gemm_bf16(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), nv = gi(p, n_p, "n_vocab", 0), ne = gi(p, n_p, "n_embd", 0); + if (M <= 0 || nv <= 0 || ne <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const RadOpdDesc list[] = { opd(D, M, ne), opd(D, nv, ne), opd(RAD_F32, M, nv) }; + R3D_PICK(list); /* x, lm_head, logits */ +} + +/* The quantised GEMM. `dtype` names the scheme, and the scheme fixes which operands are coded: + * + * fp8a16 a bf16, b the checkpoint's E4M3 [N][K], b_scale one f32 per 128x128 block (the + * container's `weight_scale_inv`, whose dtype the container states: f32 at fp8a8f32, + * bf16 as DeepSeek's own scales are). + * fp8a8 a E4M3 against a_scale, one f32 per (row, `group` of K) -- quant_act_fp8's output + * feeding the GEMM, which is the reason the two rows state the same group. + * i8a8 i8 codes on both axes with an f32 scale per (row, `group`). + * + * `b_scale`'s plane is block-major [ceil(N/pb), ceil(K/pb)] for fp8 and row-major [N, ceil(K/group)] + * for i8: the two checkpoints spell it differently and both are the bytes on disk. */ +int r3d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); + if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED; + int64_t group = gi(p, n_p, "group", 0); + if (group <= 0) group = R3D_FP8_BLOCK; /* the block every block-scaled checkpoint uses */ + const int64_t kb = (K + group - 1) / group, nb = (N + group - 1) / group; + const char* q = gs(p, n_p, "dtype"); + const bool i8a8 = q && !std::strcmp(q, "i8a8"); + const bool a8 = q && (!std::strcmp(q, "fp8a8") || i8a8); + + RadOpdDesc list[R3D_GEMM_Q_NOPERAND]; + list[0] = opd(i8a8 ? (uint32_t)RAD_I8 : (a8 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16), + M, K); /* a */ + list[1] = a8 ? in_unit(opd((uint32_t)RAD_F32, M, kb)) : opd_none(); /* a_scale */ + list[2] = opd(i8a8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3, N, K); /* b */ + list[3] = in_unit(opd((uint32_t)RAD_F32, i8a8 ? N : nb, kb)); /* b_scale */ + list[4] = opd((uint32_t)RAD_BF16, M, N); /* y */ + list[5] = opd_none(); /* a_sum */ + list[6] = opd_none(); /* b_ref */ + return pick(out, operand, list, R3D_GEMM_Q_NOPERAND); +} + +/* The OCP-MXFP4 grid, libref's description for the dtype: the weight is e2m1, two a byte, with + * one e8m0 exponent per 32 of K, so the weight's planes are [N, K] of fp4_e2m1 and [N, K/32] of + * e8m0; `b_ref` is the same exponent plane, accepted beside an e2m1 weight and ignored. The + * activation is the fp8a8 row's -- E4M3 against one f32 per (row, 128 of K), drawn in (0, 1) as + * a quantiser's is. Both zero-point operands are absent: the scale is symmetric. */ +int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); + if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED; + if (K % 128) return RAD_E_UNSUPPORTED; /* the activation's scale group and the 32-block */ + const char* q = gs(p, n_p, "dtype"); + if (!q || std::strcmp(q, "mxfp4a8") != 0) return RAD_E_UNSUPPORTED; + const int64_t kb = K / 128; + RadOpdDesc list[R3D_GEMM_Q_NOPERAND]; + list[0] = opd((uint32_t)RAD_F8E4M3, M, K); /* a */ + RadOpdDesc as = opd((uint32_t)RAD_F32, M, kb); /* a_scale */ + as.fill = RAD_FILL_SIGMOID; /* a quantiser's (0, 1) */ + list[1] = as; + list[2] = opd((uint32_t)RAD_FP4E2M1, N, K); /* b: e2m1, two a byte */ + /* The e8m0 scale, filled with 127: the factor 2^0. A normal draw of the u8 grid is an exponent + * as high as 227, a factor 2^100, and the plane would scale the output past the finiteness + * bound the run checks; 127 is the checkpoint's own cluster and no reserved value. */ + RadOpdDesc e8 = opd((uint32_t)RAD_E8M0, N, K / 32); /* b_scale: e8m0 */ + e8.fill = RAD_FILL_INDEX; + e8.idx_const = 127; + list[3] = e8; + list[4] = opd((uint32_t)RAD_BF16, M, N); /* y */ + list[5] = opd_none(); /* a_sum */ + list[6] = e8; /* b_ref: the e8 plane */ + return pick(out, operand, list, R3D_GEMM_Q_NOPERAND); +} + +/* The symmetric int4 / int8 weight grids, libref's descriptions: int8 activations in the step + * order against signed codes (I4, two a byte, or I8, one a byte) with one f16 scale per (row, + * 128 of K) and one f32 activation scale per row, drawn in (0, 1) as a quantiser's is. There is + * no zero point and no a_sum: the dequant is code times scale. */ +static int shape_inta8(const RadParam* p, int n_p, int operand, RadOpdDesc* out, const char* q, + uint32_t bdt) +{ + const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); + if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED; + if (K % 128) return RAD_E_UNSUPPORTED; /* the weight's scale group */ + const char* d = gs(p, n_p, "dtype"); + if (!d || std::strcmp(d, q) != 0) return RAD_E_UNSUPPORTED; + const int64_t kb = K / 128; + RadOpdDesc list[R3D_GEMM_Q_NOPERAND]; + list[0] = opd((uint32_t)RAD_I8, M, K); /* a, step order */ + RadOpdDesc as = opd((uint32_t)RAD_F32, M, 1); /* a_scale, per row */ + as.fill = RAD_FILL_SIGMOID; + list[1] = as; + list[2] = opd(bdt, N, K); /* b: the signed codes */ + list[3] = opd((uint32_t)RAD_F16, N, kb); /* b_scale */ + list[4] = opd((uint32_t)RAD_BF16, M, N); /* y */ + list[5] = opd_none(); /* a_sum */ + list[6] = opd_none(); /* b_ref */ + return pick(out, operand, list, R3D_GEMM_Q_NOPERAND); +} + +int r3d_shape_gemm_nt_q_w4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) +{ + return shape_inta8(p, n_p, operand, out, "w4a8", (uint32_t)RAD_I4); +} + +int r3d_shape_gemm_nt_q_w8a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) +{ + return shape_inta8(p, n_p, operand, out, "w8a8", (uint32_t)RAD_I8); +} + +} /* extern "C" */ + + +/* ==================================================================== r3d_sample_f32.hip, r3d_attn_paged_h128.hip + * + * The vocabulary and the sampler. The schemas in r3d_rows.cpp are transcribed from libref and + * checked against it, and these are the other half of that transcription. Every extent, dtype, + * fill domain and flag below is libref's: a description that differs from libref's is a case + * kbench skips, with one line saying so, and a row that is never exercised is a row that is not + * tested. + * + * The sampler's `params` operand is one plane with one fill domain, `RAD_FILL_SAMPLE_PARAMS`: the + * ABI's `RadSampleParams`, 96 bytes, 24 f32 words a row, whose fields the stages read by name. The + * history window and the mask-row count are placed *inside* that plane by `fill_chunk` and + * `idx_max`, so the draw produces a window that fits the plane and a `mask_row` that is a row of + * the bitmask plane (or -1, the unconstrained row sharing a short plane). Both are the stage's + * parameters to obey, not this file's invention. + */ + +/* The sampler's parameter plane: [M, 24] f32, one RadSampleParams a row. */ +RadOpdDesc opd_params(int64_t M, int64_t hist, int64_t mask_rows) { + RadOpdDesc d = opd((uint32_t)RAD_F32, M, 24); + d.fill = (uint32_t)RAD_FILL_SAMPLE_PARAMS; + d.fill_chunk = hist; + d.idx_max = mask_rows; + return d; +} + +/* The widths libref's shapes choose, and the reasons it gives for them: the history window is what + * a deployment sizes the plane to, 64 is plausible; the candidate width is narrower than the + * vocabulary and wide enough for the narrowing stages. */ +enum { kHist = 64, kCand = 64 }; + +/* `n_vocab` rows of f32 logits, and the parameter plane, the pair every vocabulary-width stage + * opens with. */ +int sample_vocab(const RadParam* p, int n_p, int64_t* M, int64_t* nv) { + *M = gi(p, n_p, "M", 0); + *nv = gi(p, n_p, "n_vocab", 0); + return (*M > 0 && *nv > 0) ? RAD_OK : RAD_E_UNSUPPORTED; +} + +/* silu(gate) * up over one fused projection: the operand is [M, 2n] and the output [M, n]. */ +int r3d_shape_silu_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, 2 * n), opd(D, M, n) }; /* gate_up (gate first), y */ + R3D_PICK(list); +} + +/* The fused add + norm + quantiser. `residual` is INOUT and the sum it holds is the bf16 one the + * variance reads, so x and residual are the same shape by the op's meaning, not by convenience; + * `out_bf16`, optional, is what the codes were taken over, and it exists so a test can read the + * value the quantiser saw. */ +int r3d_shape_rmsnorm_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd(D, n), + opd((uint32_t)RAD_F8E4M3, M, n), opd((uint32_t)RAD_F32, M, ng), + opd((uint32_t)RAD_BF16, M, n) }; + R3D_PICK(list); /* x, residual, w, q, scale, out_bf16 */ +} + +/* Paged attention. The context is deeper than the query: one sequence whose context is its query + * length is the smallest geometry, and the one that exercises nothing -- no deep paging, no KV + * split, no window -- so `ctx`, when a harness passes it, wins, and is never below the query. + * `q_len` is the ranged parameter; a decode row and a 2048-token prefill chunk are different + * kernels (docs/OPS.md). */ +int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "q_len", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + const int64_t bs = gi(p, n_p, "block_size", 16); + const int64_t gqa = gi(p, n_p, "gqa", 1); + const int64_t nh = gi(p, n_p, "n_head", gqa); + if (M <= 0 || hd <= 0 || bs <= 0 || gqa <= 0 || nh <= 0 || nh % gqa) return RAD_E_UNSUPPORTED; + const int64_t kvh = nh / gqa; + const int64_t S = 1; + /* `ctx`, as the reference spells it -- and it is NOT the band's `max_ctx`, which is why a + * geometry that wants a context deeper than its query chunk has to name `ctx`. When no case + * names it, the context is the query chunk. */ + int64_t ctx = gi(p, n_p, "ctx", 0); + if (ctx < M) ctx = M; + const int64_t max_blocks = (ctx + bs - 1) / bs; + + const uint32_t Q = act_dt(p, n_p); + const uint32_t kv = rad_dtype_parse(gs(p, n_p, "kv_dtype")); + const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? Q : kv; + + const RadOpdDesc list[] = { + opd(Q, S * M, nh, hd), /* q */ + opd(KV, max_blocks, kvh, bs, 2 * hd), /* kv_cache */ + opd_idx(S, max_blocks, -1, 0, max_blocks), /* block_table: indexes blocks, + may repeat -- a page table */ + opd_idx(S, 0, ctx), /* seqused: a constant, not a draw */ + opd_none(), /* k_descale: no per-(seq,head) */ + opd_none(), /* v_descale */ + opd_none(), /* cu_seqlens: the rectangular + reading at one sequence */ + opd(Q, S * M, nh, hd) /* out */ + }; + R3D_PICK(list); +} + +/* Exact per-row top-R. `pairs` is described because its packing is checked: an int32 id's bits in + * the first slot beside its value, so the plane is f32 to hold the value. */ +int r3d_shape_row_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), R = gi(p, n_p, "R", 0); + if (M <= 0 || N <= 0 || R <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const RadOpdDesc list[] = { + opd(D, M, N), opd((uint32_t)RAD_I32, M, R), opd((uint32_t)RAD_F32, M, R), + opd((uint32_t)RAD_F32, M, R, 2) + }; /* x, idx, val, pairs */ + R3D_PICK(list); +} + +int r3d_shape_sample_argmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + int64_t M = 0, nv = 0; + if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { + opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0), opd((uint32_t)RAD_I32, M) + }; /* logits, params, token */ + R3D_PICK(list); +} + +int r3d_shape_sample_temp(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + int64_t M = 0, nv = 0; + if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0) }; + R3D_PICK(list); /* logits INOUT, params */ +} + +/* DFlash2's candidate walk, slot for slot from libref's shape hook. `cand` and `anchor` hold token + * ids bounded by n_vocab so the codebook gather stays inside the plane, and cand/unary/hp carry one + * row per (sequence, step), M * steps. */ +/* The gated MLP band, slot for slot from libref's shape hook: n = N/2, the weight's scales per + * (ceil(N/group), ceil(K/group)) in **bf16** (the container's `weight_scale_inv`, which writes + * `o.t(RAD_BF16, {nb, kb})`), the output's codes per (M, n) and its scales per (M, ceil(n/group)). + * The row's set is fp8a8 only, group a power of two in [32, 256], no wider than n, and K a whole + * number of groups -- a hook that describes a shape the kernel refuses is the bug class this file + * exists to prevent. */ +int r3d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t N = gi(p, n_p, "N", 0); + const int64_t K = gi(p, n_p, "K", 0); + const int64_t group = gi(p, n_p, "group", 0); + const char* q = gs(p, n_p, "dtype"); + if (!q || std::strcmp(q, "fp8a8") != 0) return RAD_E_UNSUPPORTED; + const int64_t n = N / 2; + if (M <= 0 || M > 64 || N <= 1 || (N & 1) || K <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + if (group != 32 && group != 64 && group != 128 && group != 256) return RAD_E_UNSUPPORTED; + if (group > n || (K % group)) return RAD_E_UNSUPPORTED; + const int64_t kb = (K + group - 1) / group, nb = (N + group - 1) / group; + const int64_t ng = (n + group - 1) / group; + const RadOpdDesc list[] = { + opd((uint32_t)RAD_F8E4M3, M, K), /* a */ + opd((uint32_t)RAD_F32, M, kb), /* a_scale */ + opd((uint32_t)RAD_F8E4M3, N, K), /* b: gate rows [0,n), up rows [n,N) */ + opd((uint32_t)RAD_BF16, nb, kb), /* b_scale: the container's form */ + opd((uint32_t)RAD_F8E4M3, M, n), /* q */ + opd((uint32_t)RAD_F32, M, ng), /* scale */ + opd((uint32_t)RAD_BF16, M, n), /* out_bf16, optional */ + }; + R3D_PICK(list); +} + +int r3d_shape_dflash_select(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t steps = gi(p, n_p, "steps", 0); + const int64_t K = gi(p, n_p, "top_k", 0); + const int64_t R = gi(p, n_p, "rank", 0); + const int64_t nv = gi(p, n_p, "n_vocab", 0); + const int64_t astr = gi(p, n_p, "anchor_stride", 1); + if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0) return RAD_E_UNSUPPORTED; + const int64_t rows = M * steps; + const RadOpdDesc list[] = { + opd_idx(rows, nv, -1, 0, K), /* cand: drawn over the vocab */ + opd((uint32_t)RAD_F32, rows, K), /* unary */ + opd((uint32_t)RAD_BF16, rows, R), /* hp, absent is a plane of ones */ + opd_idx(M * astr, nv), /* anchor */ + opd((uint32_t)RAD_BF16, nv, R), /* pred */ + opd((uint32_t)RAD_BF16, nv, R), /* succ */ + opd_idx(M, nv, -1, 0, steps), /* tokens */ + }; + R3D_PICK(list); +} + +int r3d_shape_sample_mask(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + int64_t M = 0, nv = 0; + if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; + /* mask_rows is M: one bitmask row a sequence is the widest the plane gets, and an + * unconstrained row shares it with mask_row -1. A set bit is an allowed token. */ + const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, M), + opd((uint32_t)RAD_I32, M, (nv + 31) / 32) }; + R3D_PICK(list); +} + +int r3d_shape_sample_logprobs(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + int64_t M = 0, nv = 0; + if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; + const int64_t k = gi(p, n_p, "k", 0); + if (k <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0), + opd((uint32_t)RAD_F32, M, 2 + 2 * k) }; + R3D_PICK(list); /* logits, params, stats [M, 2+2k] */ +} + +int r3d_shape_sample_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + int64_t M = 0, nv = 0; + if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; + const int64_t nc = nv < (int64_t)kCand ? nv : (int64_t)kCand; + const RadOpdDesc list[] = { + opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0), + opd((uint32_t)RAD_I32, M, nc), opd((uint32_t)RAD_F32, M, nc), + opd((uint32_t)RAD_I32, M, 2 * nc) + }; /* logits, params, cand_idx, cand_val (logits, not probs), pairs */ + R3D_PICK(list); +} + +/* The four narrowing stages -- top-p, min-p, typical, XTC -- in place over the candidate set. + * The set is drawn, not sorted: the ABI has no descending fill domain, and top-p is a prefix rule + * in candidate order, which applies equally to a random order. An implementation that sorted + * internally would genuinely disagree with the schema. */ +int r3d_shape_narrow(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t nc = gi(p, n_p, "n_cand", 0); + if (M <= 0 || nc <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { opd_idx(M, nc, -1, 0, nc), opd((uint32_t)RAD_F32, M, nc), + opd_params(M, 0, 0) }; + R3D_PICK(list); /* cand_idx INOUT, cand_val INOUT, params */ +} + +int r3d_shape_sample_pick(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t nc = gi(p, n_p, "n_cand", 0); + if (M <= 0 || nc <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { opd_idx(M, nc, -1, 0, nc), opd((uint32_t)RAD_F32, M, nc), + opd_params(M, 0, 0), opd((uint32_t)RAD_I32, M) }; + R3D_PICK(list); /* cand_idx, cand_val, params (seed and pos), token */ +} + +/* Penalties and DRY: logits, params with a history window inside it, and the history itself -- real + * token ids that repeat as text repeats. DRY's breaker plane marks about half its positions, so the + * exemption runs as well as the penalty. */ +int r3d_shape_sample_penalties(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + int64_t M = 0, nv = 0; + if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { + opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0), + opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist) + }; + R3D_PICK(list); +} + +int r3d_shape_sample_dry(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + int64_t M = 0, nv = 0; + if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc brk = opd_idx(M, 2, -1, 0, kHist); + const_cast(brk).dtype = (uint32_t)RAD_U8; + const RadOpdDesc list[] = { + opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0), + opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist), brk + }; + R3D_PICK(list); +} + +/* The windowed n-gram ban adds a {n, window} pair a row and an optional exemption bitmask. */ +int r3d_shape_sample_ngram_ban(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + int64_t M = 0, nv = 0; + if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { + opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0), + opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist), + opd_idx(M, 64, -1, 0, 2), + opd((uint32_t)RAD_I32, M, (nv + 31) / 32) + }; + R3D_PICK(list); +} + +/* The four narrowing stages share the description above; the op names which predicate the kernel + * applies, and the schema they share says the operands are the same. */ +int r3d_shape_sample_topp(const RadParam* p, int n_p, int o, RadOpdDesc* out) { + return r3d_shape_narrow(p, n_p, o, out); +} +int r3d_shape_sample_minp(const RadParam* p, int n_p, int o, RadOpdDesc* out) { + return r3d_shape_narrow(p, n_p, o, out); +} +int r3d_shape_sample_typical(const RadParam* p, int n_p, int o, RadOpdDesc* out) { + return r3d_shape_narrow(p, n_p, o, out); +} +int r3d_shape_sample_xtc(const RadParam* p, int n_p, int o, RadOpdDesc* out) { + return r3d_shape_narrow(p, n_p, o, out); +} diff --git a/libr3d/r3d_tiling.h b/libr3d/r3d_tiling.h new file mode 100644 index 00000000..684e6e5e --- /dev/null +++ b/libr3d/r3d_tiling.h @@ -0,0 +1,57 @@ +/* r3d_tiling.h -- the tiled rows' LDS row law, in one place. + * + * Every tiled row in libr3d stages an [rows x pitch] f16 tile in LDS and then reads it back two + * elements at a time for dot2_f16x2. Two functions spell that out and they must agree exactly, so + * they live here and the rows include this file. + * + * srow(row, c8, pitch) the element offset of the c8-th run of EIGHT elements of `row` + * srow_pair(row, kc, pitch) the element offset of the pair (kc, kc+1) of `row`, kc even + * + * The law, and why it is shaped like this: + * + * - Granularity is EIGHT elements (16 bytes at f16): staging writes a uint4 a step, so the XOR has + * to move whole uint4s and never split one. A swizzle at pair granularity would make the store + * unaligned and the compiler would say so in bytes of spill. + * - The XOR is with (row & 7), so eight consecutive rows rotate the runs by one slot each. That is + * what kills the dot loop's bank conflict: a wavefront reads 32 rows at the same kc, and with the + * rotation the 32 reads land on 32 distinct 16-byte slots instead of the four a plain row-major + * tile puts them on. + * - The mask (pitch / 8 - 1) keeps the rotated index INSIDE the row. pitch is in elements, so a + * row has pitch/8 runs, and pitch/8 is a power of two for every tile in the library (32, 128). + * Without the mask a rotated index leaves the row and reads a neighbour's, which is the bug this + * header exists to prevent: it is silent, it is data-dependent, and it measures 30x off. + * - srow_pair takes the pair index kc>>3 -- the run the pair lives in -- and adds (kc & 7), the + * element inside the run. Reading pairs through srow is what keeps the store, the load and the + * swizzle one statement each. + * + * Measured law, in the family's numbers: a row that stages through srow and reads through + * srow_pair, with dot2_f16x2 accumulating into f32, lands at rel_l2 1.7e-03 against + * ref_gemm_nt_q's body at a bf16 output (the store's ulp binding, not the fold's) with 83% of + * outputs bit-exact. A row that gets the swizzle wrong, in either direction, lands at rel_l2 3e+01. + * + * Header-only, like the rest of libr3d. Include it in a .hip at file scope, before the kernels; the + * definitions are in an unnamed namespace, so each translation unit gets its own copy -- which is + * what the rows had before this header existed, spelled the same way, so the host pass does not see + * an unused static and the inliner sees the same function it always did. + */ +#ifndef R3D_TILING_H +#define R3D_TILING_H + +namespace { + +/* The element offset of run `c8` of `row`. pitch is a row's element count, a power of two. */ +__device__ __forceinline__ int srow(int row, int c8, int pitch) +{ + return row * pitch + (((c8 ^ (row & 7)) & (pitch / 8 - 1)) << 3); +} + +/* The element offset of the f16 pair (kc, kc+1), kc even: the run the pair lives in, plus the + * element's place inside that run. */ +__device__ __forceinline__ int srow_pair(int row, int kc, int pitch) +{ + return srow(row, kc >> 3, pitch) + (kc & 7); +} + +} // namespace + +#endif /* R3D_TILING_H */ diff --git a/libr3d/r3d_vocab_bf16.hip b/libr3d/r3d_vocab_bf16.hip new file mode 100644 index 00000000..36b6d657 --- /dev/null +++ b/libr3d/r3d_vocab_bf16.hip @@ -0,0 +1,926 @@ +/* r3d_vocab_bf16.hip -- the lm_head projection: `logits_gemm`, and the same tiling under `gemm_nt` + * at prefill sizes. + * + * y[M,N] = x[M,K] @ w[N,K]^T, f32 accumulate, k ascending. + * + * `logits_gemm` spells N and K as n_vocab and n_embd and its y is **f32**: the schema says so + * (`ref_logits_gemm_shape` writes `o.t(RAD_F32, {M, nv})`, "f32 logits, as every sampler stage reads + * them"), and none of those stages wants a bf16 logit. `gemm_nt` is the same arithmetic with a bf16 + * y, narrowed once by the store. Both entries are the same two kernels; `YF32` is the only + * difference in the code and the only difference in what the board has to report. + * + * ---- why this row exists ------------------------------------------------------------------------ + * + * The probe of the served checkpoint refuses exactly one op: `logits_gemm`. libref's + * `ref_logits_gemm` is + * `gemm_nt_impl(a, false, "n_vocab", "n_embd")` on 32 OpenMP threads: 1.1 TFLOP for the band's shape + * (M=2048, n_vocab=130560, n_embd=2048), which this card does in about a second and the CPU in + * tens. For decode it is the 535 MB vocabulary head read once a token -- one call per token, the + * head the model cannot answer without. This row is not a speed decision. It is + * a read of the container's own form, and the head is stored in two of them: bf16 plain, with + * `layout`, `relayout` and `unrelayout` all null; and E4M3 codes with a bf16 scale per 128x128 block + * as two planes of one `rad.planes` container, which is the form the served checkpoint ships and + * which is answered by `r3d_layout_logits_head`, this file's transcription of `ref_layout_head`. + * Nothing is repacked in either case, and no operand description is declined. + * + * ---- the prefill arm (M > 16) ------------------------------------------------------------------- + * + * A block is TM x TN = 128 x 128 outputs, 256 threads, eight waves, eight outputs a side a lane: 64 + * f32 accumulators a lane, grid (N/TN) x (M/TM). Lane `tid` owns rows m0 + (tid/16)*8 .. +7 by + * columns n0 + (tid%16)*8 .. +7, so its 64 outputs are one 8x8 square of the tile and its stores are + * 32-byte runs of f32 (16-byte runs of bf16). + * + * k is walked in KC = 32 code chunks. Both tiles are stored row-major in f16 -- a row is the 32 + * k-values of one m, 64 bytes -- because the global load that fills them is 8 contiguous k of one + * row: one `uint4` a thread, sixteen bytes, widened on the way in by four `bf16x2_to_f16x2`, which + * is exact for everything f16 can hold (bf16 has eight mantissa bits, f16 ten) and arrives as an inf + * for what it cannot, which the board counts rather than assumes away. The compute then reads those + * 64-byte rows in f16x2 pairs: eight activation pairs and eight weight pairs per two codes, + * sixty-four `fdot2` per two codes -- one pair-dot per output per two codes, 16 LDS reads against + * 64 dots. + * + * The tile pitch is KC elements and the rows are XOR-swizzled in eight-element units, which is the + * only arrangement that satisfies both ends at once. The staging store is a `uint4`, so a row's + * chunk offset has to stay a multiple of eight elements; an unswizzled 64-byte row stride puts all + * eight rows a lane reads on the same bank, 32-way. `srow` moves whole eight-element chunks by + * `row & 7`, which preserves the 16-byte alignment and brings the compute reads to two-way. Two-way + * and not conflict-free: the eight rows a lane owns sit at stride eight, so a period-8 swizzle + * repeats inside a lane's own set. The cost is 512 LDS cycles a block-chunk against 2048 of + * dots, a quarter, which is what the vectorised staging store buys. + * + * At the band, M=2048 n_vocab=130560 n_embd=2048, 16 x 1020 blocks of 256 threads: + * 272.24 ms = 4023 GFLOP/s, which is 37% of the 10.8 TFLOP/s this card's 32 CUs do dense f16 with + * f32 accumulate. At M=46 -- one tile row, 1020 blocks -- the same kernel does 16.64 ms = + * 1478 GFLOP/s, and the shortfall is the shape, not the kernel: 46 rows against a 128-row tile + * leaves 5/8 of every block's arithmetic idle. The host row for this op is `ref_logits_gemm`: 1.1 + * TFLOP per forward pass across the whole vocabulary, on OpenMP threads; this row is the card's + * answer to that comparison. + * + * ---- the decode arm (M <= 16) ------------------------------------------------------------------- + * + * The prefill tile reads the head M/TM times; at M=1 it would read 127/128 of it for nothing. At + * M <= 16 the block is the decode shape `r3d_gemm_bf16_nt_m16.hip` uses: a wave is MT activation + * rows by 32/MT weight rows, lane l owns (m = l % MT, n = n0 + l / MT), one accumulator a lane from + * k=0 to K, and no wave reduction anywhere -- so each output's sum is the reference's ascending + * chain, summand for summand, in the pair-dot's grouping. The activation arrives in 128-code chunks + * and stays in LDS for the chunk (MT x 128 f16, 4 KiB at MT=16, the same eight-element swizzle at + * the wider pitch); the weight goes straight from global to registers in 16-byte loads, eight codes + * at a time, widened where it lands. A wave keeps 32/MT weight rows in flight -- 4 KiB at MT=1 -- + * which is what makes 16-byte strided reads across rows cost what they fetch. `nt=1` asks for + * non-temporal head loads, the honest hint for bytes read once a token; on this card it is worth + * nothing: 3.316 ms against 3.290 ms at M=1, 0.8% the other way. It is implemented + * because the ABI names it, and left off by default because the number says to. + * + * At n_vocab = 130560, n_embd = 2048 the arm is M = 1 in 3.226 ms = 166 GB/s of head, and M = 16 in + * 8.151 ms = 1050 GFLOP/s, 66 GB/s of bytes. The w2a8 row's 22 GB/s is not this arm's bound: it is + * that kernel's own limit -- an ALU-bound pair-dot with one 16-byte weight load per 64 codes -- and + * the card's DRAM is 256 GB/s. This arm is the streaming shape, 16 bytes a lane a step with the + * activation in LDS, and it runs at two thirds of the card. + * + * So the bf16 head costs 3.23 ms per decode token, and M = 16 (a speculative verify) costs 0.51 ms + * a token. The quantised head is the same op in half the bytes: the codes are 130560 x 2048 = + * 267,386,880 bytes (255.0 MiB) and the scales 1020 x 16 bf16 = 32,640 bytes (31.9 KiB), so a decode + * reads 255.03 MiB where the bf16 head reads 510.0 MiB. At the 163 GB/s this row's bf16 arm runs at + * the floor that is 1.64 ms a token, and at the card's 256 GB/s, 1.04 ms. (The 66.8 MB figure is the + * w2a8 row's 2-bit grid, a different head form.) Every number below says which of the three + * placements the bytes were in, because the placement is worth more than anything in the kernel, and + * all three are on this page so the choice between the head's forms is made on measurement. + * + * ---- the accumulation, and what it is exact against --------------------------------------------- + * + * libref's law per output is `acc += a*b` over ascending k from zero, and for this op with no bias. + * One accumulator per output, k ascending, no reassociation across lanes, in both arms. The pair-dot + * folds two products into the accumulator per step (`acc + a0*b0 + a1*b1` in one rounding) where the + * reference rounds each product in, so the sums agree closely and are not bit-equal. f32 output, + * K = 2048: rel_l2 1.77e-06 against the reference's law, identical -- 1.77e-06, to the + * digits -- against the same law with the operands widened to f16 first, so the widening + * contributes nothing and the fusion is the whole of it. 1.77e-06 is about 30 + * f32 ulps on a sum of 2048 terms, and a random walk of one rounding per 1024 steps predicts + * sqrt(1024) * 6e-8 = 1e-6, which is where it lands. At K = 320 it is 2.0e-07, which scales the same + * way. What it means for the sampler: the head's bf16 values carry 4.9e-4 of quantisation each, so + * this is 300x finer than the input, and a top-k decision flips only on a tie tighter than 1e-6. + * + * Nothing here is integer arithmetic, so the v_fdot2_f32_f16 mantissa rule that bounds + * r3d_gemm_nt_q_w2a8.hip does not bite: the products are not integers, so there is no 2^20 wall, and + * the board's tail is ordinary rounding, counted with the plane pre-filled at 0x7fc0 -- no non-finite + * output at any size, including the 268-million-output band. + * + * ---- the head's stored form, and who answers it --------------------------------------------------- + * + * The band's `dtype=bf16` is the ACTIVATION's dtype. The head is quantised: the graph reads + * 'output.weight' as two planes of fp8_e4m3 * bf16[128x128], and the mapped tier reads the + * container where it lies, and its stored form is not the container's (rad.planes). The placement + * needs a reader for the head's stored form, and a layout hook is what a reader is. So: + * + * r3d_layout_logits_head (operand 1 -- `ref_layout_head` is `layout_scaled(operand, 1, -1, ...)`) + * tag `rad.planes`; codes E4M3 (libref's `scaled_rows` also admits int8) with a float scale -- + * bf16, f16 or f32 -- on a block of {128, 128} (`R3D_FP8_BLOCK`); ends in `rad_planes_layout`. + * It moves no byte and `relayout` stays null. `ref_layout_head` is libref-internal-static, so + * its body, and `layout_scaled`'s, and `enc_scaled_rows`' and `float_scale_dt`' with it, are + * transcribed here as the w2a8 hook transcribed `ref_layout_gemm_q`: checks and their order, + * unchanged. Two fields are worth naming: `rad_enc_is` + * compares `scheme`, and `transform` is the optional pre-transform. The + * encoding is affine with an EMPTY transform; a fixture that writes "affine" into `transform` + * makes the hook decline every head. + * + * The law. `ScaledRows::at(r, c) = codes.at(r, c) * scale.cover(r, c)`: the code widened exactly, + * multiplied by the scale covering it, one f32 rounding, then the plain ascending-k GEMM in f32. + * The widening is exact both ways -- E4M3 is 4 exponent and 3 mantissa bits, f16 is 5 and 10, and + * int8 lands in f16 whole -- so the codes reach the dot as the numbers the checkpoint means, and + * the only divergence stays the dot's fused rounding: rel_l2 2.77e-04 at M=1, K=2048, + * which is one f16 ulp's worth (2^-12 = 2.44e-04) and is the fold, not the dot; against the fold + * law, below, it is 4.5e-06, and `<=2 ulps` is 1.000 with `>6 ulps` 0 at every size, + * 268-million-output band included. y stays f32: logits are f32 and the reference's store is f32. + * + * The fold, and the hardware rule it obeys. The reference dequantises each element into f32; the + * tile is f16, so the scale enters as a f16 multiply at staging -- the tiled arm once per staged + * 8-column group, the decode arm once per 128-code chunk, and a chunk of 32 sits inside one + * 128-column block (128 % 32 == 0, 128 % 128 == 0), so one scale per staged row. That costs no + * registers: the prefill arm is the register file's at 237 VGPRs, and per-k-block partials would + * need 64 more accumulators and spill. The multiply must be a hardware f16 multiply + * (`v_mul_f16`, round to nearest, subnormals kept), not `f16x2_pack`: that builtin is + * `v_cvt_pkrtz_f16_f32`, ROUNDS TOWARD ZERO, and r3d_codecs.h says so and says to call it only + * with values f16 already represents exactly. A folded weight is not one of those -- code 431 by + * a scale of 4.5e-5 is eleven significant bits -- and a toward-zero packer biases every product + * toward zero and flushes the subnormal end: rel_l2 2.8e-04 against the fold law with only 0.53 of + * outputs within 2 ulps. The f16 multiply is one rounding in the right direction and one + * instruction: 4.5e-06 and 1.000. The number and the verdict: 2.77e-04 against the reference's + * exact law is the fold's cost, 250x finer than the E4M3 code's own quantum (2^-4 = 6.25e-2), so + * the fold does not move the logits by anything the quantisation did not already move. An f32 + * scale plane costs one more rounding (the scale to f16, 1.75e-04 against a model that folds + * after the multiply); the shipped form's bf16 scale is f16-exact and pays nothing. + * + * With the head's bytes where the engine would put them (VRAM, with the header page + * read by the shim on the host): prefill M=2048 in 325.06 ms = 3369 GFLOP/s against the bf16 head's + * 269.31 ms = 4067 -- 17% slower, all of it staging, and the case for the quantised head at prefill + * is the 255 MiB of weight traffic, not the FLOPs. M=46: 22.43 ms = 0.488 ms a token against + * 0.361. Decode M=1: 13.603 ms a token, 19.7 GB/s of codes, 8x above the 1.64 ms floor, and the + * cause is the E4M3 decoder. `__builtin_amdgcn_cvt_pk_f16_fp8` exists in clang and expands + * to software on gfx1102 -- zero `v_cvt_pk_f16_fp8` in the ISA -- so eight codes cost + * ~100 instructions of `e4m3_to_f32` against the bf16 arm's four, and the arm is ALU-bound. The + * fix has a size: a 256-entry f16 table in LDS is 512 bytes, 8 LDS reads a staged group against + * ~100 ALU, which puts the arm back near its floor; that is a tiling pass, not this row's work. + * The speculation block is where the form already pays: M=8 (7 drafts + 1) reads the head ONCE and + * costs 21.67 ms = 2.708 ms a token, 5x cheaper per token than M=1 on the same kernel. + * + * Where the bytes live, on this box, at M=1: in VRAM 13.6 ms; on the mapped tier + * (hipHostMalloc, read over PCIe by 8-byte strided loads) 643 ms a token; managed and left alone + * 2071 ms a token, 122 MB/s, because managed pages do not migrate for a read-mostly device access + * on this ROCm and the kernel faults page by page. The head is placed on + * the mapped tier. A hook makes that placement legal; it does not make it fast, and these three + * numbers are the argument for uploading the head. The board takes the timed number after + * `hipMemPrefetchAsync` and says so on every line. + * + * Both forms are served, chosen by the header: `rad_planes_header(w)` at the shim's head branch + * dispatches on it, and a plain bf16 operand goes down the bf16 path untouched. The choice is + * the container's, not the row's. The shim reads the container's header + * (which is why the operand's bytes must be host-readable: `scaled_rows()` does the same host read, + * so this is the engine's convention, not this row's invention); the kernel reads the same bytes on + * the card, so the fixture is hipMallocManaged + prefetch, or hipHostMalloc, never plain malloc -- + * plain malloc faults 700 on the kernel's first read. + * + * ---- the decoder is a table, and what the table moved -------------------------------------------- + * + * r3d_fp8_dequant.h replaces the E4M3 codec with a 256-entry f16 table in LDS (512 bytes, eight + * reads an eight-code group) because clang lists __builtin_amdgcn_cvt_pk_f16_fp8 for gfx1102 and a + * build that calls it contains ZERO v_cvt_pk_f16_fp8: the builtin is software here. The A/B is one + * source built twice (-DR3D_NO_E4M3_TBL selects the codec), same fixture, same seed: + * + * M=8 speculation 2.500 -> 0.924 ms/token (20.002 -> 7.395 ms) 2.70x THE WIN + * M=2048 prefill 323.978 -> 322.661 ms (3380 -> 3394 GFLOP/s) flat, -0.4% + * M=1 decode 12.999 -> 13.293 ms/token (20.6 -> 20.2 GB/s) NOT moved, 2.3% worse + * M=46 prefill 21.603 -> 21.792 ms (1139 -> 1129 GFLOP/s) flat + * + * The table is exact by construction -- the codec, evaluated once per bit pattern at block start -- + * and rel_l2 is bit-identical between the two binaries (2.770e-04 vs the fold law / 4.452e-06 vs the + * fold model at prefill; 2.758e-04 / 4.559e-06 at M=1), which is the check that the swap moved work + * and not arithmetic. It is a 2.70x win where the decoder was the binding resource (MT=8: four + * decodes and four folds a lane per eight codes, no memory wall in reach) and a NAMED NON-RESULT at + * M=1: 13 ms at 20 GB/s of codes is 8x off the 1.64 ms floor this row's own 163 GB/s implies, and + * removing ~100 ALU instructions an eight-code group does not move it. The suspect at M=1 is the + * load width -- eight codes a lane through an 8-byte load, where the bf16 arm takes sixteen bytes a + * lane and streams at 163 GB/s -- so the shape to try there is a 16-byte code load (16 codes, eight + * pairs, half the wavefronts), not more ALU. 44 kernels, all vgpr_spill_count: 0, both builds. + * + * ---- what is refused, and where ------------------------------------------------------------------ + * + * sk > 1: the grid is vocab-wide at every M -- 1020 blocks in x at the band for the prefill arm, + * 8160 for the decode arm at MT=16 -- so no shape this row serves is short of parallelism, and a + * split would buy a second kernel and a documented order change for nothing. kb: KC = 32 only; a + * tile pitched at anything else is a different swizzle, not a knob, and the launcher enumerates the + * values it accepts and refuses the rest. K not a multiple of KC, an x pitch not a multiple of 8, a + * y pitch not a multiple of 4 (f32) or 8 (bf16), a weight that is not contiguous, and quantised + * heads that are not this form. The head branch, in its order: + * a quantised head on the bf16-y row -- logits are f32; the tiled row keeps a bf16 head + * a `zero` plane on the head -- codes+scale+zero is gemm_nt_q's asymmetric grid, and the row + * that reads it is r3d_gemm_nt_q_w2a8.hip; that is w2a8's grid, not this op + * a joined operand that is not two planes + * a joined head whose planes are not codes + scale (a `table`, a `bias`: names it) + * codes tiled by anything but one code a cell + * sub-byte codes (4-bit: w4a16's ground, and the row that reads it is w2a8's neighbour) + * e5m2 and every other code dtype: no decoder here + * a scale plane that is a table, not a tiling + * an integer scale: not float_scale_dt's set + * a scale block that is not 128x128 -- per-(row, group) scales are gemm_nt_q's grid, and a + * per-row scale is a different indexing of the plane than ScaledRows::cover is + * a plane that does not cover the band (codes must be N x K, scales ceil(N/128) x + * ceil(K/128)); a plane whose row_bytes is shorter than its row + * and the bf16 branch's: a plain head that is not bf16, x and y dtypes, + * no axes, pitches, the head's numel and contiguity, absurd shapes, + * alignment, sk > 1. The launcher's own: a head with a null plane, a dtype + * outside the served set, a row pitch a vector load cannot walk (a 16-bit scale row is 2 + * bytes a column, so K = 320 -- 3 scale columns, 6 bytes -- is legal), addresses. + * 24 refusals, 24 as stated, and the hook's two served encodings answer RAD_OK with + * tag `rad.planes` and the codes' dtype. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_fp8_dequant.h" /* the E4M3 -> f16 table: 512 bytes of LDS for ~100 ALU a group */ +#include "r3d_tiling.h" /* the LDS row law: srow, srow_pair */ +#include "r3d_args.h" +#include "r3d_launch.h" + +#include "rad_planes.h" + +namespace { + +constexpr int kBlockThreads = 256; +constexpr int kWaves = kBlockThreads / kWave; /* 8 */ +constexpr int kTM = 128; /* activation rows a block */ +constexpr int kTN = 128; /* weight rows a block */ +constexpr int kKC = 32; /* codes a tile step */ +constexpr int kSkinnyMax = 16; /* the MT ceiling of the decode arm */ +constexpr int kChunkK = 128; /* the decode arm's activation chunk */ + +#if defined(__has_builtin) +# if __has_builtin(__builtin_nontemporal_load) +# define R3D_HAS_NT 1 +# endif +#endif +#ifndef R3D_HAS_NT +# define R3D_HAS_NT 0 +#endif + +/* The tile address, in f16 elements: `pitch`-wide rows whose eight-element chunks are XORed by the + * row's low bits. Multiples of eight in, so a uint4 store and an f16x2 read are both aligned by + * construction, at both pitches this file uses (32 and 128). */ +/* srow / srow_pair: r3d_tiling.h, the family's law in one place. */ + +/* Eight bf16 -> eight f16, exact for every value f16 can hold. */ +__device__ __forceinline__ uint4 widen8(uint4 w) +{ + return make_uint4(bf16x2_to_f16x2(w.x), bf16x2_to_f16x2(w.y), bf16x2_to_f16x2(w.z), + bf16x2_to_f16x2(w.w)); +} + +constexpr int kFp8Block = 128; /* the head's scale block: R3D_FP8_BLOCK, llama_dense_fp8 */ + +/* The head as the container stores it: E4M3 codes with one float scale per (128 x 128) block. + * Passed by value; every pointer in it is a device address, resolved by the shim out of the joined + * bytes (rad_planes_find), which is what a layout hook's absence asks of a kernel -- the container's + * own form, read where it lies, no byte moved. */ +struct HeadQ { + const uint8_t* codes; /* [N][K] */ + const uint8_t* scale; /* [ceil(N/128)][ceil(K/128)] */ + long long code_row; /* bytes a codes row: the plane's row_bytes, not K's element count */ + long long scale_row; /* bytes a scale row */ + int sdt; /* the scale's dtype: 0 bf16, 1 f16, 2 f32 (float_scale_dt's set) */ + int cdt; /* the codes' dtype: 0 E4M3, 1 int8 */ +}; + +/* The scale covering logical (n, k): `scale.cover` from the reference's ScaledRows, one scalar load a + * row a chunk. The plane is 32 KiB at the band, so it is in cache from the first block that touches + * a row and the load is not the traffic; the codes are. */ +__device__ __forceinline__ float scale_at(const HeadQ h, int n, int k) +{ + const uint8_t* p = h.scale + (long long)(n >> 7) * h.scale_row + + (long long)(k >> 7) * (h.sdt == 2 ? 4 : 2); + if (h.sdt == 2) { float f; __builtin_memcpy(&f, p, 4); return f; } + const uint16_t u = *(const uint16_t*)p; + return h.sdt == 1 ? f16_to_f32(u) : bf16_to_f32(u); +} + +/* Eight codes -> eight f16, exact. E4M3 is four exponent and three mantissa bits and f16 is five and + * ten, and int8 lands in f16 whole, so the decoder is a widening, not a rounding: the numbers the + * checkpoint means are the numbers multiplied (r3d_gemm_fp8a16_nt_m1.hip says the same about the + * same codec). e4m3x2_to_f16x2 decodes the two codes in a dword's LOW half, so the pairs straddle + * dwords: two dwords in, four pairs out. Feeding it whole dwords decodes eight codes and leaves the + * rest of the step multiplying registers that were never written -- the shape the sibling unit + * documents, and the reason this helper takes the pair the way it does. */ +#if defined(__has_builtin) +# if __has_builtin(__builtin_amdgcn_cvt_pk_f16_fp8) +# define R3D_HAS_FP8CVT 1 /* gfx11+: v_cvt_pk_f16_fp8, two codes to two f16, one instruction */ +# endif +#endif +#ifndef R3D_HAS_FP8CVT +# define R3D_HAS_FP8CVT 0 +#endif + +__device__ __forceinline__ uint32_t cvt_pk_f16_fp8(uint32_t b) +{ +#if R3D_HAS_FP8CVT + return __builtin_bit_cast(uint32_t, __builtin_amdgcn_cvt_pk_f16_fp8(b)); +#else + return f16x2_pack(e4m3_to_f32((uint8_t)(b & 0xffu)), e4m3_to_f32((uint8_t)((b >> 8) & 0xffu))); +#endif +} + +__device__ __forceinline__ void codes8_to_f16x4(const uint2 c, int cdt, const uint16_t* tbl, + uint32_t* w) +{ + const uint32_t d[2] = { c.x, c.y }; + if (tbl && !cdt) { + /* The table: eight LDS reads for eight codes. Exact by construction -- the table is built + * from the codec below, one entry per bit pattern -- so a row's numbers do not move; what + * moves is where the work happens. r3d_fp8_dequant.h carries the reason and the measurement. + * Passing null tbl asks for the codec, which is how the board A/Bs the two in one binary. */ + r3d_e4m3x8_ld(tbl, c, w); + return; + } + if (!cdt) { + /* The instruction this wants: two codes to two f16, one op. clang has the builtin on this + * target's list and gfx1102 does not have the instruction: the ISA of this build contains + * zero v_cvt_pk_f16_fp8, so the builtin expands to the software decode below and + * eight codes cost ~100 instructions of exponent work. At M=1: 19.7 GB/s of codes, + * 8x above the 1.64 ms floor, ALU-bound. The builtin stays because it says what the operation + * is and a card with the instruction gets it for free; the fix for THIS card is a 256-entry + * f16 table in LDS, 512 bytes, 8 LDS reads where the ~100 ALU are, which is a tiling pass. */ + w[0] = cvt_pk_f16_fp8(d[0]); + w[1] = cvt_pk_f16_fp8(d[0] >> 16); + w[2] = cvt_pk_f16_fp8(d[1]); + w[3] = cvt_pk_f16_fp8(d[1] >> 16); + return; + } +#pragma unroll + for (int j = 0; j < 4; ++j) { + const uint32_t pair = (d[j >> 1] >> (16 * (j & 1))) & 0xffffu; + w[j] = i8x2_to_f16x2(pair); + } +} + +/* The fold: the decoded code times the scale covering it, in f16 pairs. + * + * The reference dequantises per element into f32 (`ScaledRows::at` = code * scale, one rounding) and + * then multiplies. Folding into the staged f16 costs one f16 rounding per weight -- half an ulp, + * 2.4e-4 relative, on a code whose own quantum is 2^-4 = 6.3e-2, a factor of 250. It buys the whole + * structure: the tile stays f16, the dot loop is untouched, the accumulators do not double, and the + * register file, which is the tightest thing in the prefill arm at 237 VGPRs, does not move. The + * alternative -- a per-block partial summed separately and scaled -- needs 64 more accumulators and + * spills. The number the board prints is this fold's. */ +__device__ __forceinline__ uint32_t scale_pair(uint32_t w, float sc) +{ +#if defined(__HIP_DEVICE_COMPILE__) + /* One f16 multiply, hardware, round-to-nearest. + * + * It is NOT f16x2_pack of an f32 product: that builtin is v_cvt_pkrtz_f16_f32, rounds toward + * zero, and r3d_codecs.h says out loud to call it only with values f16 already represents + * exactly. A folded weight is not one of those -- code 431 times a scale of 4.5e-5 is a product + * with eleven significant bits -- so the packer truncates, and truncation is a bias: every + * product moves toward zero, and it shows as rel_l2 2.8e-04 (half an f16 ulp, the + * whole of it) with the subnormal end flushed to zero on top. F16 arithmetic is one v_mul_f16 + * an element and rounds the way the reference's f32 multiply rounds. + */ + const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16); + const _Float16 a = __builtin_bit_cast(_Float16, lo16); + const _Float16 b = __builtin_bit_cast(_Float16, hi16); + const _Float16 s = (_Float16)sc; /* f32 -> f16, round to nearest even */ + const _Float16 rl = a * s, rh = b * s; /* v_mul_f16: one rounding, subnormals kept */ + return (uint32_t)__builtin_bit_cast(uint16_t, rl) | + ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16); +#else + return (uint32_t)f32_to_f16(f16_to_f32((uint16_t)(w & 0xffffu)) * sc) | + ((uint32_t)f32_to_f16(f16_to_f32((uint16_t)(w >> 16)) * sc) << 16); +#endif +} + +/* The head's 16-byte load, ordinary or streamed-once. */ +template +__device__ __forceinline__ uint4 loadw8(const uint16_t* p) +{ +#if R3D_HAS_NT + if (NT) { + /* The builtin wants a native vector, not HIP's class: four unsigned ints, bit-cast. */ + typedef unsigned int v4u __attribute__((ext_vector_type(4))); + const v4u t = __builtin_nontemporal_load((const v4u*)p); + uint4 r; + __builtin_memcpy(&r, &t, 16); + return r; + } +#else + (void)NT; +#endif + return *(const uint4*)p; +} + +/* Eight codes, the quantised head's 8-byte load, ordinary or streamed-once: the same builtin + * requirement as the 16-byte one, a native vector. Half the bytes of the bf16 head is the whole + * point of the form, and it is the load that changes. */ +template +__device__ __forceinline__ uint2 loadc8(const uint8_t* p) +{ +#if R3D_HAS_NT + if (NT) { + typedef unsigned int v2u __attribute__((ext_vector_type(2))); + const v2u t = __builtin_nontemporal_load((const v2u*)p); + uint2 r; + __builtin_memcpy(&r, &t, 8); + return r; + } +#else + (void)NT; +#endif + return *(const uint2*)p; +} + +/* ============================================================ the prefill arm, M > 16 + * + * y is f32 for logits_gemm and bf16 for gemm_nt; `YF32` is that choice, and it is the only one. + */ +template +__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) +gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, HeadQ h, + void* __restrict__ y, int M, int N, int K, int a_ld, int y_ld) +{ + (void)b; /* the plain head; WQ reads the container through h */ + __shared__ __align__(16) uint16_t sA[kTM * kKC]; /* f16, TM rows x KC, swizzled */ + __shared__ __align__(16) uint16_t sB[kTN * kKC]; /* f16, TN rows x KC, swizzled */ + + const int tid = (int)threadIdx.x; + __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; /* the E4M3 decoder, 512 bytes */ +#ifndef R3D_NO_E4M3_TBL + if (WQ) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* fills, then the barrier it holds */ + const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr; +#else + (void)sTbl; /* the board's A/B: the codec, unbuilt */ + const uint16_t* const r3d_tbl = (const uint16_t*)nullptr; +#endif + const int m0 = (int)blockIdx.y * kTM; + const int n0 = (int)blockIdx.x * kTN; + const int rg = tid >> 4, cg = tid & 15; /* this lane's 8x8 square */ + + float acc[8][8]; +#pragma unroll + for (int i = 0; i < 8; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) acc[i][j] = 0.0f; + + const int m_r = m0 + rg * 8, n_c = n0 + cg * 8; + + for (int k0 = 0; k0 < K; k0 += kKC) { + /* Stage 128 rows x 4 chunks of eight a side: one uint4 a thread a side, two a side. Rows + * past M and codes past K stage as zeros, which is the clamping a ragged tail needs, keeps + * the loads straight-line and contributes nothing to a sum. */ +#pragma unroll + for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) { + const int mm = j / (kKC / 8), c8 = j % (kKC / 8); + const int m = m0 + mm, k = k0 + c8 * 8; + uint4 w = make_uint4(0, 0, 0, 0); + if (m < M && k < K) w = *(const uint4*)(a + (long long)m * a_ld + k); + *(uint4*)&sA[srow(mm, c8, kKC)] = widen8(w); + } +#pragma unroll + for (int j = tid; j < kTN * (kKC / 8); j += kBlockThreads) { + const int nn = j / (kKC / 8), c8 = j % (kKC / 8); + const int n = n0 + nn, k = k0 + c8 * 8; + uint4 staged = make_uint4(0, 0, 0, 0); + if (n < N && k < K) { + if (WQ) { + /* Eight codes, one scale: a group of 8 sits inside one 128-column block, so + * the whole staged run shares the scale, and the tile's 32-code chunk sits + * inside one block too (128 % 32 == 0). The scale indexes the tile's row, not + * the lane's: the plane is (n-block, k-block), and this row is n. */ + const uint2 c = *(const uint2*)(h.codes + (long long)n * h.code_row + k); + uint32_t w[4]; + codes8_to_f16x4(c, h.cdt, r3d_tbl, w); + const float sc = scale_at(h, n, k); + staged = make_uint4(scale_pair(w[0], sc), scale_pair(w[1], sc), + scale_pair(w[2], sc), scale_pair(w[3], sc)); + } else { + staged = widen8(*(const uint4*)(b + (long long)n * K + k)); + } + } + *(uint4*)&sB[srow(nn, c8, kKC)] = staged; + } + __syncthreads(); + +#pragma unroll + for (int kc = 0; kc < kKC; kc += 2) { + uint32_t af[8], bf[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) + af[i] = *(const uint32_t*)&sA[srow_pair(rg * 8 + i, kc, kKC)]; +#pragma unroll + for (int j = 0; j < 8; ++j) + bf[j] = *(const uint32_t*)&sB[srow_pair(cg * 8 + j, kc, kKC)]; +#pragma unroll + for (int i = 0; i < 8; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]); + } + __syncthreads(); + } + + /* The store, eight columns at a time: 32 bytes of f32, 16 of bf16. Guarded row by row, so a + * ragged M writes nothing and a ragged N writes whole runs of columns it owns. */ +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int m = m_r + i; + if (m >= M) break; + if (n_c + 8 <= N) { + if (YF32) { + float* row = (float*)y + (long long)m * y_ld; +#pragma unroll + for (int j = 0; j < 8; j += 4) + *(uint4*)(row + n_c + j) = + make_uint4(__float_as_uint(acc[i][j]), __float_as_uint(acc[i][j + 1]), + __float_as_uint(acc[i][j + 2]), __float_as_uint(acc[i][j + 3])); + } else { + uint16_t* row = (uint16_t*)y + (long long)m * y_ld; + uint32_t p[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) + p[j] = (uint32_t)f32_to_bf16(acc[i][2 * j]) | + ((uint32_t)f32_to_bf16(acc[i][2 * j + 1]) << 16); + *(uint4*)(row + n_c) = make_uint4(p[0], p[1], p[2], p[3]); + } + } else { + /* The ragged N tail, unrolled: a dynamic index into acc would put the 64 accumulators + * in local memory, and the compiler says so -- 80 KiB of spill against a 64 KiB limit. */ +#pragma unroll + for (int j = 0; j < 8; ++j) { + if (n_c + j < N) { + if (YF32) ((float*)y)[(long long)m * y_ld + n_c + j] = acc[i][j]; + else ((uint16_t*)y)[(long long)m * y_ld + n_c + j] = f32_to_bf16(acc[i][j]); + } + } + } + } +} + +/* ============================================================ the decode arm, M <= 16 + * + * A wave is MT activation rows by KLW = 32/MT weight rows, one accumulator a lane, the whole of k in + * ascending order. The activation tile is block-wide, so every wave stages it -- a wave whose row is + * past the vocabulary stages too and simply does not read, which is the rule that keeps a tile from + * coming up with holes. + */ +template +__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(4) +logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, HeadQ h, + void* __restrict__ y, int M, int N, int K, int x_ld, int y_ld) +{ + constexpr int KLW = kWave / MT; + constexpr int STEPS = MT * (kChunkK / 8); /* uint4 staging steps a chunk */ + + __shared__ __align__(16) uint16_t sX[MT * kChunkK]; /* f16, MT rows x chunk, swizzled */ + __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; +#ifndef R3D_NO_E4M3_TBL + if (WQ) r3d_e4m3_f16_init(sTbl, (int)threadIdx.x, kBlockThreads); + const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr; +#else + (void)sTbl; + const uint16_t* const r3d_tbl = (const uint16_t*)nullptr; +#endif + + const int lane = (int)threadIdx.x & (kWave - 1); + const int warp = (int)threadIdx.x / kWave; + const int m = lane & (MT - 1); + const int n = (int)blockIdx.x * (kWaves * KLW) + warp * KLW + lane / MT; + const bool live = n < N; + + /* A dead lane reads row N-1, a row that exists: the loads stay uniform and nothing is read out + * of bounds; its result is dropped at the store. */ + const uint16_t* wrow = w + (long long)(live ? n : N - 1) * K; + const int nsteps = M < MT ? M : MT; + float acc = 0.0f; + + for (int k0 = 0; k0 < K; k0 += kChunkK) { + for (int j = (int)threadIdx.x; j < STEPS; j += kBlockThreads) { + const int r = j / (kChunkK / 8), c8 = j % (kChunkK / 8); + const int k = k0 + c8 * 8; + uint4 v = make_uint4(0, 0, 0, 0); + if (r < nsteps && k < K) v = *(const uint4*)(x + (long long)r * x_ld + k); + *(uint4*)&sX[srow(r, c8, kChunkK)] = widen8(v); + } + __syncthreads(); + + if (live) { + const uint16_t* wp = wrow + k0; + const uint8_t* cp = h.codes + (long long)(live ? n : N - 1) * h.code_row + k0; + /* One scale a chunk: kChunkK is the scale block, so the lane's 128 codes are inside a + * single (n-block, k-block) and the load is one scalar per 128 codes. */ + const float sc = WQ ? scale_at(h, live ? n : N - 1, k0) : 0.0f; + const int kend = K - k0 < kChunkK ? K - k0 : kChunkK; /* a multiple of 8: the + * launcher takes K % 8 == 0 */ + for (int kc = 0; kc < kend; kc += 8) { + uint32_t w0, w1, w2, w3; + if (WQ) { + uint32_t q[4]; + codes8_to_f16x4(loadc8(cp + kc), h.cdt, r3d_tbl, q); + w0 = scale_pair(q[0], sc); w1 = scale_pair(q[1], sc); + w2 = scale_pair(q[2], sc); w3 = scale_pair(q[3], sc); + } else { + const uint4 wv = loadw8(wp + kc); + w0 = bf16x2_to_f16x2(wv.x); w1 = bf16x2_to_f16x2(wv.y); + w2 = bf16x2_to_f16x2(wv.z); w3 = bf16x2_to_f16x2(wv.w); + } + const int s = srow_pair(m, kc, kChunkK); + acc = dot2_f16x2(*(const uint32_t*)&sX[s], w0, acc); + acc = dot2_f16x2(*(const uint32_t*)&sX[s + 2], w1, acc); + acc = dot2_f16x2(*(const uint32_t*)&sX[s + 4], w2, acc); + acc = dot2_f16x2(*(const uint32_t*)&sX[s + 6], w3, acc); + } + } + __syncthreads(); + } + + if (live && m < M) { + if (YF32) ((float*)y)[(long long)m * y_ld + n] = acc; + else ((uint16_t*)y)[(long long)m * y_ld + n] = f32_to_bf16(acc); + } +} + +/* ------------------------------------------------------------------ the shared launcher + * + * Returns 0, -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 the HIP + * launch failed, -5 an address it cannot read at 16 bytes. + */ +template +int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ld, int sk, int kb, + int nt, long stream, const HeadQ* hq = nullptr) +{ + if (!xv || !wv || !yv) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (sk > 1) return -2; /* the grid is vocab-wide at every M, see header */ + if (kb == 0) kb = kKC; + if (kb != kKC) return -2; /* 32 is the tile's k-chunk and the only one */ + if (nt < 0 || nt > 1) return -2; + if (K % kKC) return -2; /* the tile's chunk; 2048 at the band */ + if (K % 8) return -3; /* 16-byte weight loads */ + if (!x_ld) x_ld = K; + if (!y_ld) y_ld = N; + if (x_ld % 8) return -3; /* 16-byte activation loads (bf16) */ + if (y_ld % (YF32 ? 4 : 8)) return -3; /* 16-byte store runs (f32: 4, bf16: 8) */ + if (x_ld < K || y_ld < N) return -3; + if ((xv & 15) || (wv & 15) || (yv & 15)) return -5; + + const uint16_t* x = (const uint16_t*)(uintptr_t)xv; + const uint16_t* w = (const uint16_t*)(uintptr_t)wv; + void* y = (void*)(uintptr_t)yv; + hipStream_t s = (hipStream_t)(uintptr_t)stream; + + /* The head's form is the shim's answer, resolved out of the container before the launch; this + * is where its pointers are checked as pointers. The declared entries pass null and get the + * plain bf16 head, which is what r3d.h's signature for them describes. */ + HeadQ h; + std::memset(&h, 0, sizeof h); + const int wq = hq != nullptr; + if (hq) { + h = *hq; + if (!h.codes || !h.scale) return -1; + if (h.sdt < 0 || h.sdt > 2 || h.cdt < 0 || h.cdt > 1) return -2; + if (h.code_row & 7) return -3; /* 8-byte code loads, one row a stride */ + if (h.scale_row & (h.sdt == 2 ? 3 : 1)) + return -3; /* a scale row is 4 bytes a column for f32, 2 for + * bf16/f16: a plane of 3 columns is 6 bytes and the + * loads land on even addresses. K = 320 is legal. */ + if (((long long)(uintptr_t)h.codes & 7) || ((long long)(uintptr_t)h.scale & 3)) return -5; + } + + if (M <= kSkinnyMax) { +#define R3D_SKINNY(MTV, NTV, WQV) \ + do { \ + const int klw = kWave / (MTV); \ + const int per = kWaves * klw; \ + const dim3 grid((unsigned)((N + per - 1) / per)), block(kBlockThreads); \ + R3D_KLAUNCH(R3D_KNAME((logits_skinny_kernel)), grid, block, s, x, w, \ + h, y, M, N, K, x_ld, y_ld); \ + } while (0) +#define R3D_SKINNY_MT(MTV) \ + do { \ + if (wq) { if (nt) R3D_SKINNY(MTV, 1, 1); else R3D_SKINNY(MTV, 0, 1); } \ + else { if (nt) R3D_SKINNY(MTV, 1, 0); else R3D_SKINNY(MTV, 0, 0); } \ + } while (0) + if (M == 1) R3D_SKINNY_MT(1); + else if (M <= 2) R3D_SKINNY_MT(2); + else if (M <= 4) R3D_SKINNY_MT(4); + else if (M <= 8) R3D_SKINNY_MT(8); + else R3D_SKINNY_MT(16); +#undef R3D_SKINNY_MT +#undef R3D_SKINNY + } else { + const dim3 grid((unsigned)((N + kTN - 1) / kTN), (unsigned)((M + kTM - 1) / kTM)); + const dim3 block(kBlockThreads); + if (wq) + R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel)), grid, block, s, x, w, h, y, M, + N, K, x_ld, y_ld); + else + R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel)), grid, block, s, x, w, h, y, M, + N, K, x_ld, y_ld); + } + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The shim's shared body: the checks the two ops agree on, then the launch. `y_is_f32` is the op's + * schema (logits are f32 because every sampler stage reads f32; gemm_nt's y is bf16), nkey/kkey the + * axis names libref spells them with ("n_vocab"/"n_embd" and "N"/"K" -- ref_logits_gemm is + * gemm_nt_impl with the axes renamed, so this body is shared by construction, not by imitation). */ +int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, const char* kkey) +{ + if (a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) + return R3D_NO(RAD_E_INVAL); + const RadTensor* x = &a->t[0]; + const RadTensor* w = &a->t[1]; + const RadTensor* y = &a->t[2]; + + const RadPlanesEntry* ce = nullptr; + const RadPlanesEntry* se = nullptr; + HeadQ h; + std::memset(&h, 0, sizeof h); + int joined = 0; + + /* ---- the head's stored form --------------------------------------------------------------- + * The band's `dtype` key is the ACTIVATION's dtype: on this graph `dtype=bf16` with the head + * stored as E4M3 codes and a bf16 scale per 128x128 block, in two planes of one container. The + * stored form is answered by a layout hook -- `ref_layout_head`, transcribed below as + * r3d_layout_logits_head, the way the w2a8 hook transcribed ref_layout_gemm_q -- and this is + * its launch-side twin: read the header, read the two planes, dispatch on what they are. The + * checks and their order are the reference's `scaled_rows`: the roles, then the dtypes and + * blocks, then the coverage (which needs N and K, so it sits below, where the reference has + * them already). + * + * The bf16 head is served as is: the container's header, not the row's preference, picks + * the form. Two forms, one row, chosen by the bytes. + */ + const RadPlanesHeader* ph = rad_planes_header(r3d_p(w)); + if (ph) { + if (!y_is_f32) return R3D_NO(RAD_E_DTYPE); /* logits are f32; the bf16-y row keeps a bf16 head */ + if (rad_planes_find(r3d_p(w), "zero", nullptr)) + return R3D_NO(RAD_E_DTYPE); /* codes+scale+zero is gemm_nt_q's asymmetric grid: w2a8 */ + if (ph->n_planes != 2) return R3D_NO(RAD_E_DTYPE); + const uint8_t* cb = (const uint8_t*)rad_planes_find(r3d_p(w), "codes", &ce); + const uint8_t* sb = (const uint8_t*)rad_planes_find(r3d_p(w), "scale", &se); + if (!cb || !sb || !ce || !se) + return R3D_NO(RAD_E_DTYPE); /* a joined head that is not codes + one scale */ + if (ce->kind != RAD_PLANE_TILED || ce->block[0] != 1 || ce->block[1] != 1) + return R3D_NO(RAD_E_DTYPE); /* codes must be one code an element, tiled plain */ + if (ce->dtype != RAD_F8E4M3 && ce->dtype != RAD_I8) { + if (rad_dtype_bytes(ce->dtype, 8) < 8) + return R3D_NO(RAD_E_DTYPE); /* sub-byte codes: w4a16's ground, not this form */ + return R3D_NO(RAD_E_DTYPE); /* e5m2 and the rest: no decoder here */ + } + if (se->kind != RAD_PLANE_TILED) return R3D_NO(RAD_E_DTYPE); + if (se->dtype == RAD_BF16) h.sdt = 0; + else if (se->dtype == RAD_F16) h.sdt = 1; + else if (se->dtype == RAD_F32) h.sdt = 2; + else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not a float_scale_dt */ + if (se->block[0] != kFp8Block || se->block[1] != kFp8Block) + return R3D_NO(RAD_E_SHAPE); /* per-(row,group) scales are gemm_nt_q's grid; per-row + * is not the indexing this kernel does */ + h.codes = cb; h.scale = sb; h.code_row = ce->row_bytes; h.scale_row = se->row_bytes; + h.cdt = ce->dtype == RAD_I8 ? 1 : 0; + joined = 1; + } else if (w->dtype != RAD_BF16) { + return R3D_NO(RAD_E_DTYPE); + } + if (x->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (y->dtype != (y_is_f32 ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16)) return R3D_NO(RAD_E_DTYPE); + + long long N = r3d_geti_or(a, nkey, 0); + long long K = r3d_geti_or(a, kkey, 0); + if (N <= 0) N = r3d_dim(w, 0); + if (K <= 0) K = r3d_dim(w, 1); + if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE); + + long long M = 0, x_rows = 0; + const long long y_pitch = r3d_rows_pitch(y, N, &M); /* M = numel(y)/N, the reference's fold */ + if (y_pitch < N || M <= 0) return R3D_NO(RAD_E_STRIDE); + const long long x_pitch = r3d_rows_pitch(x, K, &x_rows); + if (x_pitch < K || x_rows < M) return R3D_NO(RAD_E_STRIDE); + if (r3d_numel(w) < N * K) return R3D_NO(RAD_E_SHAPE); + if (!r3d_contig(w)) return R3D_NO(RAD_E_STRIDE); /* N rows of K contiguous codes */ + if (joined) { + /* The coverage checks, `scaled_rows`' last block: the planes must cover the band, and the + * scale plane covers it by blocks -- ceil, so a ragged vocabulary is fine (131 rows need 2 + * scale rows) and a plane one row short is not. */ + const long long sb_r = (N + kFp8Block - 1) / kFp8Block; + const long long sb_c = (K + kFp8Block - 1) / kFp8Block; + if (ce->rows != N || ce->cols != K) return R3D_NO(RAD_E_SHAPE); + if (se->rows != sb_r || se->cols != sb_c) return R3D_NO(RAD_E_SHAPE); + if (ce->row_bytes < ce->cols || se->row_bytes < se->cols * (h.sdt == 2 ? 4 : 2)) + return R3D_NO(RAD_E_STRIDE); + } + if (M > (long long)1 << 24 || N > (long long)1 << 28 || K > (long long)1 << 28) + return R3D_NO(RAD_E_SHAPE); + if (!r3d_aligned(r3d_p(x), 16) || !r3d_aligned(r3d_p(w), 16) || !r3d_aligned(r3d_p(y), 16)) + return R3D_NO(RAD_E_ALIGN); + + const int sk = (int)r3d_geti_or(a, "sk", 1); + if (sk > 1) return R3D_NO(RAD_E_SHAPE); /* the grid is vocab-wide at every M, see the header */ + const int kb = (int)r3d_geti_or(a, "kb", 0); + const int nt = (int)r3d_geti_or(a, "nt", 0); + + const HeadQ* hp = joined ? &h : nullptr; + const int e = y_is_f32 + ? gemm_launch(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K, + (int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp) + : gemm_launch(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K, + (int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE + : e == -3 ? RAD_E_STRIDE : e == -5 ? RAD_E_ALIGN : RAD_E_DEVICE); +} + +/* The reference's `enc_scaled_rows` and `float_scale_dt`, inlined: libref keeps them static inline in + * its own header, so a plugin that transcribes ref_layout_head transcribes them with it. Checks and + * order are its, unchanged: affine, untransformed, two planes, the roles in order, codes tiled with + * block {1,1} and a code dtype it admits, the scale tiled with a float dtype. */ +bool float_scale_dt(uint32_t dt) +{ + return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; +} + +bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n) +{ + if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return false; + if (n != 2 || !sel) return false; /* sel_roles(enc, sel, n, "codes", "scale") */ + const char* want[2] = { "codes", "scale" }; + for (int i = 0; i < 2; ++i) { + if (sel[i] < 0 || sel[i] >= enc->n_planes) return false; + if (std::strncmp(enc->plane[sel[i]].role, want[i], RAD_ENC_STR) != 0) return false; + } + const RadEncPlane& c = enc->plane[sel[0]]; + const RadEncPlane& sc = enc->plane[sel[1]]; + return c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 && + (c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && sc.kind == RAD_PLANE_TILED && + float_scale_dt(sc.dtype); +} + +} // namespace + +/* logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T, the declared entry (r3d.h's + * r3d_vocab_bf16.hip section). M <= 16 takes the decode arm, above it the prefill tile. */ +extern "C" int r3d_logits_gemm_bf16(long x, long lm, long y, int M, int n_vocab, int n_embd, + int x_ld, int y_ld, int sk, int nt, long scratch, long stream) +{ + (void)scratch; /* no split, so no partials: see the header */ + return gemm_launch(x, lm, y, M, n_vocab, n_embd, x_ld, y_ld, sk, kKC, nt, stream); +} + +/* The same tiling with a bf16 y, for gemm_nt at prefill sizes (M >= 17; M <= 16 is the m16 row). */ +extern "C" int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int K, int a_ld, + int y_ld, int sk, int kb, int nt, long scratch, long stream) +{ + (void)scratch; + return gemm_launch(a, b, y, M, N, K, a_ld, y_ld, sk, kb, nt, stream); +} + +extern "C" int r3d_rad_logits_gemm_bf16(const RadArgs* a, RadStream s) +{ + return rad_gemm_run(a, s, 1, "n_vocab", "n_embd"); +} + +extern "C" int r3d_rad_gemm_nt_bf16_tiled(const RadArgs* a, RadStream s) +{ + return rad_gemm_run(a, s, 0, "N", "K"); +} + +/* The head's layout hook, `ref::ref_layout_head` transcribed: operand 1 of + * logits_gemm, two planes, codes and one scale, untransformed -- and the answer is the container's + * own form. It moves no byte, and its `relayout` writer (below) exists for the round-trip: this is + * a reader, which is what + * the mapped tier asks for when a weight's stored form is not the container's. Operand 0 (the + * activations) and a one-plane selection are declined as `layout_scaled` declines them, and so is + * every other encoding: a silent no-op on a head is the worst failure a row can have. */ +/* The head's WRITER. A layout query that answers RAD_OK is a promise the ABI makes to the loader -- + * "out describes the stored form, and relayout will produce it" (rad_abi.h) -- and the load step + * holds the row to it. The container stores the quantiser's pair; the plan wants one operand; the + * row that owns the band assembles it, losslessly, with rad_planes_relayout: the header, the + * entries and each plane's rows, copied. + * No code is transformed and no number is derived -- a kernel doing arithmetic + * here would make the served numbers depend on which library loaded the container (rad_abi.h). + * The query and the writer share the plan through rad_planes_plan, so they cannot disagree. The + * operand guard is the hook's own rule repeated: a call routed to the wrong slot writes nothing. */ +extern "C" int r3d_relayout_logits_head(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n_planes, void* dst, + int64_t dst_bytes) +{ + (void)p; (void)n_p; + if (operand != 1) return R3D_NO(RAD_E_UNSUPPORTED); + return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes); +} + +extern "C" int r3d_layout_logits_head(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n, RadLayout* out) +{ + (void)p; (void)n_p; /* layout_scaled ignores both */ + if (n < 2 || operand != 1) return RAD_E_UNSUPPORTED; /* layout_scaled(operand, 1, -1, ...) */ + if (!enc_scaled_rows(enc, sel, n)) return RAD_E_DTYPE; + return rad_planes_layout(enc, sel, planes, n, out); +} diff --git a/tests/oot_plugins.sh b/tests/oot_plugins.sh index 77b47781..6e991c70 100644 --- a/tests/oot_plugins.sh +++ b/tests/oot_plugins.sh @@ -55,9 +55,11 @@ for d in "$S"/arch/*/ "$S"/plugin/*/; do [ -f "$d/CMakeLists.txt" ] && dirs="$dirs $(basename "$(dirname "$d")")/$(basename "$d")" done # The device libraries: built out of tree only with the tree's HIP compiler, and left out of every -# comparison below without it. +# comparison below without it. Each declares the family it serves, so a tree built for one family +# produces one of them: libr3d returns without a target when RAD_GPU_TARGETS holds no gfx11, and the +# checks below compare the two builds of the same list, not a fixed list. devlibs="" -for d in libr4d; do +for d in libr4d libr3d; do [ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && devlibs="$devlibs $d" done [ -n "$HIPC" ] && dirs="$dirs $devlibs"