Archived
radiance 1.14.0
New models and formats: - libr3d: a kernel library for RDNA3 (gfx11) cards - nomic-embed-text-v2-moe (the nomicbert plugin) - Gemma 4 E2B with its per-layer MLP width, and Google's unmodified E2B/E4B directories in bf16 - DeepSeek-V4.1-Flash converted straight from its release: the Engram tables, the fused imatrix and rad-convert --chat-template for a release that ships no template - GGUF Q8_0, Q4_K and Q6_K tensors import as their planes; rad-convert writes them without a recipe - Qwen3.8-Flash-Next-FP8 converts and serves through qwen4exp_fp8 Speed: - hc_read's decode kernels as one grid (34.7 -> 25.2 us at 4 rows) and its tiled up-mix pipelined - gemm_fp8a8: the narrow form's scales staged through LDS (Flash-Next int8 at 32 rows 83.6 -> 68.3 us), the gated three-tile form at 8 waves (gate_up at 48 rows 272.9 -> 180.6 us) - Qwen3.8-27B: the delta net's out-projection read beside its decode recurrent update (x1 19.40 -> 19.10 ms a step), and the verify's split-KV attention sized by context depth (x3 at 180K 42.4 -> 40.3 ms a step) - Hy-Memory (HYV3) decode: fused QK norm, RoPE and KV store, residual adds folded into the norms, coalesced one-token expert GEMMs - spechub: the coupled verify walks the live candidates only (151 -> 31 us a launch) Speculation: - DFlash2: lossless coupled acceptance at T > 0 (--draft-coupling on) - A block drafter's proposals verified as a tree, on by default for the Gemma 4 31B's DFlash2, with a block-16 tree that runs its short block under load Features: - Decode-hot residency: --draft-expert-placement host, --expert-profile, --expert-pin-top, and --expert-stats FILE for the routed experts each layer selects - --ngram-placement ram=DIR: one n-gram table shared by engines on separate cards - Prefix cache: --prefix-resume exact (default) resumes a hit on the cold run's own chunk grid, so it answers bit-identically; snapshots at a head other prompts share, from 528-token prompts, and for tip-only one drafter window below the tip; hits on models whose KV groups have different block sizes; the snapshot store keeps a floor of 8 ahead of --host-headroom-mib - Typed tool-call argument tags; rad-chatparse --request renders and reads back one request as the server does - MiniMax-H3: keyframes ride a latent upscale - Gemma 3's fused all-reduce junction on the lossy wire Fixes: - A speculative step shorter than its band (an MTP step of 4 rows at gqa 8) no longer stops the engine with a scratch refusal at issue (#293) - --p2p off: prefill back to 1.12.0's rate; 1.13.0's push check read a host-memory slot over the link twice (#323) - A chat template that cannot render a conversation is refused at load, not mid-request - imatrix entries found under llama.cpp's spelling; the W4A8 prefill's tail scale read; the GDN conv kernels on an f32 weight; dense integer rows at the group they compute (a Q8_0 weight at group 32) - --expert-profile refuses a profile recorded on another model - hc_read's one-grid wait traps past its deadline instead of reading a stale value Changes: Plugin ABI 31, unchanged. RADIANCE_DRAFT_TREE, DFLASH2_TREE_NODES, DFLASH2_TREE_TEMP and DFLASH_Q_TEMP are gone (trees run where the probe says they pay; temperatures 1.25 / 0.6).
This commit is contained in:
1 parent
481fcd5df0
commit
4a61d7296b
160 files changed
+8790
-6819
No files matched your search
+35
-45
@@ -1,14 +1,12 @@
|
||||
# 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 WMMA fragment layouts (RDNA3's 16x16x16 wave-matrix family is
|
||||
# a re-tile of the dot2 lane map, not a drop-in) or gfx12-only instructions such as
|
||||
# global_load_tr_b128, and they decode every quantised weight in software: the lane map, not a
|
||||
# missing instruction, is the reason.
|
||||
# libr3d serves RDNA3 only; this file is the one place that says so. Its kernels rely on wave32 and
|
||||
# on RDNA3 instructions: v_dot2acc_f32_f16 for the matrix work, v_cvt_pkrtz_f16_f32, DPP16 and
|
||||
# v_permlanex16. They do not use the WMMA fragment layouts (RDNA3's 16x16x16 wave-matrix family
|
||||
# needs a different lane map than dot2) or gfx12-only instructions such as global_load_tr_b128,
|
||||
# and they decode every quantised weight in software because of that lane map.
|
||||
#
|
||||
# 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.
|
||||
# A build targeting other cards skips libr3d. Without a device kernel library the engine refuses ops
|
||||
# only a reference library implements, unless --debug-accept-reference-kernels is passed (spec §17).
|
||||
# libr4d is the kernel library for gfx12, libr3d for gfx11.
|
||||
#
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S libr3d -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`, naming the HIP compiler as for
|
||||
@@ -20,11 +18,11 @@ if(NOT COMMAND rad_add_plugin)
|
||||
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).
|
||||
# `^gfx11` matches the family: gfx1100, gfx1101, gfx1102, gfx1103, gfx1150, gfx1151 and
|
||||
# `gfx11-generic`, as `^gfx12` does for libr4d. The RDNA3 chips differ in CU count and clock, not in
|
||||
# the instructions these kernels issue, so one code object per family serves them all. A build
|
||||
# listing both a chip and the family gets both, and the engine prefers the chip's object
|
||||
# (docs/PLUGIN.md §10).
|
||||
rad_plugin_gpu_targets(R3D_GPU_TARGETS "^gfx11")
|
||||
if(NOT R3D_GPU_TARGETS)
|
||||
message(STATUS
|
||||
@@ -32,16 +30,15 @@ if(NOT R3D_GPU_TARGETS)
|
||||
return()
|
||||
endif()
|
||||
|
||||
# R3D_UNITS is the definitive list of libr3d's device translation units, as "unit|extra flags".
|
||||
# R3D_UNITS lists 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.
|
||||
# Every unit is compiled -ffp-contract=off (rad_hipify sets it on all HIP sources). libref
|
||||
# accumulates in f32 with no FMA and no reassociation (ref_common.h), and a contracted kernel would
|
||||
# disagree with that oracle. 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.
|
||||
# Kernels and the declaration (row table, operand descriptions) share one directory. Every entry
|
||||
# point takes `(const RadArgs*, RadStream)` and sits beside its kernel. The plugin links rad_abi
|
||||
# only, like an out-of-tree plugin.
|
||||
|
||||
set(R3D_UNITS
|
||||
# The model's small ops, one workgroup per row: rmsnorm, layernorm, the binary and unary element
|
||||
@@ -49,19 +46,19 @@ set(R3D_UNITS
|
||||
# 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.
|
||||
# summary, which reads the logits plane once (the reference reads it three times).
|
||||
"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.
|
||||
# The gated MLP band: GEMM, gate and output quantiser in one launch, so the [M,N] intermediate
|
||||
# is never written to memory.
|
||||
"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.
|
||||
# The quantised GEMM at prefill heights.
|
||||
"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.
|
||||
@@ -77,18 +74,14 @@ set(R3D_UNITS
|
||||
# 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.
|
||||
# The skinny bf16 GEMM for decode, M <= 16: one output element a lane, k ascending, so the
|
||||
# accumulation order is libref's.
|
||||
"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.
|
||||
# A row in r3d_rows.cpp must name an entry point defined by one of these units: an undefined
|
||||
# symbol makes the whole plugin fail to load.
|
||||
)
|
||||
|
||||
set(R3D_SRC "")
|
||||
@@ -110,12 +103,11 @@ foreach(u ${R3D_UNITS})
|
||||
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.
|
||||
# The host sources are declaration only: the row table and the operand descriptions. They are pure
|
||||
# host C++ that includes neither r3d.h nor hip_runtime.h, so the 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). There is no fusion source because
|
||||
# no fused row exists.
|
||||
set(R3D_DECLARATION r3d_rows.cpp r3d_shapes.cpp)
|
||||
|
||||
rad_add_plugin(libr3d kernels
|
||||
@@ -137,14 +129,12 @@ 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.
|
||||
# The selftest's device phase (the per-row launch) needs the HIP runtime, which this build has.
|
||||
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 <home>/kernels/libr3d.so [--case <row>]
|
||||
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.
|
||||
# C++17, the standard all radiance plugins build device code with.
|
||||
set_target_properties(libr3d PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON)
|
||||
+693
-1028
File diff suppressed because it is too large.
Load diff
+109
-145
@@ -1,23 +1,22 @@
|
||||
/* r3d.h -- the entry points libr3d exports, and the launchers behind them.
|
||||
*
|
||||
* Two layers, in every unit, as in libr4d:
|
||||
* Every unit has two layers, as in libr4d:
|
||||
*
|
||||
* The launcher (`r3d_<op>(...)`, 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.
|
||||
* stream as a long. It 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 given stream. It returns 0 or a negative 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_<op>(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.
|
||||
* the row table names. It reads the operands with r3d_args.h, takes the dtype from the tensor
|
||||
* (not the `dtype` parameter) and the row count from the operand (not `M`, which is the band's
|
||||
* upper bound), checks strides, translates 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.
|
||||
* A launcher is defined beside its kernel, in the same translation unit as the shim that calls
|
||||
* it, so one unit shows 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
|
||||
@@ -37,22 +36,22 @@ extern "C" {
|
||||
*/
|
||||
|
||||
/* 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). */
|
||||
* gain, R3D_DT_N for none (gain 1; the shim then refuses wadd, 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. */
|
||||
/* The same at f32 activations, for an f32 checkpoint's residual stream; 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). */
|
||||
/* y = (x - mean) / sqrt(var + eps) * w + b, mean and variance 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). */
|
||||
/* y = a + b and y = a * b. `bcast`: b holds n elements, applied to every row. `div` is the `add`
|
||||
* op's optional divisor, 0 for 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,
|
||||
@@ -62,13 +61,13 @@ int r3d_mul_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y
|
||||
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. */
|
||||
/* y = x, one dtype to another, over M rows of n at the given pitches. The dtypes are R3D_DT_*.
|
||||
* An integer pair is copied directly (ids above 2^24 survive an i64 -> i32 copy); everything else
|
||||
* widens to f32 and narrows once on the store. */
|
||||
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. */
|
||||
/* Unary activations computed in f32 and narrowed once by the store: silu x*sigmoid(x), gelu
|
||||
* 0.5x(1+erf(x/sqrt2)), sigmoid 1/(1+exp(-x)). */
|
||||
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);
|
||||
@@ -80,62 +79,54 @@ int r3d_act_mul_bf16(long gate, long up, long y, int M, int n, int g_ld, int u_l
|
||||
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. */
|
||||
* gate in the first half (rad-convert's fusion order). The activation is not narrowed before the
|
||||
* product; `act_mul`, over two operands, stands for the unfused pair that stores it. `gu_ld` is the
|
||||
* fused row's pitch (>= 2n), `y_ld` the output's; 0 takes each one's dense width. */
|
||||
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 = x * s, where `s` is the op's [1] weight plane in device memory, dtype `s_dt` (R3D_DT_BF16 or
|
||||
* R3D_DT_F32). The kernel reads the scalar, not the launcher, because a launch may not copy device
|
||||
* memory to the host. Every lane loads the same address, 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. */
|
||||
* fill (y = v) takes its value as a parameter, so it is passed 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. */
|
||||
/* In-place rotary on a fused qkv row: q, then k; v is untouched. `mode` is R3D_ROPE_NEOX or
|
||||
* R3D_ROPE_GPTJ; `rot` the rotary width (<= head_dim, even). `scale` divides the position: the
|
||||
* angle of pair i is (pos / scale) * theta^-i, as in ref_rope. YaRN's magnitude (`yarn_factor`) is not
|
||||
* implemented. `pos` is M i32 positions, one per 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. */
|
||||
/* 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 reads off the operand (sb/sh/so/sd). A negative slot is
|
||||
* skipped, and so is one at or past `slot_max` = n_blocks * block_size, computed as
|
||||
* `r3d_shape_kv_store` sizes the cache. The reference refuses such a slot on the host; a launch
|
||||
* cannot refuse a slot it has not read, so the kernel drops it rather than write past the cache.
|
||||
* `kv_dt`: R3D_DT_BF16 stores the values, R3D_DT_U8 encodes E4M3 with the reciprocal of
|
||||
* k_scale / v_scale, R3D_DT_F16 stores 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. */
|
||||
/* x[r] = wte[ids[r] - vocab_offset] * wscale, narrowed once. A row whose id is outside the table
|
||||
* is zeroed, as in libref. */
|
||||
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. */
|
||||
* `src_rows` / `dst_rows` are the plane's own row count, which only the shim knows (from the
|
||||
* operand's numel). The reference refuses an out-of-range index on the host; a launch cannot refuse
|
||||
* an index it has not read, so the kernel enforces the bound: a gather at idx >= src_rows writes
|
||||
* the zero row of libref's padding form, a scatter at idx >= dst_rows drops the row. This keeps
|
||||
* every access inside the plane. 0 means unchecked and is a shim bug, not a caller option. */
|
||||
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,
|
||||
@@ -143,7 +134,7 @@ int r3d_scatter_rows(long v, long idx, long x, int M, int n, int v_ld, int x_ld,
|
||||
|
||||
/* ================================================================== r3d_quant_fp8.hip
|
||||
*
|
||||
* All three quantisers write a plain row-major code plane and one f32 scale per (row, group); no
|
||||
* The quantisers write a plain row-major code plane and one f32 scale per (row, group), with no
|
||||
* fragment permutation, because a dot2 GEMM reads codes in order.
|
||||
*/
|
||||
|
||||
@@ -155,10 +146,9 @@ int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld,
|
||||
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. */
|
||||
/* The same int8 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. The two are not interchangeable. */
|
||||
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);
|
||||
|
||||
@@ -168,14 +158,13 @@ int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group,
|
||||
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. */
|
||||
/* Residual add, RMS norm and E4M3 quantiser in one pass, so the normalised row never goes back to
|
||||
* VRAM. `res` is the residual plane (in/out), 0 when the op has none. 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 the bf16 values the codes were taken over. Pitches are in elements of their own operand,
|
||||
* `s_ld` in scales (dense: n/group). `group` must divide n; this pass has no zero-padded partial
|
||||
* group. */
|
||||
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);
|
||||
@@ -187,7 +176,7 @@ int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s
|
||||
|
||||
/* ================================================================== r3d_gemm_*.hip
|
||||
*
|
||||
* y[M,N] = a[M,K] @ b[N,K]^T. One output element a lane, k ascending, f32 accumulate, the sum
|
||||
* y[M,N] = a[M,K] @ b[N,K]^T. One output element per 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.
|
||||
@@ -200,29 +189,15 @@ int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int K, int a_ld
|
||||
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. */
|
||||
* block, pb1/pb2 the container's block sizes (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). bs_dt is the scale 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
|
||||
@@ -245,9 +220,9 @@ int r3d_attn_prefill_h128(long q, long kv, long bt, long seqused, long k_desc, l
|
||||
/* ================================================================== 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.
|
||||
* dense; `group` is the scale block, 128 on every declared band. The scales arrive as the
|
||||
* container's two planes behind one operand, as the row's layout hook presents them; 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,
|
||||
@@ -257,9 +232,9 @@ int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long b_scale, lo
|
||||
*
|
||||
* 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.
|
||||
* `a` E4M3 with `a_scale` f32 per (row, 128 of K); `y` bf16. b_row/e8_row are row strides in bytes,
|
||||
* 0 meaning dense. No zero point (symmetric scale); 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);
|
||||
@@ -269,13 +244,12 @@ int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale
|
||||
|
||||
/* ================================================================== 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.
|
||||
* The quantised GEMM at dtype=w4a8 and w8a8: symmetric int4 and int8 weight grids at decode
|
||||
* heights. `b` is the signed codes (I4 two per byte, or I8), [N, K]; `b_scale` the f16 scale, one
|
||||
* per (row, 128 of K), [N, K/128]; `a` int8 in step order with `a_scale` f32 per row; `y` bf16.
|
||||
* b_rb and sb_rb are the row strides (bytes / elements), 0 meaning dense. No zero point: the
|
||||
* dequant is code times scale. M <= 16 only; prefill heights are served by the tiled rows, and the
|
||||
* 8-bit grid at prefill heights is declared outside 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);
|
||||
@@ -287,37 +261,27 @@ int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale, long y, i
|
||||
* 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. */
|
||||
/* logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T: a decode arm for M <= 16 and a
|
||||
* prefill arm above, 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 shapes and the `params` plane are libref's: one `RadSampleParams` per row, 96 bytes of f32
|
||||
* words, read 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), as the reference
|
||||
* writes them.
|
||||
*
|
||||
* 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.
|
||||
* The full-vocabulary stages (argmax, temp, topk, logprobs, penalties, dry, ngram_ban) run one
|
||||
* block per row and are bandwidth-bound: at MiniCPM5-2B's band, 2048 rows of 130560 f32, the logits
|
||||
* are 1.02 GiB. The candidate-set stages (the four narrowings and pick) run one block per row of
|
||||
* `n_cand` and are arithmetic-bound. `pick` keeps the reference's `(float)std::exp((double)x)`,
|
||||
* because a hardware `v_exp_f32` two ulp away moves a draw whenever a 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.
|
||||
* M comes from the operand, never from the band, whose `M` is only an upper bound.
|
||||
*/
|
||||
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,
|
||||
@@ -330,9 +294,9 @@ int r3d_sample_topk(long lg, long params, long ci, long cv, long pairs, int M, i
|
||||
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. */
|
||||
/* The four narrowing stages share one shape and edit `cand_idx` / `cand_val` in place: top-p is a
|
||||
* prefix rule in candidate order, min-p a floor under the best candidate's probability, typical a
|
||||
* band around the set's entropy, XTC the exclude-top-choices 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,
|
||||
@@ -343,9 +307,9 @@ int r3d_sample_xtc(long ci, long cv, long params, int M, int n_cand, long long c
|
||||
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. */
|
||||
* [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`); the descriptor's `fill_chunk` writes the window into the
|
||||
* params plane. `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,
|
||||
@@ -355,26 +319,26 @@ int r3d_sample_ngram_ban(long lg, long params, long hist, long ngram, long white
|
||||
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. */
|
||||
/* The gated MLP GEMM: b is E4M3 codes of N = 2n rows (gate rows [0,n), up rows [n,N)), b_scale one
|
||||
* bf16 scale per (group, group) block, 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` columns: q is the codes [M,n], scale the per-(row, group) amax scales, out_bf16 the
|
||||
* narrowed gated tensor if wanted (y_ld its row pitch, n when 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. */
|
||||
/* The same kernel naming the scale plane's dtype. The entry above passes RAD_BF16, the container's
|
||||
* form for this op; f32 is accepted and gives bit-identical results. */
|
||||
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. */
|
||||
/* DFlash2's greedy walk over the candidate lattice. `hp` may be 0, meaning the plane of ones the
|
||||
* reference uses when the operand is absent. cand, unary and tokens have M * steps rows ordered
|
||||
* (sequence, step); `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,
|
||||
|
||||
+54
-66
@@ -1,14 +1,12 @@
|
||||
/* 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.
|
||||
* An entry point takes `(const RadArgs*, RadStream)` and returns a status, the RadLaunchFn
|
||||
* contract every plugin implements; there is no adapter layer. This header holds the shared
|
||||
* helpers for reading parameters, finding operands and testing contiguity, mostly one line over
|
||||
* rad_abi.h.
|
||||
*
|
||||
* 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.
|
||||
* Nothing here includes r3d.h or HIP, so host translation units (the row table, the shape hooks)
|
||||
* can include it and compile without ROCm.
|
||||
*/
|
||||
#ifndef R3D_ARGS_H
|
||||
#define R3D_ARGS_H
|
||||
@@ -23,8 +21,7 @@
|
||||
|
||||
/* ================================================================== 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. */
|
||||
* Forwards to rad_abi.h's static inline helpers under libr3d's names. */
|
||||
static inline int r3d_geti(const RadArgs* a, const char* k, long long* out) {
|
||||
return rad_args_geti(a, k, out);
|
||||
}
|
||||
@@ -37,10 +34,10 @@ 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. */
|
||||
/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so the step path
|
||||
* reads `dval` without strtod. Deliberately laxer than rad_args_getf_or: string and integer forms
|
||||
* are accepted 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) {
|
||||
@@ -57,10 +54,9 @@ static inline double r3d_getf(const RadArgs* a, const char* k, double 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. */
|
||||
/* An enumerated parameter: `act` is "silu" or "sigmoid" rather than 0 or 1, so a --debug-graph dump
|
||||
* names what runs. Returns -1 for an unknown name, which callers turn into RAD_E_INVAL. `alt` is an
|
||||
* integer-valued key for the same choice, read only when the named key 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;
|
||||
@@ -84,25 +80,20 @@ static inline const char* r3d_pgets(const RadParam* p, int n_p, const char* k) {
|
||||
|
||||
/* ================================================================== 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.
|
||||
* An absent optional operand has a null RadTensor.data (rad_abi.h). For a required operand the
|
||||
* caller turns null into RAD_E_INVAL: it is an issue bug, 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. */
|
||||
/* Whether an optional operand is present. The engine passes an unbound optional operand as a
|
||||
* descriptor with null `data`, so a bare `if (t)` is wrong: a shim that dtype-checks such a
|
||||
* descriptor refuses a call that never reads it (e.g. an empty `out_bf16` slot of
|
||||
* `rmsnorm_quant_fp8`). Every test of an optional operand goes through here. */
|
||||
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`. */
|
||||
/* The same for an operand a kernel writes. */
|
||||
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; }
|
||||
|
||||
@@ -118,8 +109,8 @@ static inline long long r3d_stride(const RadTensor* t, int 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. */
|
||||
/* [rows..., K] flattened to (M, K). Every per-row kernel owns whole rows (one workgroup per row),
|
||||
* so the leading axes are only a row count. */
|
||||
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];
|
||||
@@ -128,10 +119,9 @@ static inline int r3d_rows_of(const RadTensor* t, long long* M, long long* K) {
|
||||
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. */
|
||||
/* Dense row-major over the whole tensor. Entry points take at most one pitch, so everything else
|
||||
* must be tight, and the shim checks it: per spec §2.1 the constraint table settles geometry while
|
||||
* 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
|
||||
@@ -150,10 +140,10 @@ static inline long long r3d_row_pitch(const RadTensor* t) {
|
||||
/* [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
|
||||
* A column slice is refused. 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. */
|
||||
* apart between tokens; no single pitch describes that, and using the leading stride would read
|
||||
* most heads from the wrong place. 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);
|
||||
@@ -191,10 +181,10 @@ static inline int r3d_aligned(const void* p, unsigned bytes) {
|
||||
|
||||
/* ================================================================== 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. */
|
||||
* A shim refuses in many places with the same few codes, and the engine's report names the kernel
|
||||
* and geometry but not the failing condition. R3D_NO() wraps a refusal and, when RAD_R3D_TRACE is
|
||||
* set to a value other than "0", prints "[r3d] file:line refused -> code" to stderr. The variable
|
||||
* is read once and cached; unset, the cost is one flag load on a refusal path. */
|
||||
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'); }
|
||||
@@ -206,9 +196,10 @@ static inline int r3d_refused(int code, const char* file, int line) {
|
||||
}
|
||||
#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. */
|
||||
/* Under RAD_R3D_TRACE, prints a refused descriptor's dtype, rank, shape, strides and data pointer.
|
||||
* The engine binds shape and strides in elements, and the shape is the step's, not the band's.
|
||||
* R3D_STR refuses with RAD_E_STRIDE and, under the same flag, prints the reason and two named
|
||||
* values. */
|
||||
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; }
|
||||
@@ -229,8 +220,8 @@ static inline void r3d_trace_desc(const char* what, const RadTensor* t) {
|
||||
|
||||
/* ================================================================== 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. */
|
||||
* A row's `dtype` constraint is a necessary condition, not a promise about the tensors, so the
|
||||
* shim tests each operand's dtype with these. */
|
||||
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; }
|
||||
@@ -258,12 +249,12 @@ static inline int r3d_dt_named(uint32_t dt, const char* name) {
|
||||
|
||||
/* ================================================================== libr3d's constants
|
||||
*
|
||||
* Restated here because r3d_rows.cpp and r3d_shapes.cpp are host code built without ROCm and cannot
|
||||
* Defined 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. */
|
||||
/* The activation quantiser's group: the width a scale covers along n. It equals the weight
|
||||
* scale's block width, 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. */
|
||||
@@ -272,23 +263,20 @@ enum {
|
||||
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. */
|
||||
/* The operand count of `gemm_nt_q` (a, a_scale, b, b_scale, y, a_sum, b_ref), used by the shape
|
||||
* hook. The schema in r3d_rows.cpp is authoritative; rad-kbench checks the two agree. */
|
||||
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.
|
||||
* The knobs the row table declares, so `rad-tune` can search them and `--debug-graph` can name the
|
||||
* choice (spec §15). The chosen point is appended to RadArgs::p; these structs read several knobs
|
||||
* 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.
|
||||
* sk == 0 means "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. The GEMM unit resolves the sentinel.
|
||||
*/
|
||||
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 */
|
||||
@@ -297,10 +285,10 @@ struct R3dTopkCfg { int rc, nch; }; /* candidates a chunk keeps, chunk
|
||||
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. */
|
||||
* Read the point the core appended to RadArgs::p, falling back to each axis's default (defined in
|
||||
* the RadTunable table) when none was supplied, so a caller without a 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*);
|
||||
|
||||
+444
-633
File diff suppressed because it is too large.
Load diff
+77
-93
@@ -1,20 +1,18 @@
|
||||
/* r3d_codecs.h -- the numeric codecs, in the one spelling every libr3d unit and the host use.
|
||||
/* r3d_codecs.h -- the numeric codecs, shared by every libr3d unit and the host.
|
||||
*
|
||||
* 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.
|
||||
* 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 a `__global__` cannot reach). libref, the
|
||||
* oracle every libr3d row is checked against at kbench, is built from those, so these must match
|
||||
* bit for bit. r3d_selftest.cpp compares the two over the whole fp8 and bf16 code spaces and 2^20
|
||||
* random f32s, so a one-ulp drift fails there.
|
||||
*
|
||||
* 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.
|
||||
* to-even narrowing, no fused multiply-add, no reassociation, subnormals kept. Widening is exact.
|
||||
* `-ffp-contract=off` is a correctness flag; 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.
|
||||
* R3D_HD is `__host__ __device__` in a HIP translation unit and nothing in a host one, so the same
|
||||
* header serves kernels and r3d_selftest.cpp. Code that uses a GPU instruction sits behind
|
||||
* __HIP_DEVICE_COMPILE__ with a plain-C++ host equivalent.
|
||||
*/
|
||||
#ifndef R3D_CODECS_H
|
||||
#define R3D_CODECS_H
|
||||
@@ -22,12 +20,10 @@
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
/* 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. */
|
||||
/* The HIP runtime comes first, before R3D_HD: `__forceinline__` is a hip_runtime.h macro, and
|
||||
* r3d_common.h includes the codecs before the runtime, so without this it would parse as a type
|
||||
* name. Host translation units (the row table, the operand descriptions, r3d_selftest.cpp) pull in
|
||||
* no ROCm header. */
|
||||
#if defined(__HIPCC__)
|
||||
#include <hip/hip_runtime.h>
|
||||
#endif
|
||||
@@ -38,11 +34,10 @@
|
||||
#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. */
|
||||
/* The bit cast. Device code cannot call `memcpy` (the HIP headers do not declare a
|
||||
* `__host__ __device__` one on every release), so the device path uses the compiler's bit cast.
|
||||
* The host path keeps memcpy, which folds to a move, because GCC has `__builtin_bit_cast` only in
|
||||
* C++20 mode and r3d_selftest.cpp builds at C++17. */
|
||||
R3D_HD uint32_t bits_of(float f) {
|
||||
#if defined(__HIPCC__)
|
||||
return __builtin_bit_cast(uint32_t, f);
|
||||
@@ -68,9 +63,9 @@ R3D_HD float float_of(uint32_t u) {
|
||||
*
|
||||
* 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. */
|
||||
* `(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, as in rad_f32_to_bf16 and libref. */
|
||||
R3D_HD float bf16_to_f32(uint16_t h) {
|
||||
const uint32_t u = (uint32_t)h << 16;
|
||||
return float_of(u);
|
||||
@@ -82,15 +77,15 @@ R3D_HD uint16_t f32_to_bf16(float f) {
|
||||
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. */
|
||||
/* The same rounding without the final shift: the rounded value 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. */
|
||||
/* Two such words as one bf16 pair, `lo`'s value in the low half: 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);
|
||||
@@ -103,7 +98,7 @@ 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. */
|
||||
/* A bf16 pair word's two values as floats: a shift or a mask, no conversion. */
|
||||
R3D_HD float bf16w_lo(uint32_t w) {
|
||||
const uint32_t u = w << 16;
|
||||
return float_of(u);
|
||||
@@ -115,8 +110,8 @@ R3D_HD float bf16w_hi(uint32_t w) {
|
||||
|
||||
/* ================================================================== 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. */
|
||||
* RTNE both ways with subnormals kept, as rad_f16_to_f32 and rad_f32_to_f16 do. The hardware
|
||||
* convert is not used: its rounding mode is caller-settable and it 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;
|
||||
@@ -171,12 +166,12 @@ R3D_HD uint16_t f32_to_f16(float f) {
|
||||
|
||||
/* 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. */
|
||||
* v_cvt_pkrtz_f16_f32 rounds toward zero, not RTNE, so this is only called with values f16
|
||||
* represents exactly: a widened bf16 (seven mantissa bits into ten) or an E4M3 code (three into
|
||||
* ten). For those both paths give the same bits. */
|
||||
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. */
|
||||
/* The builtin returns a pair of __fp16; its 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);
|
||||
@@ -185,22 +180,17 @@ R3D_HD uint32_t f16x2_pack(float lo, float hi) {
|
||||
|
||||
/* 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.
|
||||
* Exact over f16's normal range, which makes the dot2 path sound: bf16 has seven mantissa bits and
|
||||
* f16 ten, so within [2^-14, 65504] widening costs no rounding and a dot over widened bf16 forms
|
||||
* 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. */
|
||||
* Outside that range: above 65504 a magnitude becomes an infinity. Below 2^-14 the operand is an
|
||||
* f16 subnormal on a coarser grid than bf16's, and v_cvt_pkrtz_f16_f32 truncates toward zero;
|
||||
* below 2^-24 it flushes. The low edge does not affect a served model: an activation below 2^-14
|
||||
* times a weight of 0.01 is 1e-18 against an accumulator of order one, and the quantised rows keep
|
||||
* the scale on the block, not the element, so scale-reduced operands are scaled back before use. No
|
||||
* checkpoint's weights live below 2^-14. 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));
|
||||
}
|
||||
@@ -210,11 +200,10 @@ R3D_HD uint32_t bf16x2_to_f16x2(uint32_t w) {
|
||||
* 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. */
|
||||
* RDNA3 has no fp8 instructions: v_cvt_pk_fp8_f32 and v_cvt_pk_f32_fp8 need the fp8 feature. The
|
||||
* builtins are declared for gfx11, so a `__has_builtin` guard (as in libr4d) passes, but they are
|
||||
* rejected at instruction selection. Both directions are bit maths, about eleven VALU per encode
|
||||
* and six per 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;
|
||||
@@ -237,9 +226,9 @@ R3D_HD float e4m3_to_f32(uint8_t b) {
|
||||
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. */
|
||||
/* Saturates at 448 rather than overflowing, because a NaN from one large activation spreads
|
||||
* through the whole row; every fp8 cast in this project clamps. The clamp is inside the codec
|
||||
* because there is no hardware convert 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);
|
||||
@@ -270,31 +259,29 @@ R3D_HD uint8_t f32_to_e4m3(float f) {
|
||||
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. */
|
||||
/* Two codes in one dword, the low element in the low byte: one lane's store. */
|
||||
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. */
|
||||
* Exact (e4m3 has four exponent and three mantissa bits, f16 five and ten). This is the fp8 matrix
|
||||
* path: a code becomes its f16 value, dot2 multiplies it, and the block scale is applied once per
|
||||
* block. Without fp8 hardware the decode is VALU work, done where the weight bytes are read. */
|
||||
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. */
|
||||
* Symmetric int8: 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. */
|
||||
/* Round to nearest, ties to even, in integer arithmetic, then clamp. The clamp follows the
|
||||
* rounding, not an early return: 127.5 rounds to the even 128 and clamps to 127, as
|
||||
* rad_round_even_sat does. */
|
||||
const float fl = __builtin_floorf(f);
|
||||
const float frac = f - fl;
|
||||
int32_t q = (int32_t)fl;
|
||||
@@ -315,28 +302,25 @@ R3D_HD uint32_t i8x2_to_f16x2(uint32_t w) {
|
||||
|
||||
/* ================================================================== 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.
|
||||
* Two f16 products into an f32 accumulator in one instruction: v_dot2acc_f32_f16, which
|
||||
* __builtin_amdgcn_fdot2 lowers to on every gfx11 target (verified in the emitted asm on gfx1100,
|
||||
* gfx1102 and gfx1151). RDNA3 pairs it as v_dual_dot2acc_f32_f16 where the scheduler can.
|
||||
*
|
||||
* 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.
|
||||
* Invariant: the last argument is always false. RDNA3 has no bf16 dot2, yet this compiler accepts
|
||||
* the bf16 selector and emits the f16 instruction, so a bf16 pair passed with sel=true is silently
|
||||
* read as two f16s. bf16 operands are widened exactly with bf16x2_to_f16x2.
|
||||
*
|
||||
* 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 two products go into `acc` in the order written, so a kernel walking k ascending follows
|
||||
* libref's summand order (`s += a[k]*b[k]` with -ffp-contract=off). The result is not bit-exact:
|
||||
* v_dot2acc_f32_f16 folds both products and the accumulator with guard bits and rounds once, where
|
||||
* the reference rounds each product and sum. The difference is under an f32 ulp per pair, a random
|
||||
* walk of about sqrt(K/2) ulps over a K-long dot: about a thousandth of the bf16 the store narrows
|
||||
* to, and inside what `rad-kbench` measures (as with libr4d's WMMA accumulation). What every loop
|
||||
* here must keep is the reference's summand order: 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. */
|
||||
* The host path is the same arithmetic with each product rounded first, for tests; 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)));
|
||||
@@ -350,8 +334,8 @@ R3D_HD float dot2_f16x2(uint32_t a, uint32_t b, float acc) {
|
||||
#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. */
|
||||
/* Four f16 products into one accumulator, the step every libr3d matmul runs. The two dot2s form a
|
||||
* dependency chain of two; a kernel keeps four such 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));
|
||||
}
|
||||
|
||||
+60
-74
@@ -1,45 +1,39 @@
|
||||
/* r3d_common.h -- the RDNA3 seams a kernel needs: the wave's lane maths, the loads, the block
|
||||
* reduce, the occupancy and LDS conventions.
|
||||
/* r3d_common.h -- RDNA3 kernel primitives: lane maths, global loads, the block reduce, occupancy
|
||||
* and LDS conventions. The codecs are in r3d_codecs.h.
|
||||
*
|
||||
* 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.
|
||||
* Instruction availability on gfx11 with the AMD clang this tree builds with (checked with
|
||||
* `__has_builtin` under --offload-device-only and llvm-mc -show-encoding per target):
|
||||
*
|
||||
* 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_dot2acc_f32_f16 yes, all gfx11, via __builtin_amdgcn_fdot2; dual-issued as
|
||||
* v_dual_dot2acc_f32_f16 where possible. Carries the matrix work.
|
||||
* v_dot2 with bf16 no. The builtin's bf16 selector is accepted and ignored (the f16
|
||||
* instruction is emitted), so bf16 is widened.
|
||||
* WMMA the assembler rejects every v_wmma_* mnemonic and inline asm fails in
|
||||
* amdgcn-link, but __builtin_amdgcn_wmma_f32_16x16x16_f16_w32 compiles on
|
||||
* gfx11. It runs at the same rate as paired dot2 (about 2 TFLOP/s each
|
||||
* on the tested part; RDNA3's matrix unit is a 2x f16-rate feature that
|
||||
* dual dot2 already reaches), so it would add a fragment layout and an
|
||||
* alignment requirement for no throughput. Without fragment layouts no
|
||||
* weight is repacked: a dot2 GEMM reads a weight in stored order.
|
||||
* fp8 convert no (needs the fp8 feature); the builtins are declared but fail at
|
||||
* instruction selection, so 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.
|
||||
* v_cvt_pk_bf16_f32 no on gfx1100/1102/1151, so bf16 packs are software.
|
||||
* DPP16, v_permlanex16 yes (RDNA1 onward). The lane maths below uses libr4d's encodings,
|
||||
* which are hardware-verified.
|
||||
* 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.
|
||||
* transposed loads no: neither global_load_tr_b128 (RDNA4) nor ds_read_b64_tr_b16 (the
|
||||
* assembler rejects it for gfx11). Transposes are 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.
|
||||
* Every kernel is written for wave32, gfx11's default; the guard below rejects a wave64 build,
|
||||
* which would compute wrong results.
|
||||
*
|
||||
* 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.
|
||||
* Register file: a gfx11 SIMD has 1024 VGPRs for wave32, allocated in groups of 8 (gfx1201 has
|
||||
* 1536). R3D_WAVES is set per kernel and each kernel's budget is computed against 1024.
|
||||
*/
|
||||
#ifndef R3D_COMMON_H
|
||||
#define R3D_COMMON_H
|
||||
@@ -57,26 +51,25 @@
|
||||
|
||||
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. */
|
||||
/* A 16-byte staging register as a native vector. HIP's uint4 is a class wrapping a union, and LLVM
|
||||
* 22 and 24 keep an array of them carried across a loop in scratch; 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. */
|
||||
* Fixes the waves per SIMD the compiler schedules for; left unstated, the choice changes 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. */
|
||||
* The hardware transcendental. Elsewhere use the accurate exp2f, powf and sincosf, not the __
|
||||
* approximations: rope positions reach 262144, past __sincosf's argument reduction, and libref uses
|
||||
* libm. exp2 is the exception because the hardware op and the reference round the same result once. */
|
||||
__device__ __forceinline__ float ex2(float x) {
|
||||
return __builtin_amdgcn_exp2f(x);
|
||||
}
|
||||
@@ -87,12 +80,11 @@ __device__ __forceinline__ float rcp(float x) { return __builtin_amdgcn_rcpf(x);
|
||||
*
|
||||
* 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.
|
||||
* then waits for, and through a generic pointer it is a flat load. The pointer must address global
|
||||
* memory.
|
||||
*
|
||||
* 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. */
|
||||
* gfx11 has no true 16-bit registers (LLVM 24 gives them to gfx12 only), so bf16 stays in whole
|
||||
* registers from load to store. */
|
||||
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; }
|
||||
@@ -102,16 +94,15 @@ __device__ __forceinline__ float ldg_f32(const 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.
|
||||
* A wave is 32 lanes, two rows of sixteen. Reductions are XOR butterflies in the order a
|
||||
* __shfl_xor loop runs them, so results are bit-identical to that loop and to libref, which sums a
|
||||
* row in ascending index order over 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. */
|
||||
* consuming VALU op, and N = 16 crosses the two rows with v_permlanex16, also one VALU op. Row and
|
||||
* bank masks are all-ones because every lane participates; bound_ctrl is moot because every lane
|
||||
* has a partner. */
|
||||
template <int N>
|
||||
__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");
|
||||
@@ -139,7 +130,7 @@ __device__ __forceinline__ unsigned long long r3d_xor_lane_u64(unsigned long lon
|
||||
* 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. */
|
||||
/* v + the partner's v, read by DPP as a modifier on the add. */
|
||||
template <int CTRL>
|
||||
__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,
|
||||
@@ -166,7 +157,7 @@ __device__ __forceinline__ float wave_max(float 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. */
|
||||
* of sixteen lanes (the sixteen columns of a bf16 pair layout) uses W = 16. */
|
||||
template <int W>
|
||||
__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");
|
||||
@@ -190,8 +181,8 @@ __device__ __forceinline__ float r3d_xor_max(float 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.
|
||||
* then the first row's total from one readlane. Lane L ends with the sum over lanes 0..L. Avoids 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 */
|
||||
@@ -205,9 +196,8 @@ __device__ __forceinline__ uint32_t wave_prefix_u32(uint32_t x, int lane) {
|
||||
/* ================================================================== 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. */
|
||||
* is part of the contract: waves cover consecutive elements, so wave order gives the same
|
||||
* bracketing at any thread count. `lds` holds NWAVES floats. */
|
||||
template <int NTHREADS>
|
||||
__device__ __forceinline__ float block_sum(float v, float* lds) {
|
||||
constexpr int NWAVES = NTHREADS / kWave;
|
||||
@@ -225,22 +215,19 @@ __device__ __forceinline__ float block_sum(float v, float* lds) {
|
||||
|
||||
/* ================================================================== 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. */
|
||||
* LLVM single-buffers LDS and drains before every dependent read unless told otherwise. On gfx11
|
||||
* there is no matrix unit to overlap a load with, so the plain barrier is enough. */
|
||||
__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 gfx11 GPU's wave slots: a CU has 4 SIMDs and a SIMD holds 16 wave32s, so 64 slots a CU. HIP's
|
||||
* multiProcessorCount reports CUs on gfx11 (WGPs on gfx12, hence libr4d's different constant). A
|
||||
* grid with more than 64 * multiProcessorCount waves runs its tail waves only after others retire,
|
||||
* so for a one-wave row-per-block kernel that row count is a performance cliff.
|
||||
*
|
||||
* 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. */
|
||||
* Host only: HIP declares no device-side hipGetDevice or hipDeviceGetAttribute. */
|
||||
static inline int wave_slot_count() {
|
||||
int dev = 0, cu = 0;
|
||||
(void)hipGetDevice(&dev);
|
||||
@@ -248,9 +235,8 @@ static inline int wave_slot_count() {
|
||||
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. */
|
||||
/* A workgroup gets 64 KiB of LDS, as on RDNA4, and no libr3d kernel needs more. No
|
||||
* hipFuncSetAttribute opt-in is needed for the full 64 KiB of dynamic shared memory. */
|
||||
enum : int { kLdsCap = 64 * 1024 };
|
||||
|
||||
#endif /* R3D_COMMON_H */
|
||||
+56
-74
@@ -1,62 +1,48 @@
|
||||
/* r3d_dflash_f32.hip -- DFlash2's candidate walk, `dflash_select`, on the card.
|
||||
/* r3d_dflash_f32.hip -- DFlash2's candidate walk, `dflash_select`.
|
||||
*
|
||||
* 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
|
||||
* l+1 is not conditioned on the drafter's choice 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.
|
||||
* where pid(0) is the anchor (the token the target just committed, at `anchor[m * anchor_stride]`)
|
||||
* and pid(l) is the walk's previous pick, `cand[l-1, chosen]`. With `hp` absent it is a plane of
|
||||
* ones and the form reduces to a low-rank bigram (DSpark's Markov head). This file transcribes the
|
||||
* arithmetic and order of libref's `ref_dflash_select`.
|
||||
*
|
||||
* ============================== why it is a kernel and not a GEMM ==============================
|
||||
* Parallelism. The walk is serial in l, because step l's predecessor is the pick of step l-1;
|
||||
* scoring the whole [steps, K, K] edge tensor up front would compute K times the edges read. The
|
||||
* sequences and, within a step, the K candidates are parallel: a block takes `256 / top_k`
|
||||
* sequences, each lane scores one (sequence, candidate) edge, and one lane per sequence takes the
|
||||
* argmax. Each step costs two LDS round trips (scores out, pick back).
|
||||
*
|
||||
* 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.
|
||||
* Cost. At the band (steps=7, top_k=16, rank=256, M=256) a walk is 7 * 16 * 256 = 28672 terms, and
|
||||
* the op is a gather over `succ` [n_vocab, rank]: 66.8 MiB of codebook, of which the walk reads
|
||||
* M * steps * K = 28672 rows (about 14.7 MiB) plus one predecessor row per step. There is no
|
||||
* arithmetic to hide the gather behind, so a tree reduction gains nothing and would break the
|
||||
* agreement below.
|
||||
*
|
||||
* 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 with the reference is bit-exact:
|
||||
*
|
||||
* ============================== 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 rank sum is `sc = unary; for (i = 0; i < rank; ++i) sc += ax[i] * succ[i];`, ascending in
|
||||
* r, one accumulator, with `-ffp-contract=off` so no FMA changes a term's rounding;
|
||||
* - `ax[i] = pred[pid][i] * hp[l][i]` is rounded to f32 before it meets `succ`, as the reference
|
||||
* stores it in a float array first (with `hp` absent, `pred * 1.0f` 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.
|
||||
* never displaces the incumbent;
|
||||
* - a predecessor outside the vocabulary contributes zero and a candidate outside it is scored by
|
||||
* `unary` alone (the reference's `pid >= 0 && pid < nv`, `tok >= 0 && tok < nv`), so 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, even 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.
|
||||
* The shim refuses, none of it reachable from a row whose constraints hold: a codebook (`pred`,
|
||||
* `succ`, `hp`) or band `dtype` other than bf16, the one instantiation (RAD_E_DTYPE); `unary` not
|
||||
* f32 or `cand`/`anchor`/`tokens` not i32, as the schema types them (RAD_E_DTYPE); a codebook whose
|
||||
* rows are not contiguous, since the gather is `token * rank + r` (RAD_E_STRIDE); `top_k` above
|
||||
* 256, one lane per candidate (RAD_E_UNSUPPORTED); a `cand` plane describing more sequences than
|
||||
* the band's `M` (RAD_E_SHAPE, not a truncation).
|
||||
*/
|
||||
|
||||
#include "r3d.h"
|
||||
@@ -72,8 +58,8 @@ 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. */
|
||||
/* Whole-register loads of the planes the walk gathers through. bf16 is a 16-bit load decoded with
|
||||
* the library's codec, the same decode as libref's `ldt`. */
|
||||
__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) {
|
||||
return (int32_t)ldg_u32((const uint32_t*)p);
|
||||
}
|
||||
@@ -81,10 +67,10 @@ __device__ __forceinline__ float ldg_f32(const float* p) { return *(const float*
|
||||
__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. */
|
||||
*
|
||||
* `per` sequences per block, `K` candidates per sequence; lane (s, c) owns the edge
|
||||
* (sequence s, candidate c) of the current step. `hp` may be null, and the factor is then 1.0f, as
|
||||
* in the reference's `(hp ? ldt(hp, ...) : 1.0f)`. */
|
||||
__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,
|
||||
@@ -100,13 +86,13 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
|
||||
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. */
|
||||
* with no sequence replays the last real one, so it reaches every __syncthreads() and its loads
|
||||
* stay in range; its stores are suppressed. */
|
||||
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. */
|
||||
/* pid(0): the anchor, at `m * anchor_stride` in a flat plane. As in the reference (`ld_int`),
|
||||
* a negative id means "no predecessor", not an error. */
|
||||
int32_t pid = ldg_i32(anc + (size_t)seq * (size_t)astr);
|
||||
const bool has_hp = (hp != nullptr);
|
||||
|
||||
@@ -116,9 +102,8 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
|
||||
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. */
|
||||
/* Out-of-vocabulary predecessor: no contribution. Out-of-vocabulary candidate: `unary`
|
||||
* alone. See the header. */
|
||||
const bool have_p = pid >= 0 && (uint32_t)pid < nv;
|
||||
const bool have_s = tok >= 0 && (uint32_t)tok < nv;
|
||||
if (have_s) {
|
||||
@@ -126,8 +111,7 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
|
||||
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. */
|
||||
/* ax[i] is rounded to f32 before the multiply, as in the reference. */
|
||||
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;
|
||||
@@ -138,8 +122,7 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
|
||||
__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. */
|
||||
/* Strict `>`, c ascending: the earliest candidate wins a tie, a NaN never leads. */
|
||||
uint32_t best_c = 0;
|
||||
float best_s = -INFINITY;
|
||||
for (uint32_t j = 0; j < K; ++j) {
|
||||
@@ -157,9 +140,8 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
/* The plane's row count (`rows`) and row pitch (`ld`) for rows of K elements. A rank-1 plane is a
|
||||
* run of rows K apart, as the reference's rowoff treats it. */
|
||||
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;
|
||||
@@ -201,7 +183,7 @@ static inline int r3d_launch_status(int rc) {
|
||||
* 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
|
||||
* tokens [M][steps] i32, out: the accepted prefix, one pick per step
|
||||
*
|
||||
* 0, -1 null, -2 bad extent, -3 pitch, -4 the HIP launch failed. No allocation, no synchronisation.
|
||||
*/
|
||||
@@ -237,10 +219,10 @@ extern "C" int r3d_dflash_select(long cand, long unary, long hp, long anchor, lo
|
||||
/* ================================================================== 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.
|
||||
* {M, steps, top_k, rank, n_vocab, anchor_stride?, dtype}. The sequence count comes from `cand`
|
||||
* (M * steps * top_k ids), with the band's M as a ceiling: a plane describing more sequences is
|
||||
* refused, not truncated. `rank` and `n_vocab` default to the predecessor codebook's shape, as in
|
||||
* the reference, and `anchor_stride` to 1.
|
||||
*/
|
||||
extern "C" int r3d_rad_dflash_select(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* cand = r3d_opt(a, 0);
|
||||
@@ -269,7 +251,7 @@ extern "C" int r3d_rad_dflash_select(const RadArgs* a, RadStream stream) {
|
||||
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. */
|
||||
/* Sequences from the plane, the band as a ceiling. */
|
||||
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;
|
||||
|
||||
+24
-35
@@ -1,36 +1,26 @@
|
||||
/* r3d_fp8_dequant.h -- the E4M3 -> f16 decoder as a table, for the rows that read fp8 codes.
|
||||
/* r3d_fp8_dequant.h -- E4M3 -> f16 decode through a 256-entry LDS table.
|
||||
*
|
||||
* WHY THIS EXISTS, WITH THE MEASUREMENT THAT ASKED FOR IT
|
||||
* gfx11 has no E4M3-to-f16 instruction: `__builtin_amdgcn_cvt_pk_f16_fp8` compiles on gfx1102 but
|
||||
* emits no `v_cvt_pk_f16_fp8`, only the same software exponent work as `e4m3_to_f32`. The codec in
|
||||
* r3d_codecs.h costs about 25 instructions a pair, 100 an eight-code group. On the M=1 vocabulary
|
||||
* head (r3d_vocab_bf16.hip, gfx1102, 32 CU) that makes the row ALU-bound at about 8x its DRAM floor.
|
||||
*
|
||||
* 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.
|
||||
* Every one of E4M3's 256 bit patterns has an exact f16 value (f16's exponent range covers E4M3's,
|
||||
* subnormals included, and NaN maps to NaN), so the decoder is a 512-byte table and eight LDS reads
|
||||
* replace about a hundred ALU instructions. The table lives in LDS, not __constant__: each lane
|
||||
* decodes a different code, and divergent constant indexes serialise.
|
||||
*
|
||||
* 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 and a 256-store fill plus a barrier at block start. Reads are
|
||||
* 16-bit loads at data-dependent addresses; random codes put about two lanes on each bank word, for
|
||||
* about two cycles a read.
|
||||
*
|
||||
* 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 filled by calling the codec once per entry, so results are bit-identical to the
|
||||
* codec. Invariant: the table must be filled before any lane reads it; r3d_e4m3_f16_init contains
|
||||
* the barrier.
|
||||
*
|
||||
* 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 need no table: `v_cvt_f32_i8` is a hardware instruction (r3d_codecs.h: i8x2_to_f16x2).
|
||||
*
|
||||
* 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.
|
||||
* Include in a .hip after r3d_codecs.h.
|
||||
*/
|
||||
#ifndef R3D_FP8_DEQUANT_H
|
||||
#define R3D_FP8_DEQUANT_H
|
||||
@@ -40,8 +30,8 @@
|
||||
#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. */
|
||||
/* Fill the block's table: `tbl` is __shared__ uint16_t[R3D_E4M3_TBL]. Ends with the barrier that
|
||||
* orders the fill before any read. */
|
||||
__device__ __forceinline__ void r3d_e4m3_f16_init(uint16_t* tbl, int tid, int nthr)
|
||||
{
|
||||
for (int i = tid; i < R3D_E4M3_TBL; i += nthr)
|
||||
@@ -49,8 +39,8 @@ __device__ __forceinline__ void r3d_e4m3_f16_init(uint16_t* tbl, int tid, int nt
|
||||
__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. */
|
||||
/* Two codes (the low 16 bits of a dword) as one f16 pair in dot2_f16x2 layout, the first code in
|
||||
* the low half. Same result as e4m3x2_to_f16x2. */
|
||||
__device__ __forceinline__ uint32_t r3d_e4m3x2_ld(const uint16_t* tbl, uint32_t pair)
|
||||
{
|
||||
const uint16_t lo = tbl[pair & 0xffu];
|
||||
@@ -58,9 +48,8 @@ __device__ __forceinline__ uint32_t r3d_e4m3x2_ld(const uint16_t* tbl, uint32_t
|
||||
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. */
|
||||
/* Eight codes (two dwords) as four f16 pairs; the fp8 counterpart of codes8_to_f16x4 in
|
||||
* r3d_vocab_bf16.hip. */
|
||||
__device__ __forceinline__ void r3d_e4m3x8_ld(const uint16_t* tbl, uint2 c, uint32_t* w)
|
||||
{
|
||||
const uint32_t d0 = c.x, d1 = c.y;
|
||||
@@ -70,7 +59,7 @@ __device__ __forceinline__ void r3d_e4m3x8_ld(const uint16_t* tbl, uint2 c, uint
|
||||
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). */
|
||||
/* One code, for rows that decode a scalar per 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];
|
||||
|
||||
+84
-106
@@ -1,89 +1,78 @@
|
||||
/* r3d_gemm_bf16_nt_m16.hip -- the skinny bf16 GEMM, M <= 16: the linear a token is made of.
|
||||
/* r3d_gemm_bf16_nt_m16.hip -- the skinny bf16 GEMM, M <= 16.
|
||||
*
|
||||
* 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 band is decode and speculative verify, where the weight stream is the cost. The kernel
|
||||
* streams the whole weight plane once, and 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
|
||||
* One output element per lane, walking k ascending. A wave covers MT activation rows by 32/MT
|
||||
* weight rows: lane l owns (m = l % MT, n = n0 + l / MT), where MT (the template argument) is M
|
||||
* rounded up to 1, 2, 4, 8 or 16. Lanes sharing an n read the same weight words; lanes sharing an m
|
||||
* read the same activation words from LDS. Each lane owns one accumulator from 0 to K and never
|
||||
* exchanges a value with another lane:
|
||||
*
|
||||
* 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.
|
||||
* which is `s += a[k]*b[k]` in ascending k, the loop r4d_gemm_bf16_nt_tiled's contract quotes and
|
||||
* ref_gemm.h's quant_tile runs. No wave reduction, so nothing reassociates: at sk = 1 the output
|
||||
* is bit-identical to libref's.
|
||||
*
|
||||
* 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.
|
||||
* 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 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 activation is staged in LDS: a tile is MT * 128 bf16 (4.25 KiB at MT = 16), one 16-byte load
|
||||
* per thread. Staging widens bf16 -> f16 once per element with the exact bf16x2_to_f16x2, so the
|
||||
* dot2 reads f16 pairs straight from LDS and the conversion is not repeated for every weight row.
|
||||
* The pitch is 68 dwords: 68 mod 32 = 4 puts the eight lanes of a ds_read_b128 phase on banks 4
|
||||
* apart (conflict-free), and 68 * 4 = 272 bytes 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 weight is not staged: with M this small a staged tile would be read by 32/MT lanes and
|
||||
* discarded, so LDS buys no reuse. Weight bytes go from global memory into registers, are widened
|
||||
* there by four v_cvt_pkrtz per eight values (one convert per two dot2 products), 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), so 16-byte-per-lane strided reads across NT rows cost only 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.
|
||||
* A gfx11 SIMD has 1024 VGPRs for a wave32. The loop holds one accumulator, four activation pairs,
|
||||
* four weight dwords, one 16-byte staging quad and some pointers and counters: about 24 live
|
||||
* VGPRs, far under the 128 that R3D_WAVES(8) (eight waves per SIMD, 1024/8) allows. The target is
|
||||
* stated for the reason r3d_common.h gives: otherwise the scheduler picks the occupancy, and this
|
||||
* kernel's throughput is waves in flight, each waiting hundreds of cycles on a memory load. Eight
|
||||
* waves per 256-thread block is the default; `wv` is the tuner's axis.
|
||||
*
|
||||
* ---- 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.
|
||||
* At M = 1 the only parallelism is N, and N = 48 (a GDN a|b projection) gives three waves on a
|
||||
* 32-CU card. `sk` splits K into that many contiguous slabs, one per 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.
|
||||
* Summing sk per-slab partials is not libref's single ascending chain: the slab sums bracket the
|
||||
* products differently. sk = 1 is bit-identical; sk > 1 agrees to the last bits, the same contract
|
||||
* libr4d's tiled row states for 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.
|
||||
* `sk == 0` picks the largest legal split from the axis's ladder {16, 8, 4, 2, 1}. A split is legal
|
||||
* when K % (sk * 8) == 0, so a slice boundary never falls inside a lane's step of eight k (four f16
|
||||
* pairs). The staged tile is 128 k wide with a ragged last tile, which allows slices as short as
|
||||
* 8 k. 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.
|
||||
* RDNA3 has no global_load_tr_b128 (an RDNA4 instruction) and no cache-swizzle 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, which lowers to flat_load_dwordx4. The axis lets kbench price the
|
||||
* two lowerings, which on this card stream the same.
|
||||
*/
|
||||
|
||||
/* 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. */
|
||||
/* hip_runtime.h first: it defines __forceinline__, which r3d_codecs.h's R3D_HD uses, and
|
||||
* r3d_common.h includes the codecs before the runtime. */
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include "r3d.h"
|
||||
@@ -96,15 +85,14 @@ 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 kKTile = 128; // k covered by one staged tile of a
|
||||
constexpr int kAPitch = kKTile / 2 + 4; // dwords per staged row of a
|
||||
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. */
|
||||
/* The split rule, shared by the launcher, the shim and the row's gemm_tune_valid. `kUnit` is the
|
||||
* k one lane step consumes (eight elements, four f16 pairs); 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; its
|
||||
* top is the split the scratch hook sizes the arena for. */
|
||||
constexpr int kUnit = 8;
|
||||
inline int pick_sk(long long K, int maxsk)
|
||||
{
|
||||
@@ -114,9 +102,8 @@ inline int pick_sk(long long K, int maxsk)
|
||||
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. */
|
||||
/* A 16-byte weight read. NT true is the address-space-1 form (global_load_b128, no cache modifier,
|
||||
* no swizzle); NT false goes through the generic pointer (flat_load_dwordx4). See the header. */
|
||||
template <bool NT>
|
||||
__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p)
|
||||
{
|
||||
@@ -129,19 +116,19 @@ __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.
|
||||
/* y[M,N] = a[M,K] @ b[N,K]^T, one output element per 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. */
|
||||
* `kslab` is the k range one blockIdx.y owns. With sk = 1 it is all of K and the store is bf16.
|
||||
* With sk > 1 each split writes an f32 partial into a dense [sk][M][N] plane, and
|
||||
* gemm_split_reduce adds them. */
|
||||
template <int MT, bool NT, bool SPLIT>
|
||||
__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. */
|
||||
/* Staged activation, widened to f16 pairs. Sized for the widest MT (4.25 KiB) in every
|
||||
* instantiation. */
|
||||
__shared__ uint32_t s_a[kMTMax * kAPitch];
|
||||
|
||||
const uint32_t tid = threadIdx.x;
|
||||
@@ -164,13 +151,12 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel(
|
||||
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. */
|
||||
/* Stage: eight elements per unit, MT * (kl/8) units. 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. */
|
||||
/* Stride by blockDim.x, not 256: the wv axis launches one, two, four or eight waves, and a
|
||||
* fixed stride would leave part of the tile unstaged (wv = 1 would stage 32 of MT*16
|
||||
* units). */
|
||||
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;
|
||||
@@ -198,33 +184,28 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel(
|
||||
for (int k = 0; k < kf; k += 8) {
|
||||
const r3d_u32x4 aw = lds_a(ap + k / 2);
|
||||
const r3d_u32x4 b16 = ldw<NT>(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. */
|
||||
/* The weight must be widened: dot2's operands are f16, and a bf16 bit pattern read as
|
||||
* f16 is a different number (bf16 1.0, 0x3F80, reads as 1.875; magnitudes >= 2^16
|
||||
* become infinities). Four v_cvt_pk_rtz_f16_f32_e32 per eight values, each with two
|
||||
* VALU of unpack, so the widening costs one ALU slot per dot2 product; RDNA3 pairs
|
||||
* some of the dots as v_dual_dot2acc_f32_f16 alongside the converts. */
|
||||
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. */
|
||||
/* The elements past the last whole step of eight, ascending. The launcher's
|
||||
* K % (sk * 8) == 0 rule leaves none, so this loop does not run. */
|
||||
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
|
||||
group_barrier(); // the next tile's stage must not race these 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. */
|
||||
/* Partial plane [sk][M][N], split-major: the reducer reads sk values M*N apart. */
|
||||
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
|
||||
@@ -232,10 +213,7 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel(
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
* At sk > 1 this differs from libref's single chain in the last bits (see the header). */
|
||||
__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)
|
||||
{
|
||||
@@ -254,14 +232,14 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_split_reduce(
|
||||
|
||||
/* 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)
|
||||
* a [M][K] bf16, `a_ld` elements per row (0 = K)
|
||||
* b [N][K] bf16, row-major, k contiguous
|
||||
* y [M][N] bf16, `y_ld` elements a row (0 = N)
|
||||
* y [M][N] bf16, `y_ld` elements per 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. */
|
||||
* sk * M * N * 4 bytes, required when sk > 1. Returns 0, -1 a null pointer, -2 an unsupported
|
||||
* shape, -3 an unreadable pitch, -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)
|
||||
{
|
||||
@@ -344,10 +322,10 @@ extern "C" int r3d_rad_gemm_nt_bf16_m16(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* The weight must be dense: every wave reads b[n][k] at n * K + k, and the launcher takes no
|
||||
* weight pitch. */
|
||||
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. */
|
||||
/* 16-byte 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);
|
||||
|
||||
|
||||
@@ -1,76 +1,67 @@
|
||||
/* r3d_gemm_fp8a16_nt_m1.hip -- the same skinny shape against a block-scaled weight.
|
||||
/* r3d_gemm_fp8a16_nt_m1.hip -- the skinny GEMM shape (M <= 16) 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`.
|
||||
* y[M,N] = a[M,K] @ b[N,K]^T, b stored as E4M3 codes with one scale (bf16 or f32) per
|
||||
* (pb1 x pb2) block, f32 accumulate, narrowed once by the store. When `a_scale` is present the
|
||||
* activation is coded too (quant_act_fp8's E4M3 codes, one f32 per (row, group)): the row
|
||||
* table's `fp8a8` form.
|
||||
*
|
||||
* 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.
|
||||
* RDNA3 has no fp8 instructions (the builtins are declared for gfx11 but fail at instruction
|
||||
* selection), so the codes are decoded in software. E4M3 has four exponent and three mantissa
|
||||
* bits and f16 five and ten, so e4m3x2_to_f16x2 is exact and the dot2 multiplies the checkpoint's
|
||||
* values. Nothing is rounded between code and product, so at sk = 1 the output matches libref bit
|
||||
* for bit.
|
||||
*
|
||||
* ---- 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.
|
||||
* As in r3d_gemm_bf16_nt_m16: lane l owns the output (m = l % MT, n = n0 + l / MT), MT being M
|
||||
* rounded up to {1,2,4,8,16}, walks k ascending and holds its own accumulator. The difference is
|
||||
* that a lane consumes sixteen codes per step, one global_load_b128, feeding eight dot2. The decode
|
||||
* (eight v_perms and shifts) sits between load and dot2, so this kernel runs slower than the bf16
|
||||
* row.
|
||||
*
|
||||
* 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.
|
||||
* Each lane owns one (m, n) pair and so one scale per block: `n / pb1` picks b_scale's row and the
|
||||
* block index its column, both hoisted out of the block's steps. A coded activation's scale is
|
||||
* `m`'s row at the same block index. 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:
|
||||
* The order is ref_gemm.h's quant_tile (and quant_dot beside it):
|
||||
*
|
||||
* for gi ascending: sub = 0
|
||||
* for k in the group, ascending: sub += a[k] * b[k] (from the CODES)
|
||||
* 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.
|
||||
* block sub-sum once, not every product: scaling each product is equal in exact arithmetic but
|
||||
* differs in the last bits, which can move an fp8 code and so a token. The parentheses in
|
||||
* `(sub * sa) * sb` are libref's and must be kept. Each block's sub-sum has its own register, so
|
||||
* the bracketing matches the reference.
|
||||
*
|
||||
* ---- 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.
|
||||
* Staged in LDS per scale block of K and widened exactly on the way in: bf16 -> f16 for fp8a16,
|
||||
* E4M3 -> f16 for fp8a8. A staged block is MT * 128 values (4.25 KiB at MT = 16). The pitch is 68
|
||||
* dwords: 68 mod 32 = 4 puts a ds_read_b128's eight lanes on banks four apart, and 272 bytes per
|
||||
* row keeps the 16-byte reads aligned. The weight is not staged: with M <= 16 a staged tile has
|
||||
* only 32/MT readers, so a round trip through LDS gains nothing over L1.
|
||||
*
|
||||
* ---- 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.
|
||||
* `sk` contiguous slices, one per blockIdx.y, each writing its f32 partial to `scratch`; a second
|
||||
* kernel adds them per output in ascending slice order. sk = 1 is libref's chain exactly; sk > 1
|
||||
* brackets the block terms by slice and agrees to the last bits. A split is legal when
|
||||
* K % (sk * group) == 0, because a slice that ends mid-block cannot apply that block's scale (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.
|
||||
* This ISA has no transposed load and no cache field on a global load. nt = 1 issues the weight
|
||||
* reads through an address-space-1 pointer (global_load_b128, no cache modifier, no swizzle);
|
||||
* nt = 0 issues the same 16-byte reads through the generic pointer. On this card both lowerings
|
||||
* stream the same.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD spells
|
||||
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD uses
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_common.h"
|
||||
@@ -83,12 +74,12 @@ 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 kStep = 16; // codes per lane step: one 16-byte load
|
||||
constexpr int kAPitch = 68; // dwords per 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. */
|
||||
/* A slice must be a whole number of scale blocks. The ladder is capped by the scratch hook's
|
||||
* widest split. */
|
||||
int pick_sk(long long K, int group, int maxsk)
|
||||
{
|
||||
static const int kLadder[] = { 16, 8, 4, 2, 1 };
|
||||
@@ -116,11 +107,9 @@ __device__ __forceinline__ uint32_t ldg_u8(const 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. */
|
||||
* e4m3x2_to_f16x2 decodes only the two codes in a dword's low half, so a 16-byte load (four
|
||||
* dwords) is eight decodes, each fed one 16-bit pair. Feeding it whole dwords would decode only
|
||||
* eight of the sixteen codes and silently shrink the result. */
|
||||
__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 };
|
||||
@@ -129,8 +118,8 @@ __device__ __forceinline__ void codes_to_f16x8(const r3d_u32x4 c, uint32_t* w)
|
||||
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. */
|
||||
/* y[M,N] = a[M,K] @ dequant(b)[N,K]^T. `A8` is the fp8a8 form: a is E4M3 codes and a_scale one
|
||||
* f32 per (row, block); otherwise a is bf16. */
|
||||
template <int MT, bool A8, bool NT, bool SPLIT>
|
||||
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
|
||||
const uint8_t* __restrict__ A, const float* __restrict__ AScale,
|
||||
@@ -155,10 +144,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
|
||||
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. */
|
||||
/* b_scale is the container's `weight_scale_inv`: bf16 for the whole quantised family (the shape
|
||||
* hook's `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})`), f32 under the separate `fp8a8f32`
|
||||
* dtype. Both are read; bf16 widens to f32 exactly. */
|
||||
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;
|
||||
@@ -166,15 +154,15 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
|
||||
|
||||
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. */
|
||||
/* One scale block per iteration: stage the block's activation, walk its k, apply its scale at
|
||||
* the end. `kb` is the block's first k. */
|
||||
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. */
|
||||
/* Stage gl elements of MT activation rows, widened to f16 pairs. Eight values per unit: a
|
||||
* 16-byte load for a bf16 row, an 8-byte one for a coded row. 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
|
||||
@@ -183,7 +171,7 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
|
||||
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
|
||||
const uint8_t* src = A + (size_t)rr * a_ld + kb + c; // codes: one byte per element
|
||||
for (int e = 0; e < cnt; e += 8) {
|
||||
const uint8_t* sp = src + e;
|
||||
uint32_t q[2];
|
||||
@@ -206,8 +194,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
|
||||
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. */
|
||||
/* A is a byte pointer (for the coded form): cast first, so the row and k offsets
|
||||
* are bf16 element offsets. */
|
||||
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];
|
||||
@@ -248,10 +236,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
|
||||
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. */
|
||||
/* A partial block's tail, ascending, two k at a time. The launcher refuses a K that is not
|
||||
* a multiple of the block (a ragged block would read past the scale plane), so this loop
|
||||
* does not run. */
|
||||
for (int k = gf; k < gl; k += 2) {
|
||||
const uint32_t aw = ap[k / 2];
|
||||
const uint32_t c0 = ldg_u8(w + kb + k);
|
||||
@@ -259,9 +246,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
|
||||
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
|
||||
group_barrier(); // the next block's stage must not race these reads
|
||||
|
||||
/* The block's finished sub-sum, scaled once, in libref's parentheses. */
|
||||
/* The block's 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]);
|
||||
}
|
||||
@@ -275,9 +262,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* The split reduction, as in the m16 unit: v = ((p0 + p1) + p2) + ... ascending by slice, then one
|
||||
* narrowing. */
|
||||
__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)
|
||||
{
|
||||
@@ -300,12 +286,12 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_reduce(
|
||||
* 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)
|
||||
* y [M][N] bf16, `y_ld` elements per 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. */
|
||||
* scale row (0 = group). `sk` splits K (0 = the widest legal), `nt` picks the weight load's
|
||||
* lowering, `scratch` is the f32 partial arena, sk * M * N * 4 bytes, required when sk > 1. Returns
|
||||
* 0, -1 a null pointer, -2 an unsupported shape, -3 an unreadable pitch, -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)
|
||||
@@ -316,7 +302,7 @@ extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale,
|
||||
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 (pb2 != group) return -2; // 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
|
||||
@@ -372,20 +358,6 @@ extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale,
|
||||
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,
|
||||
@@ -396,9 +368,8 @@ enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF };
|
||||
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. */
|
||||
/* The trace latch: distinct GEMM shapes, printed once each. A static array and a counter, no lock:
|
||||
* the trace is a diagnostic, and a duplicated line is cheaper than a lock on the served path. */
|
||||
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,
|
||||
@@ -422,13 +393,11 @@ extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* E4M3 weight codes with bf16 activations (fp8a16) or E4M3 activation 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. */
|
||||
/* Block scales are bf16 in the quantised family; f32 is the separate `fp8a8f32` dtype, which no
|
||||
* row here claims. Both are accepted; the kernel widens bf16 exactly at the load. */
|
||||
const bool bs16 = r3d_is_bf16(BS);
|
||||
if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE);
|
||||
R3D_NEED(dt_bf16(Y));
|
||||
@@ -448,8 +417,8 @@ extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* The block geometry. `group` is what the selector matched and pb2 the checkpoint's block
|
||||
* width; they describe the same bytes, and libref refuses a disagreement. */
|
||||
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);
|
||||
@@ -460,8 +429,8 @@ extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* `a_sum` removes an activation zero point this grid lacks, and `b_ref` is an mxfp4 scale
|
||||
* reference; libref refuses both with these schemes (gemm_ntq_impl). */
|
||||
if (r3d_opt(a, Q_ASUM)) return R3D_NO(RAD_E_UNSUPPORTED);
|
||||
if (r3d_opt(a, Q_BREF)) return R3D_NO(RAD_E_UNSUPPORTED);
|
||||
|
||||
@@ -479,14 +448,10 @@ extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* Under RAD_R3D_TRACE, print the plan's numbers once per distinct shape for the M <= 16 band,
|
||||
* which the tiled row's trace does not cover. M is numel(y)/N as above, and nothing is read
|
||||
* beyond what the checks already required. With the flag unset this is one cached getenv and
|
||||
* a return. */
|
||||
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 "
|
||||
|
||||
+182
-262
@@ -1,128 +1,101 @@
|
||||
/* 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.
|
||||
/* r3d_gemm_fp8a8_gated.hip -- gemm_nt_q_gated: the gated MLP's GEMM, gate and quantiser in one
|
||||
* launch, so the [M, N] bf16 intermediate is never materialised. On the 2B model it serves
|
||||
* (N=12288 K=2048 group=128 dtype=fp8a8 act=silu) 47 bands are M=64 and one is M=16.
|
||||
*
|
||||
* 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.
|
||||
* `out_bf16`, when bound, is the bf16 the codes were taken over.
|
||||
*
|
||||
* The law is ref_gemm_nt_q_gated and it is transcribed in its order:
|
||||
* Transcribed from ref_gemm_nt_q_gated, 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
|
||||
* 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`
|
||||
* Both halves are narrowed before the gate because the unfused pair writes and re-reads a bf16
|
||||
* [M, N] tensor, and the fused form must be byte-identical to it; `out_bf16` is what that tensor
|
||||
* held. The activation is not narrowed: `gt * sg` is formed in f32 and the product with `up`
|
||||
* rounds once, at the store.
|
||||
*
|
||||
* ---- the lane map: one lane owns a PAIR of dots -----------------------------------------------
|
||||
* ---- 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.
|
||||
* The gate couples column i with column n + i, which for n = 6144 is 192 waves away: no lane
|
||||
* exchange reaches it, and staging the row through LDS would cost the round trip this op avoids.
|
||||
* So each lane computes both products of its column, walking k ascending with two accumulators over
|
||||
* weight rows `i` and `n + i`. The weight traffic equals the unfused GEMM's for the two columns.
|
||||
*
|
||||
* A block covers ONE group of `group` output columns and RP = 256 / group rows, so a lane is
|
||||
* A block covers one group of `group` output columns and RP = 256 / group rows:
|
||||
*
|
||||
* 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.
|
||||
* so for group >= 32 a wave's 32 lanes are 32 consecutive columns of one group of one row. The
|
||||
* epilogue therefore closes inside the block: the group's amax is a wave max folded over group/32
|
||||
* waves in LDS, the scale is one store, the codes one byte per lane. The op is one launch with no
|
||||
* scratch, so the row is concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`).
|
||||
*
|
||||
* ---- the two streams: fp8a8 at M <= 8 reads the codes, the rest stages them -------------------
|
||||
* ---- the two arms: fp8a8 at M <= 8 reads the codes directly, the rest stage 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).
|
||||
* The staged shape below suits the bands' ceiling (M = 64) but not decode (M = 1, the whole
|
||||
* 12288 x 2048 operand, 42 calls per token). Its cost there is the path a code takes: global ->
|
||||
* LDS stage -> decode -> dot, with two `group_barrier`s per k-block, and an arithmetic decoder of
|
||||
* ten VALU per code (RDNA3 has no fp8 instructions; see r3d_codecs.h). The launcher picks the arm
|
||||
* by row count:
|
||||
*
|
||||
* 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 directly, 16 bytes at a time,
|
||||
* decode them from a 256-entry table the block builds once, and multiply. No
|
||||
* shared memory between load and dot, no barrier in the k-loop, six loads in
|
||||
* flight.
|
||||
* M >= 9, and every fp8a16 case the staged shape, with the same table decoder. At these
|
||||
* heights the grid is 48 x M/2 blocks and occupancy feeds the stream.
|
||||
*
|
||||
* 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.
|
||||
* On the band's stream (24 MiB of codes, kernel loop without the epilogue) the staged arithmetic
|
||||
* path takes 497 us, the direct table path 187 us, and the bare loads 139 us. The table decoder
|
||||
* also cuts M = 64 by about two thirds at no register cost (109 per lane, four waves per SIMD, no
|
||||
* spills).
|
||||
*
|
||||
* 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).
|
||||
* Two invariants: the table builder's codec argument is a pair, not an index (build_e4m3_table),
|
||||
* and decoded pairs go from the table into the dot inline, never through an array (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.
|
||||
* quant_dot, as in 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` with the reference's parentheses, `sa`
|
||||
* being `a_scale[m][gi]` (1 without a scale plane). Each lane's two chains are the unfused pair's
|
||||
* two calls, so the bracketing matches 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.
|
||||
* b_scale is bf16: this op's shape hook writes `o.t(RAD_BF16, {nb, kb})` with no f32 form, so the
|
||||
* plain entry reads bf16 and the `_ex` entry takes the dtype, as for the fp8 GEMM. bf16 -> f32
|
||||
* widening is exact, so an f32 plane with the same values gives bit-identical output (the test
|
||||
* driver checks this).
|
||||
*
|
||||
* ---- 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.
|
||||
* libref's sigmoid is `1.0f / (1.0f + (float)std::exp((double)(-x)))`. f64 runs at 1:64 on this
|
||||
* card, and the band needs M*n = 393216 exponentials per layer, so the kernel uses the accurate
|
||||
* device `expf` (not `__expf`), as r3d_gated_quant_fp8 (r3d_quant_fp8.hip) does. Its ~1e-7 error is
|
||||
* far under the bf16 ulp of 2^-8 the result is narrowed to, so the bf16 differs only on a tie; the
|
||||
* row's text records the tie count.
|
||||
*
|
||||
* ---- 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.
|
||||
* M > 64 (the bands' ceiling; beyond it the M reads of an [N, K] plane from L2 are a tiled
|
||||
* kernel's problem); N odd (the reference's `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 would use n for the quantiser's group but keep the stated K block, two widths this
|
||||
* kernel reads as one; K % group != 0, because a ragged K block reads past the scale plane; sk > 1,
|
||||
* because the epilogue needs the whole row. Codes: -1 null, -2 shape, -3 pitch, -4 HIP.
|
||||
*
|
||||
* ---- relayout: none, and it is a claim ---------------------------------------------------------
|
||||
* ---- no relayout ------------------------------------------------------------------------------
|
||||
*
|
||||
* 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.
|
||||
* This row reads the gated weight [N, K] row-major, as libref does. libr4d stores fp8a8 weights in
|
||||
* WMMA fragment order (`r4d.fp8.w.frag64`); the two readings differ by a relative error of ~1.35,
|
||||
* so a row that inherited the fp8 GEMM's relayout would fail the per-op oracle. The stored order
|
||||
* is the reading order, as for every row in the library.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD spells
|
||||
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD uses
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_common.h"
|
||||
@@ -134,27 +107,23 @@ 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 kStep = 16; // codes per lane step: one 16-byte load
|
||||
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 int kMMax = 64; // the bands' ceiling
|
||||
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. */
|
||||
* VALU per code (r3d_codecs.h), and this kernel decodes every weight code it multiplies (twice at
|
||||
* RP = 2). The table costs two `ds_read_u16` and a pack per pair, and is exact: entry c is what the
|
||||
* arithmetic path returns for c, computed by that path at block start. 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. */
|
||||
/* The codec's argument is a pair, low code in the low byte; the entry is indexed by code.
|
||||
* Passing the index alone would decode code 0 into every odd entry and silently zero half
|
||||
* the products (the `codes256` test case catches this). */
|
||||
*(uint32_t*)&tab[2 * u] = e4m3x2_to_f16x2((u * 2) | ((u * 2 + 1) << 8));
|
||||
}
|
||||
|
||||
@@ -165,10 +134,9 @@ __device__ __forceinline__ uint32_t tab_pair(const uint16_t* tab, uint32_t pair)
|
||||
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. */
|
||||
/* One step of the skinny arm: sixteen activation codes and sixteen weight codes, both decoded from
|
||||
* the same table as each dot consumes them. The reference's `sub += a[k] * b[k]`, k ascending: four
|
||||
* dot4, pairs in order, one accumulator. */
|
||||
__device__ __forceinline__ float dot_coded_step(const uint16_t* tab, const r3d_u32x4 a,
|
||||
const r3d_u32x4 c, float sub)
|
||||
{
|
||||
@@ -183,14 +151,11 @@ __device__ __forceinline__ float dot_coded_step(const uint16_t* tab, const r3d_u
|
||||
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. */
|
||||
/* One step's sixteen weight codes into the accumulator: four dot4, pairs decoded from the table as
|
||||
* each dot consumes them. Materialising the eight pairs in an array first lets the scheduler hoist
|
||||
* all sixteen table reads, keeping eight decoded pairs live instead of two, which spills against
|
||||
* the 128-register budget of a 256-thread block at four waves per SIMD. Pairs ascend 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)
|
||||
{
|
||||
@@ -211,8 +176,8 @@ __device__ __forceinline__ r3d_u32x4 ldc(const uint8_t* p) // 16 codes
|
||||
|
||||
__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. */
|
||||
/* q8_group's clamp, with q8_group's comparisons rather than fminf/fmaxf, which would replace a NaN
|
||||
* with the bound; the reference encodes a NaN activation as the format's NaN, not +-top. */
|
||||
__device__ __forceinline__ float clamp_top(float c)
|
||||
{
|
||||
if (c > kTopE4M3) c = kTopE4M3;
|
||||
@@ -220,16 +185,15 @@ __device__ __forceinline__ float clamp_top(float c)
|
||||
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.
|
||||
/* y[M,n] = gate(a @ b^T), with the quantiser. GROUP is at once the block's width in output columns,
|
||||
* the weight's K block and the quantiser's group: the op states one `group` key, and kb, nb and ng
|
||||
* derive from it. ACT is the gate, A8 the coded activation, NT the weight load's lowering, WIN the
|
||||
* skinny (direct-read) arm.
|
||||
*
|
||||
* 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. */
|
||||
* The tall arm stages the activation in LDS per K block, widened exactly to f16 pairs. A block
|
||||
* stages RP * GROUP values (512 bytes at every supported GROUP). All 32 lanes of a wave share one
|
||||
* m, so a wave reads its row's 16 values per step as one broadcast ds_read. The weight is not
|
||||
* staged: each lane streams two rows no other lane reads. */
|
||||
template <int GROUP, int ACT, bool A8, bool NT, bool WIN>
|
||||
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_kernel(
|
||||
const uint8_t* __restrict__ A, const float* __restrict__ AScale,
|
||||
@@ -237,8 +201,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
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 RP = kBlockThreads / GROUP; // rows per block
|
||||
constexpr int AP = GROUP / 2; // dwords per 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");
|
||||
|
||||
@@ -250,10 +214,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
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. */
|
||||
/* The block's decoder table, filled before any lane reads it: 128 dwords, one per pair of
|
||||
* codes, 128 arithmetic decodes per block. */
|
||||
build_e4m3_table(s_tab, tid);
|
||||
group_barrier();
|
||||
|
||||
@@ -263,15 +225,15 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
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
|
||||
/* 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. */
|
||||
/* b_scale is [ceil(N/group)][ceil(K/group)] (make_scales uses rblk = group), so a row's scale
|
||||
* row is its row index divided by 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;
|
||||
@@ -280,23 +242,19 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
|
||||
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. */
|
||||
/* One scale block per iteration, `nkb` of them: stage the block's activation, walk its k with
|
||||
* two chains, apply its two scales at the end. The launcher requires K % GROUP == 0, so every
|
||||
* block is whole and staging has no tail. */
|
||||
/* The skinny arm's activation 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. */
|
||||
/* Staging and its barrier belong to the tall arm. At the skinny height (M <= 8, at most
|
||||
* 16 KiB of activation at the band's K) all 48 column groups read the same activation
|
||||
* slice, so it stays in L1 and staging would only add a barrier per k-block. */
|
||||
if constexpr (!WIN) {
|
||||
constexpr int kUnit = 8; // codes (fp8a8) or elements (bf16) a unit
|
||||
constexpr int kUnit = 8; // codes (fp8a8) or elements (bf16) per unit
|
||||
constexpr int nu = GROUP / kUnit;
|
||||
#pragma unroll
|
||||
for (int u = (int)tid; u < RP * nu; u += kBlockThreads) {
|
||||
@@ -312,8 +270,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
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). */
|
||||
/* Cast to the element pointer first: the row and k offsets are bf16 element
|
||||
* offsets. */
|
||||
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);
|
||||
@@ -327,49 +285,29 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
}
|
||||
|
||||
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.
|
||||
/* The two chains, gate into `sub_g` and up into `sub_u`, each k ascending: the unfused
|
||||
* pair's two calls, each with that call's bracketing.
|
||||
*
|
||||
* 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. */
|
||||
* The skinny arm runs the chains one after the other rather than interleaved: holding
|
||||
* both streams' windows live (64 registers of loads, on top of everything else) spills at
|
||||
* 256 threads (four waves per SIMD, 128 registers per lane), while one chain's window is
|
||||
* 32 registers and does not. */
|
||||
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
|
||||
/* The skinny arm, M <= 8 (selected by `R3D_GT_G`): load the codes, decode them from
|
||||
* the block's table and multiply, with no shared memory between load and dot and no
|
||||
* barrier in the k-loop. Each step loads 16 bytes of activation and 16 of weight;
|
||||
* prefetching two steps ahead keeps loads in flight, where the tall arm relies on
|
||||
* occupancy (32 waves per CU). */
|
||||
constexpr int kNS = GROUP / kStep; // steps per block
|
||||
constexpr int kD = 2; // loads in flight per chain
|
||||
auto chain = [&](const uint8_t* w, float sub) {
|
||||
auto ld = [&](int st) {
|
||||
return ldc<NT>(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. */
|
||||
/* Named registers, not an array: an array indexed across iterations, even with a
|
||||
* constant trip count and unrolling, is placed in private (scratch) memory. Two
|
||||
* named 16-byte registers, prefetched two steps ahead, keep the frame at zero. */
|
||||
r3d_u32x4 c0 = ld(0), c1 = ld(1);
|
||||
#pragma unroll
|
||||
for (int st = 0; st < kNS; st += kD) {
|
||||
@@ -387,25 +325,19 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
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. */
|
||||
/* The tall arm: one 16-code step per iteration, both streams in the same iteration.
|
||||
* At M >= 9 the grid is 48 x M/2 blocks and occupancy feeds the stream (109 registers
|
||||
* per lane, four waves per SIMD, 32 waves per CU). A load window would cost 32
|
||||
* registers per lane here, and at M = 64 it 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. */
|
||||
/* Unroll depth is a register decision. At group = 32 the block is two steps wide, so
|
||||
* `unroll 2` is a full unroll: the scheduler hoists all 32 table reads of both chains
|
||||
* above the dots and the arm spills at 128 registers. group = 32 therefore stays a
|
||||
* one-step loop; group >= 64 unrolls by 2 without spilling. */
|
||||
/* Do not materialise the eight decoded pairs into an array on the way to the dot:
|
||||
* that form miscomputes on this arm (rel_l2 6.6e-01 at M = 7, NaN at M = 64) although
|
||||
* the table itself is exact. Keep the decode inline. */
|
||||
auto step_body = [&](int k) {
|
||||
const r3d_u32x4 a0 = lds_a(ap + k / 2);
|
||||
const r3d_u32x4 a1 = lds_a(ap + k / 2 + 4);
|
||||
@@ -421,9 +353,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
}
|
||||
}
|
||||
if constexpr (!WIN)
|
||||
group_barrier(); // the next block's stage must not race this one's reads
|
||||
group_barrier(); // the next block's stage must not race these reads
|
||||
|
||||
/* The two finished sub-sums, each scaled once, in libref's parentheses. */
|
||||
/* The two 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]);
|
||||
@@ -437,8 +369,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
|
||||
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. */
|
||||
/* A column past n or a row past M contributes 0.0f to the amax and is not stored, as in
|
||||
* quant_act_fp8 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
|
||||
@@ -449,9 +381,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
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. */
|
||||
/* One store per (row, group): the group's WPG waves hold the same max and the first writes it.
|
||||
* `scale` is dense (the launcher takes no pitch for it): `ng` scales per row, indexed by the
|
||||
* block's group. */
|
||||
if (keep && lane == 0 && (wave % WPG) == 0) S[(size_t)m * ng + gidx] = sc;
|
||||
|
||||
if (keep) {
|
||||
@@ -469,19 +401,18 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
|
||||
* 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
|
||||
* q [M][n] E4M3 codes, `q_ld` elements per row (0 = n)
|
||||
* scale [M][ceil(n/group)] f32, dense (no pitch is taken)
|
||||
* out_bf16 [M][n] bf16, `y_ld` elements per row (0 = n), optional: 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.
|
||||
* `group` is at once the weight's K block, the weight's row block and the output quantiser's group,
|
||||
* as 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;
|
||||
* needing no arena 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. */
|
||||
* Returns 0, -1 a null pointer, -2 an unsupported shape, -3 an unreadable pitch, -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,
|
||||
@@ -510,14 +441,12 @@ extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale
|
||||
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.
|
||||
/* fp8a8 at M <= 8 takes the skinny (direct-read) arm, everything else the staged arm.
|
||||
*
|
||||
* 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%. */
|
||||
* The threshold is a tunable chosen for decode (M = 1) and draft verify (M <= 8). With the table
|
||||
* decoder in both arms, at N=12288 K=2048 group=128 the skinny arm takes 402 us against 754 at
|
||||
* M = 8 and 955 against 1030 at M = 16, so the crossover lies above 16 (M = 9..15 unmeasured);
|
||||
* raising the threshold to 16 would gain about 7% for a prefill of 9..16 rows. */
|
||||
#define R3D_GT_G(G, A, A8, NTV) \
|
||||
do { \
|
||||
if (A8 && M <= 8) R3D_GT_W(G, A, A8, NTV, true); \
|
||||
@@ -546,10 +475,9 @@ extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale
|
||||
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. */
|
||||
/* The entry without a scale dtype reads bf16, the only form this op's shape hook states. A caller
|
||||
* with an f32 scale plane (the `fp8a8f32` reading of the unfused GEMM) uses `_ex` with RAD_F32;
|
||||
* bf16 widens exactly, so the two agree bit for 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,
|
||||
@@ -562,9 +490,9 @@ extern "C" int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, l
|
||||
/* ============================================================== 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,
|
||||
* M, N, K, group, dtype, act (libref's pGemmQGated/oGemmQGated: `act` and `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. */
|
||||
* the shim reads the coded activation from 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)
|
||||
@@ -586,10 +514,9 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* The activation: E4M3 codes with a per-(row, group) f32 scale (fp8a8, the scheme every band
|
||||
* states), or bf16 with no scale (fp8a16, which the shape hook declines, so no band reaches it;
|
||||
* the launcher supports it and the shim accepts it). E5M2 has no decoder here. */
|
||||
const bool a8 = AS != nullptr;
|
||||
if (a8) {
|
||||
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
|
||||
@@ -597,16 +524,14 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
|
||||
} 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. */
|
||||
/* b_scale is bf16 (the hook's `o.t(RAD_BF16, {nb, kb})`, the container's `weight_scale_inv`).
|
||||
* f32 is also accepted; the widening is exact, so both give the same output. */
|
||||
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. */
|
||||
/* `act` is required by the schema (P_STR, not P_STRO), because an implementation may compile
|
||||
* only one gate. libref defaults it to -1 and refuses that; so does this shim, with no integer
|
||||
* `mode` fallback. */
|
||||
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);
|
||||
|
||||
@@ -615,20 +540,18 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* Rows come from `q`, never from the `M` parameter (the band's upper bound). libref reads
|
||||
* numel(q) / n, which on a plane with pitch > n counts the padding, so the shape's row count
|
||||
* clamps it. Dense planes give 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. */
|
||||
/* The group: the weight's K block, row block and the quantiser's group, from the op's one key.
|
||||
* The reference would use n for the quantiser alone when group > n; this kernel reads one
|
||||
* width, so such a group is refused. */
|
||||
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);
|
||||
@@ -645,14 +568,12 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
|
||||
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". */
|
||||
/* `yrows` is only meaningful when the plane exists: `r3d_rows_pitch` leaves it zero for a null
|
||||
* operand, and an absent optional output is a null operand (r3d_args.h). */
|
||||
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. */
|
||||
/* The scale planes take no pitch argument, so they must be dense, and `scale` must hold `ng`
|
||||
* scales per 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);
|
||||
@@ -663,9 +584,8 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
|
||||
|
||||
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. */
|
||||
/* No split-K: the epilogue needs the finished row (its bf16 narrowing, the gate's partner
|
||||
* column, the group's amax), so sk > 1 is refused. */
|
||||
if (c.sk > 1) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
const int e = r3d_gemm_nt_q_gated_ex(
|
||||
|
||||
+241
-461
File diff suppressed because it is too large.
Load diff
+49
-53
@@ -1,45 +1,44 @@
|
||||
/* 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:
|
||||
* The grids (libref's descriptions): int8 activations in quant_act_i8's step order with an f32
|
||||
* scale per row, against signed weight codes (I4 two per byte, or I8) with one f16 scale per
|
||||
* (row, 128 of K). No zero point: the dequant is code times scale, so there is no a_sum and no
|
||||
* bias. The group sub-sum is formed on the integer grid and scaled once per group, in 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.
|
||||
* Each product is |a * code| <= 127 * 7 (w4a8) or 127 * 127 (w8a8), and a group's 128 of them sum
|
||||
* to at most 113,792 (w4a8) or 2,064,512 (w8a8), both under 2^24, so the lane partial and the pair
|
||||
* fold are exact and the group terms enter the accumulator in the reference's ascending order. The
|
||||
* codes widen to f16 by sign extension, 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.
|
||||
* In the activation's step order the middle two dwords of each 16-byte step are exchanged, so the
|
||||
* staging reads through the same position map as the w2a8 arm. Weight codes are plain row-major.
|
||||
*
|
||||
* ---- 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.
|
||||
* One workgroup serves kWaves weight rows, one per wave. Lane l owns activation row l & (MT-1) and
|
||||
* k-lane l / MT. A chunk is 2048 / MT codes, a multiple of the 128 group at every MT, so it holds
|
||||
* CG = 16 / MT whole groups and a group's scale is one read. A lane's 64 codes are 32 bytes at I4
|
||||
* (two 16-byte loads) and 64 at I8 (four). Lanes l and l^MT hold the two halves of one group and
|
||||
* fold with one shfl_xor(MT); the group's term, scaled by the activation's row scale and the
|
||||
* weight's group scale, goes to shared memory, 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.
|
||||
* M > 16 belongs to the tiled row, where the w2a8 arm serves the 2- and 4-bit container grids; the
|
||||
* 8-bit grid at prefill heights is declared outside 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.
|
||||
* The shim refuses every structural violation: 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. No data value is refused;
|
||||
* neither grid has a reserved value.
|
||||
*/
|
||||
|
||||
#include "r3d_common.h"
|
||||
@@ -56,18 +55,17 @@ 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. */
|
||||
/* Column c sits at byte step_pos(c): bits 2 and 3 of c swapped, a self-inverse map. On the
|
||||
* dword index it is a swap of bits 0 and 1, i.e. the middle two dwords of a 16-byte step
|
||||
* exchanged, with each dword's four columns left contiguous. */
|
||||
__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. */
|
||||
/* The LDS swizzle, at the tile's access granularity: a quad of four f16 (two dwords) moved as one
|
||||
* 8-byte word. Quads are numbered q = r*(CHUNK/4) + c; 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. */
|
||||
@@ -78,11 +76,10 @@ __device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t
|
||||
(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. */
|
||||
/* Four signed int4 codes (two bytes, the low code in the low nibble) -> two f16x2 dwords. Exact:
|
||||
* the sign extension yields an integer in -8..7. A nibble n is the value (n & 7) - (n & 8), so
|
||||
* 0..7 pass through and 8..15 map to -8..-1. The gfx1102 backend folds the bias-8 form
|
||||
* ((n ^ 8) - 8) to n ^ 16 once it has proven the nibble range, so the sign stays a bit term. */
|
||||
__device__ __forceinline__ void i4x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi)
|
||||
{
|
||||
const uint32_t n0 = w & 0xFu;
|
||||
@@ -144,8 +141,8 @@ gemm_inta8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa,
|
||||
|
||||
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. */
|
||||
/* Stage the chunk's activation rows, widened and step-unpermuted. Cells are four codes:
|
||||
* MT * CHUNK/4 = 512 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;
|
||||
@@ -160,17 +157,17 @@ gemm_inta8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa,
|
||||
__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. */
|
||||
/* 64 codes: 32 bytes at I4, 64 at I8, starting at code kl * 64 of the chunk. 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. */
|
||||
/* One value per quad: at I4 the two-byte window as a 16-bit element, at I8 the dword.
|
||||
* The I4 window is read as a 16-bit element at its own address, because 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];
|
||||
@@ -208,14 +205,13 @@ gemm_inta8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa,
|
||||
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. */
|
||||
/* One slot per (row, group-in-chunk); MT*CG is 16 at every MT. Both half-lanes of
|
||||
* a group write the same folded value. */
|
||||
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. */
|
||||
/* The chunk's groups in ascending g, into the row's owner lane: f32 adds are not
|
||||
* associative and the reference walks g ascending. */
|
||||
if (live && kl == 0) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CG; ++j)
|
||||
@@ -309,9 +305,9 @@ extern "C" int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale
|
||||
|
||||
/* ================================================================== 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).
|
||||
* gemm_nt_q's slots: 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)
|
||||
@@ -359,7 +355,7 @@ extern "C" int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s)
|
||||
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 long long bbr = r3d_row_pitch(B) / 2; /* I4 pitch is in elements, two per 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);
|
||||
|
||||
+95
-113
@@ -7,69 +7,61 @@
|
||||
*
|
||||
* ---- 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.
|
||||
* 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] beside 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, as the reference does.
|
||||
*
|
||||
* The fold this kernel runs, per 32-block:
|
||||
* 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.
|
||||
* 1. the code for element k becomes e4m3(mag): all eight e2m1 magnitudes
|
||||
* {0, .5, 1, 1.5, 2, 3, 4, 6} are e4m3 grid points, so this is exact. The unpack is a
|
||||
* 4-bit lookup on the nibble through the e4m3 bytes {0x00, 0x30, 0x38, 0x3C, 0x40, 0x44,
|
||||
* 0x48, 0x4C}, with the code's sign bit moved to the byte's sign bit.
|
||||
* 2. the products run on dot2_f16x2. A code product is at most 6 x 448 = 2688, inside f16's
|
||||
* range (65504), and an eight-term partial is under 21504.
|
||||
* 3. the block factor 2^(e-127) is applied in the epilogue: the f32 32-block partial is
|
||||
* multiplied by it (a power of two, exact short of under/overflow) and added to the running
|
||||
* f32 sum. One multiply and one add per block per output, 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 roundings are the activation-scale fold at staging (fold_pair, f16), the dot's fused
|
||||
* rounding, and the store.
|
||||
*
|
||||
* 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 RDNA4 sibling folds the e8 into a d-indexed table row because its WMMA path needs one scale
|
||||
* per row; the dot2 path here applies it per block in the epilogue, so the table is the eight
|
||||
* fixed magnitude bytes.
|
||||
*
|
||||
* ---- 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:
|
||||
* A 128x128 tile, 8x8 f32 accumulators per lane, k ascending in 32-code chunks. A chunk is one OCP
|
||||
* 32-block: the e8 byte of each tile column is staged through LDS, and the chunk's partials flush
|
||||
* at its 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.
|
||||
* activation stages as in the fp8a8 tiled row: E4M3 through the LDS table, with the f32 scale per
|
||||
* (row, 128 of K) folded in at staging. 32 divides 128, so a chunk never straddles a group.
|
||||
*
|
||||
* ---- 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.
|
||||
* One wave per weight row, as in the w2a8 row: lane l owns row m = l % MT and k-lane kl = l / MT,
|
||||
* a chunk is CHUNK = 2048/MT codes, and each lane takes 64 of them, the chunk's 32-blocks 2*kl and
|
||||
* 2*kl+1. Each lane sums its two blocks in k and scales each by its e8; one shfl_xor pair puts the
|
||||
* group's four block terms in ascending order in LDS, and the kl == 0 lane adds them to the
|
||||
* accumulator in that order. This is 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.
|
||||
* The shim refuses every structural violation: the dtypes of all seven operands (codes as
|
||||
* fp4_e2m1 or raw bytes, the e8 plane as e8m0 or u8, `b_ref` the e8 plane again, 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 and the band's M. A reserved e8 (0, 255) is refused with E_INVAL where the
|
||||
* host can read the plane: the shim scans it once per (pointer, size) pair. A plane the host
|
||||
* cannot see is not scanned; the kernel gives reserved values the scale zero, so the output stays
|
||||
* finite.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
@@ -90,26 +82,24 @@ 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 kTM = 128; /* rows per tile */
|
||||
constexpr int kTN = 128; /* columns per tile */
|
||||
constexpr int kKC = 32; /* k per 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. */
|
||||
/* The eight e2m1 magnitudes as e4m3 bytes, each exact: 0, .5, 1, 1.5 in the low word, 2, 3, 4, 6
|
||||
* in the high. */
|
||||
#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. */
|
||||
* bytes in k order (word 0 = elements 0..3, word 1 = 4..7). Even and odd nibbles each go through
|
||||
* the magnitude bytes with 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. */
|
||||
__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 */
|
||||
@@ -122,9 +112,9 @@ __device__ __forceinline__ void mxfp4_unpack8(uint32_t wv, uint32_t* lo, uint32_
|
||||
*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. */
|
||||
/* The e8m0 factor: 2^(e-127). The reserved values (e = 0 the format's zero, e = 255 its NaN) take
|
||||
* the scale zero, so such a block computes zero and stays finite; the shim refuses such a plane
|
||||
* where it can read it. */
|
||||
__device__ __forceinline__ float e8_scale(uint8_t e)
|
||||
{
|
||||
return (e == 0 || e == 255) ? 0.0f : ldexpf(1.0f, (int)e - 127);
|
||||
@@ -138,7 +128,7 @@ __device__ __forceinline__ void e4m3x4_to_f16x2(const uint16_t* tbl, uint32_t w,
|
||||
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
|
||||
/* 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)
|
||||
{
|
||||
@@ -186,13 +176,11 @@ struct MxWQ {
|
||||
};
|
||||
|
||||
/*
|
||||
* 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.
|
||||
* The tile: 128 rows x 128 columns of y, 256 threads, eight waves, 8x8 outputs per lane (64 f32
|
||||
* accumulators for the 32-block partials and 64 for the running sum), grid (N/kTN) x ceil(M/kTM).
|
||||
* k is walked in chunks of 32. The activation's E4M3 codes decode through the block's table and
|
||||
* are staged as f16 with their scale folded in. The weight's e2m1 nibbles unpack to e4m3 and are
|
||||
* staged as f16 without the block scale, which is applied to the partials at the chunk's end.
|
||||
*/
|
||||
template <int NT>
|
||||
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
|
||||
@@ -242,12 +230,12 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
|
||||
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. */
|
||||
/* The column's e8, written even past N (as 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. */
|
||||
/* 32 codes, 16 bytes, one load, aligned because k0 is a multiple of 32 and the
|
||||
* row pitch a multiple of 16 bytes. */
|
||||
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 };
|
||||
@@ -269,9 +257,8 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
|
||||
}
|
||||
__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. */
|
||||
/* The chunk's e8 for the lane's eight columns, in registers for the flush. sE8 holds
|
||||
* this tile's 128 columns, so the index is tile-local. */
|
||||
float e8s[8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) e8s[j] = e8_scale(sE8[cg * 8 + j]);
|
||||
@@ -290,8 +277,8 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
|
||||
#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. */
|
||||
/* The 32-block boundary: scale the partial by the block's factor, add it to the running
|
||||
* sum in ascending k, reset the partial. */
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i)
|
||||
#pragma unroll
|
||||
@@ -325,9 +312,9 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
|
||||
|
||||
/* ================================================================== 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. */
|
||||
/* The LDS swizzle, at the tile's access granularity: a quad of four codes (two dwords) moved as one
|
||||
* 8-byte word. Quads are numbered q = r*(CHUNK/4) + c; 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 <int MT>
|
||||
@@ -339,7 +326,7 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
|
||||
{
|
||||
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 */
|
||||
constexpr int BPR = (2048 / MT) / kMX; /* 32-blocks per chunk row: 64/MT */
|
||||
|
||||
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
|
||||
__shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/2 f16, swizzled */
|
||||
@@ -361,8 +348,8 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
|
||||
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. */
|
||||
* MT * CHUNK/4 = 512 at every MT, two per thread. A cell's four codes sit in one 128-wide
|
||||
* scale group, so one scale per 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;
|
||||
@@ -406,8 +393,8 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
* four blocks (kl even the lower two, kl odd the upper two), so one exchange puts
|
||||
* them 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]);
|
||||
@@ -419,8 +406,8 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
|
||||
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. */
|
||||
/* One slot per (row, 32-block-in-chunk); MT*BPR is 64 at every MT. Both half-lanes
|
||||
* of a group write the same four values. */
|
||||
const int j = kl >> 1;
|
||||
const int bb = warp * 64 + m * BPR + 4 * j;
|
||||
sB[bb + 0] = t0;
|
||||
@@ -429,9 +416,8 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
|
||||
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. */
|
||||
/* The chunk's block terms in ascending block order, into the row's owner lane: f32 adds
|
||||
* are not associative and the reference walks k ascending. */
|
||||
if (live && kl == 0) {
|
||||
#pragma unroll
|
||||
for (int bl = 0; bl < BPR; ++bl)
|
||||
@@ -467,7 +453,7 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_sc
|
||||
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 (a_ld % 4) return -3; /* four codes per dword, staged whole */
|
||||
if (y_ld < N) return -3;
|
||||
if (!e8_row) e8_row = K / kMX;
|
||||
if (e8_row < K / kMX) return -3;
|
||||
@@ -548,17 +534,16 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, l
|
||||
|
||||
/* ================================================================== 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).
|
||||
* gemm_nt_q's slots: 0 a (E4M3), 1 a_scale (f32, one per (row, 128 of K)), 2 b (the e2m1 codes,
|
||||
* as fp4_e2m1 or raw u8 bytes, two per 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. */
|
||||
/* The reserved-e8 scan, once per (pointer, size) pair for the process's life: the plane is a
|
||||
* weight at a stable address. The host must be able to read the plane (the mapped tier's
|
||||
* placement); a plane it cannot see is not scanned, and the kernel's e8 guard handles reserved
|
||||
* values there. */
|
||||
struct E8ScanKey { const void* p; long long n; };
|
||||
static bool e8_scan_once(const void* p, long long n)
|
||||
{
|
||||
@@ -591,20 +576,20 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* `b_ref` is the reference's per-row exponent, derived from `b_scale`. It changes no product,
|
||||
* so with an e2m1 weight only its dtype is checked. */
|
||||
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 (B->dtype != RAD_FP4E2M1 && B->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e2m1, 2 per 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. */
|
||||
/* The `group` key names the band; the kernel's blocks (128 for the activation scale, 32 for
|
||||
* the weight's e8) are fixed by the format, 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);
|
||||
|
||||
@@ -669,14 +654,13 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* The band's keys from the schema: N, K, group. A band without N or K takes them from the
|
||||
* codes plane. */
|
||||
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. */
|
||||
/* Without a K key, K comes from the codes plane: [N, K] of fp4_e2m1, [N, K/2] of raw bytes.
|
||||
* The `group` key is not checked (see the m16 shim). */
|
||||
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);
|
||||
@@ -686,10 +670,8 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
if (ap % 8) return R3D_NO(RAD_E_STRIDE); /* 8-byte code loads, 8 codes per lane */
|
||||
/* The step's M is the activation's row count; the band key M is only the upper bound. */
|
||||
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 */
|
||||
@@ -706,7 +688,7 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
|
||||
|
||||
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. */
|
||||
/* The codes plane's pitch in bytes: fp4_e2m1 counts elements, two per 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);
|
||||
|
||||
+124
-180
@@ -1,112 +1,84 @@
|
||||
/* 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.
|
||||
* integer zero per (row, group of K), an int8 activation with one f32 scale per row, and the int8
|
||||
* code sums `a_sum` that remove the zero. 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.
|
||||
* MiniCPM5-2B's `output.weight` is N=130560, K=2048, group=128, dtype=w2a8, stored as the
|
||||
* container's joined `rad.planes` operand: a scale plane and a zero plane behind one operand
|
||||
* (b_scale). libref's `gemm_q_shape` declines w2a8, so kbench has no case for it; the row is
|
||||
* verified by a driver that builds the joined operand with `rad_planes_relayout` and compares every
|
||||
* element against `ref_gemm_nt_q`. libref's host row (`gemm_zp`) costs 135 GFLOP of CPU work per
|
||||
* token, and the engine refuses a placement no loaded library can read, so this row needs
|
||||
* `r3d_layout_gemm_nt_q_w2a8` below: it describes the container's bytes (RadLayoutFn in
|
||||
* rad_abi.h) and does 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:
|
||||
* gemm_zp's 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
|
||||
* 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.
|
||||
* `a_sum` is per row and per group, group-major. `sa` is one f32 per row (ZP_I8_ROW: quant_act_i8
|
||||
* scales a whole row, not a group). The parentheses in `(sub * sa) * sb` are the reference's order.
|
||||
*
|
||||
* 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.
|
||||
* i8_step_pos(c) = (c & ~12) | ((c & 4) << 1) | ((c & 8) >> 1), bits 2 and 3 of c swapped, a
|
||||
* self-inverse map. On the dword index that is a swap of bits 0 and 1, so a dword's four columns
|
||||
* stay contiguous: staging reads a's dwords in permuted order, one 4-byte load per four codes.
|
||||
*
|
||||
* `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.
|
||||
* Exactness. In exact f32 arithmetic `is` (integer partials under 2^24) would be exact and the
|
||||
* float steps follow the reference's order. The dot instruction is not that exact (below), so
|
||||
* 0.1-0.2% of outputs land one bf16 ulp off the reference: rel_l2 5.0e-3 at the band, no
|
||||
* non-finite values. The row is not bit-exact, and its row-table text says so.
|
||||
*
|
||||
* ---- 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.
|
||||
* This ISA has no int8 dot: `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a` and the
|
||||
* matrix ops `__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are undeclared in AMD clang 24.0.0git
|
||||
* for gfx1102. The codes therefore widen to f16 and the dot runs on dot2_f16x2. v_fdot2_f32_f16
|
||||
* carries about 22 bits of mantissa on integer operands, not 24, so integer partials pushed
|
||||
* through it are inexact once they reach about 2^20. The bias choice is explained at u2x4_biased.
|
||||
*
|
||||
* The widening uses the fact that 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. The dot then returns
|
||||
* is' = SUM a[k]*(128 + q[k]) = is + 128*SUM a, and SUM a over the group is a_sum[g*mpad + m],
|
||||
* which the op already carries for the zero. 128 * a_sum is exact (a power-of-two scale of an
|
||||
* integer-valued f32), so is = is' - 128*a_sum is exact and the reference's
|
||||
* sub = (float)is - (float)z*a_sum follows unchanged, at one f32 subtraction per (m, group).
|
||||
*
|
||||
* The row is not memory-bound: its 66.8 MB of codes have a streaming floor near 0.41 ms, and the
|
||||
* cost is in the loop (the group-term plane and the two barriers per chunk).
|
||||
*
|
||||
* ---- 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.
|
||||
* One warp per weight row n; a block of 8 waves covers 8 rows. MT is the power of two covering 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, which keeps the block resident at
|
||||
* M=16. A chunk holds CHUNK/128 = 16/MT groups. Each lane takes 64 codes per chunk: one 16-byte
|
||||
* load of codes (U2 is four codes per byte), 32 dwords of activation from LDS and 32 dot2 in 16
|
||||
* dot4_f16x4. 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), folded with one shfl_xor.
|
||||
*
|
||||
* 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.
|
||||
* Group indices ascend with the chunk index, and within a chunk the row's owner lane adds the
|
||||
* chunk's group terms in ascending g, so the accumulation is the reference's ascending g loop.
|
||||
* Reassociating the g sum would change the result; no lane does.
|
||||
*
|
||||
* 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.
|
||||
* LDS is accessed one quad (two dwords, 8 bytes) at a time, swizzled by `p_ix` below; unswizzled,
|
||||
* the wavefront's 32 quads for one u would 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.
|
||||
* accepts, each named at its site: M > 16 (the tile is 16 rows and mpad is the reference's 16-row
|
||||
* pad; the prefill vocab projection is `logits_gemm`, a tiled bf16 row), and a zero plane stored
|
||||
* sub-byte (U2/U4/U5), because the kernel reads a zero one byte at a time; that would need the
|
||||
* bit-extract path (`rad_load_bits(zb, bits, g)`). w2a8's practical form, and this container's,
|
||||
* is U8.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
@@ -127,12 +99,10 @@ constexpr int kTileQuads = 512; /* MT * CHUNK/4, constant over MT: 512
|
||||
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)
|
||||
/* Column c sits at byte step_pos(c): bits 2 and 3 of c swapped, a self-inverse map. On the dword
|
||||
* index it is a swap of bits 0 and 1 (the middle two dwords of a 16-byte step exchanged), so
|
||||
* dword d starts at byte dword_pos(d). Not 4 * step_pos(d), which swaps the wrong pair of bits. */
|
||||
[[maybe_unused]] __device__ __forceinline__ int64_t step_pos(int64_t c)
|
||||
{
|
||||
return (c & ~(int64_t)12) | ((c & 4) << 1) | ((c & 8) >> 1);
|
||||
}
|
||||
@@ -141,14 +111,13 @@ __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. */
|
||||
/* The LDS swizzle, at the tile's access granularity: a quad of four codes (two dwords) moved as one
|
||||
* 8-byte word. Quads are numbered q = r*(CHUNK/4) + c; p_ix XORs q's low four bits with bits 4..7,
|
||||
* a bijection on 16-quad groups and 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 an
|
||||
* 8-byte access spanning two banks, 32 banks with no conflict. The swizzle works on quad indices
|
||||
* so the two dwords of a quad stay adjacent; XORing bits 5..9 of the dword index would 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. */
|
||||
@@ -159,17 +128,15 @@ __device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t
|
||||
(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.
|
||||
/* 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.
|
||||
* The dot returns is + 128 * (the activation's group sum), which the epilogue removes with 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. */
|
||||
* The bias sets the magnitude of the dot's partial sums: a * (B + q) is up to 128 * B, and a lane's
|
||||
* 64 of them reach 64 * 128 * (B + 3), about 2^23 at B = 1024 and 2^20 at B = 128. The dot unit
|
||||
* keeps about 22 bits of mantissa on integers, so its error grows with the magnitude: over 262144
|
||||
* sampled dots (probe below), the worst error is 1/8 at B = 1024 and 1/64 at B = 128. 128 is the
|
||||
* largest power of two that keeps a lane's partial sum under 2^21. */
|
||||
__device__ __forceinline__ void u2x4_biased(uint32_t w, uint32_t& lo, uint32_t& hi)
|
||||
{
|
||||
lo = 0x58005800u + ((w & 3u) << 3) + (((w >> 2) & 3u) << 19);
|
||||
@@ -188,10 +155,10 @@ gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int
|
||||
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. */
|
||||
/* The tile: one quad of four codes (two f16x2 dwords) per slot, typed as the quad the staging
|
||||
* writes and the dot reads. It is a `uint2[]`, not a `uint32_t[]` written through a vector
|
||||
* pointer: an f32 tile written through `*(uint4*)&sA[]` at -O2 read back 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];
|
||||
@@ -199,12 +166,10 @@ gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int
|
||||
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. */
|
||||
/* A wavefront past the last row skips the dot but still stages its share of the block-wide
|
||||
* tile. Only a block whose eight rows are all past N returns early: that test is block-uniform
|
||||
* and cannot strand a barrier, whereas a per-row return would leave tile rows unstaged. The
|
||||
* store is guarded by `live`. */
|
||||
const bool live = n < N;
|
||||
if ((int)blockIdx.x * kWaves >= N) return;
|
||||
|
||||
@@ -219,8 +184,8 @@ gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int
|
||||
|
||||
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. */
|
||||
/* Stage the chunk's activation rows, widened and step-unpermuted. Cells are four codes:
|
||||
* MT * CHUNK/4 = 512 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;
|
||||
@@ -261,26 +226,17 @@ gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int
|
||||
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. */
|
||||
/* One slot per (row, group-in-chunk); MT*CG is 16 at every MT (64 bytes). Both
|
||||
* half-lanes of a group write the same folded value. */
|
||||
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. */
|
||||
/* Groups ch*CG + j, j ascending, into the row's owner lane: f32 adds are not associative
|
||||
* and the reference walks g ascending. This gather is the only cross-k-lane step; a
|
||||
* barrier and a few 64-byte LDS reads are 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. */
|
||||
/* Group ch*CG + j comes from k-lanes 2j and 2j+1, already folded. */
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CG; ++j)
|
||||
if (m < M) acc += sT[warp * 16 + m * CG + j];
|
||||
@@ -297,25 +253,21 @@ int mt_for(int M) { return M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : k
|
||||
|
||||
/* ================================================================== 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.
|
||||
* Codes: 0, -1 a required pointer is null, -2 an unsupported shape, -3 an unreadable pitch, -4 HIP.
|
||||
* `nt` is accepted for signature uniformity and ignored: the work is one warp per weight row.
|
||||
*
|
||||
* `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. */
|
||||
* `b_scale` is the joined operand's base. The launcher finds the two planes through its header
|
||||
* (rad_planes.h's rad_planes_find) and passes each plane's base and row pitch in bytes, so the
|
||||
* kernel reads the container's bytes in place. */
|
||||
|
||||
/* 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. */
|
||||
/* A probe of the dot's exactness: one 64-code sample per lane, the f32 the dot produces beside the
|
||||
* exact integer. The test driver runs it as `dot [n]`; it is what sizes the bias. Two extern "C"
|
||||
* symbols, no row, nothing 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;
|
||||
@@ -353,8 +305,8 @@ extern "C" int r3d_gemm_nt_q_w2a8(long a, long a_scale, long b, long b_scale, lo
|
||||
(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 (M > kMTMax) return -2; /* as the row's C_LE("M", 16) */
|
||||
if (group != kGroup) return -2; /* 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);
|
||||
@@ -364,7 +316,7 @@ extern "C" int r3d_gemm_nt_q_w2a8(long a, long a_scale, long b, long b_scale, lo
|
||||
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 (a_ld % 4) return -3; /* four codes per 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);
|
||||
@@ -402,8 +354,8 @@ extern "C" int r3d_gemm_nt_q_w2a8(long a, long a_scale, long b, long b_scale, lo
|
||||
/* ================================================================== 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). */
|
||||
* 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);
|
||||
@@ -434,16 +386,13 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
|
||||
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 (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); /* declined; see the header */
|
||||
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 (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); /* step order: 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);
|
||||
@@ -459,8 +408,8 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
return R3D_NO(RAD_E_DTYPE); /* declined: a sub-byte zero plane needs the bit-extract
|
||||
* path (rad_load_bits). 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);
|
||||
|
||||
@@ -469,8 +418,7 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
|
||||
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. */
|
||||
/* Launcher codes (null, shape, pitch, HIP) to RAD codes, as in the gated row. */
|
||||
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);
|
||||
@@ -478,8 +426,8 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
|
||||
|
||||
/* ================================================================== 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:
|
||||
* One of libr3d's few layout hooks, 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";
|
||||
@@ -493,17 +441,14 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
|
||||
*
|
||||
* 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.
|
||||
* declines a sub-byte zero at its site). The answer is rad_planes.h's: the tag "rad.planes", the
|
||||
* dtype the first plane's, the shape the byte count. The hook moves no bytes.
|
||||
*/
|
||||
/* 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. */
|
||||
/* The writer for the joined operand this hook names: codes, scale and zero as one `rad.planes`
|
||||
* weight, assembled by rad_planes_relayout (header, entries, each plane's rows, copied). A layout
|
||||
* query answering RAD_OK promises "out describes the stored form, and relayout will produce it"
|
||||
* (rad_abi.h). Only a weight with no hook can be read in place, so a joined weight is placed in
|
||||
* VRAM while a plain one can stay on the mapped tier. No code is transformed. */
|
||||
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,
|
||||
@@ -514,9 +459,9 @@ extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int opera
|
||||
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. */
|
||||
/* Under RAD_R3D_TRACE, prints each layout query (operand, band dtype, planes offered) and its
|
||||
* return code. Otherwise a model that fails to load reports only that two rows want one weight in
|
||||
* two forms. */
|
||||
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,
|
||||
@@ -530,11 +475,10 @@ extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand
|
||||
{
|
||||
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. */
|
||||
/* The (scale, zero) pair joined on operand 3 describes the container, not the code width, and
|
||||
* every row that reads one weight must answer with one form. So both packed grids pass here;
|
||||
* the code width is checked by each shim (gemm_nt_q_w2a8_m16 reads U2 only,
|
||||
* gemm_nt_q_w2a8_tiled reads U2 and U4). */
|
||||
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);
|
||||
@@ -551,8 +495,8 @@ extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand
|
||||
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. */
|
||||
/* The codes plane is not part of this operand: 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; }
|
||||
|
||||
+7
-9
@@ -1,15 +1,13 @@
|
||||
/* r3d_launch.h -- the two lines a libr3d unit needs to launch a kernel.
|
||||
/* r3d_launch.h -- kernel launch macros for libr3d units.
|
||||
*
|
||||
* 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_KLAUNCH is the triple-chevron launch on the stream the engine hands the entry point, which is
|
||||
* a stream hipLaunchKernel accepts (docs/PLUGIN.md §5). It is a macro so a test can redefine it and
|
||||
* run the same sources through a host SIMT emulator.
|
||||
*
|
||||
* 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_DYN_LDS declares a kernel's dynamic LDS, sized by the launch. RDNA3 gives a workgroup 64 KiB,
|
||||
* as RDNA4 does, so a tile sized for libr4d fits.
|
||||
*
|
||||
* R3D_KNAME names a kernel in a context where commas would split a macro argument, the way
|
||||
* HIP_KERNEL_NAME does for hipLaunchKernelGGL.
|
||||
* R3D_KNAME wraps a kernel name that contains commas, like HIP_KERNEL_NAME.
|
||||
*/
|
||||
#ifndef R3D_LAUNCH_H
|
||||
#define R3D_LAUNCH_H
|
||||
|
||||
+229
-258
@@ -1,48 +1,46 @@
|
||||
/* 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").
|
||||
* elementwise arithmetic, the activations, cast, softmax, embed_lookup, gather_rows and
|
||||
* scatter_rows, rope and kv_store, plus the fused silu_mul and rmsnorm_quant_fp8. Each 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; without this unit no model runs on an RDNA3 card (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:
|
||||
* The arithmetic is libref's, the oracle every row is checked against by 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.
|
||||
* * every reduction accumulates in f32 and only the store narrows, RTNE (r3d_codecs.h restates
|
||||
* rad_plugin.h's rounders for device code, bit for bit);
|
||||
* * a row's sum is taken over lanes covering consecutive elements with `block_sum`
|
||||
* (r3d_common.h), so the bracketing is the one the contract fixes;
|
||||
* * bf16 stays 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 (CMakeLists.txt), and
|
||||
* expressions follow the reference's order and temporaries;
|
||||
* * 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 copy row 0 into 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).
|
||||
* One deliberate divergence from ref, shared with libr4d: 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 the row count is an argument and an out-of-range id takes the padding
|
||||
* path 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.
|
||||
* double and rounds once (ref_exp/ref_pow/ref_sin/ref_cos/ref_erf). The few f32 ULP between libm
|
||||
* and a device routine are the whole tolerance, far below a bf16 store's 1/256, and none of these
|
||||
* paths is a step bottleneck.
|
||||
*
|
||||
* No fusion: `rmsnorm_add` and the gated quantisers are separate entry points the architecture
|
||||
* plugin selects (spec §2.3), and live in other units.
|
||||
* `rmsnorm_add` and the gated quantisers are separate entry points the architecture plugin selects
|
||||
* (spec §2.3), 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.
|
||||
* 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 given stream;
|
||||
* and the shim the row table names, which reads the operands with r3d_args.h, takes the dtype and
|
||||
* row count from the tensors and returns a RAD status. Neither allocates or synchronises. A
|
||||
* launcher returns 0, or -1 (null), -2 (extent), -3 (pitch), -4 (HIP launch failed); a shim maps
|
||||
* any non-zero code to RAD_E_DEVICE.
|
||||
*/
|
||||
|
||||
#include "r3d.h"
|
||||
@@ -60,18 +58,17 @@ constexpr uint32_t kThreads = 256; // eight wave32s: the wide row, the hidden
|
||||
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. */
|
||||
/* The workgroup a row gets: one wave for rows a wave covers (an attention head, a KV head, a QK
|
||||
* norm), where 256 threads would leave three quarters of the lanes waiting at a barrier, and 256
|
||||
* for anything 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.
|
||||
* Whole-register stores to match r3d_common.h's whole-register loads. The dword form is the pair
|
||||
* store; the caller has proved the address even, in elements, from a base alignment of 4. The
|
||||
* address-space casts are C-style because reinterpret_cast cannot change address spaces.
|
||||
*/
|
||||
typedef uint32_t __attribute__((address_space(1))) *r3d_gu32;
|
||||
typedef float __attribute__((address_space(1))) *r3d_gf32;
|
||||
@@ -88,10 +85,9 @@ __device__ __forceinline__ void stg_i32(int32_t* p, int32_t v) { *(r3d_gi32)p =
|
||||
__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. */
|
||||
/* The max across a workgroup, shaped like block_sum: a wave butterfly and one LDS round trip. Max is
|
||||
* associative, commutative and idempotent, so the bracketing cannot change the result. The barrier
|
||||
* inside makes every wave's partial visible before any thread reads it. */
|
||||
template <int NTHREADS>
|
||||
__device__ __forceinline__ float block_max(float v, float* lds) {
|
||||
constexpr int NWAVES = NTHREADS / kWave;
|
||||
@@ -109,14 +105,12 @@ __device__ __forceinline__ float block_max(float v, float* lds) {
|
||||
/* ================================================================== 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.
|
||||
* dtypes because the dtype is a runtime launcher argument. These are the reference's ld_dt and
|
||||
* st_dt over libr3d's dtype codes, with one switch per element; none of these ops is compute-bound.
|
||||
*
|
||||
* 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.
|
||||
* The integer stores round to nearest even, saturate, and store NaN as 0 (the reference's
|
||||
* sat_round): wrapping an overflowing activation into a plausible small number would hide the
|
||||
* error.
|
||||
*/
|
||||
__device__ __forceinline__ float sat_round(float v, float lo, float hi) {
|
||||
if (v != v) return 0.0f;
|
||||
@@ -196,10 +190,10 @@ __device__ __forceinline__ int dt_bytes(int dt) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* The activation, from libref's act_* set. The reference evaluates the transcendental in double and
|
||||
* rounds once to f32 (ref_exp/ref_erf); the device's accurate expf/erff are a few f32 ULP away, and
|
||||
* the bf16 store keeps 8 mantissa bits. gelu is the exact erf form, as "gelu" means in libref; the
|
||||
* tanh approximation is a separate op name. */
|
||||
template <int ACT>
|
||||
__device__ __forceinline__ float act_of(float x) {
|
||||
if constexpr (ACT == R3D_ACT_SIGMOID) return 1.0f / (1.0f + expf(-x));
|
||||
@@ -215,14 +209,14 @@ __device__ __forceinline__ float act_of(float x) {
|
||||
* 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.
|
||||
* The mean is over the last n of the row and the gain applies to every row. An absent gain is the
|
||||
* constant 1 (the shim refuses `wadd` without one, as ref does). The gain's dtype is read off the
|
||||
* operand (WDT: R3D_DT_BF16, R3D_DT_F32, or R3D_DT_N for none), so a checkpoint that stores f32
|
||||
* gains (a QK norm's, an audio tower's) is read as stored. `wadd` is added in f32 because forming
|
||||
* 1+w in bf16 first loses 0.3% per channel.
|
||||
*
|
||||
* `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.
|
||||
* constant (e.g. 0.5 in Gemma 4's audio feed-forward); 1 leaves the product unchanged.
|
||||
*/
|
||||
template <int THR, int WDT, int F32>
|
||||
__global__ __launch_bounds__(THR) void rmsnorm_kernel(
|
||||
@@ -266,14 +260,14 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
|
||||
}
|
||||
|
||||
/* ================================================================== 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:
|
||||
* Two passes, the mean and then the squared deviations about it, rather than 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).
|
||||
* `b` is optional. The gain is bf16 only (the launcher has no gain dtype), so the shim refuses an
|
||||
* f32 gain rather than reading it as bf16.
|
||||
*/
|
||||
template <int THR>
|
||||
__global__ __launch_bounds__(THR) void layernorm_kernel(
|
||||
@@ -316,14 +310,14 @@ __global__ __launch_bounds__(THR) void layernorm_kernel(
|
||||
* 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.
|
||||
* `div` is the last step of a mean taken pairwise, (b0+b1+b2)/3 as a vocoder averages its residual
|
||||
* blocks; the sum is narrowed before the divide 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.
|
||||
* Broadcast: a b of exactly n elements applies to every row (`bcast`, set by the shim from the
|
||||
* operand's element count, as ref does). Nothing else broadcasts, so a shape bug cannot pass as a
|
||||
* plausible number. The f32 leg narrows nothing (round_dt(f32) is the identity), and `y` may alias
|
||||
* `a`: every element is read by the thread that writes it.
|
||||
*/
|
||||
template <int THR, int MUL, int PAIR, int F32>
|
||||
__global__ __launch_bounds__(THR) void binary_kernel(
|
||||
@@ -364,10 +358,9 @@ __global__ __launch_bounds__(THR) void binary_kernel(
|
||||
}
|
||||
|
||||
/* ================================================================== 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.
|
||||
* `from`/`to` select the row; the kernel moves the dtypes the tensors carry, as ref 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. One switch per element: cast is a bandwidth op, not a hot loop.
|
||||
*/
|
||||
template <int THR>
|
||||
__global__ __launch_bounds__(THR) void cast_kernel(
|
||||
@@ -384,9 +377,8 @@ __global__ __launch_bounds__(THR) void cast_kernel(
|
||||
}
|
||||
|
||||
/* ================================================================== 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. */
|
||||
* unary: one element, one activation, one narrowing by the store. The activation is a template
|
||||
* argument because the three bodies differ by one expression. */
|
||||
template <int THR, int ACT, int PAIR, int F32>
|
||||
__global__ __launch_bounds__(THR) void unary_kernel(
|
||||
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld,
|
||||
@@ -418,14 +410,14 @@ __global__ __launch_bounds__(THR) void unary_kernel(
|
||||
}
|
||||
|
||||
/* ================================================================== 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:
|
||||
* y = act(a) * b, with the activation narrowed to y's dtype first because the unfused pair stores
|
||||
* it; that rounding is part of the contract:
|
||||
*
|
||||
* 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.
|
||||
* silu, gelu (the exact erf form) and sigmoid; gelu_tanh and quick_gelu, libref's other two kActs
|
||||
* entries, are refused.
|
||||
*/
|
||||
template <int THR, int ACT, int PAIR>
|
||||
__global__ __launch_bounds__(THR) void act_mul_kernel(
|
||||
@@ -450,12 +442,12 @@ __global__ __launch_bounds__(THR) void act_mul_kernel(
|
||||
}
|
||||
|
||||
/* ================================================================== 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.
|
||||
* y[i] = silu(gate_up[i]) * gate_up[n + i] over one fused operand whose first half is the gate,
|
||||
* the order rad-convert fuses gate and up 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.
|
||||
* Nothing is narrowed between the activation and the product: act_mul rounds the activation
|
||||
* because its unfused pair stores it, while silu_mul is the fused op, so the f32 activation times
|
||||
* the f32 up is rounded once by the store.
|
||||
*/
|
||||
template <int THR, int PAIR>
|
||||
__global__ __launch_bounds__(THR) void silu_mul_kernel(
|
||||
@@ -477,24 +469,23 @@ __global__ __launch_bounds__(THR) void silu_mul_kernel(
|
||||
}
|
||||
|
||||
/* ================================================================== 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.
|
||||
* The residual add, the norm and the E4M3 quantiser in one pass, so the normalised activation is
|
||||
* never written back to VRAM. The quantiser arithmetic is r3d_quant_fp8.hip's and `q8_group`'s,
|
||||
* bit for bit: `sc = amax * (1.0f / 448.0f)` (the reciprocal multiplied), `inv = 1.0f / sc`, codes
|
||||
* `v * inv` clamped to +-448 by comparisons rather than fminf/fmaxf (which would replace a NaN with
|
||||
* the bound; a NaN activation encodes as the format's NaN), and scale 1 for an all-zero group.
|
||||
*
|
||||
* 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.
|
||||
* Two properties of ref's order are kept:
|
||||
* the residual sum is stored (narrowed to bf16) before the variance reads it, so the norm is over
|
||||
* the bf16 sum. That makes this the `add` + `rmsnorm` pair, not `rmsnorm_add`, which normalises
|
||||
* the unrounded sum;
|
||||
* the quantiser codes the bf16 normalised value, not the f32 one, so `out_bf16` holds exactly the
|
||||
* values 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.
|
||||
* A wave takes one group 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 are
|
||||
* stored as dwords. The second pass recomputes the normalised row from the same operands (hot in
|
||||
* L2), which keeps the row out of LDS and lets one workgroup take a 5120-column row.
|
||||
*/
|
||||
template <int THR, int GROUP, int WDT>
|
||||
__global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
|
||||
@@ -538,9 +529,8 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
|
||||
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. */
|
||||
/* The gain is read in the checkpoint's dtype (WDT, as in plain rmsnorm); 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)))
|
||||
@@ -580,11 +570,10 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
|
||||
* 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.
|
||||
* The maximum is subtracted first (a row spanning 60 nats would overflow f32's exp otherwise); the
|
||||
* denominator is the ascending sum `block_sum` brackets. `e` is stored to y and read back for the
|
||||
* multiply, as ref does, which is exact for an f32 plane. The shim therefore requires an f32 y: a
|
||||
* bf16 y would round `e` before the multiply where ref does not.
|
||||
*/
|
||||
template <int THR>
|
||||
__global__ __launch_bounds__(THR) void softmax_kernel(
|
||||
@@ -609,14 +598,12 @@ __global__ __launch_bounds__(THR) void softmax_kernel(
|
||||
}
|
||||
|
||||
/* ================================================================== 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 is y = x * s with s one scalar; fill is y = v over the whole plane. 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.
|
||||
* scale's scalar is the op's [1] weight plane in device memory, and the kernel reads it because a
|
||||
* launch may not copy device memory to the host. Every lane loads the same address, one uniform
|
||||
* load per block; the product is taken in f32 and narrowed by the store, as ref's `x * s`.
|
||||
*/
|
||||
template <int THR, int PAIR, int F32>
|
||||
__global__ __launch_bounds__(THR) void scale_kernel(
|
||||
@@ -661,14 +648,13 @@ __global__ __launch_bounds__(THR) void fill_kernel(void* __restrict__ y, uint32_
|
||||
* 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 pair lives in one thread, so the in-place store needs no exchange. `scale` divides the
|
||||
* position, as in ref's rope_pos (the factor on the rotated pair is YaRN's magnitude, which is 1
|
||||
* because the shims refuse YaRN).
|
||||
*
|
||||
* 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).
|
||||
* The frequency is recomputed per pair rather than built in a plane: one pow per pair per head,
|
||||
* off the critical path, with no scratch. nfreq == rot/2 always, so no pair lies past the ladder
|
||||
* (ref zeroes inv[] past nfreq only for the proportional ladder, which libr3d refuses).
|
||||
*/
|
||||
template <int THR, int GPTJ>
|
||||
__global__ __launch_bounds__(THR) void rope_kernel(
|
||||
@@ -683,10 +669,10 @@ __global__ __launch_bounds__(THR) void rope_kernel(
|
||||
|
||||
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. */
|
||||
/* ref's ladder: `1.0f / ref_pow(theta, (float)(2i) / den)`, with ref_pow the double pow
|
||||
* narrowed once. powf would put the reciprocal a ULP off, and at position 262144 a ULP of a
|
||||
* frequency is about 0.01 rad of rotation, so the ladder is computed in double. The angle
|
||||
* stays f32, as in ref. */
|
||||
const float inv = 1.0f / (float)std::pow((double)theta, (double)((float)(2 * i) / (float)rot));
|
||||
float s, c;
|
||||
sincosf(p * inv, &s, &c);
|
||||
@@ -709,14 +695,13 @@ __global__ __launch_bounds__(THR) void rope_kernel(
|
||||
* 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
|
||||
* otherwise they are a column slice of the fused QKV plane (a 256-wide slice of a 2560-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.
|
||||
* k_inv and v_inv are the reciprocals of the reader's descales, and 1 for every non-fp8 cache, so
|
||||
* the multiply is exact there. For the fp8 cache a value times 1/scale differs from ref's result by
|
||||
* at most the reciprocal's rounding, far below the fp8 code step.
|
||||
*/
|
||||
template <int THR>
|
||||
__global__ __launch_bounds__(THR) void kv_store_kernel(
|
||||
@@ -726,9 +711,8 @@ __global__ __launch_bounds__(THR) void kv_store_kernel(
|
||||
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. */
|
||||
/* A negative slot is padding. A slot at or past the cache's span names a block the cache does
|
||||
* not have; ref refuses such a launch on the host, and the kernel drops the slot. */
|
||||
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;
|
||||
|
||||
@@ -753,15 +737,15 @@ __global__ __launch_bounds__(THR) void kv_store_kernel(
|
||||
* 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.
|
||||
* A negative id, or one at or past the table, gives a zero row: padding, or in the vocab-parallel
|
||||
* split another rank's token, so summing the ranks reconstructs x. ref validates the ids on the
|
||||
* host when the table is whole and there is one rank; a kernel cannot, so the table bound is an
|
||||
* argument.
|
||||
*
|
||||
* 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.
|
||||
* The table's dtype is the launcher's `dt`: bf16, f16, f32, or E4M3 codes with the table's single
|
||||
* scale in `wscale` (embed_lookup_q's byte plane; the scale is a parameter because it is computed
|
||||
* over the whole table while 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 <int THR>
|
||||
__global__ __launch_bounds__(THR) void embed_lookup_kernel(
|
||||
@@ -789,18 +773,18 @@ __global__ __launch_bounds__(THR) void embed_lookup_kernel(
|
||||
}
|
||||
|
||||
/* ================================================================== 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).
|
||||
* y[r] = x[idx[r]] and x[idx[r]] = v[r] over rows of n: 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).
|
||||
* A negative index is padding (an unsampled row, a slot with no counterpart): gather writes a zero
|
||||
* row, scatter writes nothing. 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.
|
||||
* because the destination is often a pool shared with other sequences. Indices must be distinct
|
||||
* (RAD_OPD_F_IDX_UNIQUE in the schema): two rows landing on one destination have no defined
|
||||
* winner, so the oracle and the kernel could disagree.
|
||||
*/
|
||||
template <int THR>
|
||||
__global__ __launch_bounds__(THR) void gather_rows_kernel(
|
||||
@@ -809,10 +793,9 @@ __global__ __launch_bounds__(THR) void gather_rows_kernel(
|
||||
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. */
|
||||
/* A negative index is padding, and an index at or past the source plane is one libref refuses
|
||||
* on the host; both take the zero row, so x is never read past its end. `src_rows` 0 means the
|
||||
* caller supplied no row count (a shim bug) and disables the 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;
|
||||
@@ -827,8 +810,8 @@ __global__ __launch_bounds__(THR) void scatter_rows_kernel(
|
||||
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. */
|
||||
/* A negative index is padding, and one at or past the destination plane is a step libref
|
||||
* refuses; both are dropped, so nothing 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;
|
||||
@@ -945,10 +928,9 @@ extern "C" int r3d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps,
|
||||
|
||||
/* 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. */
|
||||
* quantiser's block and must divide n: a partial group would need the standalone quantiser's
|
||||
* zero-padded store. Pitches are in elements of their own operand, `s_ld` in scales (dense is
|
||||
* n/group). Returns 0, -1, -2, -3 or -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) {
|
||||
@@ -1179,7 +1161,7 @@ extern "C" int r3d_act_mul_bf16(long gate, long up, long y, int M, int n, int g_
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
* 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;
|
||||
@@ -1188,7 +1170,7 @@ extern "C" int r3d_silu_mul_bf16(long gate_up, long y, int M, int n, int gu_ld,
|
||||
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 */
|
||||
const int pair = row_pair(y, n, gu_ld, y_ld); /* n even keeps the up half pair-aligned */
|
||||
#define R3D_SM(THR, PAIR) \
|
||||
R3D_KLAUNCH(R3D_KNAME(silu_mul_kernel<THR, PAIR>), dim3((uint32_t)M), dim3(THR), \
|
||||
(hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)gate_up, \
|
||||
@@ -1276,8 +1258,8 @@ extern "C" int r3d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_head
|
||||
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. */
|
||||
/* One wave covers a token's rope pairs when there are at most 256 of them; 256 threads take
|
||||
* more. */
|
||||
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,
|
||||
@@ -1301,9 +1283,9 @@ extern "C" int r3d_kv_store(long k, long v, long sm, long kv, int M, int head_di
|
||||
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. */
|
||||
/* Default cache span, matching r3d_shape_kv_store: M tokens need ceil(M/block_size) blocks, plus
|
||||
* two so a step that resolves its slots before the next block is written has room. 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);
|
||||
@@ -1366,21 +1348,20 @@ extern "C" int r3d_scatter_rows(long v, long idx, long x, int M, int n, int v_ld
|
||||
|
||||
/* ================================================================== 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 shims unpack RadArgs and derive the pitches (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 dtype, off the operand: a row's `dtype` constraint is a necessary condition, not a
|
||||
* promise about the tensors, and an f32 operand read as bf16 passes every geometry check;
|
||||
* * 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.
|
||||
* * the parameters, with libref's defaults. Forms the kernels cannot match are refused with
|
||||
* RAD_E_UNSUPPORTED, and the row's constraints keep models that need them from being routed
|
||||
* here.
|
||||
*
|
||||
* Every refusal goes through R3D_NO(), so a run with RAD_R3D_TRACE set says which line said no.
|
||||
* Every refusal goes through R3D_NO(), so with RAD_R3D_TRACE set each refusal prints its line.
|
||||
*/
|
||||
|
||||
static inline int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
@@ -1394,8 +1375,8 @@ static inline int dt_same(const RadTensor* a, const RadTensor* b) {
|
||||
|
||||
#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. */
|
||||
/* A launcher's return: 0 is RAD_OK and anything else is a device failure, because the shim has
|
||||
* already checked the arguments. */
|
||||
static inline int r3d_launch_ok(int rc) { return rc == 0 ? RAD_OK : R3D_NO(RAD_E_DEVICE); }
|
||||
|
||||
/* ------------------------------------------------------------------ rmsnorm */
|
||||
@@ -1407,8 +1388,7 @@ extern "C" int r3d_rad_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
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. */
|
||||
/* bf16 or f32, the same two passes; the f32 leg's store narrows nothing. */
|
||||
const bool f32 = r3d_is_f32(x) && r3d_is_f32(y);
|
||||
if (!f32) {
|
||||
R3D_NEED(dt_bf16(x));
|
||||
@@ -1418,8 +1398,7 @@ extern "C" int r3d_rad_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
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. */
|
||||
/* `wadd` without a gain is refused, as ref does: it would be a constant scale, not a norm. */
|
||||
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;
|
||||
@@ -1449,10 +1428,9 @@ extern "C" int r3d_rad_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* The residual add, the norm and the E4M3 quantiser in one launch: libref's {x, residual?, w, q,
|
||||
* scale, out_bf16?} with {M, n, eps, group, dtype, wadd?}. The normalised row is written once, as
|
||||
* codes and an optional bf16 copy, instead of as bf16 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);
|
||||
@@ -1463,17 +1441,15 @@ extern "C" int r3d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
|
||||
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. */
|
||||
/* The gain is read in the dtype the checkpoint stores it in, bf16 or f32. The band's `dtype` is
|
||||
* the activation's, so checking the weight against it would refuse checkpoints with f32 gains. */
|
||||
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. */
|
||||
/* `residual` is validated below, under the flag that makes it read. `out_bf16` is checked only
|
||||
* when its slot carries bytes, since the kernel then writes it (as the reference does whenever
|
||||
* the operand is present). */
|
||||
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));
|
||||
@@ -1481,17 +1457,15 @@ extern "C" int r3d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
|
||||
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. */
|
||||
/* A wave covers a group, four columns a lane per 128 columns; a partial group would need the
|
||||
* standalone quantiser's zero-padded store. */
|
||||
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. */
|
||||
/* The reference reads `residual` only under `wadd`, and so does this check. The engine binds
|
||||
* the slot even when wadd=0, in any dtype, so validating it unconditionally would refuse valid
|
||||
* checkpoints. */
|
||||
if (wadd != 0.0f) {
|
||||
if (!r3d_has(res)) return R3D_NO(RAD_E_INVAL);
|
||||
R3D_NEED(dt_bf16(res));
|
||||
@@ -1531,8 +1505,8 @@ extern "C" int r3d_rad_layernorm(const RadArgs* a, RadStream s) {
|
||||
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. */
|
||||
/* libref reads a bias in any float dtype; the kernel reads bf16 only (one dtype for gain
|
||||
* and bias), so an f32 bias is refused rather than misread. */
|
||||
if (!r3d_is_bf16(b)) return R3D_NO(RAD_E_DTYPE);
|
||||
R3D_NEED(dt_bf16(b));
|
||||
}
|
||||
@@ -1555,8 +1529,8 @@ extern "C" int r3d_rad_layernorm(const RadArgs* a, RadStream 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. */
|
||||
* than one row applies to every row, and nothing else broadcasts. Only `add` has `div` (mul's
|
||||
* schema has no div key); zero, NaN and infinity are refused, as by the reference. */
|
||||
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);
|
||||
@@ -1653,8 +1627,8 @@ static int unary_shim(const RadArgs* a, RadStream s, int act) {
|
||||
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. */
|
||||
/* Only silu has an f32 leg in r3d.h; an f32 gelu or sigmoid is refused rather than run through
|
||||
* 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));
|
||||
@@ -1686,9 +1660,8 @@ extern "C" int r3d_rad_sigmoid(const RadArgs* a, RadStream s) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
* libref's kActs are silu, gelu, gelu_tanh, sigmoid and quick_gelu. libr3d serves silu, gelu and
|
||||
* sigmoid and refuses the other two with RAD_E_UNSUPPORTED. */
|
||||
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);
|
||||
@@ -1725,9 +1698,9 @@ extern "C" int r3d_rad_act_mul(const RadArgs* a, RadStream 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.
|
||||
* y[i] = silu(gate_up[i]) * gate_up[n + i]: libref's {gate_up, y} operands and {M, n, dtype}
|
||||
* schema. The llama MLP emits it; it is a distinct op from act_mul (which takes two operands), so
|
||||
* the act_mul_silu row does not serve it.
|
||||
*/
|
||||
extern "C" int r3d_rad_silu_mul(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* gu = r3d_opt(a, 0);
|
||||
@@ -1740,7 +1713,7 @@ extern "C" int r3d_rad_silu_mul(const RadArgs* a, RadStream s) {
|
||||
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 */
|
||||
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
|
||||
@@ -1750,9 +1723,9 @@ extern "C" int r3d_rad_silu_mul(const RadArgs* a, RadStream 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. */
|
||||
* f32 only: the reference casts to f32, computes and casts back, reading the intermediate `e` back
|
||||
* from an f32 plane. A bf16 y would round that intermediate, 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);
|
||||
@@ -1774,8 +1747,8 @@ extern "C" int r3d_rad_softmax(const RadArgs* a, RadStream 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. */
|
||||
* element, and the kernel reads the value, because reading a device plane on the host needs a copy
|
||||
* and a sync. */
|
||||
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);
|
||||
@@ -1828,14 +1801,12 @@ extern "C" int r3d_rad_fill(const RadArgs* a, RadStream 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.
|
||||
* In place, so operand 0 is INOUT (a null data is RAD_E_INVAL); head_dim and rot must be 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.
|
||||
* Refused with RAD_E_UNSUPPORTED: the multi-component modes (mrope, imrope, axial), which need a
|
||||
* [C, M] position plane and per-section ladders; the proportional ladder (`ladder=head`), which
|
||||
* pairs across the whole head; and YaRN and Llama 3, which rescale the ladder. Each changes the
|
||||
* angles, not the arithmetic, and the kernel implements only the plain rotary.
|
||||
*/
|
||||
extern "C" int r3d_rad_rope(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* qkv = r3d_opt(a, 0);
|
||||
@@ -1888,14 +1859,13 @@ extern "C" int r3d_rad_rope(const RadArgs* a, RadStream 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.
|
||||
* The cache is INOUT: only the mapped slots are written. Its strides are read off the operand (the
|
||||
* reference's kv_view): a rank-4 cache carries them, and 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.
|
||||
* ref also refuses a slot naming a block past the cache (RAD_E_SHAPE), which the shim cannot check
|
||||
* before the launch because the slots are in device memory. The bound travels as `slot_max` and
|
||||
* the kernel drops a slot at or past it.
|
||||
*/
|
||||
extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* k = r3d_opt(a, 0);
|
||||
@@ -1942,12 +1912,11 @@ extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream s) {
|
||||
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. */
|
||||
/* The cache's span in slots comes from the pool's own plane, not from this step. A step that
|
||||
* adopts a prefix writes its tail into the blocks the table names, at the allocator's global
|
||||
* indices (a 4-token tail in block 3 starts at slot 48), which a bound derived from T would
|
||||
* reject. A slot at or past the plane's span names memory the cache does not have and is
|
||||
* dropped by the kernel. */
|
||||
long long slot_max;
|
||||
if (kv->rank == 4) {
|
||||
slot_max = (long long)r3d_dim(kv, 0) * block_size;
|
||||
@@ -1957,17 +1926,19 @@ extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream s) {
|
||||
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. */
|
||||
/* Diagnostic, when RAD_R3D_TRACE is set: synchronises the device and prints
|
||||
* "[r3d] kvstore: T=<tokens> kvbase=<cache ptr> slots=<first 8 slot ids>", showing where this
|
||||
* step's KV lands (a tail naming slots of an adopted block overwrites the shared prefix). */
|
||||
if (r3d_trace_on())
|
||||
{
|
||||
(void)hipDeviceSynchronize();
|
||||
int slots[8];
|
||||
if (hipMemcpy(slots, (const void*)(uintptr_t)r3d_addr(sm), 8 * sizeof(int),
|
||||
const int n_print = T < 8 ? (int)T : 8;
|
||||
if (hipMemcpy(slots, (const void*)(uintptr_t)r3d_addr(sm), (size_t)n_print * 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)
|
||||
for (int c = 0; c < n_print; ++c)
|
||||
std::fprintf(stderr, "%s%d", c ? " " : "", slots[c]);
|
||||
std::fprintf(stderr, "\n");
|
||||
}
|
||||
@@ -1980,10 +1951,10 @@ extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream 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. */
|
||||
* 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 is refused, as is an E4M3 table whose scale arrives as a tensor
|
||||
* (embed_lookup_q's operand): a per-row scale read 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);
|
||||
|
||||
+67
-71
@@ -2,8 +2,8 @@
|
||||
*
|
||||
* 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 <hip/hip_runtime.h>.
|
||||
* 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.
|
||||
* The split lets the constraint table compile and be checked without ROCm, which is why every shim
|
||||
* is declared here rather than beside its definition.
|
||||
*
|
||||
* Nothing in this header may include r3d.h.
|
||||
*/
|
||||
@@ -15,56 +15,53 @@
|
||||
/* ================================================================== 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.
|
||||
* 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 inserted between two without renumbering.
|
||||
*
|
||||
* libr3d ships one row per (op, dtype) pair far more often than libr4d does: the matrix work runs
|
||||
* on the dot2 path, whose lane map takes a dtype as a template argument, so the kernel that serves
|
||||
* bf16 serves f16 as is, 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.
|
||||
* Most ops have a single row: the matrix work runs on the dot2 path, whose lane map takes the dtype
|
||||
* as a template argument, so the kernel that serves bf16 also serves f16. Where one op has two
|
||||
* rows, the reason is geometry and is stated next to the pair.
|
||||
*/
|
||||
enum {
|
||||
/* The common case: this op, these dtypes, one row. Nothing competes with it. */
|
||||
/* One row for the op; 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. */
|
||||
/* `attn_paged` is banded on q_len, and the decode row's bound (q_len <= 16) overlaps the
|
||||
* prefill row: a speculative verify at 8 query tokens matches both, and the decode kernel
|
||||
* (split-KV, one head group per workgroup, no query tile) is faster there. Decode outranks
|
||||
* prefill, as 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. */
|
||||
/* The skinny bf16 GEMM's band is M <= 16 and the tiled one's starts at M >= 16. At 16 rows the
|
||||
* skinny kernel wins: it keeps the whole weight stream in flight with one wave per row and has
|
||||
* no LDS staging. The overlap is deliberate; a caller that wants the tiled kernel at 16 rows
|
||||
* asks with M=17, as at libr4d's 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. */
|
||||
/* The vocab GEMM (N = 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 matters 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. */
|
||||
/* An fp8 weight row and an int8 weight row never compete: no dtype string reaches both, and
|
||||
* the 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. */
|
||||
/* One row per sampler stage, on f32 logits, so there is nothing to rank yet. A second row for
|
||||
* a stage (an i8 logits form, say) would rank against this value. */
|
||||
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. */
|
||||
* The launchers in r3d.h take a dtype as an int: it is a runtime value for the ops that are one
|
||||
* kernel over several dtypes (cast, fill, dequant) and a template argument everywhere else. The
|
||||
* codes are libr3d's own, not rad_types.h's RAD_DT_*, because the launcher signature is private to
|
||||
* a shim and its kernel and a dense 0..n switches more cleanly than the ABI's sparse enum. Every
|
||||
* shim translates. */
|
||||
enum {
|
||||
R3D_DT_BF16 = 0,
|
||||
R3D_DT_F16 = 1,
|
||||
@@ -103,16 +100,16 @@ static inline int r3d_dt_size(int code) {
|
||||
/* 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. */
|
||||
/* rope's `mode`, numbered as libref's kModes. Only neox and gptj are implemented, and 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).
|
||||
* Declared here so r3d_rows.cpp, host code built without ROCm, can name them. Each is defined and
|
||||
* documented beside its kernel, in the unit named below. 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" {
|
||||
|
||||
@@ -145,7 +142,6 @@ 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);
|
||||
@@ -174,15 +170,15 @@ int r3d_shape_gemm_nt (const RadParam* p, int n_p, int operand, RadOpdDe
|
||||
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 --- */
|
||||
/* --- r3d_shapes.cpp: the fused-op, attention and sampler shape hooks --- */
|
||||
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. */
|
||||
/* r3d_gemm_nt_q_w2a8.hip: the w2a8 vocab projection's layout hook, one of the library's three
|
||||
* (with 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 would have 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*);
|
||||
@@ -202,8 +198,9 @@ extern "C" int r3d_shape_sample_ngram_ban (const RadParam*, int, int, RadOpdDes
|
||||
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) --- */
|
||||
/* --- r3d_gemm_nt_q_w2a8.hip, r3d_gemm_fp8a8_gated.hip, r3d_dflash_f32.hip; r3d_sample_f32.hip's
|
||||
draw spine (row_topk, argmax, temp, topk, pick, the four narrowings) and
|
||||
r3d_sample_pre_f32.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);
|
||||
@@ -222,44 +219,39 @@ 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. */
|
||||
/* --- r3d_attn_paged_h128.hip: the paged attention, banded on q_len. The decode kernel is
|
||||
* split-KV over the cache with one head group per 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. */
|
||||
* the container's fp8 weight: codes and per-128x128 scale as two planes behind `b_scale`. The row
|
||||
* carries its own layout hook because the reference's gemm_nt_q hook answers nothing for this
|
||||
* dtype (ref_layout_gemm_q reads zp_grid, which has no fp8a8 entry). */
|
||||
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. */
|
||||
* weight is two plain u8 planes (e2m1 codes [N, K/2], e8m0 scale [N, K/32]) read in place, so the
|
||||
* row has no layout hook. Its shape hook is separate because these 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. */
|
||||
* is signed codes (I4 two per byte, or I8) with 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 have 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. */
|
||||
/* The relayout writers for the three layout hooks, each delegating to rad_planes_relayout. The
|
||||
* loader converts a quantised weight into the joined operand the plan names, 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*,
|
||||
@@ -267,18 +259,22 @@ extern "C" int r3d_relayout_gemm_q_fp8_weight(const RadParam*, int, int, const R
|
||||
extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadEncoding*,
|
||||
const int*, const RadTensor*, int, void*, int64_t);
|
||||
|
||||
/* --- r3d_vocab_bf16.hip: the vocabulary projection, both heights. Its shape hook
|
||||
* (r3d_shapes.cpp) transcribes ref_logits_gemm_shape, three plain tensors with nothing joined, so
|
||||
* the band the engine declares is the band kbench fills. */
|
||||
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. */
|
||||
/* The head's layout hook: `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 does not place a weight a loaded library cannot read in place. Transcribed from
|
||||
* ref_layout_head, with the statics it uses inlined. It moves no bytes: a round-trip through its
|
||||
* relayout writer (above) reproduces the planes exactly, and the writer exists for that
|
||||
* round-trip. */
|
||||
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*);
|
||||
|
||||
/* --- r3d_model_bf16.hip: the fused MLP activation and the fused norm-quantiser --- */
|
||||
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*);
|
||||
|
||||
+134
-194
@@ -1,39 +1,31 @@
|
||||
/* 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.
|
||||
* The arithmetic is libref's, transcribed: quant_act_fp8, quant_act_i8, quant_act_i8g,
|
||||
* gated_quant_fp8 and dequant, loop order and rounding points as written. The group core is
|
||||
* `q8_group`: an amax over the group's columns, `sc = amax * (1.0f / top)` (a multiply by the
|
||||
* reciprocal, not a divide), codes `v * (1/sc)` clamped to +-top, and scale 1 for an all-zero
|
||||
* group. The clamp is required: `amax * (1/scale)` can round an ulp above 448, and an
|
||||
* out-of-range code encodes as NaN.
|
||||
*
|
||||
* 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.
|
||||
* RDNA3 has no fp8 instruction (r3d_common.h), so both directions use the software codecs in
|
||||
* r3d_codecs.h, bit-exact mirrors of rad_plugin.h's. The absmax is a butterfly (r3d_xor_max); a
|
||||
* max is exact and order-free, so it matches q8_group 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 codes are the bytes their consumer reads, with no layout hook. Four of the five planes are
|
||||
* row-major with one f32 scale per (row, group), the order a dot2 GEMM reads. quant_act_i8 stores
|
||||
* its codes in the int8 WMMA's step order (`i8_step_pos`) because the w4a8, w8a8 and w2a8 GEMMs
|
||||
* read that, so its n is a multiple of 16. quant_act_i8g is the row-major int8 plane 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.
|
||||
* A lane owns four consecutive columns, so its codes are one dword and a wave's are 128
|
||||
* contiguous bytes; `i8_step_pos` preserves c % 4, so it never splits a lane. The launchers
|
||||
* refuse `n % 4` (quant_act_i8: `n % 16`), and a ragged last group is 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.
|
||||
* Group widths: the rows ask for 128, the checkpoint's weight-scale block width; the kernels serve
|
||||
* any power of two from 4 to 512. A group is a power of two because the amax butterfly is over
|
||||
* the GROUP/4 lanes covering it.
|
||||
*/
|
||||
|
||||
#include "r3d.h"
|
||||
@@ -51,15 +43,13 @@ enum : uint32_t {
|
||||
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. */
|
||||
/* The largest code each quantiser saturates at; 448 is E4M3's largest finite value. The scale is a
|
||||
* dequant multiplier like the checkpoint's weight_scale_inv: the GEMM multiplies, 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. */
|
||||
/* The floor quant_act_i8's amax is raised to before it divides by 127. quant_act_fp8 multiplies by
|
||||
* a reciprocal instead, so the two can round one ulp apart; both follow libref. */
|
||||
constexpr float kI8Floor = 1e-8f;
|
||||
|
||||
/* The LDS code-sum accumulator's width, in groups, as in libr4d's r4d_quant_act_i8. */
|
||||
@@ -70,10 +60,9 @@ __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. */
|
||||
/* q8_group's clamp, in its order and with its comparisons, at the codec's top (448 for E4M3, 127
|
||||
* for int8). Not fminf/fmaxf: they replace a NaN with the bound, and the reference encodes a NaN
|
||||
* activation as the format's NaN. */
|
||||
__device__ __forceinline__ float clamp_top(float c, float top) {
|
||||
if (c > top) c = top;
|
||||
if (c < -top) c = -top;
|
||||
@@ -87,9 +76,7 @@ __device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) {
|
||||
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. */
|
||||
/* The same four codes as int8: clamp to +-127, then the codec's round-to-nearest-even. */
|
||||
__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));
|
||||
@@ -98,24 +85,22 @@ __device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
|
||||
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. */
|
||||
/* q8_group's scale from the group's amax: multiplied by the reciprocal of `top`, not divided. The
|
||||
* per-row quant_act_i8 divides, which is why it 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. */
|
||||
/* libref's map from column c to its position in the step-ordered int8 plane: bits 2 and 3 of c
|
||||
* exchanged, i.e. the middle two dwords of every 16-byte step swapped, the order the int8 WMMA
|
||||
* reads an A fragment. It is its own inverse and preserves c % 4, so a lane's 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. */
|
||||
/* block_sum's (r3d_common.h) twin for a maximum. A max is exact, so the wave partials combine in
|
||||
* any order. `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);
|
||||
@@ -129,18 +114,16 @@ __device__ __forceinline__ float block_max(float v, float* lds) {
|
||||
|
||||
/* ================================================================== 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.
|
||||
* 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, chosen for the store (one dword a lane, 128
|
||||
* contiguous bytes a wave), 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.
|
||||
* At GROUP = 128 a wave covers one group and the amax is r3d_xor_max<32>. A narrower group is
|
||||
* covered by GROUP/4 lanes, so one wave quantises 128/GROUP groups a pass; a wider one is walked
|
||||
* by one wave in 128-column sub-blocks whose maxima are fmaxf'd.
|
||||
*
|
||||
* 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.
|
||||
* input) is one row per token, as libref reads it: the consuming GEMM's K is heads*width.
|
||||
*/
|
||||
template <int GROUP>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
|
||||
@@ -168,8 +151,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
|
||||
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. */
|
||||
* no part in the amax. n is a multiple of 4, so the edge never splits a lane. */
|
||||
v[sb][j] = c < n ? ld_bf(xr, c) : 0.0f;
|
||||
}
|
||||
float m = 0.0f;
|
||||
@@ -178,10 +160,9 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
|
||||
am = fmaxf(am, r3d_xor_max<kLanes>(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. */
|
||||
/* Guarded by the group count as well as the lane: a wave covers kPer = 128/GROUP groups
|
||||
* and ceil(n/group) need not be a multiple of kPer, so the surplus lanes would write past
|
||||
* the scale row (and on the last row, past the plane). */
|
||||
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;
|
||||
@@ -197,17 +178,14 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
|
||||
|
||||
/* ================================================================== 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.
|
||||
* q8_group at top 127: one scale per (row, group), `sc = amax * (1.0f / 127)` as in the fp8 path
|
||||
* (so this is quant_act_fp8 with an int8 codec, not quant_act_i8 at a finer granularity), codes
|
||||
* clamp(v * (1/sc), +-127) rounded to nearest even, 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.
|
||||
* The store is row-major because libr3d's int8 GEMM (i8a8) is a dot2 GEMM that reads a row in
|
||||
* stored order. The step-ordered plane is quant_act_i8's, read by libr4d's WMMA GEMMs.
|
||||
*
|
||||
* Same lane mapping and same ragged rules as quant_act_fp8_kernel, so the two bodies read as one
|
||||
* shape with the codec swapped.
|
||||
* Lane mapping and ragged rules are quant_act_fp8_kernel's.
|
||||
*/
|
||||
template <int GROUP>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8g_kernel(
|
||||
@@ -258,13 +236,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8g_kernel(
|
||||
} /* 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
|
||||
* q [M][n] E4M3, dense (the launcher takes no code pitch)
|
||||
* 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. */
|
||||
* Each launcher validates 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 does not synchronise. */
|
||||
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;
|
||||
@@ -301,27 +278,20 @@ 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 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.
|
||||
* The codes are stored in libref's step order (`i8_step_pos`), hence n % 16 == 0. That order is
|
||||
* the op's contract (those GEMMs read it and kbench compares the plane element-wise), so it is
|
||||
* kept on a card without WMMA; the row-major plane is quant_act_i8g.
|
||||
*
|
||||
* 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.
|
||||
* libref reduces with std::max and this with fmaxf. Both drop a NaN operand, so they agree on
|
||||
* every input; an all-NaN row has amax 0 and scale 1e-8/127 in both.
|
||||
*
|
||||
* 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.
|
||||
* ASUM also writes each row's code sums per `group` columns, group-major [n/group][Mpad] with
|
||||
* Mpad = ceil(M/16)*16: an asymmetric weight grid subtracts z_g * sum_k a_k once per group instead
|
||||
* of N times, and reads whole 16-row tiles. The sums are integers, so the LDS atomics are exact in
|
||||
* any order. Rows M..Mpad-1 are not written; the caller zeroes them, as libref does.
|
||||
*/
|
||||
template <bool ASUM>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel(
|
||||
@@ -359,10 +329,9 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel(
|
||||
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. */
|
||||
/* n % group == 0 and group % 4 == 0, so a lane's four columns are in one group. Sums
|
||||
* are over logical columns, which equals libref reading qr[i8_step_pos(i)] since the
|
||||
* map is its own inverse. */
|
||||
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 */
|
||||
@@ -377,17 +346,14 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel(
|
||||
} /* 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.
|
||||
* q [M][n] i8, dense, in libref's step order (i8_step_pos), n % 16 == 0
|
||||
* s [M] f32, one scale a row at element pitch `s_ld` (0 = 1). A larger
|
||||
* plane is legal and filled as libref fills it: the row's scale at
|
||||
* s[r], the tail left to the caller.
|
||||
* 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. */
|
||||
* `group` is the width of the code sums, not of the scale, and is ignored without asum (as in
|
||||
* libref). */
|
||||
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;
|
||||
@@ -419,13 +385,11 @@ extern "C" int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n,
|
||||
}
|
||||
|
||||
/* 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
|
||||
* 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. */
|
||||
* `group` is the scale's width; `group >= n` is one scale a row (the shim clamps an absent group
|
||||
* to n, as libref does). Return codes as r3d_quant_act_fp8. */
|
||||
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;
|
||||
@@ -462,20 +426,17 @@ 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.
|
||||
* act(gate) * up, then quant_act_fp8's quantiser, in one pass. `gate_up` is [M, 2n], gate first,
|
||||
* as a fused gate_up projection writes it; `out_bf16`, when bound, receives the product.
|
||||
*
|
||||
* 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.
|
||||
* The product is narrowed to bf16 and read back before the absmax, matching the unfused pair
|
||||
* (which quantises a bf16 tensor), so out_bf16 holds exactly the value the codes came from.
|
||||
* Rounding points are libref's: sg = 1/(1+exp(-gate)) in f32, then gate*sg for silu (multiplied,
|
||||
* not divided), then * up, then one bf16 narrowing. `expf` is the accurate form, not __expf
|
||||
* (r3d_common.h). The reference evaluates exp in double, so a code can differ by one where the
|
||||
* bf16 narrowing lands on a tie; everything else is bit-exact.
|
||||
*
|
||||
* No row reduction, so no first pass and no barrier: a wave a group, a lane four columns.
|
||||
* No row reduction, so no barrier: a wave a group, a lane four columns.
|
||||
*/
|
||||
template <int GROUP, int ACT>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void gated_quant_fp8_kernel(
|
||||
@@ -567,8 +528,7 @@ extern "C" int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16,
|
||||
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. */
|
||||
/* The activation is a template argument, so the inner loop has no branch on it. */
|
||||
if (act == R3D_ACT_SILU) { R3D_GQ_ACT(R3D_ACT_SILU); }
|
||||
else { R3D_GQ_ACT(R3D_ACT_SIGMOID); }
|
||||
#undef R3D_GQ_ACT
|
||||
@@ -580,16 +540,13 @@ 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.
|
||||
* y = code * scale, the read of a container's own quantised weight. Elementwise; each code
|
||||
* decodes exactly to f32 (E4M3 is a subset of f16 and f32, E5M2 is f16's top byte per
|
||||
* rad_plugin.h, int8 is exact), one f32 multiply follows, and the store narrows to bf16, the width
|
||||
* every consumer of a dequantised weight here reads.
|
||||
*
|
||||
* 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.
|
||||
* The shim requires the scale stream [M, ceil(n/group)] to carry every group, so the index clamp
|
||||
* below (libref's behaviour for a short stream) never fires on a well-formed call.
|
||||
*/
|
||||
template <int QDT>
|
||||
__device__ __forceinline__ float code_value(uint8_t b) {
|
||||
@@ -612,8 +569,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void dequant_kernel(
|
||||
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. */
|
||||
/* One 8-byte store a lane. bf16x2_rne is software RTNE since gfx11 has no
|
||||
* v_cvt_pk_bf16_f32 (r3d_common.h). */
|
||||
uint32_t* yp = (uint32_t*)(yr + c);
|
||||
yp[0] = bf16x2_rne(code_value<QDT>((uint8_t)(w & 0xffu)) * sc,
|
||||
code_value<QDT>((uint8_t)(w >> 8)) * sc);
|
||||
@@ -624,13 +581,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void dequant_kernel(
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* q [M][n] codes, DENSE: E4M3, E5M2 or i8, one byte apiece
|
||||
/* 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. */
|
||||
* `q_dt` names the codes; the output is always bf16, since a dequantised weight here feeds a bf16
|
||||
* dot2 GEMM. An f32 output is r3d_cast's job. */
|
||||
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;
|
||||
@@ -660,22 +616,17 @@ extern "C" int r3d_dequant(long q, long s, long y, int M, int n, int group, int
|
||||
|
||||
/* ================================================================== the plugin ABI entry points
|
||||
*
|
||||
* Three things every shim here reads off the operands and not off the parameters:
|
||||
* Every shim reads three things off the operands, not 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 dtype. A row's `dtype` constraint is a condition on the geometry, not a promise about the
|
||||
* tensors, and an f32 activation read as bf16 would pass every other check.
|
||||
* * the row count. `M` is the band's upper bound; the operand carries the call's rows.
|
||||
* * the pitch. r3d_rows_pitch() answers in elements, or -1 for a strided inner axis.
|
||||
*
|
||||
* 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. */
|
||||
* Code planes are dense: no launcher takes a code pitch, and a plane with a hole is a stride
|
||||
* refusal, 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. */
|
||||
/* bf16 is the only activation dtype these kernels read; an f32 activation goes through r3d_cast. */
|
||||
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". */
|
||||
@@ -695,11 +646,10 @@ static inline int r3d_launch_status(int e) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* The group must be a power of two from 4 to 512, the instantiated widths. As in libref,
|
||||
* `group <= 0 || group > n` means one scale a row (n). Any other width is refused, not rounded,
|
||||
* since a rounded group would quantise on a grid the weight's scales are not on. Returns 0 on
|
||||
* refusal. */
|
||||
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;
|
||||
@@ -752,20 +702,15 @@ extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) {
|
||||
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 */
|
||||
if (r3d_has(as)) R3D_NEED(dt_f32(as)); /* a slot with no bytes is an absent operand */
|
||||
|
||||
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. */
|
||||
/* One scale a row, a flat stream at element pitch 1 as libref writes it (`group` is the
|
||||
* width of the row sums, not the scale). A larger plane, such as the [M, ceil(n/group)] one
|
||||
* the row's operand description may give, is accepted: libref requires only
|
||||
* numel(s) >= rows, writes s[r] and leaves the rest untouched. */
|
||||
|
||||
long long rows = 0, qrows = 0, srows = 0;
|
||||
const long long x_ld = r3d_rows_pitch(x, n, &rows);
|
||||
@@ -777,8 +722,7 @@ extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) {
|
||||
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. */
|
||||
/* `group` sizes asum only. n % group == 0, and the LDS accumulator is kI8MaxGroups wide. */
|
||||
int group = 0;
|
||||
if (as) {
|
||||
group = (int)r3d_geti_or(a, "group", R3D_W8_GROUP);
|
||||
@@ -797,8 +741,8 @@ extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream 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. */
|
||||
/* The int8 plane at group granularity, read by this library's i8a8 GEMM. Operands are libref's
|
||||
* oQuantFp8 shape {x, q, scale} with int8 codes. */
|
||||
enum { QAG_X = 0, QAG_Q, QAG_S };
|
||||
|
||||
extern "C" int r3d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) {
|
||||
@@ -812,9 +756,7 @@ extern "C" int r3d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) {
|
||||
|
||||
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. */
|
||||
/* Absent `group` defaults to 0, which r3d_group_of turns into one scale a row. */
|
||||
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;
|
||||
@@ -846,12 +788,11 @@ extern "C" int r3d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) {
|
||||
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 */
|
||||
if (r3d_has(y)) R3D_NEED(dt_bf16(y)); /* an empty slot is an absent operand */
|
||||
|
||||
/* "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. */
|
||||
/* "silu" (down_proj's input) or "sigmoid" (a gated attention o_proj's); `mode` is the integer
|
||||
* spelling and `act` wins when both are given. libref defines only these two, so a gelu gate
|
||||
* is unsupported. */
|
||||
const int act = r3d_act_code(a, "act", "mode", R3D_ACT_SILU);
|
||||
if (act < 0) return R3D_NO(RAD_E_UNSUPPORTED);
|
||||
|
||||
@@ -861,8 +802,8 @@ extern "C" int r3d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) {
|
||||
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. */
|
||||
/* gate_up must be dense [M, 2n], as the fused projection writes it; a sliced gate goes through
|
||||
* r3d_act_mul_bf16, which takes 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);
|
||||
@@ -890,15 +831,14 @@ extern "C" int r3d_rad_dequant(const RadArgs* a, RadStream stream) {
|
||||
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. */
|
||||
/* The codes' dtype is the encoding, read off the tensor since E4M3 and E5M2 bytes look alike.
|
||||
* A plain u8 plane carries no encoding and is refused (R3D_DT_U8 is the E4M3 code here). */
|
||||
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 */
|
||||
R3D_NEED(dt_bf16(y)); /* the launcher writes bf16 only */
|
||||
|
||||
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);
|
||||
@@ -911,8 +851,8 @@ extern "C" int r3d_rad_dequant(const RadArgs* a, RadStream stream) {
|
||||
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). */
|
||||
/* As in libref, `group` gives each group's width; without it the width is ceil(n/ngrp), with
|
||||
* ngrp taken from the scale stream's extent. */
|
||||
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;
|
||||
|
||||
+250
-322
@@ -1,52 +1,44 @@
|
||||
/* r3d_rows.cpp -- what libr3d can compute, and for which geometry.
|
||||
/* r3d_rows.cpp -- the libr3d row table: what each kernel computes 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.
|
||||
* 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 into this file to select, and nothing outside libr3d names libr3d's kernels.
|
||||
*
|
||||
* ============================================================ 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.
|
||||
* disagrees is refused at load (rad_abi.h, spec §2.3): arguments are positional, so two schemas
|
||||
* would give one call two meanings. libref declares the vocabulary (`docs/OPS.md`), so every schema
|
||||
* below is libref's: the same keys, types, requiredness, operand roles and optionality, in the same
|
||||
* order. The prose describes this library's rows; the loader compares only the positional slots.
|
||||
*
|
||||
* 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.
|
||||
* libr3d declares no new op: an op declared only by a kernel plugin has no reference to be checked
|
||||
* against.
|
||||
*
|
||||
* ============================================================ 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.
|
||||
* A constraint is a necessary condition on the geometry (spec §2.1). An operand's dtype is a
|
||||
* property of the call, and the shim checks it on the tensor. Constraints state 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 kernel
|
||||
* does not actually honour 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 end shifts every later initialiser, and because `nullptr` converts to any function pointer,
|
||||
* part of the shift still compiles. Unused trailing slots are left off and zero-initialised. 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 wave-matrix instructions use a 16x16 fragment layout
|
||||
* this table's dot2 kernels do not (r3d_common.h has the measurements).
|
||||
* The `layout` and `relayout` hooks here only 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 and scales. A
|
||||
* dot2 GEMM reads a weight in stored order; libr4d's fragment permutations exist for WMMA, which
|
||||
* these kernels do not use (see r3d_common.h).
|
||||
*
|
||||
* Pure host C++: no r3d.h, no HIP, so this table compiles and can be read and tested without ROCm.
|
||||
* Pure host C++ (no r3d.h, no HIP), so the table compiles and can be tested without ROCm.
|
||||
*/
|
||||
|
||||
#include "r3d_plugin.h"
|
||||
@@ -83,9 +75,8 @@
|
||||
|
||||
/* ================================================================== 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.
|
||||
* Operand names are diagnostics only; roles and optionality are positional and must match.
|
||||
* Operand names may differ from libref's (`b` for a gate, say) without changing the schema.
|
||||
*/
|
||||
|
||||
/* --- norms and elementwise --- */
|
||||
@@ -112,11 +103,10 @@ static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_
|
||||
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. */
|
||||
/* `s` is a weight operand, as the reference declares it: the issue resolves a handle and waits on
|
||||
* the mover, because a scale plane comes from the container or a quantiser, not from a buffer the
|
||||
* planner allocated for the step. The loader compares roles positionally, so declaring it IN would
|
||||
* get the whole library refused. */
|
||||
static const RadOperandSpec oScale[] = { { "x", RAD_OPD_IN, 0 }, { "s", RAD_OPD_WEIGHT, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 } };
|
||||
|
||||
@@ -189,38 +179,28 @@ static const RadOperandSpec oGemmQ[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RA
|
||||
|
||||
/* ================================================================== 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 vocab and sampler schemas, transcribed from libref. `r3d_selftest`'s schema phase compares
|
||||
* every declared schema against libref's, slot for slot, when the library loads, so a misspelled
|
||||
* key is caught at load rather than when a row first uses 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 sampler's behaviour is fully specified: the candidate set, the top-k tie-break, the order of
|
||||
* the renormalisations and the seeded draw are all observable, and libref is the oracle for each.
|
||||
*/
|
||||
|
||||
/* 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. */
|
||||
/* The gated MLP's activation as llama-family graphs emit it: one fused [M, 2n] projection, the
|
||||
* gate half activated and multiplied by the other half. `act_mul` is the same arithmetic over two
|
||||
* operands; an architecture emits one op 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. */
|
||||
/* The gated MLP band: one weight of N = 2n rows (gate first, then up), with the GEMM, the gate and
|
||||
* the output quantiser in one launch so the [M, N] intermediate is never stored. `act` is a required
|
||||
* string because an implementation compiles one gate; an optional key would let a row resolve for a
|
||||
* 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. */
|
||||
/* 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, which is why
|
||||
* the op is separate from gemm_nt. */
|
||||
static const RadParamSpec pLogits[] = { P_INT("M"), P_INT("n_vocab"), P_INT("n_embd"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oLogits[] = {
|
||||
@@ -233,6 +213,10 @@ static const RadOperandSpec oGemmQGated[] = {
|
||||
{ "out_bf16", RAD_OPD_OUT, 1 },
|
||||
};
|
||||
|
||||
/* DFlash2's candidate walk: a draft block of `steps` proposals with `top_k` candidates each,
|
||||
* rescored against the target's rank-d codebooks. `anchor_stride` is optional and defaults to 1.
|
||||
* `hp` is an optional per-edge scaling of the predecessor's codebook row; absent, it is a plane of
|
||||
* ones, as the reference computes. */
|
||||
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") };
|
||||
@@ -243,6 +227,10 @@ static const RadOperandSpec oDflashSelect[] = {
|
||||
{ "tokens", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* Paged attention. `block_size` is RAD_DERIVED (the container's cache geometry, admitted by a
|
||||
* constraint that only refuses its absence). `n_head`, `max_seqs`, `max_ctx` and `prefill_fp8` are
|
||||
* listed because a plugin's scratch hook sizes the split-KV buffer from them and both libraries must
|
||||
* agree on the parameter list; libref ignores them. */
|
||||
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"),
|
||||
@@ -305,13 +293,12 @@ static const RadOperandSpec oPick[] = { { "cand_idx", 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. */
|
||||
/* The fused norm-quantiser from the model unit, libref's slot for slot. `residual` is 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. */
|
||||
/* `residual` is optional because the op has a no-residual form (the launcher's `res` pointer is 0);
|
||||
* libref declares it INOUT optional 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 }
|
||||
@@ -361,8 +348,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"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 "
|
||||
"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, "
|
||||
@@ -383,17 +370,17 @@ static const RadOpSchema kSchemas[] = {
|
||||
|
||||
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 "
|
||||
"residual sum is stored as bf16 before the variance reads it, so the norm is taken over "
|
||||
"the rounded sum, as the `add` + `rmsnorm` pair computes it (`rmsnorm_add` 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."),
|
||||
"never narrowed. act_mul is the same arithmetic over two operands, narrowing the "
|
||||
"activation first, as a stored activation is."),
|
||||
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, "
|
||||
@@ -473,37 +460,32 @@ extern "C" const RadOpSchema* rad_kernel_schema_at(int 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.
|
||||
* The axes a kernel is instantiated along, measured per card by `rad-tune` (spec §15). Without a
|
||||
* matrix instruction to size a tile against, the rows have few axes: 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. */
|
||||
/* Split-K. 0 is not a point in the space but the kernel's rule, "the largest split legal at this
|
||||
* K" (r3d_args.h: libr3d's tunables). */
|
||||
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. */
|
||||
/* Non-temporal weight streaming: a decode GEMM reads a weight once per token, so the L2 serves
|
||||
* latency, not reuse. RDNA3 has no transposed-load instruction, so this axis only switches the cache
|
||||
* hints on the plain 128-bit stream. */
|
||||
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. */
|
||||
/* No `kb` axis: only a GEMM that stages a K slab through LDS has a slab width to tune, and the
|
||||
* skinny rows stream the weight through registers. */
|
||||
|
||||
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. */
|
||||
/* No `wv` axis: the quantised kernel's launcher uses a fixed block of eight waves, because its
|
||||
* weight decode (sixteen codes a lane into eight dot2) fills a wave's issue budget at any block
|
||||
* size. An axis the kernel ignores would only spend tuner time. */
|
||||
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" },
|
||||
@@ -524,8 +506,8 @@ static int gemm_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_
|
||||
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. */
|
||||
/* The chosen point, read back. `TUNE` falls back to the axis's default when the core appended
|
||||
* nothing, so a caller 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)
|
||||
@@ -551,21 +533,15 @@ extern "C" void r3d_cfg_topk(const RadArgs* a, R3dTopkCfg* out) {
|
||||
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. */
|
||||
/* Split-KV 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, halving it until they fit, so this is the request at the slice count the walk benefits
|
||||
* from, capped at 16 MiB. Attaching scratch makes the row non-concurrent (rad_kernel_concurrent is
|
||||
* `scratch == nullptr`), which is the cost 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. */
|
||||
/* Sized from the shape: a scratch hook runs at declare, when the operands' shapes are bound
|
||||
* but every tensor's `data` is still null. A hook that required data would answer 0 and the
|
||||
* split pass would find no buffer. gemm_scratch sizes from RadParam dims for the same 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;
|
||||
@@ -577,6 +553,9 @@ static int64_t attn_scratch(const RadArgs* a) {
|
||||
return want < cap ? want : cap;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
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];
|
||||
@@ -586,9 +565,9 @@ static int64_t gemm_scratch(const RadParam* p, int n_p) {
|
||||
|
||||
/* ================================================================== 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.
|
||||
* What the kernel cannot do, and what the selector needs. Divisibility follows the unit's lane map:
|
||||
* 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. */
|
||||
@@ -630,14 +609,12 @@ 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. */
|
||||
/* rope: the two modes this kernel implements and an even head_dim. The yarn, llama3 and ladder
|
||||
* parameters are absent from these rows' bands, so a geometry carrying them is not routed here.
|
||||
* `rotary_dim` cannot be constrained: it is optional, a constraint on a key the band does not carry
|
||||
* does not hold (see r3d_selftest.cpp's band-reachability phase), and llama-family graphs, which
|
||||
* rotate the whole head, omit it. The shim refuses an odd rotary_dim (RAD_E_SHAPE); absent, it is
|
||||
* head_dim, which the constraint keeps even. */
|
||||
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
|
||||
@@ -661,17 +638,17 @@ static const RadConstraint cScatterBf16[] = { C_IN("dtype", "bf16"), C_DIV("n",
|
||||
* 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. */
|
||||
/* `quant_act_i8` is the per-row int8 whose codes are in the int8 WMMA's step order, so its width
|
||||
* is a whole 16-byte step. `quant_act_i8g` is per group with row-major codes, as a dot2 GEMM reads
|
||||
* them; 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. */
|
||||
/* Not `C_IN("act", "silu sigmoid")`: `act` is optional on the op (a graph may carry libref's
|
||||
* integer `mode` instead, and libref defaults to silu), so a band with neither would match no row.
|
||||
* The shim reads `act`, then `mode`, then defaults to silu, and refuses gelu, which this unit has no
|
||||
* kernel for, 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"),
|
||||
@@ -681,50 +658,35 @@ static const RadConstraint cDequantE5[] = { C_IN("dtype", "fp8_e5m2"),
|
||||
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. */
|
||||
/* The GEMMs. The skinny row's band is the decode and verify height, M <= 16: it covers a
|
||||
* speculative verify with room to spare and stays below the height where staging the activations
|
||||
* through LDS pays. K even because the inner loop consumes pairs. N has no bound: a wave covering N
|
||||
* handles the tail, and feed-forward and vocabulary widths (11008, 14336, 128256, a checkpoint's
|
||||
* `intermediate_size`) vary. */
|
||||
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. */
|
||||
/* The vocabulary projection has no `dtype` constraint because its band carries no `dtype` key: the
|
||||
* head's dtype is a property of the weight (libref checks it with a `check_dtypes` hook). A
|
||||
* constraint on a key the band lacks does not hold, which would leave only the host kernel and the
|
||||
* engine would refuse to start, so the shim refuses an unsupported dtype instead.
|
||||
* `n_embd % 32` is the entry's chunk rule, stated so a band outside it is refused at declare rather
|
||||
* than at launch. `n_vocab >= 4` is the store's granularity (16-byte runs); a narrower band (a
|
||||
* shard's padding, a 1-id test vocabulary) is refused here. Above that floor the grid spans the
|
||||
* vocabulary at every M, so every vocabulary width runs 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. */
|
||||
/* The quantised GEMM above decode heights. Here `dtype` is the operand scheme (gemm_q_shape
|
||||
* switches on it), so C_IN filters rows, unlike logits_gemm, where the band's dtype names the
|
||||
* activation. M >= 17 complements gemm_nt_q_fp8a8_m16's M <= 16; a higher floor would leave batched
|
||||
* decode at 17..64 rows unserved. The tile's k-chunk (32) divides the container's scale block
|
||||
* (128), so `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. */
|
||||
/* The OCP-MXFP4 rows: e2m1 weight codes with one e8m0 scale per 32 of K, the activation scaled per
|
||||
* 128. Both are fixed by the format, so the `group` key has no kernel-side meaning and is not
|
||||
* constrained (the reference derives the planes from it). K % 128 covers the 32-block, the bands
|
||||
* split at M = 16 / 17 as for fp8a8, and the dtype names 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) };
|
||||
@@ -732,9 +694,8 @@ 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. */
|
||||
/* The symmetric int4 / int8 weight grids at decode heights: the block is the weight's scale group
|
||||
* (128) and the band is M <= 16. No row serves the 8-bit grid at prefill heights. */
|
||||
static const RadConstraint cGemmQW4A8M16[] = { C_IN("dtype", "w4a8"),
|
||||
C_GE("M", 1), C_LE("M", 16),
|
||||
C_DIV("K", 128), C_GE("N", 1) };
|
||||
@@ -742,26 +703,26 @@ static const RadConstraint cGemmQW8A8M16[] = { C_IN("dtype", "w8a8"),
|
||||
C_GE("M", 1), C_LE("M", 16),
|
||||
C_DIV("K", 128), C_GE("N", 1) };
|
||||
|
||||
/* The tiled bf16 GEMM at prefill heights. M >= 17 complements cGemmM16's M <= 16, so the two rows
|
||||
* never compete for a band: the skinny shape (a wave a run of columns, the weight streamed through
|
||||
* registers) suits up to 16 rows and the 128x128 tile suits more. K % 32 is the tile's k-chunk and
|
||||
* N >= 8 the bf16 store run. */
|
||||
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. */
|
||||
* must end on a block boundary (gemm_tune_valid). `group` is required and every band names it, so
|
||||
* the row constrains it. `pb1` and `pb2` are optional, and a constraint on a key the band omits does
|
||||
* not hold, so constraining them would send every GEMM band of a container using the default block
|
||||
* to the reference's host kernel. The launcher defaults them to `group` (r3d_gemm_fp8a16_nt_m1.hip)
|
||||
* and refuses a pb2 that differs from the code group, the container's own invariant. */
|
||||
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. */
|
||||
/* The int8 GEMM's constraints. No row uses them: a row must name an entry point the library
|
||||
* defines, or the plugin fails to load. */
|
||||
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) };
|
||||
@@ -771,30 +732,25 @@ static const RadConstraint cGemmQI8[] = { C_IN("dtype", "i8a8"),
|
||||
* 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. */
|
||||
/* Constraint arrays are declared ahead of the rows that use them, each with a comment naming the
|
||||
* 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.
|
||||
* Two rows llama graphs ask for that the model unit serves. `silu_mul` constrains only the dtype
|
||||
* and an even `n`: `act` is not in this op's parameter list (the op fuses one fixed activation), and
|
||||
* a constraint on a key the band lacks does not hold, so the act_mul constraints would match no band.
|
||||
* `rmsnorm_quant_fp8` requires the group the kernel covers with a wave to divide `n`; the standalone
|
||||
* quantiser's `n % 4` would admit bands this kernel refuses at launch.
|
||||
*/
|
||||
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.
|
||||
/* The sampler's pre-filters constrain only `n_vocab`. Their bands carry `n_vocab` and `M` (plus
|
||||
* `vocab_off`, and `k` for logprobs) and no `dtype` key, so a dtype constraint would match no band;
|
||||
* the shims check that the tensors are f32. `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) };
|
||||
@@ -814,25 +770,18 @@ 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.
|
||||
/* `row_topk` is banded on dtype, so it has two rows. The candidate stages are banded on `n_cand`,
|
||||
* capped at the kernel's ceiling: five f32 arrays of n_cand in LDS is 20 KiB of the 64 KiB, and the
|
||||
* shim refuses a wider band (RAD_E_SHAPE). The vocab stages carry `n_vocab` and no dtype key; the
|
||||
* shim checks that the logits are f32.
|
||||
*/
|
||||
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. */
|
||||
/* The container's 2-bit vocab weights. `group` is both the weight's K block and the scale's block.
|
||||
* K must also be a multiple of the launcher's chunk (2048 / M-tile), which the launcher refuses and
|
||||
* the row does not express. */
|
||||
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) };
|
||||
@@ -844,12 +793,18 @@ static const RadConstraint cGemmQW2A8Tiled[] = { C_IN("dtype", "w2a8 w4a8_asym")
|
||||
C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 17),
|
||||
C_DIV("K", 128) };
|
||||
|
||||
/* `group` is one key for three things: 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 launcher's ceiling. */
|
||||
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) };
|
||||
|
||||
/* Every key the walk reads is required and in the band, so all are bound; `top_k <= 256` gives each
|
||||
* candidate one lane. `anchor_stride` is deliberately unbound: it is optional, defaults to 1, and
|
||||
* the kernel serves any value >= 1, so a band that omits it must still resolve. */
|
||||
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),
|
||||
@@ -1121,11 +1076,10 @@ static const RadKernelInfo kKernels[] = {
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* Plain row-major code planes with one f32 scale per (row, group). A dot2 GEMM reads codes in
|
||||
* stored order, so they carry no fragment permutation, and a container converted on this card is
|
||||
* readable by libref and by `rad-convert` on any card. Only `quant_act_i8` keeps libref's
|
||||
* permutation, because its order is part of the op (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",
|
||||
@@ -1136,12 +1090,11 @@ static const RadKernelInfo kKernels[] = {
|
||||
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. */
|
||||
/* The per-row int8, in libref's step order. The order belongs to the op: the codes are the WMMA
|
||||
* A-fragment's and the oracle compares the plane, so the kernel's store address applies the
|
||||
* permutation. libr3d's own int8 GEMM reads the row-major `quant_act_i8g` plane (two rows below);
|
||||
* this row exists so an architecture that emits the op 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 "
|
||||
@@ -1199,8 +1152,8 @@ static const RadKernelInfo kKernels[] = {
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* past an activation kept in registers. There is no fragment layout, so the 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",
|
||||
@@ -1218,9 +1171,9 @@ static const RadKernelInfo kKernels[] = {
|
||||
|
||||
/* ------------------------------------------------------------------ r3d_gemm_fp8a16_nt_m1.hip
|
||||
*
|
||||
* The same shape against a block-scaled weight. The codes are E4M3, widened to f16 exactly and
|
||||
* The same shape against a block-scaled weight. The E4M3 codes are 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.
|
||||
* products, 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",
|
||||
@@ -1286,8 +1239,8 @@ static const RadKernelInfo kKernels[] = {
|
||||
|
||||
{ "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",
|
||||
"any n; a workgroup a row; the activation is not narrowed before the product, as ref's is not "
|
||||
"(act_mul, over two operands, narrows it, as a stored activation is)",
|
||||
"bf16 in and out, fp32 arithmetic",
|
||||
RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY,
|
||||
ROW(cSiluMul), NOTUNE,
|
||||
@@ -1309,8 +1262,8 @@ static const RadKernelInfo kKernels[] = {
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* sparse (a row's history is a few hundred tokens against a vocabulary of about 130K), so walking
|
||||
* the window rather than the row, the reference's shape, is also the fast one.
|
||||
*/
|
||||
{ "sample_penalties_f32", "sample_penalties", "sample",
|
||||
"presence, frequency and repetition penalties from the row's history, in place",
|
||||
@@ -1379,11 +1332,10 @@ static const RadKernelInfo kKernels[] = {
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* in what a workgroup is: decode is one head group over 16 query rows with split-KV, prefill a
|
||||
* 16-token query tile. The walk's block bounds are per workgroup: a tile is staged once into LDS
|
||||
* and every wave consumes it, so a wave must not narrow the walk to its own query positions, or the
|
||||
* waves would stage different blocks into the same LDS.
|
||||
*/
|
||||
{ "attn_paged_bf16_decode", "attn_paged", "attn",
|
||||
"paged attention over a bf16 cache: one head group a workgroup, 16-token tiles, split-KV",
|
||||
@@ -1432,14 +1384,14 @@ static const RadKernelInfo kKernels[] = {
|
||||
|
||||
/* ------------------------------------------------------------------ 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
|
||||
* The sampler's spine: the row's top-R and the stages that turn its 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.
|
||||
* `topk_next` is a sort by (-value, +column) written as a loop (`v == *pv && i <= *pi` steps through
|
||||
* a run of equal values), so one pass keeping the best R returns the reference's R pairs, in its
|
||||
* order and 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",
|
||||
@@ -1561,30 +1513,25 @@ static const RadKernelInfo kKernels[] = {
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* The speculative decoder's accept step. It is a gather, not arithmetic: two 63.8 MiB codebooks and
|
||||
* `M * steps * rank` gathered elements, so each score's rank sum is one lane's serial chain. There
|
||||
* is no work to hide the gather behind, and a tree reduction would change the 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.
|
||||
* `output.weight`: U2 codes, int8 activations, one f32 scale per activation row (ZP_I8_ROW), and a
|
||||
* joined `b_scale` stored as two planes (scale f16, zero u8) behind one operand, which only a layout
|
||||
* hook can present. libref's shape hook declines the dtype for that reason, so kbench has no case
|
||||
* for the band: the row's opd_shape is null (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.
|
||||
* Exactness: `v_fdot2_f32_f16` carries about 22 bits of mantissa on integer operands, not 24, so an
|
||||
* integer dot through it is inexact above 2^20. The error is about 2^-22 of the magnitude, so a
|
||||
* smaller bias shrinks the tail; the bias is 128 (sampled worst |err| 0.015625, against 0.125 at
|
||||
* bias 1024). 0.1-0.2% of outputs land one bf16 ulp off the reference (rel_l2 5.0e-3, max_abs
|
||||
* 9.8e-4, no non-finite values). This row is not bit-exact; the unit's dot probe states the bound.
|
||||
*
|
||||
* 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).
|
||||
* M <= 16 is decode.
|
||||
*/
|
||||
{ "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",
|
||||
@@ -1612,17 +1559,15 @@ static const RadKernelInfo kKernels[] = {
|
||||
"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",
|
||||
"a scalar load with nothing to overlap it dominates the band otherwise (the output bits are "
|
||||
"the same either way). 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)",
|
||||
"(U2/U4) is refused and named, not approximated (rad_load_bits reads codes, not zeros). 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 is far from its read floor; a wider k-chunk, not more loads in flight, is what would "
|
||||
"close it",
|
||||
RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1,
|
||||
ROW(cGemmQW2A8Tiled), NOTUNE,
|
||||
nullptr, nullptr, r3d_rad_gemm_nt_q_w2a8_tiled, nullptr,
|
||||
@@ -1631,12 +1576,10 @@ static const RadKernelInfo kKernels[] = {
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* weight traffic. The block is one group by 256/group rows so the group's amax closes in-block. That
|
||||
* block shape is the quantiser's rule, so there is nothing to tune, and the row states its M ceiling
|
||||
* in the prose. Throughput is low (about 0.7% of the card's fp8 peak at M=64), but the alternative
|
||||
* is the reference's host GEMM.
|
||||
*/
|
||||
{ "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",
|
||||
@@ -1678,14 +1621,11 @@ static const RadKernelInfo kKernels[] = {
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* The head is the largest read in a decode step (510 MiB at 130560 x 2048), and the sampler reads
|
||||
* f32, so the store is f32 rather than narrowed and a prefill band writes about 1 GB. Against the
|
||||
* reference the f32 plane is at rel_l2 1.77e-6 (about 30 f32 ulps at K=2048), from dot2 folding two
|
||||
* products into one rounding; widening the operands to f16 first changes nothing. The head's own
|
||||
* bf16 quantisation (4.9e-4 an element) is 300x coarser.
|
||||
*/
|
||||
{ "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",
|
||||
@@ -1710,14 +1650,9 @@ static const RadKernelInfo kKernels[] = {
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* The prefill projection. At these densities the dot product, not memory bandwidth, is the limit
|
||||
* (about 27-36% of the card's dense f16 peak at the graph's bands), which is why the E4M3 decoder is
|
||||
* a table: 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 "
|
||||
@@ -1757,10 +1692,8 @@ static const RadKernelInfo kKernels[] = {
|
||||
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. */
|
||||
/* The same tiling on gemm_nt's bf16 operands, the prefill projection the reference runs on the
|
||||
* host. 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 "
|
||||
@@ -1769,7 +1702,7 @@ static const RadKernelInfo kKernels[] = {
|
||||
"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",
|
||||
"further",
|
||||
RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_TILED,
|
||||
ROW(cGemmNTTiled), NOTUNE,
|
||||
nullptr, nullptr, r3d_rad_gemm_nt_bf16_tiled, nullptr,
|
||||
@@ -1779,17 +1712,16 @@ static const RadKernelInfo kKernels[] = {
|
||||
|
||||
/* ================================================================== the exports
|
||||
*
|
||||
* The two every plugin must export, the four that make a kernel library, and `rad_kernel_concurrent`.
|
||||
* The two exports every plugin needs, 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").
|
||||
* No `rad_kernel_chain`: chaining replaces the queue's ordering between two dependent launches with
|
||||
* a spin in the kernel, and no row here has a chained form, so every answer would be 0. Omitting the
|
||||
* symbol means the same (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.
|
||||
* No `rad_kernel_collective`: these rows run on single-GPU cards, and an all-reduce over the PCIe x1
|
||||
* slot most of them sit in is slower than going through the host.
|
||||
*/
|
||||
extern "C" int rad_kernel_count(void) {
|
||||
return (int)(sizeof(kKernels) / sizeof(kKernels[0]));
|
||||
@@ -1799,18 +1731,16 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) {
|
||||
return &kKernels[i];
|
||||
}
|
||||
|
||||
/* Which rows touch nothing but their operands and the scratch they were handed.
|
||||
/* Which rows touch nothing but their operands and their scratch.
|
||||
*
|
||||
* 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 elementwise, norm, quant, cast, rope, cache and gather rows: one launch, one pass, no state
|
||||
* between launches, so two may run at once and the engine can start one 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.
|
||||
* Not the GEMM rows, because of the scratch: the arena belongs to the op instance, so two layers'
|
||||
* decode GEMMs launched together share it and their split-K partials and arrival counters would
|
||||
* collide. With sk = 1 a GEMM has no partials, but the promise is per row and sk is chosen per
|
||||
* geometry, so the row states the worst case.
|
||||
*/
|
||||
extern "C" int rad_kernel_concurrent(int i) {
|
||||
const RadKernelInfo* k = rad_kernel_at(i);
|
||||
@@ -1824,14 +1754,12 @@ static const RadPluginInfo kInfo = {
|
||||
"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",
|
||||
"fp8a16 GEMMs, the matrix work through v_dot2acc_f32_f16 rather than RDNA3's WMMA "
|
||||
"fragment layout",
|
||||
/* 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. */
|
||||
* loader warns once when the code object it picked names a card this list does not
|
||||
* (`target_covers`), so the string must be the build's real targets. R3D_BUILD_TARGET comes
|
||||
* from CMakeLists.txt as a compile definition; the fallback is the whole family. */
|
||||
R3D_BUILD_TARGET,
|
||||
};
|
||||
|
||||
|
||||
+148
-295
@@ -1,95 +1,62 @@
|
||||
/* 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.
|
||||
* The arithmetic is libref's, transcribed, including the order of its passes. `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 frozen at declare and two rows of one batch with different top_p must
|
||||
* resolve to one kernel. The params plane must be 32-bit words (see params_ok).
|
||||
*
|
||||
* ============================== what has to agree, and with what ==============================
|
||||
* ============================== reproducibility ==============================
|
||||
*
|
||||
* The draws must REPRODUCE, so the summation order is transcription and not performance:
|
||||
* Draws must reproduce, so summation order is transcribed, not chosen for speed:
|
||||
*
|
||||
* - 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.
|
||||
* - Every max is a strict `>`, order-free, and keeps NaN out: libref's `if (v > mx) mx = v` from
|
||||
* -infinity never adopts a NaN, and the butterfly merges the same way.
|
||||
* - An f32 sum is not order-free. libref's sums (the pick, the narrowing stages) and the CDF scan
|
||||
* run over the candidates in index order, so exps are computed in parallel and accumulated
|
||||
* serially on one lane in index order: parallel values, serial sums.
|
||||
* - The draw is specified by the ABI: splitmix64 over `seed * 0x9E3779B97F4A7C15 + pos`, top 24
|
||||
* bits over 2^24, integer arithmetic, so device and host agree. Independent draws at one
|
||||
* position XOR the seed with a key: RAD_SAMPLE_KEY_PICK (0) for the pick, RAD_SAMPLE_KEY_XTC for
|
||||
* XTC's coin.
|
||||
* - `ref_exp`/`ref_log` are `(float)std::exp((double)x)` and `(float)std::log((double)x)`, as in
|
||||
* the reference. On gfx1102 the device's double exp/log match glibc's bit for bit over 2^20
|
||||
* points in [-100, 100], while `expf` differs from the host's by 1 ulp on 5.7% of them, and a
|
||||
* `u < cum` comparison on an ulp boundary changes the drawn token. Consumer RDNA3 runs fp64 at
|
||||
* 1:64, which the candidate set (1024 exponentials a row) can afford. The attention unit, at
|
||||
* millions of exponentials a layer, uses a 0.5-ulp polynomial instead.
|
||||
*
|
||||
* 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.
|
||||
* ============================== one-pass top-k ==============================
|
||||
*
|
||||
* ============================== 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. That is a sort by (-value, +column), so one pass keeping
|
||||
* the best R in that order yields the same R pairs in the same order. At N=130560, R=16, M=1792
|
||||
* this reads the row once instead of sixteen times. The pass is bound by accepted inserts into
|
||||
* each lane's list, not by memory; filtering against a block-wide threshold instead of each lane's
|
||||
* own tail would cut the inserts about tenfold.
|
||||
*
|
||||
* 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.
|
||||
* The per-lane list is at most 64 deep, and the merge keeps the best 64 of two lists. Almost every
|
||||
* element costs one comparison against the lane's last entry (about 12% clear it at 510 elements a
|
||||
* lane). 64 covers R=16, a 64-wide candidate set and practical top_k values; a larger k takes
|
||||
* ceil(k/64) passes, carrying the chain's state, so the answer is the same at any k.
|
||||
*
|
||||
* 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.
|
||||
* 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 becomes the best even when it is a NaN, and
|
||||
* nothing displaces it. A row whose first logit is NaN yields R identical (NaN, 0) slots. The
|
||||
* kernels test the first element for that case explicitly.
|
||||
*
|
||||
* ============================== 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)
|
||||
* One block a row everywhere. At the band a row is 130560 f32 (510 KiB) and M is 2048, so argmax
|
||||
* and top-k each read 1 GiB and temp reads and writes 2 GiB: these are memory-bound. A candidate
|
||||
* row is at most 1024 f32 and the work is transcendentals, so the same shape costs nothing and
|
||||
* gives the serial order for free; the stages keep the row in LDS, which 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.
|
||||
* Single rank. `vocab_off` is applied where libref applies it (`row_topk`'s reported ids,
|
||||
* `sample_topk`'s `pairs` plane), and the pair planes are written as the shape hooks describe them.
|
||||
* There is no merge kernel: libref's own shape hook declines `sample_merge_topk`.
|
||||
*/
|
||||
|
||||
#include "r3d.h"
|
||||
@@ -106,31 +73,18 @@ 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. */
|
||||
/* The candidate pool's depth, and the widest candidate set the narrowing stages carry in LDS (the
|
||||
* engine's declared buffer width). */
|
||||
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
|
||||
/* The reference's transcendentals: a double call rounded once to f32 (see the file header), so the
|
||||
* draws are the reference's. */
|
||||
__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. */
|
||||
* in [0, 1). 24 bits fit f32's mantissa exactly. */
|
||||
__device__ __forceinline__ uint64_t splitmix64(uint64_t z) {
|
||||
z += 0x9E3779B97F4A7C15ull;
|
||||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
|
||||
@@ -142,17 +96,8 @@ __device__ __forceinline__ float uniform01(uint64_t seed, uint64_t 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. */
|
||||
/* A block-wide maximum: a wave butterfly of fmaxf, then the wave partials. fmaxf drops a NaN, so a
|
||||
* NaN is never the result. `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 */
|
||||
@@ -166,30 +111,20 @@ __device__ __forceinline__ float block_max(float v, float* lds) {
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* The largest logit, ties to the lower column, so greedy and top-1 agree. The reference's scan is
|
||||
* `bi < 0 || v > best`: strict, so the first of a run wins, and a NaN is adopted only as the row's
|
||||
* first element. The parallel form uses the same total order, which is associative, so the
|
||||
* butterfly and the serial scan agree.
|
||||
*/
|
||||
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. */
|
||||
/* `best_take(a, b)` keeps `a` unless `b` is strictly better (larger, or equal with a lower column);
|
||||
* `b.i == 0xffffffff` means nothing examined yet. */
|
||||
__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];
|
||||
@@ -223,9 +158,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_argmax_kernel(
|
||||
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. */
|
||||
/* topk_next's seed: a row whose first element is NaN reports column 0 (see the file
|
||||
* header); every other NaN is skipped. */
|
||||
const float x0 = ldg_f32(lr);
|
||||
tok[row] = (int32_t)(x0 != x0 ? 0u : t.i);
|
||||
}
|
||||
@@ -233,10 +167,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_argmax_kernel(
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
* `inv = 1/t` once per row, then every logit multiplied by it (not divided), in place. A row with
|
||||
* `!(t > 0) || t == 1` is left bit-exact, so temp 1.0 and temp 0.0 (greedy) are no-ops.
|
||||
*/
|
||||
__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) {
|
||||
@@ -255,8 +187,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_temp_kernel(
|
||||
|
||||
/* 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.
|
||||
* params [M] 24 words a row; argmax does not read it (libref describes it anyway)
|
||||
*
|
||||
* 0, -1 null, -2 bad extent, -3 pitch that does not describe the operand, -4 the HIP launch failed.
|
||||
* No allocation, no synchronisation. */
|
||||
@@ -290,20 +221,16 @@ extern "C" int r3d_sample_temp(long lg, long params, int M, int n_vocab, long lo
|
||||
|
||||
/* ================================================================== 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:
|
||||
* One lane's share of a row, kept as the POOL best by (value descending, column ascending), the
|
||||
* order `topk_next` walks.
|
||||
*
|
||||
* - 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.
|
||||
* - The order is strict and total, so merging two lists keeps the first POOL of the union.
|
||||
* - The list lives in registers, so insertion is a POOL-step sift with static indices; a dynamic
|
||||
* index would spill the array to private memory. Only elements that beat the lane's last entry
|
||||
* (one compare) are sifted.
|
||||
*
|
||||
* 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.
|
||||
* Unfilled slots hold (-INFINITY, 0xffffffff): below any real value and above any real column, so a
|
||||
* real -infinity logit (a masked one) beats a pad and extraction stops at the first pad.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
@@ -314,27 +241,23 @@ __device__ __forceinline__ bool pool_better(float av, uint32_t ai, float bv, uin
|
||||
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.
|
||||
/* Insert (v, i) into a lane's register list. POOL is the list depth and the width of a pass, so a
|
||||
* router's top_k of 16 uses a 16-deep pool rather than paying for 64.
|
||||
*
|
||||
* `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. */
|
||||
* `pv`/`pi` carry the pick chain across passes: an element above the last pick, or equal to it at
|
||||
* or before its column, was already picked (`topk_next`'s two skips, in its order). */
|
||||
template <int POOL>
|
||||
__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 != v) return; /* skip NaN; the caller handles a NaN first element */
|
||||
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 */
|
||||
if (!pool_better(v, i, lv[POOL - 1], li[POOL - 1])) return; /* 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 */
|
||||
for (int j = 0; j < POOL; ++j) { /* the sift, static indices */
|
||||
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;
|
||||
@@ -342,26 +265,22 @@ __device__ __forceinline__ void pool_insert(float v, uint32_t i, float pv, uint3
|
||||
}
|
||||
}
|
||||
|
||||
/* The best 64 of the union of two lists, in the pool's order.
|
||||
/* The best POOL 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. */
|
||||
* A and B are descending, so C[j] = the better of A[j] and B[POOL-1-j] is a bitonic sequence
|
||||
* holding the union's top POOL; a bitonic sort in registers with static strides finishes it without
|
||||
* spilling. Both lanes of a shuffle pair compute the same result, so a butterfly of merges is a
|
||||
* wave reduction. */
|
||||
template <int POOL>
|
||||
__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<J>(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
|
||||
@@ -370,8 +289,8 @@ __device__ __forceinline__ void pool_merge(const float* av, const uint32_t* ai,
|
||||
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". */
|
||||
/* One descending run: every compare-exchange moves the better entry 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;
|
||||
@@ -381,8 +300,7 @@ __device__ __forceinline__ void pool_merge(const float* av, const uint32_t* ai,
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* One lane's pass over its columns of a row. STEP is 1 (scalar) or 4 (one vector load a step). */
|
||||
template <int XDT, int STEP, int POOL>
|
||||
__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) {
|
||||
@@ -399,7 +317,7 @@ __device__ __forceinline__ void pool_scan(const void* __restrict__ x, uint32_t n
|
||||
pool_insert<POOL>(bf16_to_f32((uint16_t)(hi & 0xffffu)), 4 * w + 2, pv, pi, lv, li);
|
||||
pool_insert<POOL>(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 */
|
||||
for (uint32_t c = nw * 4 + tid; c < n; c += kThreads) /* the row's tail */
|
||||
pool_insert<POOL>(bf16_to_f32((uint16_t)ldg_u16(p + c)), c, pv, pi, lv, li);
|
||||
} else {
|
||||
for (uint32_t c = tid; c < n; c += kThreads)
|
||||
@@ -426,10 +344,8 @@ __device__ __forceinline__ void pool_scan(const void* __restrict__ x, uint32_t n
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
* LDS, and the block's POOL best left in LDS at [kWaves*POOL, ...) (in LDS because the extraction
|
||||
* walks them with a runtime index). Returns how many are real. */
|
||||
template <int POOL>
|
||||
__device__ __forceinline__ uint32_t pool_pass(const void* __restrict__ x, uint32_t n,
|
||||
uint32_t x_ld, int xdt, int vec,
|
||||
@@ -471,7 +387,7 @@ __device__ __forceinline__ uint32_t pool_pass(const void* __restrict__ x, uint32
|
||||
__syncthreads();
|
||||
|
||||
uint32_t nout = 0;
|
||||
if (threadIdx.x == 0) { /* the eight lists, merged with cursors */
|
||||
if (threadIdx.x == 0) { /* merge the eight wave lists with cursors */
|
||||
uint32_t cur[kWaves];
|
||||
#pragma unroll
|
||||
for (int w = 0; w < kWaves; ++w) cur[w] = 0;
|
||||
@@ -492,19 +408,14 @@ __device__ __forceinline__ uint32_t pool_pass(const void* __restrict__ x, uint32
|
||||
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.
|
||||
* 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's bits in the
|
||||
* first f32 slot, the value in the second, id -1 for an unfilled slot). One scan per POOL entries
|
||||
* (see the file header).
|
||||
*/
|
||||
namespace {
|
||||
|
||||
@@ -523,22 +434,24 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void row_topk_kernel(
|
||||
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. */
|
||||
/* topk_next's seed: a row whose first element is NaN reports (0, NaN) in every slot. */
|
||||
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;
|
||||
/* The test reads shared memory after the barrier, so the whole block takes the same branch
|
||||
* and none of it reaches the pool passes' barriers. */
|
||||
if (st[0] != st[0]) {
|
||||
if (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;
|
||||
@@ -552,8 +465,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void row_topk_kernel(
|
||||
__syncthreads();
|
||||
const uint32_t nout = pool_pass<POOL>(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. */
|
||||
/* Only the first `nout` block entries were written this pass (the rest are stale), 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;
|
||||
@@ -582,18 +495,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void row_topk_kernel(
|
||||
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). */
|
||||
/* One row's top_k: the request's, clamped to the buffer; the whole width when absent; none for a
|
||||
* greedy row, whose token is sample_argmax's. */
|
||||
__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;
|
||||
@@ -654,14 +561,13 @@ extern "C" int r3d_row_topk(long x, long idx, long val, long pairs, int M, int N
|
||||
|
||||
/* ================================================================== 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.
|
||||
* 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. Unlike row_topk, the width is
|
||||
* the buffer's (a declare-time bound) and the row's top_k narrows within it (top_k 40 in a 1024-wide
|
||||
* buffer is 40 candidates and 984 holes), and a greedy row takes none.
|
||||
*
|
||||
* `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.
|
||||
* `cand_val` carries logits, not probabilities: each narrowing stage takes its own softmax over the
|
||||
* set, so the stages compose in any order.
|
||||
*/
|
||||
template <int POOL>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel(
|
||||
@@ -679,8 +585,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel(
|
||||
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. */
|
||||
/* The whole buffer is written every step, since a stale candidate from the previous step would
|
||||
* be drawn. */
|
||||
auto hole = [&](uint32_t r) {
|
||||
ir[r] = -1;
|
||||
vr[r] = -INFINITY;
|
||||
@@ -706,8 +612,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel(
|
||||
__syncthreads();
|
||||
const uint32_t nout = pool_pass<POOL>(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. */
|
||||
/* As in row_topk: `nout` 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;
|
||||
@@ -716,7 +621,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel(
|
||||
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 */
|
||||
ir[done + j] = (int32_t)col; /* cand_idx is local to 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;
|
||||
@@ -734,8 +639,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel(
|
||||
|
||||
/* 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
|
||||
* 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
|
||||
@@ -771,66 +676,21 @@ extern "C" int r3d_sample_topk(long lg, long params, long ci, long cv, long pair
|
||||
|
||||
/* ================================================================== 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:
|
||||
* One block a row of the candidate set, the row in LDS (five arrays of up to 1024 f32, 20 KiB):
|
||||
*
|
||||
* - 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.
|
||||
* - the max is libref's strict `if (v > mx) mx = v` from -infinity, so a hole, a masked
|
||||
* candidate at -infinity and a NaN are never the max;
|
||||
* - exp(v - mx) is computed for all candidates in parallel into LDS;
|
||||
* - every sum (the normaliser, the top-p prefix, the entropy, the inverse-CDF scan) is libref's
|
||||
* loop in index order on lane 0. A parallel prefix sum would round differently and could draw a
|
||||
* different token; the serial loop is 1024 adds, small next to the transcendentals.
|
||||
*
|
||||
* 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.
|
||||
* Every stage leaves a greedy row alone, as the reference does.
|
||||
*/
|
||||
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;
|
||||
@@ -867,8 +727,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel(
|
||||
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. */
|
||||
/* mx over live candidates with a strict `>` from -infinity, excluding holes, masked candidates
|
||||
* and NaN, as the reference's loop does. */
|
||||
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];
|
||||
@@ -927,9 +787,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel(
|
||||
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`. */
|
||||
/* Count and last index are order-free (a sum of small integers and a max), so no serial
|
||||
* loop is needed; candidates are re-tested below from the same `s_ev`. */
|
||||
const float n_above = block_sum<kThreads>(cnt, red);
|
||||
const float hi = block_max(last, red);
|
||||
if (n_above < 2.0f) return; /* needs two to exclude all but the least likely */
|
||||
@@ -939,8 +798,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel(
|
||||
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 */
|
||||
} else if (STAGE == ST_TYPICAL) { /* overwrites s_ev with log(q); only the pick
|
||||
* reads s_ev afterwards, and it never runs this */
|
||||
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)
|
||||
@@ -962,7 +821,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel(
|
||||
__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. */
|
||||
* p but does not depend on candidate order. */
|
||||
float cut = INFINITY;
|
||||
for (uint32_t c = threadIdx.x; c < n_cand; c += kThreads) {
|
||||
if (!(s_q[c] > 0.0f)) continue;
|
||||
@@ -1004,8 +863,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel(
|
||||
} /* 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
|
||||
* 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. */
|
||||
@@ -1056,10 +915,9 @@ extern "C" int r3d_sample_pick(long ci, long cv, long params, long tok, int M, i
|
||||
|
||||
/* ================================================================== 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.
|
||||
* Nine shims, one per op. Dtypes come from the tensors and geometry from the operands; `M` is the
|
||||
* band's ceiling, never the row count. The params plane is checked as libref checks it (a 32-bit
|
||||
* dtype and enough bytes for M rows) and must be contiguous, since the kernels index it flat.
|
||||
*/
|
||||
|
||||
#define R3D_NEED(expr) do { const int r3d_s = (expr); if (r3d_s) return R3D_NO(r3d_s); } while (0)
|
||||
@@ -1079,9 +937,8 @@ 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. */
|
||||
/* The params plane: [M, 24] words. The dtype test matters: a 16-bit view passes a byte-count check
|
||||
* and then misreads every row. */
|
||||
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;
|
||||
@@ -1159,8 +1016,7 @@ extern "C" int r3d_rad_sample_argmax(const RadArgs* a, RadStream stream) {
|
||||
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. */
|
||||
/* argmax reads nothing from params, so a missing plane is not a refusal. */
|
||||
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));
|
||||
@@ -1199,7 +1055,7 @@ extern "C" int r3d_rad_sample_topk(const RadArgs* a, RadStream stream) {
|
||||
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. */
|
||||
/* The width is the buffer's 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;
|
||||
@@ -1244,10 +1100,7 @@ static inline int cand_row_ok(const RadArgs* a, const RadTensor* ci, const RadTe
|
||||
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. */
|
||||
/* The step's rows come from the operand; the band key `M` is only checked as an upper bound. */
|
||||
const long long rows = cirows;
|
||||
if (rows <= 0 || rows > 0x7fffffffLL) { r3d_trace_desc("ci", ci);
|
||||
if (r3d_trace_on())
|
||||
|
||||
+126
-207
@@ -3,78 +3,54 @@
|
||||
* `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.
|
||||
* The arithmetic is libref's, transcribed, and `abi/rad_sample.h` is the wire format for every
|
||||
* scalar (one 96-byte row per sampled position). Order is transcribed wherever it is visible: the
|
||||
* penalties law (sign-dependent repetition, count times frequency, presence once per distinct
|
||||
* token, all 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 whitelist exemption, and the mask's bit-per-token rule.
|
||||
*
|
||||
* ============================== what each stage reads, and why the shapes differ ==============
|
||||
* ============================== stage shapes ==============================
|
||||
*
|
||||
* 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:
|
||||
* At the band a row is 130560 f32 and there are 2048 rows: the logits plane is 1.02 GiB, about
|
||||
* 3.6 ms a pass on gfx1102. The stages fall into two shapes by how many columns they touch, as
|
||||
* the reference does:
|
||||
*
|
||||
* 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.
|
||||
* History stages (penalties, dry, ngram_ban). A window is 64 tokens, so a row touches at most 64
|
||||
* columns: one block of 64 threads a row, a position a thread, the window read straight from L2
|
||||
* (4096 integer reads a row). The quadratic scans cost little, so there is no LDS copy.
|
||||
*
|
||||
* 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.
|
||||
* Row stages (mask, logprobs). These read or write the whole plane and are bandwidth-bound: 256
|
||||
* threads a row, each lane a contiguous run of columns.
|
||||
*
|
||||
* `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
|
||||
* `sample_logprobs` reads the row once where libref reads it three times (max, sum of
|
||||
* `exp(v - max)`, k-list). Each lane keeps a running max and a running double sum of
|
||||
* `exp(v - its own max)`, rescaling the sum when its max rises, and pairs merge 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.
|
||||
* which is the reference's sum shifted by a constant per lane; it agrees to about 1e-15 relative,
|
||||
* far below the f32 store's 6e-8. The max and the k-list cross lanes by shuffle; the sum merges in
|
||||
* LDS (see sample_logprobs_kernel), checked by `r3d_lanes_check` at the end of the file, which
|
||||
* `r3d_selftest.cpp` runs. The exp is `exp(double)`, the reference's width, which makes this the
|
||||
* file's one fp64-heavy kernel (consumer RDNA3 runs doubles at 1:64); at the band most of its time
|
||||
* is the double exp, not the read.
|
||||
*
|
||||
* 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.
|
||||
* The k-list is per lane, k deep, in the reference's order (descending by value, ties to the lower
|
||||
* column, `topk_next`'s total order) and merged pairwise in the same butterfly. The pool is 64
|
||||
* deep; a larger k is refused, not truncated.
|
||||
*
|
||||
* ============================== agreement, and where this file declines ==============================
|
||||
* ============================== agreement and 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.
|
||||
* Maxima use a strict `>` with the max as the first argument (`std::max`'s law), so a NaN is never
|
||||
* adopted as the row's max. A NaN in the sum propagates, as the reference's `exp(NaN - mx)` does.
|
||||
*
|
||||
* 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.
|
||||
* A row whose parameters turn the stage off is left bit-exact; the flag test is the reference's,
|
||||
* and for penalties so is the identity test (rep 1, freq 0, pres 0).
|
||||
*
|
||||
* 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.
|
||||
* Declines (RAD_E_UNSUPPORTED or a dtype refusal from the shim, none reachable from a row that
|
||||
* carries its constraints): a history plane wider than 2^31/8 columns; `k` above 64 for logprobs;
|
||||
* an `ngram` plane of the wrong dtype; mask or whitelist planes that are not 32-bit words.
|
||||
*/
|
||||
|
||||
#include "r3d.h"
|
||||
@@ -88,8 +64,8 @@
|
||||
|
||||
/* ================================================================== 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.
|
||||
* Helpers are per-unit and internal-linkage: a non-static copy would collide at link with the same
|
||||
* helper in another unit.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
@@ -99,17 +75,9 @@ 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
|
||||
/* The row's summary accumulates `exp` in double, as the reference's sum does. At the band the
|
||||
* double exp is most of the kernel's time; it stays, so the summary is the reference's arithmetic. */
|
||||
__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) {
|
||||
@@ -122,12 +90,10 @@ template <int N>
|
||||
__device__ __forceinline__ int32_t xor_i32(int32_t v) {
|
||||
return (int32_t)r3d_xor_lane_u32<N>((uint32_t)v);
|
||||
}
|
||||
/* There is no 64-bit lane shuffle here on purpose: see sample_logprobs_kernel. */
|
||||
/* No 64-bit numeric lane shuffle: 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. */
|
||||
/* The reference's window, verbatim, 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. */
|
||||
__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;
|
||||
@@ -144,8 +110,8 @@ __device__ __forceinline__ bool hist_window(const RadSampleParams& sp, int32_t l
|
||||
return hl > 0;
|
||||
}
|
||||
|
||||
/* The law, verbatim, including the stop short of overflow: repeated multiplication, so
|
||||
* every implementation lands on the same float. */
|
||||
/* The reference's penalty, verbatim, including the stop short of overflow. Repeated multiplication
|
||||
* rather than powf, 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;
|
||||
@@ -157,8 +123,8 @@ __device__ __forceinline__ float dry_penalty(float multiplier, float base, int64
|
||||
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. */
|
||||
/* The k-list's order: descending by value, ties to the lower column. `above(x, y)` means x comes
|
||||
* first (the reference's comparator, `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);
|
||||
@@ -166,13 +132,12 @@ __device__ __forceinline__ bool above(Cand x, Cand y) {
|
||||
|
||||
/* ================================================================== 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.
|
||||
* 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 is id -1, logit
|
||||
* -infinity. Rows without RAD_SP_LOGPROBS are not written.
|
||||
*
|
||||
* 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.
|
||||
* One pass (see the file header): max, sum and k-list accumulate from the same read, and the sum is
|
||||
* rescaled into the final max at each merge.
|
||||
*/
|
||||
struct Acc {
|
||||
float mx;
|
||||
@@ -181,17 +146,17 @@ struct Acc {
|
||||
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. */
|
||||
/* A lane's running state over its own elements. A new maximum rescales the sum so far, the cost
|
||||
* of not knowing the max up front as the reference does. */
|
||||
__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). */
|
||||
/* The reference's insertion: an element not above the k-th is dropped; otherwise it goes in
|
||||
* the first slot it beats. A NaN beats no slot, so it lands at the tail and the list is
|
||||
* unchanged. */
|
||||
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;
|
||||
@@ -201,10 +166,9 @@ __device__ __forceinline__ void acc_push(Acc& a, int k, uint32_t col, float v) {
|
||||
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). */
|
||||
/* The merge of two lanes' states: a strict max, the sum of both shifted sums, and the lists merged
|
||||
* in the same order. Equal values at equal columns cannot occur (each column belongs to one lane),
|
||||
* and a NaN entry is above nothing. */
|
||||
__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;
|
||||
@@ -234,35 +198,20 @@ __global__ __launch_bounds__(THR) void sample_logprobs_kernel(
|
||||
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 k-list and the max meet their partners by lane shuffle, five rounds. The shuffle mask
|
||||
* on wave32 is `0xFFFFFFFFull`; `~0ull` would name lanes 32..63, which do not exist.
|
||||
*
|
||||
* 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<N>((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. */
|
||||
* The sum does not cross lanes; it merges in LDS below. A double can cross lanes only as its
|
||||
* bits: `(unsigned long long)d` converts by value and truncates the partner's term to its
|
||||
* integer part (see lanes_check_kernel). The k-list entries are bit patterns (a float's
|
||||
* pattern and an int packed into 8 bytes), so they cross as one 64-bit shuffle. */
|
||||
#define R3D_ACC_XOR(M) \
|
||||
{ \
|
||||
Acc b; \
|
||||
b.mx = r3d_xor_lane<M>(a.mx); \
|
||||
b.n = xor_i32<M>((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. */ \
|
||||
/* One entry, a float's pattern and a column, crosses lanes as one 8-byte pattern. */ \
|
||||
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); \
|
||||
@@ -270,8 +219,7 @@ __global__ __launch_bounds__(THR) void sample_logprobs_kernel(
|
||||
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 */ \
|
||||
const float mx = a.mx > b.mx ? a.mx : b.mx; /* no lane's max is a NaN (strict test) */ \
|
||||
a = acc_merge(a, b, (int)k); \
|
||||
a.mx = mx; \
|
||||
}
|
||||
@@ -282,9 +230,9 @@ __global__ __launch_bounds__(THR) void sample_logprobs_kernel(
|
||||
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. */
|
||||
/* The wave's sum in LDS: the wave's max, 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. */
|
||||
__shared__ float s_mx[kThreads];
|
||||
__shared__ double s_sum[kThreads];
|
||||
__shared__ float w_mx[kWaves];
|
||||
@@ -345,16 +293,15 @@ __global__ __launch_bounds__(THR) void sample_logprobs_kernel(
|
||||
|
||||
/* ================================================================== sample_penalties
|
||||
*
|
||||
* The law. llama.cpp's ordering, at the token's first occurrence in the window:
|
||||
* llama.cpp's ordering, applied 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.
|
||||
* count carries the multiplicity, so the update runs once per distinct token; the scan is the
|
||||
* reference's: walk the window from the front, stop at an earlier occurrence, count the rest.
|
||||
*
|
||||
* 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.
|
||||
@@ -395,15 +342,14 @@ __global__ __launch_bounds__(kPre) void sample_penalties_kernel(
|
||||
|
||||
/* ================================================================== 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.
|
||||
* DRY (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 repeat limit. The token at j+1 would extend that
|
||||
* repeat and is penalised once by multiplier * base^(n - allowed), using the longest repeat it
|
||||
* follows. A breaker token is never penalised, and only lengths >= `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.
|
||||
* A thread a position, the window read from L2. The reference's per-token map becomes a maximum
|
||||
* over the threads sharing a token, applied by the thread at the token's first occurrence, so each
|
||||
* column is written once.
|
||||
*/
|
||||
__global__ __launch_bounds__(kPre) void sample_dry_kernel(
|
||||
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist,
|
||||
@@ -434,8 +380,8 @@ __global__ __launch_bounds__(kPre) void sample_dry_kernel(
|
||||
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. */
|
||||
/* The longest repeat any position attributes to this token; the lowest qualifying j is
|
||||
* the one writer. */
|
||||
int64_t longest = m;
|
||||
bool first = true;
|
||||
for (int64_t q = 0; q + 1 < hl; ++q) {
|
||||
@@ -455,18 +401,17 @@ __global__ __launch_bounds__(kPre) void sample_dry_kernel(
|
||||
|
||||
/* ================================================================== sample_ngram_ban
|
||||
*
|
||||
* The law, the windowed no-repeat-ngram ban. With the row's window s[0, hl):
|
||||
* 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.
|
||||
* The window bounds the start index, so an n-gram straddling the window's edge is searched. A
|
||||
* banned token's logit becomes -infinity; whitelisted columns are exempt and never touched. n == 1
|
||||
* bans every token in the window (empty prefix). A row with n 0 is left unchanged.
|
||||
*
|
||||
* 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.
|
||||
* A thread a search index. Several indices may ban the same token, but all write the same
|
||||
* -infinity.
|
||||
*/
|
||||
__global__ __launch_bounds__(kPre) void sample_ngram_ban_kernel(
|
||||
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist,
|
||||
@@ -514,16 +459,12 @@ __global__ __launch_bounds__(kPre) void sample_ngram_ban_kernel(
|
||||
|
||||
/* ================================================================== 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.
|
||||
* A set bit means allowed; an unset column's logit becomes -infinity. A thread takes one bitmask
|
||||
* word and its 32 columns, a contiguous 128-byte segment. An all-ones word is skipped; an all-zeros
|
||||
* word is a straight run of stores.
|
||||
*
|
||||
* `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.
|
||||
* `mask_row` selects the row of the bitmask plane; as in the reference, a row index outside the
|
||||
* plane (-1 included) leaves the row unmasked.
|
||||
*/
|
||||
__global__ __launch_bounds__(kThreads) void sample_mask_kernel(
|
||||
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ bm,
|
||||
@@ -556,9 +497,8 @@ 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. */
|
||||
/* The params plane: [M, 24] words. The dtype test matters: a 16-bit view passes a byte-count check
|
||||
* and then misreads every row. */
|
||||
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;
|
||||
@@ -600,8 +540,8 @@ static inline int r3d_launch_status(int rc) {
|
||||
/* 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. */
|
||||
/* As in the reference: the width from the band, else the plane's last dimension; a rank-1
|
||||
* plane has none, 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;
|
||||
@@ -697,13 +637,11 @@ extern "C" int r3d_sample_mask(long lg, long params, long bitmask, int M, int n_
|
||||
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 */
|
||||
if (mask_rows < M) return -3; /* the plane must hold at least M rows */
|
||||
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. */
|
||||
/* mask_rows is the bitmask plane's own row count, the bound the reference tests mask_row
|
||||
* against; it may exceed M when a caller passes a larger plane. The grid stays M, the logits
|
||||
* row count. */
|
||||
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,
|
||||
@@ -725,8 +663,7 @@ extern "C" int r3d_rad_sample_logprobs(const RadArgs* a, RadStream stream) {
|
||||
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. */
|
||||
/* The pool is 64 deep per lane; the row's C_LE("k", 64) keeps larger requests 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));
|
||||
@@ -770,7 +707,7 @@ extern "C" int r3d_rad_sample_dry(const RadArgs* a, RadStream stream) {
|
||||
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. */
|
||||
/* One exemption byte per history 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);
|
||||
@@ -822,8 +759,7 @@ extern "C" int r3d_rad_sample_mask(const RadArgs* a, RadStream stream) {
|
||||
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. */
|
||||
/* The plane's own row count is the bound the reference tests; it may exceed the logits'. */
|
||||
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,
|
||||
@@ -832,32 +768,20 @@ extern "C" int r3d_rad_sample_mask(const RadArgs* a, RadStream 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.
|
||||
* Every wave-sum in libr3d is a butterfly over lane shuffles, and an error in a lane helper (say, a
|
||||
* stale half of a 64-bit value) is invisible to a codec sweep. The logprobs k-list crosses lanes as
|
||||
* 8-byte values, so this file carries the on-device control for the helpers: one entry per lane of
|
||||
* all 8 waves, seeds at wave-local lanes 6, 9, 19 and 25, five butterfly rounds, over
|
||||
* `r3d_xor_lane_u64` (two 32-bit shuffles), and one 64-bit shuffle.
|
||||
*
|
||||
* 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:
|
||||
* The form that must not be written converts by value:
|
||||
*
|
||||
* d += (double)r3d_xor_lane_u64<N>((unsigned long long)d); // WRONG
|
||||
* d += (double)r3d_xor_lane_u64<N>((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.
|
||||
* The partner's term arrives truncated to its integer part, so a wave of fractions sums to the
|
||||
* largest integer part; the error vanishes for integer terms. The correct form moves bits
|
||||
* (`bits_of` / `d_from_bits` below), as the k-list's shuffle does. The control catches both traps:
|
||||
* summing an IEEE pattern as an integer, and converting a pattern to a value.
|
||||
*/
|
||||
__device__ __forceinline__ double d_from_bits(unsigned long long b) {
|
||||
double d;
|
||||
@@ -871,12 +795,11 @@ __device__ __forceinline__ unsigned long long bits_of(double d) {
|
||||
}
|
||||
|
||||
__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. */
|
||||
/* kThreads and kWave are ambiguous outside the anonymous namespace, 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. */
|
||||
/* Four non-zero lanes per wave, expected sum 0.08945 + 1 + 0.5971 + 0.9768 in the butterfly's
|
||||
* order; every wave carries them. */
|
||||
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;
|
||||
@@ -886,8 +809,7 @@ __global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ o
|
||||
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. */
|
||||
/* Form 0: the 32-bit butterfly, over a value read from LDS so it is not a constant. */
|
||||
float f = s_f[threadIdx.x];
|
||||
f += r3d_xor_lane<16>(f);
|
||||
f += r3d_xor_lane<8>(f);
|
||||
@@ -896,24 +818,21 @@ __global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ o
|
||||
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. */
|
||||
/* Form 1: the halves form over a value derived from the lane index, passed as bits. */
|
||||
double d = seed;
|
||||
#define R3D_L64(N) d += d_from_bits(r3d_xor_lane_u64<N>(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. */
|
||||
/* Form 2: the halves form over a value loaded from LDS, as an accumulator is. */
|
||||
d = s_d[threadIdx.x];
|
||||
#define R3D_L64B(N) d += d_from_bits(r3d_xor_lane_u64<N>(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. */
|
||||
/* Form 3: one 64-bit shuffle, the k-list's form; the mask names wave32's 32 lanes. */
|
||||
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)
|
||||
@@ -921,9 +840,9 @@ __global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ o
|
||||
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. */
|
||||
/* Writes four forms x 256 lanes of doubles (8 KiB, caller-owned). 0, -1 null, -4 the launch
|
||||
* failed. r3d_selftest.cpp resolves 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),
|
||||
|
||||
+147
-242
@@ -1,57 +1,45 @@
|
||||
/* 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:
|
||||
* wrong kernel, so the table is printed 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;
|
||||
* - every row's `op` has a schema declared by this plugin;
|
||||
* - every constraint key is a declared parameter of that op (a key renamed in one place only
|
||||
* 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.
|
||||
* values (the loader refuses a plugin otherwise), and layout hooks appear only on the
|
||||
* joined-weight rows, always with their relayout writer;
|
||||
* - every `opd_shape` describes as many operands as its schema declares, 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 -- the lane map, not a missing instruction, is the reason, 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.
|
||||
* The codecs are checked against the ABI's host versions in `rad_plugin.h`: bf16 and f16 over all
|
||||
* 65536 patterns, E4M3 over all 256 codes, the E4M3 encoder over saturating, subnormal,
|
||||
* signed-zero and NaN cases, int8 against `rad_round_even_sat` over every tie in its band.
|
||||
* rad-kbench compares whole ops, where a codec error appears only as a diffuse percentage.
|
||||
* libr3d's codecs are software (its bf16 packing is `v_perm`, not `v_cvt_pk_bf16_f32`), so they
|
||||
* are the plugin's own arithmetic.
|
||||
*
|
||||
* 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.
|
||||
* 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 what a
|
||||
* table check cannot: an untested null operand, a stride from the wrong axis, an operand index off
|
||||
* by one, an undefined symbol, a stray write.
|
||||
*
|
||||
* The numerical oracle is `rad-kbench` (`kernels.rkb` against libref); this program checks that
|
||||
* the rows are reachable on this device, from this .so, at 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 <name>`; 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.
|
||||
* One child process per row: a GPU page fault makes ROCr print a line and abort the process, so
|
||||
* the parent runs the static phase and then re-execs itself per row with `--case <name>`. A child
|
||||
* killed by a signal is a FAIL naming the signal. posix_spawn rather than fork, because the
|
||||
* parent's HIP runtime threads are already up and only exec resets them.
|
||||
*
|
||||
* `--case <name>` is also the reproducer: it runs one row, alone, in the foreground.
|
||||
* `--case <name>` also reproduces 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 "r3d_plugin.h" /* the entry points */
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <spawn.h>
|
||||
@@ -83,9 +71,7 @@ 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. */
|
||||
/* The plugin's table, through the symbols dlsym'd in main (the program does not link libr3d). */
|
||||
static int (*P_count)(void) = nullptr;
|
||||
static const RadKernelInfo* (*P_at)(int) = nullptr;
|
||||
static int (*P_scount)(void) = nullptr;
|
||||
@@ -96,8 +82,7 @@ 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. */
|
||||
/* printf into a string, as the loader builds its messages. */
|
||||
static std::string fmt(const char* f, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, f);
|
||||
@@ -140,11 +125,9 @@ static const RadParamSpec* find_param(const RadOpSchema* s, const char* key) {
|
||||
|
||||
/* ================================================================== 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).
|
||||
* Failure modes: a constraint on an undeclared key (the row silently matches nothing), a tunable
|
||||
* default outside its axis (the loader refuses the whole plugin), a row whose `op` names another
|
||||
* op's schema, a description whose operand count disagrees with its schema (every case skipped).
|
||||
*/
|
||||
static void check_table() {
|
||||
const int n = rows();
|
||||
@@ -167,28 +150,20 @@ static void check_table() {
|
||||
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. */
|
||||
/* No row repacks a weight; kernels read the container's stored order. The exception is the
|
||||
* container's quantised weight (codes and scales as planes behind one operand), which the
|
||||
* mapped tier places only if a loaded library can read it in place. The rows below cover
|
||||
* w2a8's {1,group} grid with a zero, and the fp8a8 GEMM's and lm_head's {128,128} grid
|
||||
* without, each transcribed from the reference's hook. Any other name is a rule change and
|
||||
* 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. */
|
||||
/* A layout hook and its relayout writer come as a pair (abi/rad_abi.h: a query answering
|
||||
* RAD_OK promises the loader the writer produces that form; a hook without one fails at
|
||||
* load). No row may carry an unrelayout, since this library invents no format a tool
|
||||
* would need to invert. */
|
||||
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);
|
||||
@@ -207,8 +182,8 @@ static void check_table() {
|
||||
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. */
|
||||
/* String constraints match string parameters and integer ones integers; 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);
|
||||
@@ -251,21 +226,16 @@ static void check_table() {
|
||||
|
||||
/* ================================================================== 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.
|
||||
* The loader refuses the whole .so when its schema for an op differs from the first declarer's
|
||||
* (core/plugin/loader.cpp, `schema_same`). The comparison is positional: parameter count, each
|
||||
* parameter's key, type and requiredness; operand count, each operand's role and optionality.
|
||||
* Names and doc strings are free. This repeats that comparison against libref, naming the op and
|
||||
* the slot, since a mismatch otherwise shows only as one log line at engine load.
|
||||
*/
|
||||
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. */
|
||||
/* libref.so beside the plugin under test, as 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";
|
||||
@@ -287,9 +257,7 @@ static void check_reference_schemas() {
|
||||
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. */
|
||||
/* Not a refusal: an op the reference does not declare has nothing to agree with. */
|
||||
skip("'%s' has no schema in the reference, so nothing to compare against", mine->op);
|
||||
continue;
|
||||
}
|
||||
@@ -343,19 +311,11 @@ static void check_reference_schemas() {
|
||||
|
||||
/* ================================================================== 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.
|
||||
* A constraint on a key the band's geometry lacks does not hold (core/util/rad_util.cpp,
|
||||
* constraint_holds), and bands carry only the parameters their graph set. So a row that constrains
|
||||
* an optional parameter serves only graphs that state it. kbench cannot show this, because its
|
||||
* fixtures name every parameter. Such a constraint is legitimate but must be deliberate, so each one
|
||||
* is listed here.
|
||||
*/
|
||||
static void check_band_reach() {
|
||||
std::printf("== band reachability\n");
|
||||
@@ -377,7 +337,7 @@ static void check_band_reach() {
|
||||
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 */
|
||||
if (!s) continue; /* not in the reference: nothing to compare */
|
||||
for (int ci = 0; ci < k->n_constraints; ++ci) {
|
||||
const RadConstraint& c = k->constraints[ci];
|
||||
if (!c.key) continue;
|
||||
@@ -399,11 +359,9 @@ static void check_band_reach() {
|
||||
|
||||
/* ================================================================== 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.
|
||||
* Against the schemas, for one geometry per op at real model widths (4096 hidden, 128 head, 11008
|
||||
* intermediate, 128256 vocabulary). A wrong operand count, rank or zero extent is a bug in the
|
||||
* description or the schema; rad-kbench would only report it as skipped cases.
|
||||
*/
|
||||
static void check_shapes() {
|
||||
/* RadParam is { key, kind, ival, ihi, sval, dval }. */
|
||||
@@ -439,14 +397,13 @@ static void check_shapes() {
|
||||
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),
|
||||
{ "rmsnorm_quant_fp8", { PI("M", 1792), PI("n", 5120), PF("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. */
|
||||
/* The rest are MiniCPM5-2B's bands: vocab 130560, MLP 6144 wide, head 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"),
|
||||
@@ -456,10 +413,8 @@ static void check_shapes() {
|
||||
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. */
|
||||
/* A context deeper than the query chunk, so the walk covers keys before the chunk; then a
|
||||
* window that starts mid-block over an fp8 cache, which exercises tile sharing. */
|
||||
{ "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),
|
||||
@@ -468,9 +423,8 @@ static void check_shapes() {
|
||||
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. */
|
||||
/* A 27B model's sliding-window band as the fixture draws it: the descales are absent, so an
|
||||
* fp8 cache has no scale plane and the reference reads 1.0. */
|
||||
{ "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),
|
||||
@@ -489,9 +443,8 @@ static void check_shapes() {
|
||||
{ "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. */
|
||||
/* MiniCPM5-2B's speculative decoder band: a 7-token draft block, 16 candidates a step, a
|
||||
* rank-256 codebook over a 130560-token vocabulary (63.8 MiB each), anchors 7 apart. */
|
||||
{ "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") } },
|
||||
};
|
||||
@@ -499,13 +452,8 @@ static void check_shapes() {
|
||||
#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. */
|
||||
/* Shape hooks for ops with no row in the table, found by symbol name in the plugin, so their
|
||||
* descriptions are checked even without a kernel. */
|
||||
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" },
|
||||
@@ -533,7 +481,7 @@ static void check_shapes() {
|
||||
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);
|
||||
if (!row) std::printf(" -- '%s': operand description from the shape hook (no row)\n", gm.op);
|
||||
|
||||
bool bad = false;
|
||||
for (int o = 0; o < s->n_operands && !bad; ++o) {
|
||||
@@ -561,23 +509,17 @@ static void check_shapes() {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== 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. */
|
||||
* quiets a NaN the way the ABI's does 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.
|
||||
* Against the ABI's host implementations, bit for bit: the widenings are exact (seven mantissa bits
|
||||
* into ten; four exponent and three mantissa bits into five and ten) and the encoders mirror
|
||||
* `rad_plugin.h`.
|
||||
*/
|
||||
static void check_codecs() {
|
||||
std::printf("== codecs\n");
|
||||
@@ -587,15 +529,14 @@ static void check_codecs() {
|
||||
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. */
|
||||
/* Encoder against encoder: both quiet a NaN's payload, 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. */
|
||||
/* f16: the same, subnormals included (a naive shift-and-round loses them). */
|
||||
bad = 0;
|
||||
for (uint32_t u = 0; u < 0x10000 && !bad; ++u) {
|
||||
const uint16_t h = (uint16_t)u;
|
||||
@@ -606,13 +547,10 @@ static void check_codecs() {
|
||||
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. */
|
||||
/* A bf16 pair widened to an f16 pair in one register, which the dot2 path relies on. Exact over
|
||||
* f16's normal range [2^-14, 65504] (r3d_codecs.h), which is what is swept. Outside it the
|
||||
* widening saturates above 65504 and truncates toward zero below 2^-14, where f16's subnormal
|
||||
* grid is coarser than bf16's; those patterns are counted in the message. */
|
||||
bad = 0;
|
||||
int inside = 0, outside = 0;
|
||||
for (uint32_t u = 0; u < 0x10000 && !bad; ++u) {
|
||||
@@ -630,8 +568,8 @@ static void check_codecs() {
|
||||
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. */
|
||||
/* E4M3, both directions, over every code, and the exact widening to f16 (448 is well inside
|
||||
* f16's range). */
|
||||
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; }
|
||||
@@ -645,8 +583,8 @@ static void check_codecs() {
|
||||
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. */
|
||||
/* The encoder over the cases that break a naive one: saturation at 448, subnormals below 2^-6,
|
||||
* the sign of zero, NaN, and typical scale values. */
|
||||
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,
|
||||
@@ -670,18 +608,17 @@ static void check_codecs() {
|
||||
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. */
|
||||
/* dot2's operand order only: the device instruction folds the products with guard bits, so
|
||||
* this checks that pairs are read low-then-high; accumulation order is rad-kbench's to check. */
|
||||
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. */
|
||||
/* The epilogue's bf16 store: two values, one dword, round to nearest even, the high value in
|
||||
* the high half. A `v_perm` picking the wrong bytes shows here; in a kernel's output a swapped
|
||||
* pair looks plausible. */
|
||||
bad = 0;
|
||||
for (int i = -500; i < 500 && !bad; ++i) {
|
||||
const float lo = (float)i * 0.001f, hi = (float)i * -0.002f;
|
||||
@@ -704,20 +641,18 @@ struct Case {
|
||||
RadTensor t[MAX_OPD];
|
||||
RadParam p[32];
|
||||
std::vector<void*> dev;
|
||||
std::vector<void*> host; /* pinned operands: read on the host, read by the kernel too */
|
||||
std::vector<void*> host; /* pinned operands, read by both host and kernel */
|
||||
std::vector<std::string> 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.
|
||||
* Every wave-sum in the library is five butterfly rounds over lane shuffles, and an error there 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 sums to an integer. The device 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");
|
||||
@@ -800,9 +735,8 @@ static uint32_t xorshift(uint32_t& s) {
|
||||
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. */
|
||||
/* Fill a host plane per its description. "Normals" are a sum of four uniforms: any non-special
|
||||
* value exercises the arithmetic, and special cases are rad-kbench's. */
|
||||
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
|
||||
@@ -823,8 +757,8 @@ static void fill_plane(const RadOpdDesc& d, uint8_t* p, size_t nel, uint32_t see
|
||||
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. */
|
||||
/* Two signed codes a byte, low nibble first, drawn in -7..7 and stored as the low four bits
|
||||
* of two's complement. */
|
||||
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;
|
||||
@@ -835,8 +769,8 @@ static void fill_plane(const RadOpdDesc& d, uint8_t* p, size_t nel, uint32_t see
|
||||
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. */
|
||||
/* Two e2m1 codes a byte over all 16 values, exercising the unpack's magnitude and sign
|
||||
* paths. */
|
||||
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);
|
||||
@@ -864,21 +798,16 @@ static void fill_plane(const RadOpdDesc& d, uint8_t* p, size_t nel, uint32_t see
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* The geometry a row runs at: the row's constraint values where it has them, real model widths
|
||||
* elsewhere, so the constraint table itself is what is tested. */
|
||||
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. */
|
||||
/* Only required and constrained parameters, as the engine passes them: an optional
|
||||
* parameter the graph did not set is absent, and the kernel uses libref's `p_*` default.
|
||||
* Filling every optional slot would test geometries no graph produces (for rope, the
|
||||
* `sections` string would switch to a mode the row's constraints exclude). */
|
||||
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))
|
||||
@@ -911,18 +840,15 @@ static void make_params(Case& c, const RadKernelInfo* k, const RadOpSchema* s) {
|
||||
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. */
|
||||
/* A constraint's own value wins; a C_IN 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. */
|
||||
/* out.sval must outlive the loop, so the words live in c.words, reserved once so
|
||||
* no reallocation moves them. */
|
||||
c.words.emplace_back(x.sval);
|
||||
std::string& w = c.words.back();
|
||||
const size_t sp0 = w.find(' ');
|
||||
@@ -936,19 +862,17 @@ static void make_params(Case& c, const RadKernelInfo* k, const RadOpSchema* s) {
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
* `gemm_q_shape` declines w2a8: the container stores scale and zero as two planes behind the one
|
||||
* `b_scale` operand, and a RadOpdDesc names one dtype and extent set. A byte-count-only hook would
|
||||
* fill a container header with random bytes. So the row's `opd_shape` is null and this builds its
|
||||
* case by hand at MiniCPM5-2B's band, with the joined plane built by rad_planes_relayout as
|
||||
* r3d_gemm_nt_q_w2a8_driver.cpp builds it. */
|
||||
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 */
|
||||
c.n_p = 0; /* the model's band, not the constraint 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;
|
||||
@@ -992,12 +916,9 @@ static int build_w2a8(Case& c, const RadOpSchema* s) {
|
||||
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). */
|
||||
/* Schema order: a, a_scale, b, b_scale (the joined blob), y, a_sum, b_ref (absent: a null
|
||||
* tensor). y is pre-filled with a bf16 NaN, since a shim that returns RAD_OK without launching
|
||||
* would otherwise leave finite bytes behind. */
|
||||
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 } };
|
||||
@@ -1022,16 +943,11 @@ static int build_w2a8(Case& c, const RadOpSchema* s) {
|
||||
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. */
|
||||
/* The joined operand is pinned host memory, as the engine's mapped tier holds a joined
|
||||
* weight: the shim reads its header on the host and the kernel reads the same bytes.
|
||||
* Plain malloc is not device-addressable. */
|
||||
if (hipHostMalloc(&d, bytes, 0) != hipSuccess) { fail("w2a8: hipHostMalloc(%zu) failed", bytes); return 1; }
|
||||
c.dev.push_back(d);
|
||||
c.host.push_back(d);
|
||||
@@ -1065,8 +981,7 @@ static int run_row(int 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. */
|
||||
/* No device is a skip, not a failure: build machines and CI run the static phase alone. */
|
||||
int ndev = 0;
|
||||
if (hipGetDeviceCount(&ndev) != hipSuccess || ndev == 0) {
|
||||
skip("no device visible");
|
||||
@@ -1104,13 +1019,10 @@ static int run_row(int i) {
|
||||
: (size_t)nel * dt_bytes(d.dtype);
|
||||
std::vector<uint8_t> 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. */
|
||||
/* TODO: pre-fill output planes with the dtype's NaN, to catch a shim that returns RAD_OK
|
||||
* without launching. Doing so makes `quant_act_i8_bf16` and `sample_logprobs_f32` die on
|
||||
* signal 11 in the spawned child (both pass with `--case`); both write planes the
|
||||
* reference pads. build_w2a8 already NaN-fills its output. */
|
||||
void* p = nullptr;
|
||||
if (hipMalloc(&p, bytes) != hipSuccess) { fail("hipMalloc(%zu) failed", bytes); return 1; }
|
||||
c.dev.push_back(p);
|
||||
@@ -1150,9 +1062,7 @@ launched:
|
||||
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. */
|
||||
/* Print the geometry, since the return code alone does not say what the shim was given. */
|
||||
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)");
|
||||
@@ -1162,7 +1072,7 @@ launched:
|
||||
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]);
|
||||
for (uint32_t r = 0; r < t.rank; ++r) std::printf(" %lld/%lld", (long long)t.shape[r], (long long)t.stride[r]);
|
||||
std::printf("\n");
|
||||
}
|
||||
ret = 1;
|
||||
@@ -1175,16 +1085,13 @@ launched:
|
||||
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. */
|
||||
/* A joined plane is pinned host memory holding the container's bytes, not the row's
|
||||
* output: nothing to read back. */
|
||||
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. */
|
||||
/* Sub-byte planes are counted in codes, not bytes (a U2 code is a quarter byte). */
|
||||
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)
|
||||
@@ -1207,24 +1114,20 @@ launched:
|
||||
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. */
|
||||
/* -infinity is the sampler's contract (a dropped or unfilled candidate, a masked or
|
||||
* banned logit, an unfilled row_topk slot); a NaN is always a failure. */
|
||||
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. */
|
||||
/* Two planes are padded to the reference's grid: `asum`, the int8 activation's row sums on
|
||||
* a 16-row grid, and `stats`. The row leaves the pad unwritten, so a NaN there is not
|
||||
* the row's work. Named planes only; NaN anywhere else is a failure. */
|
||||
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);
|
||||
"reference's grid, not the row's work)", outs, outs == 1 ? "" : "s", nan,
|
||||
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) {
|
||||
@@ -1240,16 +1143,18 @@ launched:
|
||||
}
|
||||
|
||||
if (scratch) (void)hipFree(scratch);
|
||||
for (void* p : c.dev) (void)hipFree(p);
|
||||
for (void* p : c.dev) {
|
||||
if (std::find(c.host.begin(), c.host.end(), p) != c.host.end()) (void)hipHostFree(p);
|
||||
else (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. */
|
||||
/* Unbuffered stdout, so when a row dies the last line printed is the last thing that worked,
|
||||
* even when output goes to a file or pipe. */
|
||||
std::setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
const char* path = nullptr;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
@@ -1262,7 +1167,7 @@ int main(int argc, char** argv) {
|
||||
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. */
|
||||
/* dlopen, not link, so an undefined symbol in the .so is reported here. */
|
||||
void* h = dlopen(path, RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) { std::fprintf(stderr, "r3d_selftest: %s\n", dlerror()); return 2; }
|
||||
g_h = h;
|
||||
|
||||
+113
-160
@@ -1,45 +1,37 @@
|
||||
/* 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.
|
||||
* libr3d's side of the `RadShapeFn` hook. The component that reads an operand knows its extent,
|
||||
* and a row that exists only here is invisible to the hand-written table in `tools/`. Correctness
|
||||
* checks, benchmarks and the coverage census size 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.
|
||||
* The shim is the authority for every extent: each `r3d_rad_*` entry point unpacks `RadArgs.t[i]`
|
||||
* into extents and pitches, 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
|
||||
* Content matters as much as size. A token id gathers a codebook row, 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.
|
||||
* range, such an operand tests out-of-range handling instead of arithmetic, and colliding scatter
|
||||
* indices are a race. `RAD_FILL_INDEX` with an explicit `idx_max` states each range, and
|
||||
* `RAD_OPD_F_IDX_UNIQUE` marks 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`:
|
||||
* yields a meaningless pass.
|
||||
*
|
||||
* 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.
|
||||
* Does not arise here (libr4d declines it): both quantised rows state their activation
|
||||
* dtype in `dtype`, so `a` is bf16 against fp8 (fp8a16) or i8 against i8 (i8a8).
|
||||
*
|
||||
* 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.
|
||||
* mrope, imrope and axial take one position per component, component-major, with the count
|
||||
* from `sections`. libr3d's kernel implements neox and gptj only 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.
|
||||
* No tuned axis is read: 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.
|
||||
* Pure host code (no r3d.h, no HIP), like r3d_rows.cpp, so it compiles without ROCm.
|
||||
*/
|
||||
|
||||
#include <cstdint>
|
||||
@@ -52,12 +44,12 @@ 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
|
||||
* count can be checked against the schema in r3d_rows.cpp (the tool checks
|
||||
* `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. */
|
||||
* extent (`pick` refuses 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;
|
||||
@@ -83,8 +75,7 @@ RadOpdDesc opd_idx(int64_t d0, int64_t idx_max, int64_t konst = -1, uint32_t fla
|
||||
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. */
|
||||
/* An optional operand this description does not pass; to the ABI it means a null RadTensor. */
|
||||
RadOpdDesc opd_none() {
|
||||
RadOpdDesc d{};
|
||||
d.idx_const = -1;
|
||||
@@ -92,16 +83,13 @@ RadOpdDesc opd_none() {
|
||||
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. */
|
||||
/* Restricts the fill to (0, 1); `RAD_FILL_SIGMOID` is the ABI's only such draw. A scale drawn from
|
||||
* a normal is negative half the time, and a negative descale inverts a whole 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. */
|
||||
/* Hands out operand `operand` after checking the whole list, so a geometry missing a parameter
|
||||
* declines every operand. A non-positive extent means a needed parameter was absent or zero
|
||||
* (RAD_E_UNSUPPORTED); an index outside the list is a bug here or in the schema (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) {
|
||||
@@ -119,12 +107,11 @@ int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) {
|
||||
|
||||
/* ==================================================================== 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.
|
||||
* `M` and the other ranged parameters read as the band's bound, not one step's row count: 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.
|
||||
* Not r3d_pgeti_or(), which reads RAD_P_INT only; this hook can see ranges still open, and
|
||||
* rad_param_getdim 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);
|
||||
@@ -134,10 +121,9 @@ 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. */
|
||||
/* The activation dtype, from `dtype` or `q_dtype`; 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 mean by it: the scheme picks the weight's dtype. */
|
||||
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");
|
||||
@@ -161,8 +147,8 @@ int64_t scale_groups(int64_t n, int64_t group) {
|
||||
|
||||
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. */
|
||||
/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. The gain is described at full width; the
|
||||
* form with no gain 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);
|
||||
@@ -170,8 +156,7 @@ int r3d_shape_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
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. */
|
||||
/* The two-pass form. `b` is optional and passed: the biased form covers strictly more code. */
|
||||
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);
|
||||
@@ -180,8 +165,7 @@ int r3d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
* form is not, since a tool that sizes by shape alone cannot tell it from a shape bug. */
|
||||
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);
|
||||
@@ -196,9 +180,8 @@ 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. */
|
||||
/* y = act(gate) * up over two [M, n] operands, the halves as the kernel sees them (the model
|
||||
* issues the fused [M, 2n] form). */
|
||||
int r3d_shape_act_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return binary_shape(p, n_p, operand, out);
|
||||
}
|
||||
@@ -236,7 +219,7 @@ 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. */
|
||||
/* y = x * s with `s` a single broadcast element. */
|
||||
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);
|
||||
@@ -244,7 +227,7 @@ int r3d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* y = value. The only operand is the output, so a case's whole content is the kernel's. */
|
||||
/* y = value. The only operand is the output. */
|
||||
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);
|
||||
@@ -256,10 +239,9 @@ int r3d_shape_fill(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
* 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". */
|
||||
/* In-place rotary over a fused qkv row: n_head q heads, then n_head_kv each of k and v. Positions
|
||||
* are drawn over the row count; positions contiguous from an arbitrary start are a hand case,
|
||||
* since no fill domain spells them. */
|
||||
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);
|
||||
@@ -274,8 +256,7 @@ int r3d_shape_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
* dense prefix. Only the cache takes `kv_dtype`; k and v are always bf16. */
|
||||
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);
|
||||
@@ -311,8 +292,8 @@ int r3d_shape_embed_lookup(const RadParam* p, int n_p, int operand, RadOpdDesc*
|
||||
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. */
|
||||
/* The source is 4x the gathered height so the gather is not the identity; `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);
|
||||
@@ -320,9 +301,9 @@ int r3d_shape_gather_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* o
|
||||
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. */
|
||||
/* The destination is 4x the scattered height, since onto exactly M rows a kernel ignoring `idx`
|
||||
* could pass; unnamed rows must come back unchanged. Indices are distinct, as a shared 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);
|
||||
@@ -348,14 +329,10 @@ int r3d_shape_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc*
|
||||
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. */
|
||||
/* The per-row int8: one scale per row in the tightest [M, 1] plane (the reference writes it at
|
||||
* pitch 1). The optional `asum`, group-major as libref's quant_act_i8 writes it, is described
|
||||
* whenever `group` divides n so a case checks the row sums too. `q` is in the step order; a
|
||||
* description states size and content domain, not a permutation, so it is described by extent. */
|
||||
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);
|
||||
@@ -368,8 +345,7 @@ int r3d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc*
|
||||
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. */
|
||||
/* The per-group int8 the i8a8 GEMM reads: the fp8 quantiser's extents with int8 codes. */
|
||||
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);
|
||||
@@ -395,9 +371,8 @@ int r3d_shape_gated_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDes
|
||||
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. */
|
||||
/* y = code * scale. `dtype` names the code: E4M3 or E5M2 (checkpoint fp8) or i8. The scale is
|
||||
* drawn in (0, 1), see in_unit(). */
|
||||
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);
|
||||
@@ -414,8 +389,7 @@ int r3d_shape_dequant(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
* 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]. */
|
||||
/* y[M,N] = a[M,K] @ b[N,K]^T. Both operands are k-contiguous (the "nt" in the name). */
|
||||
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);
|
||||
@@ -424,15 +398,10 @@ int r3d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
* [n_vocab, n_embd] in the activation's dtype, logits in f32 because every sampler stage reads
|
||||
* f32 (a prefill band's plane is 1.07 GB at M=2048). Unlike the reference row, which also places
|
||||
* the head (`ref_layout_head`), this row reads the head where it is stored, so it declares only a
|
||||
* shape hook. */
|
||||
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;
|
||||
@@ -441,17 +410,17 @@ int r3d_shape_logits_gemm_bf16(const RadParam* p, int n_p, int operand, RadOpdDe
|
||||
R3D_PICK(list); /* x, lm_head, logits */
|
||||
}
|
||||
|
||||
/* The quantised GEMM. `dtype` names the scheme, and the scheme fixes which operands are coded:
|
||||
/* The quantised GEMM. `dtype` names the scheme, which 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.
|
||||
* fp8a8 a E4M3 against a_scale, one f32 per (row, `group` of K): quant_act_fp8's output, so
|
||||
* 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. */
|
||||
* `b_scale` is block-major [ceil(N/pb), ceil(K/pb)] for fp8 and row-major [N, ceil(K/group)] for
|
||||
* i8, as each checkpoint stores it. */
|
||||
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;
|
||||
@@ -474,11 +443,10 @@ int r3d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out
|
||||
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. */
|
||||
/* The OCP-MXFP4 grid, as libref describes it: an e2m1 weight [N, K], two a byte, with one e8m0
|
||||
* exponent per 32 of K ([N, K/32]); `b_ref` is the same exponent plane, accepted and ignored. The
|
||||
* activation is the fp8a8 row's: E4M3 against one f32 per (row, 128 of K), drawn in (0, 1). Both
|
||||
* zero-point operands are absent since 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;
|
||||
@@ -492,9 +460,9 @@ int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdD
|
||||
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. */
|
||||
/* The e8m0 scale is filled with 127, the factor 2^0. A normal draw of the u8 grid reaches
|
||||
* exponents near 227 (2^100) and overflows the output's finiteness check; 127 is where real
|
||||
* checkpoints cluster and is not a reserved value. */
|
||||
RadOpdDesc e8 = opd((uint32_t)RAD_E8M0, N, K / 32); /* b_scale: e8m0 */
|
||||
e8.fill = RAD_FILL_INDEX;
|
||||
e8.idx_const = 127;
|
||||
@@ -505,10 +473,10 @@ int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdD
|
||||
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. */
|
||||
/* The symmetric int4 / int8 weight grids, as libref describes them: int8 activations in the step
|
||||
* order against signed codes (I4 two a byte, or I8) with one f16 scale per (row, 128 of K) and one
|
||||
* f32 activation scale per row, drawn in (0, 1). 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)
|
||||
{
|
||||
@@ -546,18 +514,14 @@ int r3d_shape_gemm_nt_q_w8a8(const RadParam* p, int n_p, int operand, RadOpdDesc
|
||||
|
||||
/* ==================================================================== 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 vocabulary and the sampler. The schemas in r3d_rows.cpp are transcribed from libref, and
|
||||
* every extent, dtype, fill domain and flag below is libref's: a description that differs is a
|
||||
* case kbench skips with a one-line notice.
|
||||
*
|
||||
* 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 `params` operand is one plane with fill domain `RAD_FILL_SAMPLE_PARAMS`: the ABI's
|
||||
* `RadSampleParams`, 96 bytes (24 f32 words) a row. `fill_chunk` and `idx_max` place the history
|
||||
* window and the mask-row count inside it, so the draw yields a window that fits and a `mask_row`
|
||||
* that is a row of the bitmask plane (or -1, an unconstrained row).
|
||||
*/
|
||||
|
||||
/* The sampler's parameter plane: [M, 24] f32, one RadSampleParams a row. */
|
||||
@@ -569,13 +533,11 @@ RadOpdDesc opd_params(int64_t M, int64_t hist, int64_t 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. */
|
||||
/* libref's widths: a plausible deployment history window, and a candidate width narrower than the
|
||||
* vocabulary but 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. */
|
||||
/* Reads M and n_vocab, the extents 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);
|
||||
@@ -590,10 +552,8 @@ int r3d_shape_silu_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
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. */
|
||||
/* The fused add + norm + quantiser. `residual` is INOUT and holds the bf16 sum the variance reads,
|
||||
* so it has x's shape. The optional `out_bf16` is the value the codes were taken over, for tests. */
|
||||
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);
|
||||
@@ -604,11 +564,9 @@ int r3d_shape_rmsnorm_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdD
|
||||
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). */
|
||||
/* Paged attention over one sequence. A context equal to the query length exercises no deep paging,
|
||||
* KV split or window, so `ctx` wins when given and is never below the query. `q_len` is the ranged
|
||||
* parameter; decode and prefill chunks 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);
|
||||
@@ -618,9 +576,8 @@ int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
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. */
|
||||
/* `ctx` as the reference spells it, not the band's `max_ctx`; absent, 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;
|
||||
@@ -644,8 +601,8 @@ int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
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. */
|
||||
/* Exact per-row top-R. `pairs` packs an int32 id's bits in the first slot beside its value, in an
|
||||
* f32 plane. */
|
||||
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;
|
||||
@@ -673,15 +630,11 @@ int r3d_shape_sample_temp(const RadParam* p, int n_p, int operand, RadOpdDesc* o
|
||||
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. */
|
||||
* (ceil(N/group), ceil(K/group)) in bf16 (the container's `weight_scale_inv`), the output's codes
|
||||
* per (M, n) and its scales per (M, ceil(n/group)). The checks mirror the kernel's: fp8a8 only,
|
||||
* group a power of two in [32, 256] no wider than n, and K a whole number of groups, so the hook
|
||||
* never describes a shape the kernel refuses. */
|
||||
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);
|
||||
@@ -707,6 +660,9 @@ int r3d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand, RadOpdDes
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* 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; cand/unary/hp carry one
|
||||
* row per (sequence, step), M * steps. */
|
||||
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);
|
||||
@@ -760,10 +716,9 @@ int r3d_shape_sample_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* o
|
||||
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. */
|
||||
/* 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 to any order. */
|
||||
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);
|
||||
@@ -782,9 +737,8 @@ int r3d_shape_sample_pick(const RadParam* p, int n_p, int operand, RadOpdDesc* o
|
||||
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. */
|
||||
/* Penalties and DRY: logits, params with a history window, and the history of token ids. 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;
|
||||
@@ -798,8 +752,8 @@ int r3d_shape_sample_penalties(const RadParam* p, int n_p, int operand, RadOpdDe
|
||||
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<RadOpdDesc&>(brk).dtype = (uint32_t)RAD_U8;
|
||||
RadOpdDesc brk = opd_idx(M, 2, -1, 0, kHist);
|
||||
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
|
||||
@@ -820,8 +774,7 @@ int r3d_shape_sample_ngram_ban(const RadParam* p, int n_p, int operand, RadOpdDe
|
||||
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. */
|
||||
/* The four narrowing stages share one description; the op names the predicate. */
|
||||
int r3d_shape_sample_topp(const RadParam* p, int n_p, int o, RadOpdDesc* out) {
|
||||
return r3d_shape_narrow(p, n_p, o, out);
|
||||
}
|
||||
|
||||
+18
-30
@@ -1,38 +1,26 @@
|
||||
/* r3d_tiling.h -- the tiled rows' LDS row law, in one place.
|
||||
/* r3d_tiling.h -- the LDS swizzle shared by libr3d's tiled rows.
|
||||
*
|
||||
* 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.
|
||||
* A tiled row stages an [rows x pitch] f16 tile in LDS and reads it back in pairs for dot2_f16x2.
|
||||
* The store and the load must use the same swizzle, so both are defined here:
|
||||
*
|
||||
* 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
|
||||
* srow(row, c8, pitch) element offset of the c8-th run of eight elements of `row`
|
||||
* srow_pair(row, kc, pitch) 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) because staging writes one uint4 per step; a
|
||||
* finer swizzle would split the store and make it unaligned.
|
||||
* - The XOR with (row & 7) rotates the runs of eight consecutive rows by one slot each. A wavefront
|
||||
* reads 32 rows at the same kc, and the rotation spreads those reads over 32 distinct 16-byte
|
||||
* slots instead of the four a plain row-major tile uses, which removes the bank conflict.
|
||||
* - The mask (pitch / 8 - 1) keeps the rotated index inside the row. pitch is in elements and
|
||||
* pitch/8 must be a power of two (32 or 128 for every tile in the library). Without the mask the
|
||||
* index reads a neighbouring row, a silent, data-dependent error.
|
||||
* - srow_pair finds the run the pair lives in (kc >> 3) and adds the element inside it (kc & 7).
|
||||
*
|
||||
* - 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.
|
||||
* With dot2_f16x2 accumulating into f32, a row using these functions matches ref_gemm_nt_q at a
|
||||
* bf16 output to rel_l2 1.7e-03 (bounded by the store's rounding); a wrong swizzle gives rel_l2 3e+01.
|
||||
*
|
||||
* 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.
|
||||
* Include at file scope in a .hip before the kernels. The definitions are in an unnamed namespace,
|
||||
* so each translation unit gets its own copy.
|
||||
*/
|
||||
#ifndef R3D_TILING_H
|
||||
#define R3D_TILING_H
|
||||
|
||||
+163
-334
@@ -3,235 +3,119 @@
|
||||
*
|
||||
* 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.
|
||||
* `logits_gemm` spells N and K as n_vocab and n_embd, and its y is f32 because the schema says so
|
||||
* (`ref_logits_gemm_shape`) and every sampler stage reads f32 logits. `gemm_nt` is the same
|
||||
* arithmetic with a bf16 y, narrowed once by the store. Both entries run the same two kernels;
|
||||
* `YF32` is the only difference.
|
||||
*
|
||||
* ---- 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.
|
||||
* libref's `ref_logits_gemm` is a CPU GEMM (OpenMP), about 1.1 TFLOP at the M=2048,
|
||||
* n_vocab=130560, n_embd=2048 band. The head is read in either of its stored forms, with nothing
|
||||
* repacked: plain bf16 (no layout hook), or E4M3 codes with a bf16 scale per 128x128 block as two
|
||||
* planes of one `rad.planes` container, answered by r3d_layout_logits_head below.
|
||||
*
|
||||
* ---- 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).
|
||||
* A block is TM x TN = 128 x 128 outputs, 256 threads (eight waves), grid (N/TN) x (M/TM). Lane
|
||||
* `tid` owns rows m0 + (tid/16)*8 .. +7 by columns n0 + (tid%16)*8 .. +7: 64 f32 accumulators, one
|
||||
* 8x8 square, stored as 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.
|
||||
* k is walked in KC = 32 chunks. Both tiles are row-major f16 (a row is 32 k-values, 64 bytes),
|
||||
* filled by one `uint4` load of 8 contiguous k a thread and widened by `bf16x2_to_f16x2`, which is
|
||||
* exact for every value f16 can hold and gives inf for the rest. The compute reads f16x2 pairs:
|
||||
* 16 LDS reads against 64 `fdot2` per two k.
|
||||
*
|
||||
* 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.
|
||||
* Tile rows are XOR-swizzled in eight-element units (`srow`, r3d_tiling.h). The staging store is a
|
||||
* `uint4`, so chunks must stay eight-element aligned; unswizzled, the 64-byte row stride puts the
|
||||
* eight rows a lane reads on one bank (32-way). Swizzling by `row & 7` brings that to two-way (a
|
||||
* lane's rows sit at stride eight, so a period-8 swizzle repeats within them): 512 LDS cycles a
|
||||
* block-chunk against 2048 of dots.
|
||||
*
|
||||
* ---- 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.
|
||||
* The prefill tile reads the head M/TM times, so at M=1 it would read 127/128 of it for nothing.
|
||||
* At M <= 16 the block uses r3d_gemm_bf16_nt_m16.hip's decode shape: a wave is MT activation rows
|
||||
* by 32/MT weight rows, lane l owns (m = l % MT, n = n0 + l / MT), one accumulator from k=0 to K
|
||||
* and no wave reduction, so each sum is the reference's ascending chain in the pair-dot's grouping.
|
||||
* The activation is staged in 128-k chunks in LDS (MT x 128 f16, 4 KiB at MT=16, same swizzle);
|
||||
* the weight goes from global to registers in 16-byte loads, eight values at a time.
|
||||
*
|
||||
* 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.
|
||||
* `nt=1` requests non-temporal head loads. On gfx1102 it measures within 1% of the default at M=1,
|
||||
* so it is off by default.
|
||||
*
|
||||
* 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 quantised head is half the bytes of the bf16 one (255 MiB of codes plus 32 KiB of scales
|
||||
* against 510 MiB at the band), which is its case for decode.
|
||||
*
|
||||
* ---- the accumulation, and what it is exact against ---------------------------------------------
|
||||
* ---- the accumulation ---------------------------------------------------------------------------
|
||||
*
|
||||
* 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.
|
||||
* libref's law per output is `acc += a*b` over ascending k from zero, no bias. Both arms keep one
|
||||
* accumulator per output, k ascending, no reassociation across lanes. The pair-dot folds two
|
||||
* products per rounding (`acc + a0*b0 + a1*b1`) where the reference rounds each, so results are
|
||||
* close but not bit-equal: rel_l2 about 1.8e-6 at K = 2048 with f32 output (the widening to f16
|
||||
* contributes nothing), far below the 4.9e-4 quantisation of the head's bf16 values.
|
||||
*
|
||||
* 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.
|
||||
* This is not integer arithmetic, so the v_fdot2_f32_f16 mantissa limit that bounds
|
||||
* r3d_gemm_nt_q_w2a8.hip does not apply.
|
||||
*
|
||||
* ---- the head's stored form, and who answers it ---------------------------------------------------
|
||||
* ---- the quantised head -------------------------------------------------------------------------
|
||||
*
|
||||
* 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:
|
||||
* The band's `dtype=bf16` is the activation's dtype; the head may be stored quantised.
|
||||
*
|
||||
* 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.
|
||||
* r3d_layout_logits_head (operand 1, as `ref_layout_head` is `layout_scaled(operand, 1, -1, ...)`)
|
||||
* Tag `rad.planes`; codes E4M3 (libref's `scaled_rows` also admits int8) with a bf16, f16 or
|
||||
* f32 scale on a {128, 128} block (`R3D_FP8_BLOCK`); ends in `rad_planes_layout` and moves no
|
||||
* byte. `ref_layout_head` is static inside libref, so it and `layout_scaled`,
|
||||
* `enc_scaled_rows` and `float_scale_dt` are transcribed here with their checks in order.
|
||||
* `rad_enc_is` compares `scheme`, and `transform` is the optional pre-transform: the encoding
|
||||
* is affine with an empty transform, so 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 law is `ScaledRows::at(r, c) = codes.at(r, c) * scale.cover(r, c)` in f32, then the plain
|
||||
* ascending-k GEMM. Decoding a code to f16 is exact (E4M3 has 4 exponent and 3 mantissa bits, f16
|
||||
* 5 and 10; int8 fits whole). Here the scale is folded into the staged f16 weight instead (see
|
||||
* scale_pair): once per staged 8-column group in the tiled arm and once per 128-k chunk in the
|
||||
* decode arm, both inside one 128-column block. That costs one f16 rounding per weight, rel_l2
|
||||
* about 2.8e-4 at M=1, K=2048 against the reference, 250x finer than the E4M3 quantum (2^-4).
|
||||
* An f32 scale plane adds one rounding (the scale to f16); a bf16 scale is f16-exact. y stays 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.
|
||||
* Placement dominates the kernel: a head on the mapped tier (hipHostMalloc, read over PCIe) runs
|
||||
* about 50x slower than in VRAM, and an unprefetched managed head faults page by page because
|
||||
* this ROCm does not migrate managed pages for read-mostly device access.
|
||||
*
|
||||
* 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.
|
||||
* The container header picks the form: the shim calls `rad_planes_header(w)` and a plain bf16
|
||||
* operand takes the bf16 path. The shim reads the header on the host (as `scaled_rows()` does)
|
||||
* and the kernel reads the same bytes on the device, so the operand must be managed memory
|
||||
* (prefetched) or hipHostMalloc; plain malloc faults on the kernel's first read.
|
||||
*
|
||||
* 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.
|
||||
* gfx1102 has no v_cvt_pk_f16_fp8 (clang lists the builtin but it expands to software), so the
|
||||
* E4M3 decode uses r3d_fp8_dequant.h's 256-entry f16 table in LDS (512 bytes, eight reads per
|
||||
* eight codes). The table is built from the codec, so results are bit-identical; it pays most at
|
||||
* M=8 (about 2.7x per token), where decoding is the binding resource. At M=1 the quantised arm
|
||||
* runs far below memory bandwidth; the likely limit is its 8-byte code load (the bf16 arm
|
||||
* loads 16 bytes a lane).
|
||||
*
|
||||
* 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.
|
||||
* ---- refusals -----------------------------------------------------------------------------------
|
||||
*
|
||||
* ---- 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
|
||||
* sk > 1: the grid is vocab-wide at every M (1020 blocks at the band for the prefill arm, 8160 for
|
||||
* the decode arm at MT=16), so a split would buy nothing. kb: KC = 32 only, since another pitch is
|
||||
* a different swizzle. Also refused: 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 non-contiguous weight. The head branch, in order:
|
||||
* a quantised head on the bf16-y row (logits are f32)
|
||||
* a `zero` plane: codes+scale+zero is gemm_nt_q's asymmetric grid (r3d_gemm_nt_q_w2a8.hip)
|
||||
* a joined operand that is not two planes
|
||||
* a joined head whose planes are not codes + scale (a `table`, a `bias`: names it)
|
||||
* planes that are not codes + scale (a `table`, a `bias`)
|
||||
* 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)
|
||||
* sub-byte codes (4-bit)
|
||||
* 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.
|
||||
* an integer scale (not in 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 indexes the plane differently from ScaledRows::cover
|
||||
* planes that do not cover the band (codes N x K, scales ceil(N/128) x ceil(K/128)), or a
|
||||
* row_bytes shorter than the row
|
||||
* The bf16 branch refuses a plain head that is not bf16, wrong x and y dtypes, bad pitches, a short
|
||||
* or non-contiguous head, absurd shapes, misalignment and sk > 1. The launcher refuses 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, 6 bytes a row, is legal), and misaligned addresses.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
@@ -239,8 +123,8 @@
|
||||
#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_fp8_dequant.h" /* the E4M3 -> f16 LDS table */
|
||||
#include "r3d_tiling.h" /* LDS tile addressing: srow, srow_pair */
|
||||
#include "r3d_args.h"
|
||||
#include "r3d_launch.h"
|
||||
|
||||
@@ -265,10 +149,8 @@ constexpr int kChunkK = 128; /* the decode arm's activ
|
||||
# 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. */
|
||||
/* Tile addressing (srow, srow_pair) is r3d_tiling.h's: `pitch`-wide f16 rows whose eight-element
|
||||
* chunks are XORed by the row's low bits, used here at pitches 32 and 128. */
|
||||
|
||||
/* Eight bf16 -> eight f16, exact for every value f16 can hold. */
|
||||
__device__ __forceinline__ uint4 widen8(uint4 w)
|
||||
@@ -279,10 +161,9 @@ __device__ __forceinline__ uint4 widen8(uint4 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. */
|
||||
/* The head as the container stores it: E4M3 (or int8) codes with one float scale per 128x128
|
||||
* block. Passed by value; the pointers are device addresses the shim resolved out of the joined
|
||||
* bytes (rad_planes_find). */
|
||||
struct HeadQ {
|
||||
const uint8_t* codes; /* [N][K] */
|
||||
const uint8_t* scale; /* [ceil(N/128)][ceil(K/128)] */
|
||||
@@ -292,9 +173,8 @@ struct HeadQ {
|
||||
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. */
|
||||
/* The scale covering logical (n, k), the reference's `ScaledRows::cover`. The plane is 32 KiB at
|
||||
* the band and stays in cache, so the codes are the traffic, not these loads. */
|
||||
__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
|
||||
@@ -304,16 +184,12 @@ __device__ __forceinline__ float scale_at(const HeadQ h, int n, int k)
|
||||
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. */
|
||||
/* Eight codes -> eight f16, exact: E4M3 (4 exponent, 3 mantissa bits) and int8 both fit f16, so
|
||||
* decoding is a widening, not a rounding. The pair decoder reads the two codes in a dword's low
|
||||
* half, so each dword is decoded as two pairs (d and d >> 16): two dwords in, four pairs out. */
|
||||
#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 */
|
||||
# define R3D_HAS_FP8CVT 1 /* two codes to two f16; software on gfx1102, see the header */
|
||||
# endif
|
||||
#endif
|
||||
#ifndef R3D_HAS_FP8CVT
|
||||
@@ -334,21 +210,15 @@ __device__ __forceinline__ void codes8_to_f16x4(const uint2 c, int cdt, const ui
|
||||
{
|
||||
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. */
|
||||
/* The LDS table: eight reads for eight codes, built from the codec below, so the results
|
||||
* are identical (r3d_fp8_dequant.h). A null tbl selects the codec. */
|
||||
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. */
|
||||
/* The codec: on gfx1102 the builtin expands to software, about 100 instructions per eight
|
||||
* codes, which is why the table path exists. A target with v_cvt_pk_f16_fp8 gets the
|
||||
* single instruction. */
|
||||
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]);
|
||||
@@ -364,25 +234,19 @@ __device__ __forceinline__ void codes8_to_f16x4(const uint2 c, int cdt, const ui
|
||||
|
||||
/* 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. */
|
||||
* The reference dequantises each element into f32 (`ScaledRows::at`). Folding into the staged f16
|
||||
* costs one f16 rounding per weight (2.4e-4 relative, against the code's own 2^-4 quantum) and
|
||||
* keeps the tile f16, the dot loop unchanged and the prefill arm's 237 VGPRs as they are. A
|
||||
* per-block partial summed and scaled separately would need 64 more accumulators and spill. */
|
||||
__device__ __forceinline__ uint32_t scale_pair(uint32_t w, float sc)
|
||||
{
|
||||
#if defined(__HIP_DEVICE_COMPILE__)
|
||||
/* One f16 multiply, hardware, round-to-nearest.
|
||||
/* One hardware f16 multiply (v_mul_f16), round to nearest, subnormals kept.
|
||||
*
|
||||
* 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.
|
||||
* Not f16x2_pack of an f32 product: that is v_cvt_pkrtz_f16_f32, which rounds toward zero and
|
||||
* is only for values f16 represents exactly (r3d_codecs.h). A folded weight generally is not
|
||||
* (code 431 times a scale of 4.5e-5 has eleven significant bits), and truncation biases every
|
||||
* product toward zero and flushes the subnormal end.
|
||||
*/
|
||||
const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16);
|
||||
const _Float16 a = __builtin_bit_cast(_Float16, lo16);
|
||||
@@ -416,9 +280,7 @@ __device__ __forceinline__ uint4 loadw8(const uint16_t* p)
|
||||
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. */
|
||||
/* The quantised head's 8-byte load of eight codes, ordinary or streamed-once. */
|
||||
template <int NT>
|
||||
__device__ __forceinline__ uint2 loadc8(const uint8_t* p)
|
||||
{
|
||||
@@ -438,7 +300,7 @@ __device__ __forceinline__ uint2 loadc8(const uint8_t* 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.
|
||||
* y is f32 for logits_gemm and bf16 for gemm_nt (`YF32`). WQ reads the quantised head through h.
|
||||
*/
|
||||
template <bool YF32, bool WQ>
|
||||
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
|
||||
@@ -451,13 +313,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b
|
||||
|
||||
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 */
|
||||
if (WQ) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* fills, then barriers */
|
||||
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 */
|
||||
@@ -471,9 +328,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b
|
||||
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. */
|
||||
/* Stage 128 rows x 4 chunks of eight per side, two uint4 a thread a side. Rows past M and
|
||||
* k past K stage as zeros, which contribute 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);
|
||||
@@ -489,10 +345,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b
|
||||
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. */
|
||||
/* Eight codes, one scale: the staged run lies inside one 128x128 block, and
|
||||
* the scale is indexed by this staged row n, not the lane's output row. */
|
||||
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);
|
||||
@@ -524,8 +378,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b
|
||||
__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. */
|
||||
/* The store, eight columns at a time: 32 bytes of f32, 16 of bf16. Rows past M are skipped
|
||||
* and a ragged N tail is written column by column. */
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const int m = m_r + i;
|
||||
@@ -548,8 +402,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b
|
||||
*(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. */
|
||||
/* Unrolled: a dynamic index into acc would put the 64 accumulators in local memory
|
||||
* (80 KiB of spill against a 64 KiB limit). */
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
if (n_c + j < N) {
|
||||
@@ -563,10 +417,9 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b
|
||||
|
||||
/* ============================================================ 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.
|
||||
* A wave is MT activation rows by KLW = 32/MT weight rows, one accumulator a lane over all of k in
|
||||
* ascending order. The activation tile is block-wide, so every thread stages it, including lanes
|
||||
* whose weight row is past the vocabulary; those lanes skip the dot and the store.
|
||||
*/
|
||||
template <int MT, bool YF32, int NT, bool WQ>
|
||||
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(4)
|
||||
@@ -578,13 +431,8 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_
|
||||
|
||||
__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;
|
||||
@@ -592,8 +440,7 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_
|
||||
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. */
|
||||
/* A dead lane's row pointer is clamped to N-1 so it never points past the head. */
|
||||
const uint16_t* wrow = w + (long long)(live ? n : N - 1) * K;
|
||||
const int nsteps = M < MT ? M : MT;
|
||||
float acc = 0.0f;
|
||||
@@ -611,8 +458,8 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_
|
||||
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. */
|
||||
/* One scale a chunk: kChunkK equals the scale block, so a lane's 128 codes share one
|
||||
* (n-block, k-block). */
|
||||
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 */
|
||||
@@ -673,9 +520,9 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_
|
||||
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. */
|
||||
/* `hq` is the quantised head the shim resolved from the container; its pointers are checked
|
||||
* here. The declared entries pass null and get the plain bf16 head their r3d.h signature
|
||||
* describes. */
|
||||
HeadQ h;
|
||||
std::memset(&h, 0, sizeof h);
|
||||
const int wq = hq != nullptr;
|
||||
@@ -685,9 +532,8 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_
|
||||
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. */
|
||||
return -3; /* scale loads are 4 bytes (f32) or 2 (bf16/f16), so a
|
||||
* 3-column 16-bit row (6 bytes, K = 320) is legal */
|
||||
if (((long long)(uintptr_t)h.codes & 7) || ((long long)(uintptr_t)h.scale & 3)) return -5;
|
||||
}
|
||||
|
||||
@@ -725,10 +571,9 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_
|
||||
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). */
|
||||
/* The shim body both ops share (ref_logits_gemm is gemm_nt_impl with the axes renamed).
|
||||
* `y_is_f32` is the op's output dtype; nkey/kkey are libref's axis names ("n_vocab"/"n_embd" or
|
||||
* "N"/"K"). */
|
||||
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)
|
||||
@@ -744,23 +589,16 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey,
|
||||
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.
|
||||
* The launch-side twin of r3d_layout_logits_head: a `rad.planes` header means the quantised
|
||||
* head, read as its two planes; no header means a plain bf16 head. The checks follow the
|
||||
* reference's `scaled_rows` in order: roles, then dtypes and blocks, then coverage (below,
|
||||
* once N and K are known).
|
||||
*/
|
||||
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 (!y_is_f32) return R3D_NO(RAD_E_DTYPE); /* the bf16-y row takes a bf16 head only */
|
||||
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 */
|
||||
return R3D_NO(RAD_E_DTYPE); /* codes+scale+zero: gemm_nt_q's asymmetric grid */
|
||||
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);
|
||||
@@ -770,17 +608,16 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey,
|
||||
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); /* sub-byte codes */
|
||||
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 */
|
||||
else return R3D_NO(RAD_E_DTYPE); /* not in float_scale_dt's set */
|
||||
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 */
|
||||
return R3D_NO(RAD_E_SHAPE); /* only 128x128 blocks; other grids are gemm_nt_q's */
|
||||
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;
|
||||
@@ -804,9 +641,8 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey,
|
||||
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. */
|
||||
/* `scaled_rows`' coverage checks: the planes must cover the band, the scale plane by
|
||||
* ceil-divided blocks, so a ragged vocabulary is fine (131 rows need 2 scale rows). */
|
||||
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);
|
||||
@@ -820,7 +656,7 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey,
|
||||
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 */
|
||||
if (sk > 1) return R3D_NO(RAD_E_SHAPE); /* see the header's refusals */
|
||||
const int kb = (int)r3d_geti_or(a, "kb", 0);
|
||||
const int nt = (int)r3d_geti_or(a, "nt", 0);
|
||||
|
||||
@@ -835,10 +671,9 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey,
|
||||
: 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. */
|
||||
/* The reference's `enc_scaled_rows` and `float_scale_dt`, transcribed (libref keeps them static
|
||||
* inline), checks in its order: affine, untransformed, two planes, the roles in order, codes tiled
|
||||
* with block {1,1} in an admitted dtype, the scale tiled with a float dtype. */
|
||||
bool float_scale_dt(uint32_t dt)
|
||||
{
|
||||
return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32;
|
||||
@@ -889,22 +724,12 @@ 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. */
|
||||
/* The head's relayout writer. A layout query that answers RAD_OK promises the loader that
|
||||
* relayout will produce the described form (rad_abi.h). The container stores the quantiser's
|
||||
* pair and the plan wants one operand, so rad_planes_relayout assembles it losslessly: the header,
|
||||
* the entries and each plane's rows, copied. No code is transformed, so the served numbers do not
|
||||
* depend on which library loaded the container. The query and the writer share one plan
|
||||
* (rad_planes_plan). The operand guard repeats the hook's, so a misrouted call 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,
|
||||
@@ -915,6 +740,10 @@ extern "C" int r3d_relayout_logits_head(const RadParam* p, int n_p, int operand,
|
||||
return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes);
|
||||
}
|
||||
|
||||
/* The head's layout hook, `ref::ref_layout_head` transcribed: operand 1 of logits_gemm, two planes
|
||||
* (codes and one scale), untransformed, answered with the container's own form and no byte moved.
|
||||
* Operand 0 (the activations), a one-plane selection and every other encoding are declined, as
|
||||
* `layout_scaled` declines them. */
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user