Archived
libr3d: the gfx11 (RDNA3) kernel library
A complete row set for the gfx11 family (1100/1101/1102/1103/1150/1151 plus gfx11-generic), mirroring libr4d's structure: the quantised GEMM rows (m16, tiled, gated, the bf16 logits gemm), the paged and ragged attention for decode and prefill, the KV store, the sampler spine and the spec rows, with the recorded-fixture, board, selftest and comparison-driver gates for each. The gates are the record. Every row is measured against libref on the shape matrix: the recorded fixture at 1153 cases with worst rel_l2 1.362e-03, the board's five modes with bit-identical decision lines, the selftest at 74 rows, and the 233-case served-shape pairing at 0 divergent against the tree libref. End-to-end on a 2B fp8 checkpoint served on the card, coherent through prefix-cache adoption. Two platform laws each shape the design. A kernel that calls device printf takes the implicit hidden_hostcall_buffer argument and is undispatchable by the AQL backend, so the trace records are plain stores behind a budget. And a plugin-owned __device__ global is not a channel into the engine's dispatch path: in a dlopened plugin the runtime's symbol stub is not the address the kernel's module writes, so the served trace channel is a hipMalloc'd record slot passed as a kernel argument, with the device-global ring kept for the board. kv_store bounds its slots at the pool's own plane (n_blocks x block_size), the span the cache operand declares, not at the step's own span: a request that adopts a cached prefix writes its new tokens at the allocator's global block indices, which sit past any bound built from the step's token count, and a slot lost there is KV that attention then reads stale. A corrupt slot map is dropped at the same bound.
This commit is contained in:
1 parent
1ffa770901
commit
6cb9826975
30 files changed
+19972
-2
No files matched your search
@@ -297,6 +297,14 @@ add_subdirectory(libquant)
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
|
||||
add_subdirectory(libr4d)
|
||||
endif()
|
||||
# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP
|
||||
# toolchain. It declares itself for `^gfx11` and returns without a target when the build's
|
||||
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it (and a card
|
||||
# with no kernel library of its own keeps refusing device-only ops, which is the rule, not a
|
||||
# regression: docs/PLUGIN.md §10).
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt)
|
||||
add_subdirectory(libr3d)
|
||||
endif()
|
||||
# libavx: the production host kernels (x86 SIMD, dispatched by CPU feature), built on every x86-64.
|
||||
# Not optional: host-placed ops need a kernel other than the oracle (rad_gate_reference_kernels
|
||||
# refuses libref), and a table too large for the card, such as the n-gram embedding's gather, runs
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
|
||||
# A row listed here and not reached fails the replay; regenerate with
|
||||
# --coverage-write when a row is added or deliberately retired.
|
||||
add_bf16
|
||||
attn_paged_fp8_decode
|
||||
cast_bf16_bf16
|
||||
dflash_select_bf16
|
||||
gated_quant_fp8_bf16
|
||||
gather_rows_bf16
|
||||
gemm_nt_bf16_m16
|
||||
gemm_nt_bf16_tiled
|
||||
gemm_nt_q_fp8a8_m16
|
||||
gemm_nt_q_fp8a8_tiled
|
||||
gemm_nt_q_gated_fp8a8
|
||||
kv_store_fp8
|
||||
layernorm_bf16
|
||||
quant_act_fp8_bf16
|
||||
quant_act_i8_bf16
|
||||
rmsnorm_bf16
|
||||
rmsnorm_quant_fp8_bf16
|
||||
rope_bf16
|
||||
row_topk_bf16
|
||||
sample_argmax_f32
|
||||
sample_dry_f32
|
||||
sample_logprobs_f32
|
||||
sample_mask_f32
|
||||
sample_minp_f32
|
||||
sample_penalties_f32
|
||||
sample_pick_f32
|
||||
sample_temp_f32
|
||||
sample_topk_f32
|
||||
sample_topp_f32
|
||||
sample_typical_f32
|
||||
sample_xtc_f32
|
||||
scatter_rows_bf16
|
||||
silu_mul_bf16
|
||||
@@ -0,0 +1,149 @@
|
||||
# libr3d serves RDNA3 only, declared here and nowhere else. Its kernels rely on wave32 and on
|
||||
# instructions RDNA3 has: v_dot2acc_f32_f16 for the matrix work, v_cvt_pkrtz_f16_f32, DPP16 and
|
||||
# v_permlanex16. They do not use the gfx12 WMMA fragment layouts or gfx12-only instructions such as
|
||||
# global_load_tr_b128, and they decode every quantised weight in software, because RDNA3 has no
|
||||
# fp8 conversion instruction and this ROCm declares no WMMA builtin for any gfx11 target.
|
||||
#
|
||||
# A build targeting other cards skips libr3d. The engine then has no device kernel library for that
|
||||
# card and refuses ops only a reference library implements, unless
|
||||
# --debug-accept-reference-kernels is passed (spec §17). The supported fix is a kernel library for
|
||||
# that card; libr4d is that library for gfx12 and libr3d is it for gfx11.
|
||||
#
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S libr3d -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`, naming the HIP compiler as for
|
||||
# the tree); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(libr3d LANGUAGES CXX HIP)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
# `^gfx11` is the family, not a chip: gfx1100, gfx1101, gfx1102, gfx1103, gfx1150, gfx1151 and the
|
||||
# family target `gfx11-generic` all take these kernels, exactly as `^gfx12` covers RDNA4 for libr4d.
|
||||
# The RDNA3 cards differ in CU count and clock, never in the instructions these kernels issue, so
|
||||
# one code object per family serves the lot; a build that lists both a chip and the family gets
|
||||
# both, and the engine picks the chip's object first (docs/PLUGIN.md §10).
|
||||
rad_plugin_gpu_targets(R3D_GPU_TARGETS "^gfx11")
|
||||
if(NOT R3D_GPU_TARGETS)
|
||||
message(STATUS
|
||||
"libr3d: RDNA3 (gfx11xx) only, and this build targets ${RAD_GPU_TARGETS} -- not built")
|
||||
return()
|
||||
endif()
|
||||
|
||||
# R3D_UNITS is the definitive list of libr3d's device translation units, as "unit|extra flags".
|
||||
#
|
||||
# Every unit is compiled -ffp-contract=off, which rad_hipify puts on all HIP sources. It is not a
|
||||
# style preference: libref accumulates in f32 with no FMA and no reassociation (ref_common.h), and
|
||||
# a contracted device kernel disagrees with the oracle it is checked against. It also keeps the
|
||||
# instruction counts quoted in kernel comments true.
|
||||
|
||||
# Kernels and libr3d's declaration (row table, operand descriptions) share one directory. There is
|
||||
# no launch adapter: every entry point takes `(const RadArgs*, RadStream)` and sits beside its
|
||||
# kernel. The plugin links rad_abi only, like one written out of tree.
|
||||
|
||||
set(R3D_UNITS
|
||||
# The model's small ops, one workgroup per row: rmsnorm, layernorm, the binary and unary element
|
||||
# ops, the activations, cast, softmax, embed_lookup, gather_rows and scatter_rows, rope and
|
||||
# kv_store. This is the set the engine refuses on a card with no device kernel library.
|
||||
"r3d_model_bf16|"
|
||||
# The sampler's pre-filters: penalties, DRY, the n-gram ban, the bitmask, and the logprobs
|
||||
# summary, which reads the logits plane once where the reference reads it three.
|
||||
"r3d_sample_pre_f32|"
|
||||
# The speculative decoder's accept step: a walk over the draft block's candidate lattice, which is
|
||||
# a gather out of two codebooks rather than arithmetic.
|
||||
"r3d_dflash_f32|"
|
||||
# The gated MLP band: GEMM, gate and output quantiser in one launch, so the [M,N] intermediate the
|
||||
# unfused chain writes and re-reads never exists.
|
||||
"r3d_gemm_fp8a8_gated|"
|
||||
# The vocab projection at decode: U2 codes, int8 activations, a joined scale+zero operand.
|
||||
"r3d_gemm_nt_q_w2a8|"
|
||||
# The vocabulary projection at both heights: the head streamed for M <= 16, tiled above it.
|
||||
"r3d_vocab_bf16|"
|
||||
# The quantised GEMM at prefill heights: the 176 bands a forward pass ran on the CPU.
|
||||
"r3d_gemm_fp8a8_tiled|"
|
||||
# The OCP-MXFP4 weight against the fp8 activation, both heights: e2m1 codes with one e8m0 scale
|
||||
# per 32 of K, the block's partials scaled at the block boundary.
|
||||
"r3d_gemm_mxfp4a8|"
|
||||
"r3d_gemm_inta8|"
|
||||
# Paged attention at head_dim 128: the decode leg (one head group a workgroup, 16-token tiles,
|
||||
# split-KV) and the prefill leg (a 16-token query tile staged in LDS), over a bf16 or an E4M3
|
||||
# cache. The walk is shared; the tile is what a workgroup stages once and every wave consumes.
|
||||
"r3d_attn_paged_h128|"
|
||||
# The sampler's spine: the row's top-R in one scan, and the stages that turn the candidate plane
|
||||
# the top-R produces into one token -- argmax, temp, top-k, the draw, and the four narrowings.
|
||||
"r3d_sample_f32|"
|
||||
# Activation quantisation: per-(row, group) symmetric E4M3 and int8, the gated form that
|
||||
# quantises a silu-gated pair, and the dequantise that reads a container's own quantised weights.
|
||||
"r3d_quant_fp8|"
|
||||
# The skinny bf16 GEMM, M <= 16: one output element a lane, k ascending, so the accumulation order
|
||||
# is libref's. The decode GEMM -- the op a token is made of.
|
||||
"r3d_gemm_bf16_nt_m16|"
|
||||
# The same shape over a block-scaled fp8 weight, decoded to f16 exactly (E4M3's four exponent bits
|
||||
# and three mantissa bits are a subset of f16's), and over int8 codes.
|
||||
"r3d_gemm_fp8a16_nt_m1|"
|
||||
# Landing next, in the same shape as libr4d's: the prefill GEMM (an 8x8 tile a wave over LDS, the
|
||||
# same dot2 inner product), paged causal attention (the decode leg split-KV, the prefill leg a
|
||||
# query tile a workgroup, bf16 or fp8 KV), the vocab (logits as a GEMM over the embedding, the row
|
||||
# top-k, the cross-rank top-1) and the sampler's stages. Their rows are not in r3d_rows.cpp yet,
|
||||
# because a row naming an entry point that is not in the library is an undefined symbol and the
|
||||
# plugin would fail to load, taking every other row with it.
|
||||
)
|
||||
|
||||
set(R3D_SRC "")
|
||||
foreach(u ${R3D_UNITS})
|
||||
string(REPLACE "|" ";" parts "${u}")
|
||||
list(GET parts 0 unit)
|
||||
list(LENGTH parts n)
|
||||
set(extra "")
|
||||
if(n GREATER 1)
|
||||
list(GET parts 1 extra)
|
||||
endif()
|
||||
set(src "${CMAKE_CURRENT_SOURCE_DIR}/${unit}.hip")
|
||||
if(NOT EXISTS "${src}")
|
||||
message(FATAL_ERROR "libr3d unit ${unit}.hip is missing from ${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
endif()
|
||||
if(extra)
|
||||
set_source_files_properties("${src}" PROPERTIES COMPILE_OPTIONS "${extra}")
|
||||
endif()
|
||||
list(APPEND R3D_SRC "${src}")
|
||||
endforeach()
|
||||
|
||||
# The host sources are declaration only: the row table, the operand descriptions and the fusion
|
||||
# claims. They are pure host C++ that includes neither r3d.h nor hip_runtime.h, so these tables
|
||||
# compile and can be inspected without ROCm. libr3d has no layout source: nothing it serves is
|
||||
# repacked, because a dot2 GEMM reads a weight in the order it is stored (see r3d_rows.cpp).
|
||||
# r3d_fuse.cpp joins the list with the first fused row: a `replaces` chain with no row naming it
|
||||
# would be dead code, and the fused rmsnorm-then-quant kernel is the first one worth its bytes.
|
||||
set(R3D_DECLARATION r3d_rows.cpp r3d_shapes.cpp)
|
||||
|
||||
rad_add_plugin(libr3d kernels
|
||||
SOURCES ${R3D_DECLARATION}
|
||||
HIP_SOURCES ${R3D_SRC}
|
||||
GPU_TARGETS ${R3D_GPU_TARGETS}
|
||||
INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
# rad_plugin_info's build_target is this build's own target list, spelled as the device reports its
|
||||
# arch, because the loader warns when a plugin claims a card the running device is not
|
||||
# (core/plugin/loader.cpp, target_covers). A library built for two archs says two.
|
||||
string(REPLACE ";" " " R3D_BUILD_TARGET "${R3D_GPU_TARGETS}")
|
||||
target_compile_definitions(libr3d PRIVATE R3D_BUILD_TARGET="${R3D_BUILD_TARGET}")
|
||||
|
||||
# Catalogue dump: prints every row and, on a card, calls each launch with a minimal valid input, to
|
||||
# catch transcription errors in the constraint table. It dlopens the plugin so an undefined symbol
|
||||
# in the .so is caught too.
|
||||
add_executable(r3d_selftest ${CMAKE_CURRENT_SOURCE_DIR}/r3d_selftest.cpp)
|
||||
# Links the HIP runtime to allocate the device buffers it feeds the kernels.
|
||||
target_link_libraries(r3d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME})
|
||||
target_include_directories(r3d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
# The device phase of the selftest -- the per-row launch -- is built only when the HIP runtime is
|
||||
# there, which in this plugin's build it always is.
|
||||
target_compile_definitions(r3d_selftest PRIVATE RAD_HAVE_HIP)
|
||||
set_target_properties(r3d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
# Installed beside the tools, so the image can run the rows' own card checks without a build tree:
|
||||
# r3d_selftest <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.
|
||||
set_target_properties(libr3d PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON)
|
||||
+1193
File diff suppressed because it is too large.
Load diff
+387
@@ -0,0 +1,387 @@
|
||||
/* r3d.h -- the entry points libr3d exports, and the launchers behind them.
|
||||
*
|
||||
* Two layers, in every unit, as in libr4d:
|
||||
*
|
||||
* The launcher (`r3d_<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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* A launcher is declared here and defined beside its kernel, in the same translation unit as the
|
||||
* shim that calls it: there is no adapter, and an out-of-tree author reading one unit sees the whole
|
||||
* path from RadArgs to the grid.
|
||||
*
|
||||
* Streams: a RadStream is the engine's queue, usable with hipLaunchKernel (and so <<<>>>),
|
||||
* hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync and with nothing else in HIP
|
||||
* (docs/PLUGIN.md §5). libr3d passes it to the launch and nowhere else.
|
||||
*/
|
||||
#ifndef RAD_R3D_H
|
||||
#define RAD_R3D_H
|
||||
|
||||
#include "r3d_plugin.h"
|
||||
|
||||
extern "C" {
|
||||
|
||||
/* ================================================================== r3d_model_bf16.hip
|
||||
*
|
||||
* One workgroup per row. Every launcher takes a row pitch in elements for each operand that can be
|
||||
* a slice (a column slice of a fused projection is the usual case), 0 meaning "dense, so n".
|
||||
*/
|
||||
|
||||
/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. `wdt` is R3D_DT_BF16 or R3D_DT_F32 for a
|
||||
* gain, R3D_DT_N for none (the gain is then 1, and wadd is refused by the shim, as libref does). */
|
||||
int r3d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, float mult,
|
||||
int x_ld, int y_ld, int wdt, long stream);
|
||||
|
||||
/* The same at f32 activations, for an f32 checkpoint's residual stream: the row is the op's, the
|
||||
* store narrows nothing. `wdt` is the gain's dtype code, R3D_DT_N for none. */
|
||||
int r3d_rmsnorm_f32(long x, long w, long y, int M, int n, float eps, float wadd, float mult,
|
||||
int x_ld, int y_ld, int wdt, long stream);
|
||||
|
||||
/* y = (x - mean) / sqrt(var + eps) * w + b, the mean and variance both taken in the reference's
|
||||
* two passes. `b` may be 0 (no bias). */
|
||||
int r3d_layernorm_bf16(long x, long w, long b, long y, int M, int n, float eps,
|
||||
int x_ld, int y_ld, long stream);
|
||||
|
||||
/* y = a + b, and y = a * b. `bcast` says b carries n elements and rides every row. `div` is the
|
||||
* `add` op's optional divisor, 0 meaning none: with it, y = rd(rd(a + b) / div). */
|
||||
int r3d_add_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, float div,
|
||||
int bcast, long stream);
|
||||
int r3d_add_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, float div,
|
||||
int bcast, long stream);
|
||||
int r3d_mul_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, int bcast,
|
||||
long stream);
|
||||
int r3d_mul_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, int bcast,
|
||||
long stream);
|
||||
|
||||
/* y = x, one dtype to another, over M rows of n at the given pitches. The dtypes are R3D_DT_*;
|
||||
* an integer pair goes straight through (ids above 2^24 survive an i64 -> i32 copy), everything
|
||||
* else widens to f32 and narrows once on the way out. */
|
||||
int r3d_cast(long x, long y, int M, int n, int x_ld, int y_ld, int from_dt, int to_dt, long stream);
|
||||
|
||||
/* The unary activations, f32 in, narrowed once by the store: y = x*sigmoid(x), 0.5x(1+erf(x/sqrt2))
|
||||
* and 1/(1+exp(-x)) respectively. */
|
||||
int r3d_silu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
|
||||
int r3d_gelu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
|
||||
int r3d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
|
||||
int r3d_silu_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
|
||||
|
||||
/* y = act(gate) * up, `act` R3D_ACT_SILU, R3D_ACT_GELU (the exact erf form) or R3D_ACT_SIGMOID.
|
||||
* The two inputs are the halves of a fused [M, 2n] projection, so their pitches are separate. */
|
||||
int r3d_act_mul_bf16(long gate, long up, long y, int M, int n, int g_ld, int u_ld, int y_ld,
|
||||
int act, long stream);
|
||||
|
||||
/* y[i] = silu(gate_up[i]) * gate_up[n + i]: the llama MLP's gated product over one fused plane,
|
||||
* the gate the FIRST half, which is the order rad-convert fuses gate and up in. The activation is
|
||||
* not narrowed before the product: that is `act_mul`'s order, over two operands, and it stands for
|
||||
* the unfused pair that stored the activation. `gu_ld` is the FUSED row's pitch (>= 2n), `y_ld` the
|
||||
* output's; 0 takes each one's dense width. 0, -1, -2, -3, -4. */
|
||||
int r3d_silu_mul_bf16(long gate_up, long y, int M, int n, int gu_ld, int y_ld, long stream);
|
||||
|
||||
/* Row-wise softmax over f32, maximum subtracted, the denominator summed in ascending order. */
|
||||
int r3d_softmax_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
|
||||
|
||||
/* y = x * s, where `s` is the op's [1] weight plane, in device memory, of dtype `s_dt`
|
||||
* (R3D_DT_BF16 or R3D_DT_F32). The scalar is read by the kernel, not by the launcher: a launch may
|
||||
* not copy device memory to the host, and the reference reads the same one value on the host because
|
||||
* its operands are host planes. Every lane loads the same address, which is one uniform load per
|
||||
* block; `s` is 0 only for a call the shim has already refused.
|
||||
*
|
||||
* y = v (fill) is the other scalar-carried op, and its value is a parameter, so it is by value. */
|
||||
int r3d_scale_bf16(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, long stream);
|
||||
int r3d_scale_f32(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, long stream);
|
||||
int r3d_fill(long y, int M, int n, int y_ld, int dt, float v, long stream);
|
||||
|
||||
/* In-place rotary on a fused qkv row: q, then k, then v untouched. `mode` is R3D_ROPE_NEOX or
|
||||
* R3D_ROPE_GPTJ; `rot` the rotary width (<= head_dim, even). `scale` is the position divisor: the
|
||||
* angle of pair i is (pos / scale) * theta^-i, which is libref's proportional ladder at a factor
|
||||
* other than 1 (ref_rope's `scale` divides the position, and YaRN's magnitude is carried by
|
||||
* `yarn_factor`, which this kernel does not implement). `pos` is M i32 positions, one a row. */
|
||||
int r3d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_head, int n_head_kv, float theta,
|
||||
float scale, int mode, int rot, int qkv_ld, long stream);
|
||||
|
||||
/* K and V into a paged cache, at slot_mapping's slots. The cache is [blocks, kv_heads, block_size,
|
||||
* 2*head_dim] with the strides the shim read off the operand and passes as sb/sh/so/sd; a negative
|
||||
* slot is skipped, and so is one at or past `slot_max` = n_blocks * block_size, which the launcher
|
||||
* computes from M and block_size exactly as `r3d_shape_kv_store` sizes the cache. The reference
|
||||
* *refuses* such a slot on the host, where it can see the block count; a launch cannot refuse a
|
||||
* slot it has not read, and writing past the cache is the one failure mode worse than a value
|
||||
* dropped, so the bound is the kernel's and the divergence is a slot lost rather than a step lost. `kv_dt` R3D_DT_BF16 stores the values, R3D_DT_U8 encodes them as E4M3 with the
|
||||
* reciprocal of k_scale / v_scale, R3D_DT_F16 as f16. */
|
||||
int r3d_kv_store(long k, long v, long sm, long kv, int M, int head_dim, int n_head_kv,
|
||||
int block_size, int kv_dt, float k_scale, float v_scale, int k_ld, int v_ld,
|
||||
long long slot_max, long sb, long sh, long so, long sd, long stream);
|
||||
|
||||
/* x[r] = wte[ids[r] - vocab_offset] * wscale, narrowed once. A row whose id is out of the table's
|
||||
* range is zeroed, as libref does. */
|
||||
int r3d_embed_lookup(long ids, long wte, long x, int M, int n_embd, int n_vocab, int vocab_offset,
|
||||
float wscale, float mult, int x_ld, int w_ld, int dt, long stream);
|
||||
|
||||
/* y[r] = x[idx[r]] and x[idx[r]] = v[r], rows of n elements.
|
||||
*
|
||||
* `src_rows` and `dst_rows` are the plane's own row count. Only the shim can supply it -- it has the
|
||||
* operand's numel, the launcher has a pointer -- and the kernel needs it, because the reference
|
||||
* reads the index plane on the host and refuses an index outside the row count, while a launch
|
||||
* cannot refuse an index it has not read. So the bound travels to the kernel and the kernel acts on
|
||||
* it: a gather at idx >= src_rows takes the padding path (the zero row libref's padding form
|
||||
* writes), a scatter at idx >= dst_rows drops the row, which is the same refusal seen from inside a
|
||||
* launch. The worst failure here is a read or a write past the plane, and a dropped row is what
|
||||
* stands between this card and it. 0 means unchecked: the shim's bug to avoid, not a caller's to
|
||||
* supply. */
|
||||
int r3d_gather_rows(long x, long idx, long y, int M, int n, int x_ld, int y_ld, int dt,
|
||||
long long src_rows, long stream);
|
||||
int r3d_scatter_rows(long v, long idx, long x, int M, int n, int v_ld, int x_ld, int dt,
|
||||
long long dst_rows, long stream);
|
||||
|
||||
/* ================================================================== r3d_quant_fp8.hip
|
||||
*
|
||||
* All three quantisers write a plain row-major code plane and one f32 scale per (row, group); no
|
||||
* fragment permutation, because a dot2 GEMM reads codes in order.
|
||||
*/
|
||||
|
||||
/* Per-(row, group) symmetric quantisation. scale = amax * (1/top) with top 448 for E4M3 and 127
|
||||
* for int8, the codes v * (1/scale) clamped to +-top and rounded by the codec. An all-zero group
|
||||
* gets scale 1. */
|
||||
int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld, int s_ld,
|
||||
long stream);
|
||||
int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n, int group, int x_ld, int s_ld,
|
||||
long stream);
|
||||
|
||||
/* quant_act_i8g: the same code at `group` granularity -- amax / 127 per (row, group), 1 for an
|
||||
* all-zero group -- stored row-major. This is the plane libr3d's i8a8 GEMM reads; `quant_act_i8`
|
||||
* above is the per-row plane the WMMA-ordered ops read, and the two are not interchangeable.
|
||||
* 0, -1, -2, -3, -4. */
|
||||
int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group,
|
||||
long long x_ld, long long s_ld, long stream);
|
||||
|
||||
/* The gated form: gate_up is [M, 2n] (gate in the first n, up in the second), and what is
|
||||
* quantised is act(gate) * up. `q`/`s` carry that product's codes and scales; `out_bf16`, when
|
||||
* present, also receives the product in bf16. */
|
||||
int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16, int M, int n, int group,
|
||||
int act, long stream);
|
||||
|
||||
/* The residual add, the RMS norm and the E4M3 quantiser in one pass, so the normalised row never
|
||||
* goes back to VRAM. `res` is the residual plane, INOUT, and 0 when the op has no residual: with it
|
||||
* the sum is STORED, narrowed to bf16, BEFORE the variance reads it, so the norm is over the bf16
|
||||
* sum -- the `add` + `rmsnorm` pair, not `rmsnorm_add`, which normalises the unrounded sum. `ob`,
|
||||
* when present, receives exactly the bf16 values the codes were taken over. Pitches are in elements
|
||||
* of their own operand, `s_ld` in scales, so a dense scale plane is n/group. `group` must divide n:
|
||||
* a partial group is the standalone quantiser's zero-padded store, which this pass does not have.
|
||||
* 0, -1, -2, -3, -4. */
|
||||
int r3d_rmsnorm_quant_fp8(long x, long res, long w, long q, long s, long ob, int M, int n,
|
||||
int group, float eps, float wadd, int x_ld, int res_ld, int ob_ld,
|
||||
int q_ld, int s_ld, int wdt, long stream);
|
||||
|
||||
/* y = code * scale, the read of a container's own quantised weight: group-wide f32 scales, E4M3 or
|
||||
* int8 codes. */
|
||||
int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s_ld, int y_ld,
|
||||
long stream);
|
||||
|
||||
/* ================================================================== r3d_gemm_*.hip
|
||||
*
|
||||
* y[M,N] = a[M,K] @ b[N,K]^T. One output element a lane, k ascending, f32 accumulate, the sum
|
||||
* narrowed once by the store. Split-K (sk > 0) writes partials to `scratch` and reduces them in a
|
||||
* second kernel on the same stream; the row's scratch hook sizes the arena for the largest sk the
|
||||
* band allows.
|
||||
*/
|
||||
|
||||
/* bf16 (and f16) operands. `nt` 1 streams the weight with non-temporal loads. */
|
||||
int r3d_gemm_nt_bf16_m16(long a, long b, long y, int M, int N, int K, int a_ld, int y_ld, int sk,
|
||||
int wv, int nt, long scratch, long stream);
|
||||
int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int K, int a_ld, int y_ld, int sk,
|
||||
int kb, int nt, long scratch, long stream);
|
||||
|
||||
/* A block-scaled fp8 weight: b is E4M3 codes, b_scale one scale per (pb1 rows of N, pb2 of K)
|
||||
* block, pb1/pb2 the block sizes the container states (absent, both default to `group`). The
|
||||
* scale plane is **bf16** in the container's quantised family -- `gemm_q_shape` writes
|
||||
* `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})` -- and f32 only under the separate dtype `fp8a8f32`.
|
||||
* a is bf16 (fp8a16, no a_scale) or E4M3 codes with per-(row, group) f32 a_scale (fp8a8). */
|
||||
int r3d_gemm_nt_q_fp8(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K,
|
||||
int group, int pb1, int pb2, int a_ld, int y_ld, int sk, int nt,
|
||||
long scratch, long stream);
|
||||
|
||||
/* The same kernel with the scale plane's dtype named, which the 17-argument entry above cannot
|
||||
* state: it forwards RAD_F32, and the container's quantised weights carry bf16 block scales. Land
|
||||
* new callers on this one; the older entry is kept for callers written against its RAD_F32
|
||||
* behaviour. bs_dt is the plane's RadDataType: RAD_BF16 reads bf16, anything else -- 0 included --
|
||||
* reads f32. */
|
||||
int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K,
|
||||
int group, int pb1, int pb2, int a_ld, int y_ld, int sk, int nt,
|
||||
long scratch, int bs_dt, long stream);
|
||||
|
||||
/* The int8 weight twin, with the optional a_sum / b_ref row sums an int8 GEMM with a zero point
|
||||
* needs (libquant's symmetric form leaves them null). */
|
||||
int r3d_gemm_nt_q_i8(long a, long a_scale, long b, long b_scale, long a_sum, long b_ref, long y,
|
||||
int M, int N, int K, int group, int a_ld, int y_ld, int sk, int nt,
|
||||
long scratch, long stream);
|
||||
|
||||
/* ================================================================== r3d_attn_paged_h128.hip
|
||||
*
|
||||
* Paged causal attention. `kv` is the cache the shim read its strides from; `bt` a
|
||||
* [num_seqs, blocks] block table; `seqused` per-sequence lengths; cu_seqlens, when present, the
|
||||
* ragged query layout; k_descale / v_descale the per-(seq, head) fp8 cache descales.
|
||||
*/
|
||||
int r3d_attn_decode_h128(long q, long kv, long bt, long seqused, long k_desc, long v_desc,
|
||||
long cu, long out, int num_seqs, int q_len, int head_dim, int gqa,
|
||||
int n_head, int block_size, int bt_cols, int bt_rs, int bt_cs,
|
||||
int max_ctx, int window, int causal,
|
||||
float scale, int kv_dt, long q_ld, long out_ld, int splits, long scratch,
|
||||
long stream);
|
||||
int r3d_attn_prefill_h128(long q, long kv, long bt, long seqused, long k_desc, long v_desc,
|
||||
long cu, long out, int num_seqs, int q_len, int head_dim, int gqa,
|
||||
int n_head, int block_size, int bt_cols, int bt_rs, int bt_cs,
|
||||
int max_ctx, int window, int causal,
|
||||
float scale, int kv_dt, long q_ld, long out_ld, long scratch,
|
||||
long stream);
|
||||
|
||||
/* ================================================================== r3d_gemm_fp8a8_tiled.hip
|
||||
*
|
||||
* The quantised GEMM at prefill heights. b_row/bs_row are the container's row strides, 0 meaning
|
||||
* dense; `group` is the scale block, 128 on every band this checkpoint declares. The scales arrive
|
||||
* as the container's two planes behind one operand, which is what the row's layout hook presents;
|
||||
* the plain two-tensor form is the same entry with bs_row dense.
|
||||
*/
|
||||
int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M, int N,
|
||||
int K, int group, int a_ld, long long b_row, int as_ld, long long bs_row,
|
||||
int y_ld, int nt, long stream);
|
||||
|
||||
/* ================================================================== r3d_gemm_mxfp4a8.hip
|
||||
*
|
||||
* The quantised GEMM at dtype=mxfp4a8: an OCP-MXFP4 weight against the fp8 activation. `b` is the
|
||||
* e2m1 codes, two per byte, [N, K/2] u8; `b_scale` the e8m0 scale, one per 32 of K, [N, K/32] u8;
|
||||
* `a` E4M3 with `a_scale` f32 per (row, 128 of K); `y` bf16. b_row/e8_row are the row strides in
|
||||
* bytes, 0 meaning dense. There is no zero point: the scale is symmetric, and a reserved e8 (0,
|
||||
* 255) is refused. M <= 16 takes the m16 launcher, M >= 17 the tiled one.
|
||||
*/
|
||||
int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N,
|
||||
int K, int group, int a_ld, int y_ld, long long e8_row, long stream);
|
||||
int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M,
|
||||
int N, int K, int group, int a_ld, long long b_row, int as_ld,
|
||||
long long e8_row, int y_ld, int nt, long stream);
|
||||
|
||||
/* ================================================================== r3d_gemm_inta8.hip
|
||||
*
|
||||
* The quantised GEMM at dtype=w4a8 and w8a8: the symmetric int4 and int8 weight grids at decode
|
||||
* heights. `b` is the signed codes (I4, two a byte, or I8, one a byte), [N, K]; `b_scale` the f16
|
||||
* scale, one per (row, 128 of K), [N, K/128]; `a` int8 in the step order with `a_scale` f32 per
|
||||
* row; `y` bf16. b_rb and sb_rb are the row strides (bytes / elements), 0 meaning dense.
|
||||
* There is no zero point:
|
||||
* the dequant is code times scale. M <= 16 only; the prefill band is the tiled rows' and the
|
||||
* 8-bit grid at prefill heights is declared out of this unit.
|
||||
*/
|
||||
int r3d_gemm_nt_q_w4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N,
|
||||
int K, int a_ld, int y_ld, long long b_rb, long long sb_rb, long stream);
|
||||
int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N,
|
||||
int K, int a_ld, int y_ld, long long b_rb, long long sb_rb, long stream);
|
||||
|
||||
/* ================================================================== r3d_vocab_bf16.hip
|
||||
*
|
||||
* The vocab-sharded logits and the top-k that follows them.
|
||||
*/
|
||||
|
||||
/* logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T: the decode heights (M <= 16) on
|
||||
* the decode arm, a prefill arm above them, over a vocabulary-wide N. */
|
||||
int r3d_logits_gemm_bf16(long x, long lm, long y, int M, int n_vocab, int n_embd, int x_ld,
|
||||
int y_ld, int sk, int nt, long scratch, long stream);
|
||||
|
||||
/* Per-row top-R of a [M, N] logits row: idx (i32) and val (f32), descending, ties to the lower
|
||||
* index. `pairs`, when present, also receives the (index, value) dwords a cross-rank merge reads. */
|
||||
int r3d_row_topk_bf16(long x, long idx, long val, long pairs, int M, int N, int R, int vocab_off,
|
||||
int x_ld, int rc, int nch, long scratch, long stream);
|
||||
|
||||
/* The cross-rank top-1: one id and one value a row, out of [M, n] candidate pairs. */
|
||||
int r3d_pair_argmax(long pairs, long idx, long val, int M, int n, long stream);
|
||||
|
||||
/* ================================================================== r3d_sample_f32.hip
|
||||
* The sampler, and the vocabulary row it starts from.
|
||||
*
|
||||
* The shapes are libref's, operand for operand, and so is the `params` plane:
|
||||
* one `RadSampleParams` a row, 96 bytes of f32 words, which every stage reads by field. `logits` is
|
||||
* f32 and the candidate planes are word-typed -- `cand_idx` i32, `cand_val` f32, the pair planes
|
||||
* i32 holding an id's bits beside a logit -- because that is what the reference writes.
|
||||
*
|
||||
* The stages over the full vocabulary (argmax, temp, topk, logprobs, penalties, dry, ngram_ban) are
|
||||
* one block a row and are bound by the plane: at the band MiniCPM5-2B asks for, 2048 rows of 130560
|
||||
* f32, the logits are 1.02 GiB and one pass is the floor. The stages over the candidate set (the
|
||||
* four narrowings and pick) are one block a row of `n_cand` and are bound by the arithmetic, which
|
||||
* is why `pick` keeps the reference's double `exp`: the law is `(float)std::exp((double)x)`, and a
|
||||
* hardware `v_exp_f32` two ulp away moves a draw whenever a true probability lands within an ulp of
|
||||
* the `u < cum` boundary.
|
||||
*
|
||||
* M comes off the operand, never off the band: the band's `M` is a range's bound and a step's row
|
||||
* count is what the planes hold. 0, -1 null pointer, -2 bad extent, -3 pitch, -4 launch failed.
|
||||
*/
|
||||
int r3d_row_topk(long x, long idx, long val, long pairs, int M, int N, int R, int x_dt,
|
||||
long long x_ld, long long idx_ld, long long val_ld, long long pairs_ld,
|
||||
int vocab_off, long stream);
|
||||
int r3d_sample_argmax(long lg, long tok, int M, int n_vocab, long long lg_ld, long stream);
|
||||
int r3d_sample_temp(long lg, long params, int M, int n_vocab, long long lg_ld, long stream);
|
||||
int r3d_sample_topk(long lg, long params, long ci, long cv, long pairs, int M, int n_vocab,
|
||||
int n_cand, long long lg_ld, long long ci_ld, long long cv_ld,
|
||||
long long pairs_ld, int vocab_off, long stream);
|
||||
int r3d_sample_pick(long ci, long cv, long params, long tok, int M, int n_cand,
|
||||
long long ci_ld, long long cv_ld, long stream);
|
||||
|
||||
/* The four narrowing stages: one shape, `cand_idx` and `cand_val` in place, one predicate each --
|
||||
* top-p a prefix rule in candidate order, min-p a floor under the best candidate's probability,
|
||||
* typical the band around the set's entropy, XTC the exclusion-the-model-would-not-choose cut. */
|
||||
int r3d_sample_topp(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
|
||||
long long cv_ld, long stream);
|
||||
int r3d_sample_minp(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
|
||||
long long cv_ld, long stream);
|
||||
int r3d_sample_typical(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
|
||||
long long cv_ld, long stream);
|
||||
int r3d_sample_xtc(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
|
||||
long long cv_ld, long stream);
|
||||
|
||||
/* The pre-filters over the logits row. `hist` is the row's history of global token ids, i32
|
||||
* [M, max_hist]; its window, and the rule that a token is penalised at its first occurrence in the
|
||||
* window, are libref's (`hist_window`), and the window is placed inside the params plane by the
|
||||
* descriptor's `fill_chunk`. `vocab_off` shifts the ids a stage reports, for a split vocabulary. */
|
||||
int r3d_sample_penalties(long lg, long params, long hist, int M, int n_vocab, long long lg_ld,
|
||||
long long hist_ld, int vocab_off, long stream);
|
||||
int r3d_sample_dry(long lg, long params, long hist, long breakers, int M, int n_vocab,
|
||||
long long lg_ld, long long hist_ld, int vocab_off, long stream);
|
||||
int r3d_sample_ngram_ban(long lg, long params, long hist, long ngram, long whitelist, int M,
|
||||
int n_vocab, long long lg_ld, long long hist_ld, int vocab_off,
|
||||
long stream);
|
||||
int r3d_sample_mask(long lg, long params, long bitmask, int M, int n_vocab, long long lg_ld,
|
||||
int mask_rows, long stream);
|
||||
/* The gated MLP band: b is E4M3 codes of N = 2n rows (gate rows [0,n), up rows [n,N)), b_scale one
|
||||
* scale per (group, group) block, bf16 as the container writes it. The row is narrowed to bf16 as
|
||||
* the unfused pair leaves it, gated (act: R3D_ACT_SILU | R3D_ACT_SIGMOID), narrowed again, and coded
|
||||
* per group of `group` columns: q is the codes [M,n], scale the per-(row, group) amax scales, and
|
||||
* out_bf16 the narrowed gated tensor when the caller wants it (y_ld is its row pitch, n when the
|
||||
* plane is absent). M <= 64, sk == 1; no scratch, because the row never leaves the registers. */
|
||||
int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, long q, long scale,
|
||||
long out_bf16, int M, int N, int K, int group, int act,
|
||||
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch, long stream);
|
||||
|
||||
/* The same kernel naming the scale plane's dtype. The entry above forwards RAD_BF16, which is the
|
||||
* container's form for this op; f32 is accepted and equal bit for bit. */
|
||||
int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale, long q, long scale,
|
||||
long out_bf16, int M, int N, int K, int group, int act,
|
||||
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
|
||||
int bs_dt, long stream);
|
||||
|
||||
/* DFlash2's greedy walk over the candidate lattice. `hp` may be 0: the plane of ones the reference
|
||||
* computes when the operand is absent. The rows of cand, unary and tokens are (sequence, step),
|
||||
* M * steps of them; `anchor` is a row of M * anchor_stride ids. */
|
||||
int r3d_dflash_select(long cand, long unary, long hp, long anchor, long pred, long succ,
|
||||
long tokens, int M, int steps, int top_k, int rank, int n_vocab,
|
||||
int anchor_stride, long long cand_ld, long long un_ld, long long hp_ld,
|
||||
long long pred_ld, long long succ_ld, long long tok_ld, long stream);
|
||||
int r3d_sample_logprobs(long lg, long params, long stats, int M, int n_vocab, int k,
|
||||
long long lg_ld, long long stats_ld, int vocab_off, long stream);
|
||||
|
||||
} /* extern "C" */
|
||||
|
||||
#endif /* RAD_R3D_H */
|
||||
@@ -0,0 +1,310 @@
|
||||
/* r3d_args.h -- how a libr3d entry point reads its arguments.
|
||||
*
|
||||
* There is no adapter layer. An entry point takes `(const RadArgs*, RadStream)` and returns a
|
||||
* status, the same RadLaunchFn contract every other plugin implements; an out-of-tree author can
|
||||
* write the same kernel without an adapter they could not reach.
|
||||
*
|
||||
* This header holds the shared helpers: reading a parameter, finding an operand, testing
|
||||
* contiguity. Most are one line over rad_abi.h.
|
||||
*
|
||||
* Nothing here includes r3d.h or HIP: host translation units (the row table, the shape hooks)
|
||||
* include it too, so those tables compile and can be checked without ROCm.
|
||||
*/
|
||||
#ifndef R3D_ARGS_H
|
||||
#define R3D_ARGS_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
/* ================================================================== parameter access
|
||||
*
|
||||
* Forwards to rad_abi.h's static inline helpers, the ones a third-party plugin gets, keeping
|
||||
* libr3d's spelling at its call sites. */
|
||||
static inline int r3d_geti(const RadArgs* a, const char* k, long long* out) {
|
||||
return rad_args_geti(a, k, out);
|
||||
}
|
||||
|
||||
static inline long long r3d_geti_or(const RadArgs* a, const char* k, long long dflt) {
|
||||
return rad_args_geti_or(a, k, dflt);
|
||||
}
|
||||
|
||||
static inline const char* r3d_gets(const RadArgs* a, const char* k) {
|
||||
return rad_args_gets(a, k);
|
||||
}
|
||||
|
||||
/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so `dval` arrives
|
||||
* and the step path runs no strtod. Deliberately laxer than rad_args_getf_or: string and integer
|
||||
* spellings are still read, because a tool or selftest may call a launch directly with no declare
|
||||
* to enforce the type. */
|
||||
static inline double r3d_getf(const RadArgs* a, const char* k, double dflt) {
|
||||
if (!a || !k) return dflt;
|
||||
for (int i = 0; i < a->n_p; ++i) {
|
||||
if (!a->p[i].key || std::strcmp(a->p[i].key, k) != 0) continue;
|
||||
if (a->p[i].kind == RAD_P_F64) return a->p[i].dval;
|
||||
if (a->p[i].kind == RAD_P_INT) return (double)a->p[i].ival;
|
||||
if (a->p[i].kind == RAD_P_STR && a->p[i].sval && a->p[i].sval[0]) {
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(a->p[i].sval, &end);
|
||||
return (end && end != a->p[i].sval) ? v : dflt;
|
||||
}
|
||||
return dflt;
|
||||
}
|
||||
return dflt;
|
||||
}
|
||||
|
||||
/* An enumerated parameter: `act` is "silu" or "sigmoid", not 0 or 1, so a --debug-graph dump says
|
||||
* what runs; the mapping to libr3d's integer lives in the shim. Returns -1 for an unknown name,
|
||||
* which every caller turns into RAD_E_INVAL. `alt` is libr3d's own integer spelling of the same
|
||||
* key, consulted only when the name is absent. */
|
||||
static inline int r3d_act_code(const RadArgs* a, const char* key, const char* alt, int dflt) {
|
||||
if (const char* s = r3d_gets(a, key)) {
|
||||
if (!std::strcmp(s, "silu") || !std::strcmp(s, "swish")) return 0;
|
||||
if (!std::strcmp(s, "sigmoid")) return 1;
|
||||
return -1;
|
||||
}
|
||||
long long v = 0;
|
||||
if (alt && r3d_geti(a, alt, &v)) return (v == 0 || v == 1) ? (int)v : -1;
|
||||
return dflt;
|
||||
}
|
||||
|
||||
/* Same, off a bare RadParam list (init() and the layout hooks); forwards to rad_plugin.h's
|
||||
* rad_param_*. */
|
||||
static inline long long r3d_pgeti_or(const RadParam* p, int n_p, const char* k, long long dflt) {
|
||||
return rad_param_geti(p, n_p, k, dflt);
|
||||
}
|
||||
|
||||
static inline const char* r3d_pgets(const RadParam* p, int n_p, const char* k) {
|
||||
return rad_param_gets(p, n_p, k, nullptr);
|
||||
}
|
||||
|
||||
/* ================================================================== operand access
|
||||
*
|
||||
* An absent optional operand is a null RadTensor.data (rad_abi.h). r3d_opt() returns null both
|
||||
* past the end and for a present-but-null operand, so an optional test is one pointer test. For a
|
||||
* required operand the caller turns null into RAD_E_INVAL: it is a bug in the issue, not a shape
|
||||
* the kernel declines.
|
||||
*/
|
||||
static inline const RadTensor* r3d_opt(const RadArgs* a, int i) { return rad_arg_in(a, i); }
|
||||
|
||||
/* An optional operand the plan carries a slot for, with no bytes behind it, is ABSENT -- it is not a
|
||||
* dtype problem. The engine hands the slots of an op's optional operands as descriptors with a null
|
||||
* `data` when the graph did not bind one, and a shim that dtype-checks such a descriptor would refuse
|
||||
* a band the op never reads -- `rmsnorm_quant_fp8` answering E_DTYPE to a band whose dtype is fine,
|
||||
* for an empty `out_bf16` slot. Every test of an optional operand goes through here; a bare `if (t)`
|
||||
* is the bug. */
|
||||
static inline bool r3d_has(const RadTensor* t) { return t && t->data; }
|
||||
|
||||
static inline const void* r3d_p(const RadTensor* t) { return t ? t->data : nullptr; }
|
||||
|
||||
/* The same for an operand a kernel writes, so an output cast reads as one rather than as a pointer
|
||||
* laundered through `long`. */
|
||||
static inline void* r3d_wp(const RadTensor* t) { return t ? t->data : nullptr; }
|
||||
static inline long r3d_addr(const RadTensor* t) { return t ? (long)(uintptr_t)t->data : 0L; }
|
||||
|
||||
static inline long long r3d_dim(const RadTensor* t, int i) {
|
||||
if (!t || i < 0 || (uint32_t)i >= t->rank) return 0;
|
||||
return t->shape[i];
|
||||
}
|
||||
|
||||
static inline long long r3d_stride(const RadTensor* t, int i) {
|
||||
if (!t || i < 0 || (uint32_t)i >= t->rank) return 0;
|
||||
return t->stride[i];
|
||||
}
|
||||
|
||||
static inline long long r3d_numel(const RadTensor* t) { return rad_tensor_numel(t); }
|
||||
|
||||
/* [rows..., K] flattened to (M, K). Every per-row kernel in libr3d owns whole rows (one workgroup
|
||||
* per row), so the leading axes are only a row count. The GEMM makes the same fold explicitly. */
|
||||
static inline int r3d_rows_of(const RadTensor* t, long long* M, long long* K) {
|
||||
if (!t || t->rank < 1) return RAD_E_SHAPE;
|
||||
*K = t->shape[t->rank - 1];
|
||||
*M = 1;
|
||||
for (uint32_t i = 0; i + 1 < t->rank; ++i) *M *= t->shape[i];
|
||||
return (*M >= 1 && *K >= 1) ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
/* Dense row-major over the whole tensor. libr3d's entry points take at most one pitch, so
|
||||
* everything else must be tight, and the shim checks it. This is the "necessary condition only"
|
||||
* boundary of spec §2.1: the constraint table settles geometry, contiguity is a property of the
|
||||
* call. */
|
||||
static inline int r3d_contig(const RadTensor* t) { return rad_tensor_is_contiguous(t); }
|
||||
|
||||
/* Contiguous in every axis but the leading one, whose stride is the row pitch libr3d takes as an
|
||||
* explicit argument (`x_ld`, `a_stride`, ...). Returns the pitch in elements, or -1. */
|
||||
static inline long long r3d_row_pitch(const RadTensor* t) {
|
||||
if (!t || t->rank == 0) return -1;
|
||||
if (t->rank == 1) return 1;
|
||||
long long acc = 1;
|
||||
for (int i = (int)t->rank - 1; i >= 1; --i) {
|
||||
if (t->shape[i] != 1 && t->stride[i] != acc) return -1;
|
||||
acc *= t->shape[i];
|
||||
}
|
||||
return t->stride[0];
|
||||
}
|
||||
|
||||
/* [rows..., n] read as (rows, n): the leading axes are a row count and only the last is
|
||||
* structural. Returns the pitch in elements, or -1.
|
||||
*
|
||||
* A column slice must refuse. k out of a fused [tok, 2*kv_dim] projection, read as
|
||||
* [tok*n_head_kv, head_dim] for a per-head norm, has rows `n` apart within a token and a buffer row
|
||||
* apart between tokens; no single pitch describes that, and the leading stride would make the
|
||||
* consumer read most heads from garbage. So the trailing axes must cover the whole row. */
|
||||
static inline long long r3d_rows_pitch(const RadTensor* t, long long n, long long* rows) {
|
||||
if (!t || t->rank < 1 || n <= 0) return -1;
|
||||
const long long nel = rad_tensor_numel(t);
|
||||
if (nel % n) return -1;
|
||||
*rows = nel / n;
|
||||
if (t->rank == 1) return n;
|
||||
if (t->shape[t->rank - 1] == n) {
|
||||
if (t->stride[t->rank - 1] != 1) return -1;
|
||||
return t->rank >= 2 ? t->stride[t->rank - 2] : n;
|
||||
}
|
||||
if (rad_tensor_is_contiguous(t)) return n;
|
||||
long long trail = 1;
|
||||
for (int i = 1; i < (int)t->rank; ++i) trail *= t->shape[i];
|
||||
return trail == n ? r3d_row_pitch(t) : -1;
|
||||
}
|
||||
|
||||
/* An attention operand, [tokens, heads * head_dim] over its trailing axes: the token count, head
|
||||
* count and row pitch in elements. False when the trailing axes are not whole heads or no single
|
||||
* pitch describes the rows. */
|
||||
static inline bool r3d_head_rows(const RadTensor* t, long long head_dim, long long* n_tok,
|
||||
long long* n_head, long long* ld) {
|
||||
long long width = 1;
|
||||
for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i];
|
||||
if (t->rank < 2 || width % head_dim) return false;
|
||||
*n_head = width / head_dim;
|
||||
*ld = r3d_rows_pitch(t, width, n_tok);
|
||||
return *ld >= 0;
|
||||
}
|
||||
|
||||
/* 16-byte alignment, needed by every kernel that loads a dword pair per lane. The kernels do not
|
||||
* check it, so the shim does. */
|
||||
static inline int r3d_aligned(const void* p, unsigned bytes) {
|
||||
return p ? (((uintptr_t)p & (uintptr_t)(bytes - 1)) == 0) : 1;
|
||||
}
|
||||
|
||||
/* ================================================================== which check refused
|
||||
*
|
||||
* A shim refuses in many places with the same few codes, so the engine's report names the kernel
|
||||
* and geometry but not the failing condition. R3D_NO() wraps a refusal and prints its own line when
|
||||
* RAD_R3D_TRACE is set; otherwise it is the bare return plus one cached-flag load on a path that is
|
||||
* failing anyway. */
|
||||
static inline int r3d_trace_on(void) {
|
||||
static int on = -1;
|
||||
if (on < 0) { const char* e = std::getenv("RAD_R3D_TRACE"); on = (e && *e && *e != '0'); }
|
||||
return on;
|
||||
}
|
||||
static inline int r3d_refused(int code, const char* file, int line) {
|
||||
if (r3d_trace_on()) std::fprintf(stderr, "[r3d] %s:%d refused -> %d\n", file, line, code);
|
||||
return code;
|
||||
}
|
||||
#define R3D_NO(code) r3d_refused((code), __FILE__, __LINE__)
|
||||
|
||||
/* The descriptor we were handed, printed when we decline one. A stride refusal that names no stride
|
||||
* is a refusal the reader has to reproduce, and reproducing it costs a probe cycle: the engine binds
|
||||
* rank, shape and strides in ELEMENTS, and the shape it binds is the step's, not the band's. */
|
||||
static inline void r3d_trace_desc(const char* what, const RadTensor* t) {
|
||||
if (!r3d_trace_on()) return;
|
||||
if (!t) { std::fprintf(stderr, "[r3d] %s: (absent)\n", what); return; }
|
||||
std::fprintf(stderr, "[r3d] %s: dtype %u rank %u shape [", what, t->dtype, t->rank);
|
||||
for (int i = 0; i < (int)t->rank; ++i) std::fprintf(stderr, "%s%lld", i ? "," : "", (long long)t->shape[i]);
|
||||
std::fprintf(stderr, "] stride [");
|
||||
for (int i = 0; i < (int)t->rank; ++i) std::fprintf(stderr, "%s%lld", i ? "," : "", (long long)t->stride[i]);
|
||||
std::fprintf(stderr, "] data %p\n", t->data);
|
||||
}
|
||||
#define R3D_STR(why, a1, v1, a2, v2) \
|
||||
do { \
|
||||
if (r3d_trace_on()) \
|
||||
std::fprintf(stderr, "[r3d] %s:%d stride refusal: %s, %s %lld, %s %lld\n",\
|
||||
__FILE__, __LINE__, (why), (a1), (long long)(v1), (a2), \
|
||||
(long long)(v2)); \
|
||||
return R3D_NO(RAD_E_STRIDE); \
|
||||
} while (0)
|
||||
|
||||
/* ================================================================== dtype helpers
|
||||
*
|
||||
* A row's `dtype` constraint is a necessary condition on the geometry, not a promise about the
|
||||
* tensors: the shim reads the dtype off the operand, and these are the tests it reads it with. */
|
||||
static inline int r3d_is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; }
|
||||
static inline int r3d_is_f16(const RadTensor* t) { return t && t->dtype == RAD_F16; }
|
||||
static inline int r3d_is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; }
|
||||
static inline int r3d_is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; }
|
||||
static inline int r3d_is_i64(const RadTensor* t) { return t && t->dtype == RAD_I64; }
|
||||
static inline int r3d_is_fp8(const RadTensor* t) {
|
||||
return t && (t->dtype == RAD_F8E4M3 || t->dtype == RAD_F8E5M2);
|
||||
}
|
||||
static inline int r3d_is_e4m3(const RadTensor* t) { return t && t->dtype == RAD_F8E4M3; }
|
||||
static inline int r3d_is_i8(const RadTensor* t) { return t && t->dtype == RAD_I8; }
|
||||
static inline int r3d_is_u8(const RadTensor* t) { return t && t->dtype == RAD_U8; }
|
||||
|
||||
/* The dtype name a row's constraint table carries, for a shim that must match a string parameter
|
||||
* against an operand. */
|
||||
static inline int r3d_dt_named(uint32_t dt, const char* name) {
|
||||
if (!name) return 0;
|
||||
if (!std::strcmp(name, "bf16")) return dt == RAD_BF16;
|
||||
if (!std::strcmp(name, "f16") || !std::strcmp(name, "fp16")) return dt == RAD_F16;
|
||||
if (!std::strcmp(name, "f32") || !std::strcmp(name, "fp32")) return dt == RAD_F32;
|
||||
if (!std::strcmp(name, "fp8_e4m3") || !std::strcmp(name, "e4m3")) return dt == RAD_F8E4M3;
|
||||
if (!std::strcmp(name, "fp8_e5m2") || !std::strcmp(name, "e5m2")) return dt == RAD_F8E5M2;
|
||||
if (!std::strcmp(name, "i8") || !std::strcmp(name, "int8")) return dt == RAD_I8;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ================================================================== libr3d's constants
|
||||
*
|
||||
* Restated here because r3d_rows.cpp and r3d_shapes.cpp are host code built without ROCm and cannot
|
||||
* include r3d.h, and because a .rad container records them in its layout tag. */
|
||||
enum {
|
||||
R3D_WAVE = 32,
|
||||
/* The activation quantiser's group: the width a scale covers along n. 128 is the WEIGHT
|
||||
* scale's block width and therefore a property of the checkpoint, not a knob. */
|
||||
R3D_ACT_GROUP = 128,
|
||||
/* Block-scaled fp8, on both axes: the checkpoint's `quantization_config.weight_block_size`,
|
||||
* which the bytes on disk follow. The entry points reject a mismatch. */
|
||||
R3D_FP8_BLOCK = 128,
|
||||
/* The int8 weight group, the same 128 the checkpoint's scales use. */
|
||||
R3D_W8_GROUP = 128,
|
||||
/* The largest N a dot2 GEMM's per-lane accumulator grid spans in one wave. */
|
||||
R3D_NTILE = 16,
|
||||
/* The operand count of `gemm_nt_q` (a, a_scale, b, b_scale, y, a_sum, b_ref). The shape hook
|
||||
* builds the whole list at once and needs a name for its length; the schema in r3d_rows.cpp is
|
||||
* the authority, and rad-kbench checks the two against each other. */
|
||||
R3D_GEMM_Q_NOPERAND = 7
|
||||
};
|
||||
|
||||
/* ================================================================== libr3d's tunables
|
||||
*
|
||||
* The knobs the row table declares, exposed so `rad-tune` can walk them and `--debug-graph` can
|
||||
* name the pick (spec §15). The chosen point comes back appended to RadArgs::p, so a launch reads
|
||||
* it with r3d_geti_or like any other parameter; these structs are how a launch reads several at
|
||||
* once, with the row's defaults where a caller supplied none.
|
||||
*
|
||||
* sk == 0 means "choose the largest legal split count at issue". Split-K requires
|
||||
* K % (sk * group) == 0, so no fixed default is legal at every shape, and an illegal default would
|
||||
* make an untuned install fail rather than run slowly. The sentinel is resolved in one place, in
|
||||
* the GEMM unit.
|
||||
*/
|
||||
struct R3dGemmCfg { int wv, sk, kb, nt; }; /* waves a block, split-K, K slab, non-temporal loads */
|
||||
struct R3dSplitCfg { int splits; }; /* split-KV segments; 0 is the kernel's own law */
|
||||
struct R3dTopkCfg { int rc, nch; }; /* candidates a chunk keeps, chunk width in columns */
|
||||
|
||||
extern "C" {
|
||||
/* -- the tuned configuration (r3d_rows.cpp) --
|
||||
*
|
||||
* The core picked a point in the space the row declared and appended it to RadArgs::p. These read
|
||||
* it back, falling to the axis's default (defined once, in the RadTunable table) when a caller
|
||||
* supplied none, so a checker with no tuned key runs what an untuned install runs. They cannot
|
||||
* fail: the loader refuses a plugin whose default is not one of the axis's values. */
|
||||
void r3d_cfg_gemm (const RadArgs*, struct R3dGemmCfg*);
|
||||
void r3d_cfg_split(const RadArgs*, struct R3dSplitCfg*);
|
||||
void r3d_cfg_topk (const RadArgs*, struct R3dTopkCfg*);
|
||||
|
||||
} /* extern "C" */
|
||||
|
||||
#endif /* R3D_ARGS_H */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,359 @@
|
||||
/* r3d_codecs.h -- the numeric codecs, in the one spelling every libr3d unit and the host use.
|
||||
*
|
||||
* These define what a result is, so they are stated once: rad_plugin.h's bf16 / f16 / fp8 / int8
|
||||
* rounders, restated so a device kernel can call them. rad_plugin.h's are `static inline` host
|
||||
* functions, which a `__global__` cannot reach, and libref -- the oracle every libr3d row is
|
||||
* checked against at kbench -- is built out of them. The mirror is therefore not a style choice,
|
||||
* and r3d_selftest.cpp compares the two over the whole fp8 code space, the whole bf16 code space
|
||||
* and 2^20 random f32s, so a drift of one ulp is a test failure here and not a tolerance argument
|
||||
* at kbench.
|
||||
*
|
||||
* The contract, from ref_common.h and rad_plugin.h: f32 accumulation, IEEE round-to-nearest-ties-
|
||||
* to-even narrowing, no fused multiply-add and no reassociation, subnormals kept. Widening is
|
||||
* exact. `-ffp-contract=off` is a correctness flag, and rad_hipify puts it on every HIP source.
|
||||
*
|
||||
* R3D_HD is `__host__ __device__` in a HIP translation unit and nothing in a host one, which is how
|
||||
* the same header serves a kernel and r3d_selftest.cpp. The pieces that want a GPU instruction are
|
||||
* behind __HIP_DEVICE_COMPILE__ and have a plain-C++ twin a device build never takes.
|
||||
*/
|
||||
#ifndef R3D_CODECS_H
|
||||
#define R3D_CODECS_H
|
||||
|
||||
#include <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. */
|
||||
#if defined(__HIPCC__)
|
||||
#include <hip/hip_runtime.h>
|
||||
#endif
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define R3D_HD __device__ __host__ __forceinline__
|
||||
#else
|
||||
#define R3D_HD inline
|
||||
#endif
|
||||
|
||||
/* The bit cast, in one place. Device code cannot call `memcpy` and the HIP headers do not declare a
|
||||
* `__host__ __device__` one on every release, so the device path is the compiler's bit cast; the
|
||||
* host path keeps memcpy, which the optimiser folds to a move, because GCC only grew
|
||||
* `__builtin_bit_cast` in C++20 mode and r3d_selftest.cpp is built at C++17 by the tree's host
|
||||
* compiler. */
|
||||
R3D_HD uint32_t bits_of(float f) {
|
||||
#if defined(__HIPCC__)
|
||||
return __builtin_bit_cast(uint32_t, f);
|
||||
#else
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &f, sizeof u);
|
||||
return u;
|
||||
#endif
|
||||
}
|
||||
|
||||
R3D_HD float float_of(uint32_t u) {
|
||||
#if defined(__HIPCC__)
|
||||
return __builtin_bit_cast(float, u);
|
||||
#else
|
||||
float f;
|
||||
std::memcpy(&f, &u, sizeof f);
|
||||
return f;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/* ================================================================== bf16
|
||||
*
|
||||
* bf16 is f32's top half: widening is a shift, narrowing one add and a shift.
|
||||
*
|
||||
* `(u >> 16) & 1` is the tie-break -- it adds one more than the halfway point when the surviving
|
||||
* bit is odd, so ties go to even. Overflow carries into the bf16 infinity; a NaN is forced quiet so
|
||||
* it cannot round into an infinity, which is what rad_f32_to_bf16 does and what libref does. */
|
||||
R3D_HD float bf16_to_f32(uint16_t h) {
|
||||
const uint32_t u = (uint32_t)h << 16;
|
||||
return float_of(u);
|
||||
}
|
||||
|
||||
R3D_HD uint16_t f32_to_bf16(float f) {
|
||||
const uint32_t u = bits_of(f);
|
||||
if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t)((u >> 16) | 0x0040u);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
/* The same rounding, stopped one shift short: the rounded value sitting in a word's high half, the
|
||||
* form a packed store wants. gfx11 in this ROCm has no v_cvt_pk_bf16_f32 (llvm-mc rejects it on
|
||||
* gfx1100, gfx1102 and gfx1151), so a bf16 pair is two of these and one byte permute. */
|
||||
R3D_HD uint32_t bf16_hi_rne(float f) {
|
||||
const uint32_t u = bits_of(f);
|
||||
return u + 0x7fffu + ((u >> 16) & 1u);
|
||||
}
|
||||
|
||||
/* Two such words as one bf16 pair, `lo`'s half in the low half of the result: one v_perm_b32. */
|
||||
R3D_HD uint32_t bf16_pack_hi(uint32_t lo, uint32_t hi) {
|
||||
#if defined(__HIP_DEVICE_COMPILE__)
|
||||
return __builtin_amdgcn_perm(hi, lo, 0x07060302u);
|
||||
#else
|
||||
return ((lo >> 16) & 0xffffu) | (hi & 0xffff0000u);
|
||||
#endif
|
||||
}
|
||||
|
||||
R3D_HD uint32_t bf16x2_rne(float lo, float hi) {
|
||||
return bf16_pack_hi(bf16_hi_rne(lo), bf16_hi_rne(hi));
|
||||
}
|
||||
|
||||
/* A bf16 pair word's two values as floats: a shift and a mask, no conversion. */
|
||||
R3D_HD float bf16w_lo(uint32_t w) {
|
||||
const uint32_t u = w << 16;
|
||||
return float_of(u);
|
||||
}
|
||||
R3D_HD float bf16w_hi(uint32_t w) {
|
||||
const uint32_t u = w & 0xffff0000u;
|
||||
return float_of(u);
|
||||
}
|
||||
|
||||
/* ================================================================== f16
|
||||
*
|
||||
* RTNE both ways with subnormals kept, as rad_f16_to_f32 and rad_f32_to_f16 do -- not the hardware
|
||||
* convert, whose rounding mode a caller could have changed and which flushes subnormal halves. */
|
||||
R3D_HD float f16_to_f32(uint16_t h) {
|
||||
const uint32_t s = (uint32_t)(h >> 15) << 31;
|
||||
const uint32_t e = (uint32_t)(h >> 10) & 0x1fu;
|
||||
uint32_t m = (uint32_t)h & 0x3ffu;
|
||||
uint32_t u;
|
||||
if (e == 0u) {
|
||||
if (m == 0u) {
|
||||
u = s;
|
||||
} else {
|
||||
int sh = 0; /* subnormal: renormalise into f32's range */
|
||||
while (!(m & 0x400u)) { m <<= 1; ++sh; }
|
||||
m &= 0x3ffu;
|
||||
u = s | ((uint32_t)(127 - 15 - sh + 1) << 23) | (m << 13);
|
||||
}
|
||||
} else if (e == 0x1fu) {
|
||||
u = s | 0x7f800000u | (m << 13);
|
||||
} else {
|
||||
u = s | ((e - 15u + 127u) << 23) | (m << 13);
|
||||
}
|
||||
return float_of(u);
|
||||
}
|
||||
|
||||
R3D_HD uint16_t f32_to_f16(float f) {
|
||||
const uint32_t u = bits_of(f);
|
||||
const uint32_t s = (u >> 16) & 0x8000u;
|
||||
const uint32_t a = u & 0x7fffffffu;
|
||||
|
||||
if (a >= 0x7f800000u) /* inf or nan */
|
||||
return (uint16_t)(s | 0x7c00u | (a > 0x7f800000u ? ((a >> 13) & 0x3ffu) | 0x200u : 0u));
|
||||
if (a >= 0x47800000u) return (uint16_t)(s | 0x7c00u); /* overflow -> inf */
|
||||
if (a < 0x33000000u) return (uint16_t)s; /* underflow -> zero */
|
||||
|
||||
const int e = (int)(a >> 23) - 127;
|
||||
uint32_t m = a & 0x7fffffu;
|
||||
if (e < -14) { /* subnormal half */
|
||||
const int sh = -14 - e + 13;
|
||||
m |= 0x800000u;
|
||||
const uint32_t lo = m & ((1u << sh) - 1u);
|
||||
uint32_t q = m >> sh;
|
||||
const uint32_t half = 1u << (sh - 1);
|
||||
if (lo > half || (lo == half && (q & 1u))) ++q;
|
||||
return (uint16_t)(s | q);
|
||||
}
|
||||
uint32_t q = m >> 13;
|
||||
const uint32_t lo = m & 0x1fffu;
|
||||
uint32_t he = (uint32_t)(e + 15);
|
||||
if (lo > 0x1000u || (lo == 0x1000u && (q & 1u))) ++q;
|
||||
if (q == 0x400u) { q = 0; ++he; } /* rounding carried into the exp */
|
||||
if (he >= 0x1fu) return (uint16_t)(s | 0x7c00u);
|
||||
return (uint16_t)(s | (he << 10) | q);
|
||||
}
|
||||
|
||||
/* Two f32 as one dword of two f16, `lo` in the low half.
|
||||
*
|
||||
* v_cvt_pkrtz_f16_f32 rounds toward zero, which is not RTNE, so this is only ever called with
|
||||
* values f16 represents exactly: a bf16 widened (seven mantissa bits into ten) or an E4M3 code
|
||||
* (three into three). For those the two spellings give the same bits and the instruction is free. */
|
||||
R3D_HD uint32_t f16x2_pack(float lo, float hi) {
|
||||
#if defined(__HIP_DEVICE_COMPILE__)
|
||||
/* The builtin answers as a pair of __fp16; the bits are the dword the dot2 reads. */
|
||||
return __builtin_bit_cast(uint32_t, __builtin_amdgcn_cvt_pkrtz(lo, hi));
|
||||
#else
|
||||
return (uint32_t)f32_to_f16(lo) | ((uint32_t)f32_to_f16(hi) << 16);
|
||||
#endif
|
||||
}
|
||||
|
||||
/* A dword of two bf16 as a dword of two f16.
|
||||
*
|
||||
* Exact over f16's normal range, and that is what makes the dot2 path sound: a bf16 has seven
|
||||
* mantissa bits and an f16 ten, so within [2^-14, 65504] a widening costs no rounding and a dot
|
||||
* product over widened bf16 accumulates the sums libref forms over its bf16 operands.
|
||||
*
|
||||
* Outside it the widening is not exact, and the two edges behave differently. Above 65504 a
|
||||
* magnitude becomes an infinity (the packing instruction saturates, which is the kinder of the two
|
||||
* answers). Below 2^-14 the operand is an f16 subnormal, whose grid is a power of two coarser than
|
||||
* bf16's at the same magnitude, so a widening truncates toward zero -- and below 2^-24 it flushes.
|
||||
* The truncation is what the packing instruction does, `v_cvt_pkrtz_f16_f32` rounding toward zero.
|
||||
*
|
||||
* The low edge costs a served model nothing: an activation below 2^-14 times a weight of a
|
||||
* hundredth is 1e-18, against an accumulator of order one, so it is not a term the sum can see;
|
||||
* and a scale-reduced operand is scaled back up before it is used, which is why the quantised rows
|
||||
* put the scale on the block, not the element. What would be visible is a weight stream whose
|
||||
* magnitudes live below 2^-14, and no checkpoint's do. The rows whose band can reach 65504 say so
|
||||
* in their `shape` text. */
|
||||
R3D_HD uint32_t bf16x2_to_f16x2(uint32_t w) {
|
||||
return f16x2_pack(bf16w_lo(w), bf16w_hi(w));
|
||||
}
|
||||
|
||||
/* ================================================================== fp8 e4m3 ("e4m3fn")
|
||||
*
|
||||
* 1-4-3, bias 7, no infinity, S1111111 the only NaN, 448 the largest finite. The KV-cache and
|
||||
* block-scaled weight format, so the attention oracle and every fp8 row depend on its rounding.
|
||||
*
|
||||
* RDNA3 has no instruction for it: v_cvt_pk_fp8_f32 and v_cvt_pk_f32_fp8 need the fp8 feature,
|
||||
* which RDNA3 does not have. The builtins are *declared* for gfx11 -- so `__has_builtin` is true
|
||||
* here, which is the trap a `__has_builtin` guard falls into, and libr4d's guards are exactly that
|
||||
* -- and rejected at instruction selection. Both directions are bit maths, about eleven VALU an
|
||||
* encode and six a decode. */
|
||||
R3D_HD float e4m3_to_f32(uint8_t b) {
|
||||
const uint32_t s = (uint32_t)(b >> 7) << 31;
|
||||
const uint32_t e = (uint32_t)(b >> 3) & 0xfu;
|
||||
uint32_t m = (uint32_t)b & 0x7u;
|
||||
uint32_t u;
|
||||
if (e == 0u) {
|
||||
if (m == 0u) {
|
||||
u = s;
|
||||
} else {
|
||||
int sh = 0; /* subnormal: 2^-9 * m/8 */
|
||||
while (!(m & 0x8u)) { m <<= 1; ++sh; }
|
||||
m &= 0x7u;
|
||||
u = s | ((uint32_t)(127 - 6 - sh) << 23) | (m << 20);
|
||||
}
|
||||
} else if (e == 0xfu && m == 0x7u) {
|
||||
u = s | 0x7fc00000u; /* the single NaN encoding */
|
||||
} else {
|
||||
u = s | ((e - 7u + 127u) << 23) | (m << 20);
|
||||
}
|
||||
return float_of(u);
|
||||
}
|
||||
|
||||
/* Saturates at 448 rather than overflowing: a NaN from one large activation spreads through the
|
||||
* whole row, and every fp8 cast in this project clamps for that reason. The clamp is inside the
|
||||
* codec here because there is no instruction to clamp in front of. */
|
||||
R3D_HD uint8_t f32_to_e4m3(float f) {
|
||||
const uint32_t u = bits_of(f);
|
||||
const uint8_t s = (uint8_t)((u >> 24) & 0x80u);
|
||||
const uint32_t a = u & 0x7fffffffu;
|
||||
if (a > 0x7f800000u) return (uint8_t)(s | 0x7fu); /* nan */
|
||||
if (a >= 0x43e00000u) return (uint8_t)(s | 0x7eu); /* >= 448: the largest finite */
|
||||
const int e = (int)(a >> 23) - 127;
|
||||
uint32_t m = a & 0x7fffffu;
|
||||
/* The smallest subnormal is 2^-9, so everything below half of it (exponent -11 and below)
|
||||
* rounds to zero. Exponent -10 is [2^-10, 2^-9): its tie point 2^-10 rounds to the even zero
|
||||
* and the rest up to 2^-9, which the subnormal branch does with a 24-bit shift. */
|
||||
if (e < -10) return s;
|
||||
if (e < -6) { /* subnormal fp8 */
|
||||
const int sh = -6 - e + 20;
|
||||
m |= 0x800000u;
|
||||
const uint32_t lo = m & ((1u << sh) - 1u);
|
||||
uint32_t q = m >> sh;
|
||||
const uint32_t half = 1u << (sh - 1);
|
||||
if (lo > half || (lo == half && (q & 1u))) ++q;
|
||||
return (uint8_t)(s | q);
|
||||
}
|
||||
uint32_t q = m >> 20;
|
||||
const uint32_t lo = m & 0xfffffu;
|
||||
int ee = e + 7;
|
||||
if (lo > 0x80000u || (lo == 0x80000u && (q & 1u))) ++q;
|
||||
if (q == 0x8u) { q = 0; ++ee; }
|
||||
if (ee > 15 || (ee == 15 && q >= 7u)) return (uint8_t)(s | 0x7eu);
|
||||
return (uint8_t)(s | ((uint32_t)ee << 3) | q);
|
||||
}
|
||||
|
||||
/* Two codes in one dword, the low element in the low byte: the store a wave's lane does. */
|
||||
R3D_HD uint32_t e4m3x2_pack(float lo, float hi) {
|
||||
return (uint32_t)f32_to_e4m3(lo) | ((uint32_t)f32_to_e4m3(hi) << 8);
|
||||
}
|
||||
|
||||
/* A dword of two E4M3 codes as a dword of two f16.
|
||||
*
|
||||
* Exact -- e4m3 has four exponent and three mantissa bits, f16 five and ten -- and this is the fp8
|
||||
* matrix path: a code becomes the f16 the checkpoint means, dot2 multiplies it, and the block
|
||||
* scale is applied once per block. RDNA3 has no fp8 hardware, so the decode is VALU, and it is
|
||||
* paid where the weight bytes are being read anyway. */
|
||||
R3D_HD uint32_t e4m3x2_to_f16x2(uint32_t w) {
|
||||
return f16x2_pack(e4m3_to_f32((uint8_t)(w & 0xffu)), e4m3_to_f32((uint8_t)(w >> 8)));
|
||||
}
|
||||
|
||||
/* ================================================================== int8
|
||||
*
|
||||
* The symmetric int8 twin: amax/127, RTNE, saturating. f16 holds every int8 exactly, so widening
|
||||
* into a dot product is exact and the scale is the only float in the path. */
|
||||
R3D_HD int8_t f32_to_i8_rtne(float f) {
|
||||
if (!(f == f)) return 0;
|
||||
/* Round to nearest, ties to even, in integer arithmetic. A tie at the top of the range would
|
||||
* round to a code that does not exist (+128), so the clamp is applied after the rounding, not
|
||||
* as an early return: 127.5 goes to the even 128 and then clamps to 127, which is what
|
||||
* rad_round_even_sat gives. */
|
||||
const float fl = __builtin_floorf(f);
|
||||
const float frac = f - fl;
|
||||
int32_t q = (int32_t)fl;
|
||||
if (frac > 0.5f) ++q;
|
||||
else if (frac == 0.5f && (q & 1)) ++q;
|
||||
if (q > 127) q = 127;
|
||||
if (q < -128) q = -128;
|
||||
return (int8_t)q;
|
||||
}
|
||||
|
||||
R3D_HD uint32_t i8x2_pack(float lo, float hi) {
|
||||
return (uint32_t)(uint8_t)f32_to_i8_rtne(lo) | ((uint32_t)(uint8_t)f32_to_i8_rtne(hi) << 8);
|
||||
}
|
||||
|
||||
R3D_HD uint32_t i8x2_to_f16x2(uint32_t w) {
|
||||
return f16x2_pack((float)(int8_t)(uint8_t)(w & 0xffu), (float)(int8_t)(uint8_t)(w >> 8));
|
||||
}
|
||||
|
||||
/* ================================================================== the dot product
|
||||
*
|
||||
* Two f16 products into an f32 accumulator, one instruction: v_dot2acc_f32_f16, which
|
||||
* __builtin_amdgcn_fdot2 lowers to on every gfx11 target (checked by reading the emitted asm on
|
||||
* gfx1100, gfx1102 and gfx1151). RDNA3 pairs it as v_dual_dot2acc_f32_f16 where the scheduler can,
|
||||
* which is how libr3d's inner loops reach the matrix unit's absence without noticing.
|
||||
*
|
||||
* The selector is FALSE, always. RDNA3 has no bf16 dot2, and this compiler accepts the bf16
|
||||
* selector and emits the f16 instruction anyway: a bf16 pair passed with sel=true is read as two
|
||||
* f16s and the products are nonsense, silently, on every gfx11 target. bf16 operands are widened
|
||||
* with bf16x2_to_f16x2, which is exact.
|
||||
*
|
||||
* The two products go into `acc` in the order written, and a kernel that walks k ascending
|
||||
* reproduces libref's summand-for-summand: the reference loop is `s += a[k]*b[k]` with
|
||||
* -ffp-contract=off. The match is not bit-exact and cannot be: `v_dot2acc_f32_f16` folds the two
|
||||
* products and the accumulator with guard bits and rounds once, where the reference rounds each
|
||||
* product and each sum. The difference is under an f32 ulp a pair, a random walk of about
|
||||
* sqrt(K/2) ulps over a K-long dot, which is a thousandth of the bf16 the store narrows to -- so it
|
||||
* sits inside what `rad-kbench` measures, exactly as libr4d's WMMA accumulation does. What is
|
||||
* required, and what every loop here keeps, is that the *order* of the summands be the reference's:
|
||||
* k ascending, one accumulator per output element, no reassociation across lanes.
|
||||
*
|
||||
* The host path below is the same arithmetic with each product rounded first, which is what a test
|
||||
* needs it to be. It is not the hardware's rounding. */
|
||||
R3D_HD float dot2_f16x2(uint32_t a, uint32_t b, float acc) {
|
||||
#if defined(__HIP_DEVICE_COMPILE__)
|
||||
typedef __fp16 v2h __attribute__((ext_vector_type(2)));
|
||||
return __builtin_amdgcn_fdot2(__builtin_bit_cast(v2h, a), __builtin_bit_cast(v2h, b), acc,
|
||||
false);
|
||||
#else
|
||||
const uint32_t alo = a & 0xffffu, ahi = a >> 16;
|
||||
const uint32_t blo = b & 0xffffu, bhi = b >> 16;
|
||||
return acc + f16_to_f32((uint16_t)alo) * f16_to_f32((uint16_t)blo)
|
||||
+ f16_to_f32((uint16_t)ahi) * f16_to_f32((uint16_t)bhi);
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Four f16 products into one accumulator: the step every libr3d matmul runs. The two dot2s are a
|
||||
* dependency chain of two; a kernel keeps four of these chains in flight. */
|
||||
R3D_HD float dot4_f16x4(uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1, float acc) {
|
||||
return dot2_f16x2(a1, b1, dot2_f16x2(a0, b0, acc));
|
||||
}
|
||||
|
||||
#endif /* R3D_CODECS_H */
|
||||
@@ -0,0 +1,256 @@
|
||||
/* r3d_common.h -- the RDNA3 seams a kernel needs: the wave's lane maths, the loads, the block
|
||||
* reduce, the occupancy and LDS conventions.
|
||||
*
|
||||
* What RDNA3 gives, measured on the ROCm this tree builds against (AMD clang 24; `__has_builtin`
|
||||
* off --offload-device-only, and llvm-mc -show-encoding per target). The codecs are in r3d_codecs.h;
|
||||
* this header is what is left.
|
||||
*
|
||||
* v_dot2acc_f32_f16 yes, every gfx11 target, from __builtin_amdgcn_fdot2, and RDNA3 pairs
|
||||
* it as v_dual_dot2acc_f32_f16 where the scheduler can. The matrix work.
|
||||
* v_dot2 with bf16 no, and the builtin's bf16 selector is accepted and ignored -- the f16
|
||||
* instruction is emitted -- so bf16 is widened, never asserted.
|
||||
* WMMA the mnemonic is unreachable -- every v_wmma_* is rejected by the
|
||||
* assembler on gfx1100, gfx1102, gfx1151 and gfx1201 alike, and inline
|
||||
* asm dies in amdgcn-link -- but the builtin is not:
|
||||
* __builtin_amdgcn_wmma_f32_16x16x16_f16_w32 compiles for the three gfx11
|
||||
* targets and emits a real tile instruction. Measured here against dot2 at
|
||||
* four occupancies, 1.99 against 1.97 TFLOP/s: RDNA3's AI accelerator is a
|
||||
* 2x f16-rate feature and a paired dot2 is already at that rate, so the
|
||||
* tile buys a fragment layout and a block-alignment requirement and no
|
||||
* throughput. No fragment layouts here, so no repacked weights, so no
|
||||
* layout hook: a dot2 GEMM reads a weight in the order it is stored.
|
||||
* fp8 convert no (needs the fp8 feature); the builtins are declared and die at
|
||||
* instruction selection, which is why the codecs are software.
|
||||
* v_cvt_pkrtz_f16_f32 yes. Used only where it is exact.
|
||||
* v_cvt_pk_bf16_f32 no on gfx1100/1102/1151 in this build, so bf16 packs are software.
|
||||
* DPP16, v_permlanex16 yes, RDNA1 onward. The lane maths below is libr4d's, unchanged: the
|
||||
* encodings are the same silicon, and they were verified on hardware.
|
||||
* ballot_w32, readlane,
|
||||
* readfirstlane, ds_bpermute,
|
||||
* v_perm_b32, exp2f, rcpf,
|
||||
* s_barrier, fence,
|
||||
* sched_group_barrier yes.
|
||||
* transposed loads no: neither global_load_tr_b128 (RDNA4) nor ds_read_b64_tr_b16 (dropped
|
||||
* by RDNA4, kept here as a fact about gfx11 -- this ROCm's assembler
|
||||
* rejects it too). A transpose is done in registers.
|
||||
*
|
||||
* Wave32 is gfx11's default and every kernel here is written for it; the guard below fires if a
|
||||
* build asks for wave64, because that computes garbage rather than running slower.
|
||||
*
|
||||
* The register file is the one number that is NOT the same as RDNA4's: a gfx11 SIMD has 1024 VGPRs
|
||||
* for a wave32, allocated in groups of 8, against gfx1201's 1536. R3D_WAVES is stated per kernel,
|
||||
* and a kernel's budget is computed against 1024.
|
||||
*/
|
||||
#ifndef R3D_COMMON_H
|
||||
#define R3D_COMMON_H
|
||||
|
||||
#include "r3d_codecs.h"
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
|
||||
#if defined(__HIP_DEVICE_COMPILE__) && defined(__AMDGCN_WAVEFRONT_SIZE)
|
||||
#if __AMDGCN_WAVEFRONT_SIZE != 32
|
||||
#error "libr3d kernels are written for wave32, gfx11's default; a wave64 build computes garbage"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
enum : int { kWave = 32 };
|
||||
|
||||
/* A 16-byte staging register as a native vector. HIP's uint4 is a class template wrapping a union,
|
||||
* and an array of them carried across a loop is kept in scratch by LLVM 22 and 24; an
|
||||
* ext_vector_type array is promoted to registers. Loaded and stored whole only. */
|
||||
typedef unsigned int r3d_u32x4 __attribute__((ext_vector_type(4)));
|
||||
typedef unsigned int r3d_u32x2 __attribute__((ext_vector_type(2)));
|
||||
|
||||
/* ================================================================== the occupancy a kernel is
|
||||
* built for
|
||||
*
|
||||
* Fixes the waves per SIMD the compiler schedules for. Left unstated, the scheduler picks the
|
||||
* target itself and the choice moves between compiler releases. gfx11's budget is 1024 VGPRs a
|
||||
* SIMD at wave32, in granules of 8: a kernel asking for 5 waves has 204 registers to spend. */
|
||||
#define R3D_WAVES(n) __attribute__((amdgpu_waves_per_eu((n), (n))))
|
||||
|
||||
/* ================================================================== exp2
|
||||
*
|
||||
* The hardware transcendental. libr4d's rule applies: exp2f, powf and sincosf are the accurate
|
||||
* forms, not the __ approximations -- rope positions reach 262144, past __sincosf's argument
|
||||
* reduction, and libref uses libm. exp2f itself is the one place the hardware op is exactly what
|
||||
* the reference computes, because both sides round the same result once. */
|
||||
__device__ __forceinline__ float ex2(float x) {
|
||||
return __builtin_amdgcn_exp2f(x);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float rcp(float x) { return __builtin_amdgcn_rcpf(x); }
|
||||
|
||||
/* ================================================================== one element, one register
|
||||
*
|
||||
* A 16-bit element of global memory, zero-extended into a whole register (global_load_u16). Read as
|
||||
* `uint16_t` it lands in a register half (global_load_d16_b16) whose other half the waitcnt pass
|
||||
* then waits for; through a generic pointer it is also a flat load. The pointer must address global
|
||||
* memory, which every caller's operand is.
|
||||
*
|
||||
* libr4d notes that LLVM 24 gives gfx12 real 16-bit registers and the packability that follows;
|
||||
* gfx11 does not have them, so keeping bf16 in whole registers from load to store is the plain
|
||||
* reading as well as the portable one. */
|
||||
typedef const uint16_t __attribute__((address_space(1))) *r3d_gu16;
|
||||
__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r3d_gu16)p; }
|
||||
__device__ __forceinline__ uint32_t ldg_u32(const uint32_t* p) { return *(const __attribute__((address_space(1))) uint32_t*)p; }
|
||||
__device__ __forceinline__ float ldg_f32(const float* p) {
|
||||
return *(const __attribute__((address_space(1))) float*)p;
|
||||
}
|
||||
|
||||
/* ================================================================== lane maths
|
||||
*
|
||||
* A wave is 32 lanes, two rows of sixteen. Reductions are XOR butterflies, in the order a
|
||||
* __shfl_xor loop runs in, so the result is bit-identical to that loop -- which is what libref
|
||||
* sums, since the reference sums a row in ascending index order and a wave of lanes maps to
|
||||
* consecutive elements.
|
||||
*
|
||||
* `__shfl_xor` lowers to ds_bpermute_b32 plus s_wait_dscnt, an LDS round trip that dominates a
|
||||
* dependency chain. DPP16's ROW_XMASK (control 0x160 | N) makes the partner read a modifier on the
|
||||
* consuming VALU op, and N = 16 crosses the two rows of a wave32 with v_permlanex16, still one VALU
|
||||
* op. Row and bank masks are all-ones because every lane participates; bound_ctrl is moot because
|
||||
* every lane has a partner. These are libr4d's encodings, verified on hardware. */
|
||||
template <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");
|
||||
if constexpr (N < 16)
|
||||
return (uint32_t)__builtin_amdgcn_update_dpp(0, (int)v, 0x160 | N, 0xf, 0xf, true);
|
||||
else
|
||||
return (uint32_t)__builtin_amdgcn_permlanex16((int)v, (int)v, 0x76543210u, 0xFEDCBA98u,
|
||||
false, false);
|
||||
}
|
||||
|
||||
template <int N>
|
||||
__device__ __forceinline__ float r3d_xor_lane(float v) {
|
||||
return __uint_as_float(r3d_xor_lane_u32<N>(__float_as_uint(v)));
|
||||
}
|
||||
|
||||
/* A 64-bit value's partner: the halves exchanged separately, as a 64-bit shuffle does. */
|
||||
template <int N>
|
||||
__device__ __forceinline__ unsigned long long r3d_xor_lane_u64(unsigned long long v) {
|
||||
const uint32_t lo = r3d_xor_lane_u32<N>((uint32_t)v);
|
||||
const uint32_t hi = r3d_xor_lane_u32<N>((uint32_t)(v >> 32));
|
||||
return ((unsigned long long)hi << 32) | lo;
|
||||
}
|
||||
|
||||
/* v_permlanex16 swaps only with identity selectors (each 4-bit field names the source lane in the
|
||||
* other half; sel0 covers lanes 0-7, sel1 lanes 8-15); zero selectors silently broadcast lane 0. */
|
||||
__device__ __forceinline__ float swap16(float x) { return r3d_xor_lane<16>(x); }
|
||||
|
||||
/* v + the partner's v, the partner read by DPP so the add carries it. */
|
||||
template <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,
|
||||
true));
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float wave_sum(float v) {
|
||||
v += swap16(v); /* xor 16 -- crosses the two rows of sixteen */
|
||||
v = r3d_dpp_xor_add<0x168>(v); /* xor 8 -- row_xmask from here down */
|
||||
v = r3d_dpp_xor_add<0x164>(v); /* xor 4 */
|
||||
v = r3d_dpp_xor_add<0x162>(v); /* xor 2 */
|
||||
v = r3d_dpp_xor_add<0x161>(v); /* xor 1 */
|
||||
return v;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float wave_max(float v) {
|
||||
v = fmaxf(v, r3d_xor_lane<16>(v));
|
||||
v = fmaxf(v, r3d_xor_lane<8>(v));
|
||||
v = fmaxf(v, r3d_xor_lane<4>(v));
|
||||
v = fmaxf(v, r3d_xor_lane<2>(v));
|
||||
v = fmaxf(v, r3d_xor_lane<1>(v));
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The same butterflies over a group of W lanes (a power of two up to the wave), in the order
|
||||
* `for (o = W/2; o; o >>= 1) v = op(v, __shfl_xor(v, o))` runs them, so bit-identical to it. A row
|
||||
* of sixteen lanes -- the sixteen columns a lane owns in a bf16 pair layout -- uses W = 16. */
|
||||
template <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");
|
||||
if constexpr (W >= 32) v += r3d_xor_lane<16>(v);
|
||||
if constexpr (W >= 16) v += r3d_xor_lane<8>(v);
|
||||
if constexpr (W >= 8) v += r3d_xor_lane<4>(v);
|
||||
if constexpr (W >= 4) v += r3d_xor_lane<2>(v);
|
||||
if constexpr (W >= 2) v += r3d_xor_lane<1>(v);
|
||||
return v;
|
||||
}
|
||||
|
||||
template <int W>
|
||||
__device__ __forceinline__ float r3d_xor_max(float v) {
|
||||
static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave");
|
||||
if constexpr (W >= 32) v = fmaxf(v, r3d_xor_lane<16>(v));
|
||||
if constexpr (W >= 16) v = fmaxf(v, r3d_xor_lane<8>(v));
|
||||
if constexpr (W >= 8) v = fmaxf(v, r3d_xor_lane<4>(v));
|
||||
if constexpr (W >= 4) v = fmaxf(v, r3d_xor_lane<2>(v));
|
||||
if constexpr (W >= 2) v = fmaxf(v, r3d_xor_lane<1>(v));
|
||||
return v;
|
||||
}
|
||||
|
||||
/* A wave's inclusive prefix sum in registers: row_shr 1, 2, 4 and 8 within each row of sixteen,
|
||||
* then the other row's total from one readlane. Lane L ends with the sum over lanes 0..L. Replaces
|
||||
* an LDS step-doubling scan, which costs two barriers a round. Integer, so combine order is free.
|
||||
* Every lane must be active. */
|
||||
__device__ __forceinline__ uint32_t wave_prefix_u32(uint32_t x, int lane) {
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x111, 0xF, 0xF, true); /* row_shr:1 */
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x112, 0xF, 0xF, true); /* row_shr:2 */
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x114, 0xF, 0xF, true); /* row_shr:4 */
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x118, 0xF, 0xF, true); /* row_shr:8 */
|
||||
const uint32_t lo = (uint32_t)__builtin_amdgcn_readlane((int)x, 15);
|
||||
return lane >= 16 ? x + lo : x;
|
||||
}
|
||||
|
||||
/* ================================================================== a block's sum
|
||||
*
|
||||
* Wave sum, one LDS round trip, then every thread adds the wave partials in wave order. The order
|
||||
* is the contract: libref sums a row in ascending index order, the waves cover consecutive
|
||||
* elements, and adding the partials in wave order is the same bracketing at any thread count.
|
||||
* `lds` holds NWAVES floats. */
|
||||
template <int NTHREADS>
|
||||
__device__ __forceinline__ float block_sum(float v, float* lds) {
|
||||
constexpr int NWAVES = NTHREADS / kWave;
|
||||
const uint32_t lane = threadIdx.x & (kWave - 1);
|
||||
const uint32_t w = threadIdx.x / kWave;
|
||||
v = wave_sum(v);
|
||||
if (lane == 0) lds[w] = v;
|
||||
__syncthreads();
|
||||
if constexpr (NWAVES == 1) return lds[0];
|
||||
float t = lds[0];
|
||||
#pragma unroll
|
||||
for (int i = 1; i < NWAVES; ++i) t += lds[i];
|
||||
return t;
|
||||
}
|
||||
|
||||
/* ================================================================== scheduling
|
||||
*
|
||||
* LLVM single-buffers LDS and drains before every dependent read unless told otherwise; on gfx11
|
||||
* the matrix unit is absent so there is nothing to overlap a load with, and the barrier the
|
||||
* kernels need is the plain one. */
|
||||
__device__ __forceinline__ void sched_barrier() { __builtin_amdgcn_sched_barrier(0); }
|
||||
__device__ __forceinline__ void group_barrier() { __syncthreads(); }
|
||||
|
||||
/* ================================================================== the geometry constants
|
||||
*
|
||||
* A gfx11 GPU's wave slots: a CU has 4 SIMDs, a SIMD holds 16 wave32s, so 64 slots a CU. HIP's
|
||||
* multiProcessorCount reports CUs on gfx11 (it reports WGPs on gfx12, which is where libr4d's 2048
|
||||
* comes from), and a launch whose grid passes 64 * multiProcessorCount waves has more work than
|
||||
* slots: the tail waves start after another wave retires. A row-per-block kernel with one wave a
|
||||
* block is exactly that cliff, and its row count is where the cliff is.
|
||||
*
|
||||
* A launcher's question, so a host function: this HIP declares no device-side hipGetDevice or
|
||||
* hipDeviceGetAttribute, and a __device__ body does not compile at all. */
|
||||
static inline int wave_slot_count() {
|
||||
int dev = 0, cu = 0;
|
||||
(void)hipGetDevice(&dev);
|
||||
(void)hipDeviceGetAttribute(&cu, hipDeviceAttributeMultiprocessorCount, dev);
|
||||
return 64 * cu;
|
||||
}
|
||||
|
||||
/* The LDS a workgroup gets is 64 KiB, the same figure RDNA4 gives, and no kernel in libr3d needs
|
||||
* more. There is no hipFuncSetAttribute opt-in: 64 KiB of dynamic shared memory is available as
|
||||
* soon as it is asked for. */
|
||||
enum : int { kLdsCap = 64 * 1024 };
|
||||
|
||||
#endif /* R3D_COMMON_H */
|
||||
@@ -0,0 +1,309 @@
|
||||
/* r3d_dflash_f32.hip -- DFlash2's candidate walk, `dflash_select`, on the card.
|
||||
*
|
||||
* A block-diffusion drafter proposes every position of a block in one backbone pass, so position
|
||||
* l+1 is not conditioned on what the drafter chose at l. This op restores that dependence: it walks
|
||||
* the `steps` positions in order and, at each, picks the candidate that maximises
|
||||
*
|
||||
* score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * hp[l][r] * succ[cand[l, c]][r]
|
||||
*
|
||||
* where pid(0) is the anchor -- the token the target just committed, read at
|
||||
* `anchor[m * anchor_stride]` -- and pid(l) is the walk's own previous pick, `cand[l-1, chosen]`.
|
||||
* `hp` absent is a plane of ones, which drops the trilinear form to a low-rank bigram (DSpark's
|
||||
* Markov head). libref's `ref_dflash_select` is the law, and this file transcribes its arithmetic
|
||||
* and its order.
|
||||
*
|
||||
* ============================== why it is a kernel and not a GEMM ==============================
|
||||
*
|
||||
* The walk is serial in l: the predecessor of step l is not known until step l-1 has been decided,
|
||||
* so the [steps, K, K] edge tensor cannot be scored in advance -- scoring it computes K times the
|
||||
* edges that are ever read. What is parallel is the sequences (M of them) and, inside a step, the K
|
||||
* candidates. So a block takes `256 / top_k` sequences and gives each lane one (sequence,
|
||||
* candidate) pair: the lane runs the rank sum for its own edge, in the reference's order, and one
|
||||
* lane per sequence scans the K scores and takes the pick. The loop over `steps` stays serial, with
|
||||
* the two LDS round trips per step (the scores out, the pick back) that the dependence requires.
|
||||
*
|
||||
* The rank sum is the whole cost: at the band (steps=7, top_k=16, rank=256, M=256) a walk is
|
||||
* 7 * 16 * 256 = 28672 fused terms, and the bytes it touches are the K successor rows a step reads,
|
||||
* 16 * 512 B of bf16, so the op is a gather over `succ` [n_vocab, rank] -- 66.8 MiB of codebook at
|
||||
* the band, of which the walk reads M * steps * K = 28672 rows, about 14.7 MiB, plus one
|
||||
* predecessor row a step. There is no arithmetic to hide that behind, which is why the sum is a
|
||||
* plain ascending chain and not a tree: a tree buys nothing here and costs the agreement.
|
||||
*
|
||||
* ============================== agreement, and where this file declines ==============================
|
||||
*
|
||||
* Bit-exact by construction, not by tolerance:
|
||||
*
|
||||
* - the rank sum is `sc = unary; for (i = 0; i < rank; ++i) sc += ax[i] * succ[i];` -- ascending
|
||||
* in r, one accumulator, no reduction, no tree, with `-ffp-contract=off` so no FMA fusion
|
||||
* changes the rounding of a term;
|
||||
* - `ax[i] = pred[pid][i] * hp[l][i]` is rounded to f32 before it meets `succ`, because the
|
||||
* reference writes it into a float array first (and with `hp` absent it is `pred * 1.0f`, which
|
||||
* is the same value);
|
||||
* - the argmax is a strict `>` over c ascending, so the earliest candidate wins a tie and a NaN
|
||||
* never displaces the incumbent -- the reference's loop, statement for statement;
|
||||
* - a predecessor outside the vocabulary contributes zero, and a candidate outside it is scored
|
||||
* by `unary` alone: both are the reference's tests (`pid >= 0 && pid < nv`, `tok >= 0 &&
|
||||
* tok < nv`), and both are why padding rows -- a shard's unused rows, a block shorter than
|
||||
* `steps` -- are legal inputs;
|
||||
* - the pick of step l is written to `tokens[m, l]` and becomes pid(l+1) unchanged, including
|
||||
* when it is out of range for the codebooks.
|
||||
*
|
||||
* Declines, all of them the shim's, none reachable from a row that carries the constraints its row
|
||||
* states: a codebook (`pred`, `succ`, `hp`) that is not bf16, because this is the bf16
|
||||
* instantiation -- the band's `dtype` is the codebooks' width and a row asks for bf16 (RAD_E_DTYPE);
|
||||
* `unary` that is not f32, `cand`/`anchor`/`tokens` that are not i32, exactly as the schema's
|
||||
* operand list types them (RAD_E_DTYPE); a codebook whose rows are not contiguous -- the gather is
|
||||
* `token * rank + r` and a row stride inside the row is not that (RAD_E_STRIDE); `top_k` above 256,
|
||||
* which is one lane a candidate and no more candidates than lanes (RAD_E_UNSUPPORTED); and a `cand`
|
||||
* plane that describes more sequences than the band's `M`, which is `band_rows` refusing and is
|
||||
* RAD_E_SHAPE, not a truncation.
|
||||
*/
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_args.h"
|
||||
#include "r3d_codecs.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_launch.h"
|
||||
|
||||
#include <rad_types.h>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kThr = 256; /* 8 waves: the block's (sequence, candidate) lanes */
|
||||
constexpr uint32_t kKMax = kThr; /* one lane a candidate, so top_k <= 256 */
|
||||
|
||||
/* Whole-register loads of the planes the walk gathers through. bf16 is a 16-bit load and the
|
||||
* library's codec, which is the same decode libref's `ldt` performs. */
|
||||
__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) {
|
||||
return (int32_t)ldg_u32((const uint32_t*)p);
|
||||
}
|
||||
__device__ __forceinline__ float ldg_f32(const float* p) { return *(const float*)p; }
|
||||
__device__ __forceinline__ uint16_t ldg_u16(const uint16_t* p) { return *(const uint16_t*)p; }
|
||||
|
||||
/* ------------------------------------------------------------------ the walk
|
||||
|
||||
* `per` sequences per block, `K` candidates per sequence, so lane (s, c) owns the edge
|
||||
* (sequence s, candidate c) of the step in hand. `hp` may be null: then the `hp` factor is 1.0f,
|
||||
* exactly as the reference's `(hp ? ldt(hp, ...) : 1.0f)` writes it. */
|
||||
__global__ __launch_bounds__(kThr) void dflash_select_kernel(
|
||||
const int32_t* __restrict__ cand, const float* __restrict__ un,
|
||||
const uint16_t* __restrict__ hp, const int32_t* __restrict__ anc,
|
||||
const uint16_t* __restrict__ pred, const uint16_t* __restrict__ succ,
|
||||
int32_t* __restrict__ out, uint32_t M, uint32_t steps, uint32_t K, uint32_t R, uint32_t nv,
|
||||
uint32_t astr, long long cand_ld, long long un_ld, long long hp_ld, long long pred_ld,
|
||||
long long succ_ld, long long tok_ld, uint32_t per) {
|
||||
|
||||
__shared__ int32_t s_pid[kThr]; /* the walk's predecessor, one per sequence */
|
||||
__shared__ float s_sc[kThr]; /* this step's K scores, one per lane */
|
||||
|
||||
const uint32_t s = threadIdx.x / K; /* the sequence this lane walks for */
|
||||
const uint32_t c = threadIdx.x - s * K; /* the candidate this lane scores */
|
||||
const uint32_t seq0 = blockIdx.x * per + s;
|
||||
/* A block of 256 lanes holds ceil(256 / K) sequences and the last group can be partial. A lane
|
||||
* with no sequence replays the last real one: it reaches every __syncthreads() and its stores
|
||||
* are suppressed, and the loads it performs are in range because the sequence it replays is. */
|
||||
const uint32_t seq = seq0 < M ? seq0 : M - 1;
|
||||
const bool mine = seq0 < M;
|
||||
|
||||
/* pid(0): the anchor, at `m * anchor_stride` in a flat plane. The reference reads it through
|
||||
* `ld_int`, so a negative id is a legal "no predecessor" and not an error. */
|
||||
int32_t pid = ldg_i32(anc + (size_t)seq * (size_t)astr);
|
||||
const bool has_hp = (hp != nullptr);
|
||||
|
||||
for (uint32_t l = 0; l < steps; ++l) {
|
||||
const uint32_t r = seq * steps + l; /* cand/unary/hp are one row per (m, l) */
|
||||
const size_t cb = (size_t)r * (size_t)cand_ld;
|
||||
const int32_t tok = ldg_i32(cand + cb + c);
|
||||
float sc = ldg_f32(un + (size_t)r * (size_t)un_ld + c);
|
||||
|
||||
/* A predecessor outside the vocabulary contributes nothing; a candidate outside it is
|
||||
* scored by `unary` alone. Both tests are the reference's, and both are why a shard's
|
||||
* padding rows and a block shorter than `steps` are legal inputs. */
|
||||
const bool have_p = pid >= 0 && (uint32_t)pid < nv;
|
||||
const bool have_s = tok >= 0 && (uint32_t)tok < nv;
|
||||
if (have_s) {
|
||||
const uint16_t* pp = pred + (size_t)(have_p ? pid : 0) * (size_t)pred_ld;
|
||||
const uint16_t* sp = succ + (size_t)tok * (size_t)succ_ld;
|
||||
const uint16_t* hpb = hp + (size_t)r * (size_t)hp_ld;
|
||||
for (uint32_t i = 0; i < R; ++i) {
|
||||
/* ax[i], rounded to f32 where the reference writes it into its float array, and
|
||||
* then the ascending chain. 1.0f for a missing hp is the reference's own factor. */
|
||||
const float ax = have_p
|
||||
? bf16_to_f32(ldg_u16(pp + i)) * (has_hp ? bf16_to_f32(ldg_u16(hpb + i)) : 1.0f)
|
||||
: 0.0f;
|
||||
sc += ax * bf16_to_f32(ldg_u16(sp + i));
|
||||
}
|
||||
}
|
||||
s_sc[threadIdx.x] = sc; /* == s_sc[s * K + c] */
|
||||
__syncthreads();
|
||||
|
||||
if (c == 0) {
|
||||
/* The reference's argmax: strict `>`, c ascending, so the earliest candidate wins a
|
||||
* tie and a NaN never takes the lead from a number. */
|
||||
uint32_t best_c = 0;
|
||||
float best_s = -INFINITY;
|
||||
for (uint32_t j = 0; j < K; ++j) {
|
||||
const float v = s_sc[s * K + j];
|
||||
if (v > best_s) { best_s = v; best_c = j; }
|
||||
}
|
||||
const int32_t pick = ldg_i32(cand + cb + best_c);
|
||||
if (mine) out[(size_t)seq * (size_t)tok_ld + l] = pick;
|
||||
s_pid[s] = pick; /* pid(l+1), out-of-range included */
|
||||
}
|
||||
__syncthreads();
|
||||
pid = s_pid[s];
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ shim helpers */
|
||||
|
||||
/* The plane's row pitch, from the plane: `rows` is its row count and `ld` the pitch a row's
|
||||
* elements start at, K apart. A rank-1 plane is a run of rows K apart, which is what the
|
||||
* reference's rowoff does for one. */
|
||||
static inline int rows_pitch(const RadTensor* t, long long K, long long* rows, long long* ld) {
|
||||
const long long p = r3d_rows_pitch(t, K, rows);
|
||||
if (p < 0) return RAD_E_STRIDE;
|
||||
if (K <= 0 || *rows <= 0 || *rows > 0x7fffffffLL) return RAD_E_SHAPE;
|
||||
if (p < K) return RAD_E_SHAPE;
|
||||
*ld = p;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A codebook: [n, rank] bf16 with contiguous rows, because the gather is `token * rank + r`. */
|
||||
static inline int codebook_ok(const RadTensor* t, long long rank) {
|
||||
if (!t || !t->data) return RAD_E_INVAL;
|
||||
if (!r3d_is_bf16(t)) return RAD_E_DTYPE;
|
||||
if (!r3d_aligned(r3d_p(t), 2)) return RAD_E_ALIGN;
|
||||
if (rank > 0 && t->rank >= 1 && r3d_stride(t, (int)t->rank - 1) != 1) return RAD_E_STRIDE;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static inline int r3d_launch_status(int rc) {
|
||||
if (rc == 0) return RAD_OK;
|
||||
switch (rc) {
|
||||
case -1: return RAD_E_INVAL;
|
||||
case -2: return RAD_E_SHAPE;
|
||||
case -3: return RAD_E_STRIDE;
|
||||
default: return RAD_E_DEVICE;
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
#define R3D_NEED(x) \
|
||||
do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
|
||||
|
||||
/* ================================================================== launcher
|
||||
*
|
||||
* cand [M*steps][top_k] i32, candidate token ids, -1 for padding
|
||||
* unary [M*steps][top_k] f32, the candidate-independent half of the score
|
||||
* hp [M*steps][rank] bf16, the step's factor; 0 (absent) is a plane of ones
|
||||
* anchor [M*anchor_stride] i32, the token each walk starts from, at m*anchor_stride
|
||||
* pred [n_vocab][rank] bf16, the predecessor codebook
|
||||
* succ [n_vocab][rank] bf16, the successor codebook the walk gathers with its picks
|
||||
* tokens [M][steps] i32, out: the accepted prefix, one pick a step
|
||||
*
|
||||
* 0, -1 null, -2 bad extent, -3 pitch, -4 the HIP launch failed. No allocation, no synchronisation.
|
||||
*/
|
||||
extern "C" int r3d_dflash_select(long cand, long unary, long hp, long anchor, long pred, long succ,
|
||||
long tokens, int M, int steps, int top_k, int rank, int n_vocab,
|
||||
int anchor_stride, long long cand_ld, long long un_ld,
|
||||
long long hp_ld, long long pred_ld, long long succ_ld,
|
||||
long long tok_ld, long stream) {
|
||||
if (!cand || !unary || !anchor || !pred || !succ || !tokens) return -1;
|
||||
if (M <= 0 || steps <= 0 || top_k <= 0 || rank <= 0 || n_vocab <= 0 || anchor_stride <= 0)
|
||||
return -2;
|
||||
if ((unsigned)top_k > kKMax) return -2; /* one lane a candidate */
|
||||
if (!cand_ld) cand_ld = top_k;
|
||||
if (!un_ld) un_ld = top_k;
|
||||
if (!hp_ld) hp_ld = rank;
|
||||
if (!pred_ld) pred_ld = rank;
|
||||
if (!succ_ld) succ_ld = rank;
|
||||
if (!tok_ld) tok_ld = steps;
|
||||
if (cand_ld < top_k || un_ld < top_k) return -3;
|
||||
if (hp_ld < rank || pred_ld < rank || succ_ld < rank) return -3;
|
||||
if (tok_ld < steps) return -3;
|
||||
const uint32_t per = (kThr + (uint32_t)top_k - 1) / (uint32_t)top_k;
|
||||
R3D_KLAUNCH(R3D_KNAME(dflash_select_kernel), dim3((M + per - 1) / per), dim3(kThr),
|
||||
(hipStream_t)(uintptr_t)stream, (const int32_t*)(uintptr_t)cand,
|
||||
(const float*)(uintptr_t)unary, (const uint16_t*)(uintptr_t)hp,
|
||||
(const int32_t*)(uintptr_t)anchor, (const uint16_t*)(uintptr_t)pred,
|
||||
(const uint16_t*)(uintptr_t)succ, (int32_t*)(uintptr_t)tokens, (uint32_t)M,
|
||||
(uint32_t)steps, (uint32_t)top_k, (uint32_t)rank, (uint32_t)n_vocab,
|
||||
(uint32_t)anchor_stride, cand_ld, un_ld, hp_ld, pred_ld, succ_ld, tok_ld, per);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* ================================================================== shim
|
||||
*
|
||||
* libref's operand list is {cand, unary, hp?, anchor, pred, succ, tokens} and its parameter list is
|
||||
* {M, steps, top_k, rank, n_vocab, anchor_stride?, dtype}. Sequences come from `cand` -- the plane
|
||||
* holds M * steps * top_k ids -- through `band_rows`, so a plane describing more sequences than the
|
||||
* band's M is refused, not truncated. `rank` and `n_vocab` fall back to the predecessor codebook's
|
||||
* own shape, as the reference's do, and `anchor_stride` defaults to 1.
|
||||
*/
|
||||
extern "C" int r3d_rad_dflash_select(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* cand = r3d_opt(a, 0);
|
||||
const RadTensor* un = r3d_opt(a, 1);
|
||||
const RadTensor* hp = r3d_opt(a, 2); /* OPD_O: absent is a plane of ones */
|
||||
const RadTensor* anc = r3d_opt(a, 3);
|
||||
const RadTensor* pred = r3d_opt(a, 4);
|
||||
const RadTensor* succ = r3d_opt(a, 5);
|
||||
const RadTensor* tok = r3d_opt(a, 6);
|
||||
if (!cand || !cand->data || !un || !un->data || !anc || !anc->data || !pred || !pred->data ||
|
||||
!succ || !succ->data || !tok || !tok->data)
|
||||
return R3D_NO(RAD_E_INVAL);
|
||||
|
||||
/* The band names the codebooks' width; this is the bf16 instantiation. */
|
||||
const char* dt = r3d_gets(a, "dtype");
|
||||
if (dt && !r3d_dt_named(RAD_BF16, dt)) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
const long long steps = r3d_geti_or(a, "steps", 0);
|
||||
const long long K = r3d_geti_or(a, "top_k", 0);
|
||||
const long long astr = r3d_geti_or(a, "anchor_stride", 1);
|
||||
long long R = r3d_geti_or(a, "rank", pred->rank >= 2 ? r3d_dim(pred, (int)pred->rank - 1) : 0);
|
||||
long long nv = r3d_geti_or(a, "n_vocab",
|
||||
pred->rank >= 2 ? r3d_dim(pred, (int)pred->rank - 2) : 0);
|
||||
const long long band_M = r3d_geti_or(a, "M", 0);
|
||||
if (steps <= 0 || K <= 0 || astr <= 0 || R <= 0 || nv <= 0) return R3D_NO(RAD_E_SHAPE);
|
||||
if (K > (long long)kKMax) return R3D_NO(RAD_E_UNSUPPORTED);
|
||||
if (steps > 0x7fffffffLL / (K * 256) ) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* Sequences from the plane, the band as a ceiling -- band_rows refuses, it does not truncate. */
|
||||
const long long all = steps * K;
|
||||
if (all <= 0 || r3d_numel(cand) % all) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long M = r3d_numel(cand) / all;
|
||||
if (M <= 0 || (band_M > 0 && M > band_M)) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* The reference's extent tests, in its order. */
|
||||
if (r3d_numel(un) < M * steps * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(anc) < (M - 1) * astr + 1) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(tok) < M * steps) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(pred) < nv * R || r3d_numel(succ) < nv * R) return R3D_NO(RAD_E_SHAPE);
|
||||
if (hp && hp->data && r3d_numel(hp) < M * steps * R) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
if (!r3d_is_i32(cand)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_f32(un)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_i32(anc)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_i32(tok)) return R3D_NO(RAD_E_DTYPE);
|
||||
R3D_NEED(codebook_ok(pred, R));
|
||||
R3D_NEED(codebook_ok(succ, R));
|
||||
if (hp && hp->data) R3D_NEED(codebook_ok(hp, R));
|
||||
if (!r3d_aligned(r3d_p(cand), 4) || !r3d_aligned(r3d_p(un), 4) || !r3d_aligned(r3d_p(anc), 4) ||
|
||||
!r3d_aligned(r3d_p(tok), 4))
|
||||
return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
long long cand_ld = 0, un_ld = 0, tok_ld = 0, rows = 0;
|
||||
R3D_NEED(rows_pitch(cand, K, &rows, &cand_ld));
|
||||
R3D_NEED(rows_pitch(un, K, &rows, &un_ld));
|
||||
R3D_NEED(rows_pitch(tok, steps, &rows, &tok_ld));
|
||||
long long hp_ld = R, pred_ld = R, succ_ld = R;
|
||||
if (hp && hp->data) R3D_NEED(rows_pitch(hp, R, &rows, &hp_ld));
|
||||
R3D_NEED(rows_pitch(pred, R, &rows, &pred_ld));
|
||||
R3D_NEED(rows_pitch(succ, R, &rows, &succ_ld));
|
||||
|
||||
return r3d_launch_status(r3d_dflash_select(
|
||||
r3d_addr(cand), r3d_addr(un), (hp && hp->data) ? r3d_addr(hp) : 0L, r3d_addr(anc),
|
||||
r3d_addr(pred), r3d_addr(succ), r3d_addr(tok), (int)M, (int)steps, (int)K, (int)R, (int)nv,
|
||||
(int)astr, cand_ld, un_ld, hp_ld, pred_ld, succ_ld, tok_ld, (long)(uintptr_t)stream));
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/* r3d_fp8_dequant.h -- the E4M3 -> f16 decoder as a table, for the rows that read fp8 codes.
|
||||
*
|
||||
* WHY THIS EXISTS, WITH THE MEASUREMENT THAT ASKED FOR IT
|
||||
*
|
||||
* gfx11 has no instruction that converts E4M3 to f16. clang lists `__builtin_amdgcn_cvt_pk_f16_fp8`
|
||||
* for the target, and a build that calls it on gfx1102 contains ZERO `v_cvt_pk_f16_fp8` in its ISA:
|
||||
* the builtin is software here, lowered to the same exponent work `e4m3_to_f32` does. r3d_codecs.h's
|
||||
* codec is two `e4m3_to_f32` (a dozen instructions of shifts, exponent bias and subnormal handling
|
||||
* each) plus a pack, about 25 instructions a pair, 100 an eight-code group. Measured on the
|
||||
* vocabulary head at M=1 (r3d_vocab_bf16.hip, RX 7600 / gfx1102 / 32 CU): 13.603 ms a token at
|
||||
* 19.6 GB/s of codes, 8x above the 1.64 ms the codes' 255 MiB floor at this row's own 163 GB/s, and
|
||||
* the ALU was the binding resource, not DRAM.
|
||||
*
|
||||
* E4M3 has 256 bit patterns and every one of them has an f16 value (f16's exponent range covers
|
||||
* E4M3's, its subnormals included, and E4M3's NaN maps to an f16 NaN). So the decoder is a
|
||||
* 256-entry table of 512 bytes, and eight LDS reads replace the hundred ALU instructions. That is
|
||||
* the whole idea, and the table goes in LDS -- not __constant__, whose broadcast is a liability here
|
||||
* because every lane decodes a DIFFERENT code, and divergent constant indexes serialise.
|
||||
*
|
||||
* Cost: 512 bytes of LDS a block, one fill of 256 stores at block start plus a barrier. Conflict
|
||||
* behaviour on the reads: 16-bit loads at data-dependent addresses, so a wavefront's 32 lanes land
|
||||
* on 16 bank words; random codes give roughly two lanes per word, and measured cost is about two
|
||||
* cycles a read -- eight reads an eight-code group against the codec's hundred instructions.
|
||||
*
|
||||
* The table is EXACT: it is built by calling the codec once per entry, so it is the codec, moved
|
||||
* from the loop to the block's start. Nothing about the arithmetic changes, and a row's rel_l2
|
||||
* against its reference is unchanged by this header. The one thing to keep: the table must be filled
|
||||
* before any lane reads it, so every use is `..._init` then the barrier it contains, then reads.
|
||||
*
|
||||
* int8 codes do NOT want a table: `v_cvt_f32_i8` is a hardware instruction, so
|
||||
* r3d_codecs.h's i8x2_to_f16x2 is two converts and a pack. This header serves the fp8 codes.
|
||||
*
|
||||
* Header-only, like the rest of libr3d. Include it in a .hip after r3d_codecs.h.
|
||||
*/
|
||||
#ifndef R3D_FP8_DEQUANT_H
|
||||
#define R3D_FP8_DEQUANT_H
|
||||
|
||||
#include "r3d_codecs.h"
|
||||
|
||||
#define R3D_E4M3_TBL 256 /* every E4M3 bit pattern, in order, as the f16 it means */
|
||||
#define R3D_E4M3_TBL_BYTES (R3D_E4M3_TBL * 2)
|
||||
|
||||
/* Fill the block's table: `tbl` is __shared__ uint16_t[R3D_E4M3_TBL]. The barrier is inside it,
|
||||
* because the only correct order is fill-then-read and the row should not have to remember it. */
|
||||
__device__ __forceinline__ void r3d_e4m3_f16_init(uint16_t* tbl, int tid, int nthr)
|
||||
{
|
||||
for (int i = tid; i < R3D_E4M3_TBL; i += nthr)
|
||||
tbl[i] = f32_to_f16(e4m3_to_f32((uint8_t)i));
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
/* Two codes (the low 16 bits of a dword) as one f16 pair, the pair layout dot2_f16x2 reads: the
|
||||
* first code in the low half. Same answer as e4m3x2_to_f16x2, eight table reads per eight codes. */
|
||||
__device__ __forceinline__ uint32_t r3d_e4m3x2_ld(const uint16_t* tbl, uint32_t pair)
|
||||
{
|
||||
const uint16_t lo = tbl[pair & 0xffu];
|
||||
const uint16_t hi = tbl[(pair >> 8) & 0xffu];
|
||||
return (uint32_t)lo | ((uint32_t)hi << 16);
|
||||
}
|
||||
|
||||
/* Eight codes (two dwords, straddling pairs as always) as four f16 pairs. The sibling of
|
||||
* codes8_to_f16x4 in r3d_vocab_bf16.hip; the int8 side of that helper stays with the codec, because
|
||||
* int8 has a hardware convert and fp8 does not. */
|
||||
__device__ __forceinline__ void r3d_e4m3x8_ld(const uint16_t* tbl, uint2 c, uint32_t* w)
|
||||
{
|
||||
const uint32_t d0 = c.x, d1 = c.y;
|
||||
w[0] = r3d_e4m3x2_ld(tbl, d0 & 0xffffu);
|
||||
w[1] = r3d_e4m3x2_ld(tbl, d0 >> 16);
|
||||
w[2] = r3d_e4m3x2_ld(tbl, d1 & 0xffffu);
|
||||
w[3] = r3d_e4m3x2_ld(tbl, d1 >> 16);
|
||||
}
|
||||
|
||||
/* One code, for the rows that decode a scalar a step (an activation tile staged a byte a lane). */
|
||||
__device__ __forceinline__ uint16_t r3d_e4m3_ld(const uint16_t* tbl, uint8_t code)
|
||||
{
|
||||
return tbl[code];
|
||||
}
|
||||
|
||||
#endif /* R3D_FP8_DEQUANT_H */
|
||||
@@ -0,0 +1,374 @@
|
||||
/* r3d_gemm_bf16_nt_m16.hip -- the skinny bf16 GEMM, M <= 16: the linear a token is made of.
|
||||
*
|
||||
* y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store.
|
||||
*
|
||||
* The band is decode and speculative verify, where the weight is the cost and the activation is
|
||||
* free: the kernel is built so the whole weight plane streams once, and so every output's sum is
|
||||
* the sum libref forms.
|
||||
*
|
||||
* ---- the lane map --------------------------------------------------------------------------
|
||||
*
|
||||
* One output element a lane, walking k ascending. A wave covers MT rows of the activation by
|
||||
* 32/MT rows of the weight: lane l owns (m = l % MT, n = n0 + l / MT), MT being the template
|
||||
* argument -- the request's M rounded up to 1, 2, 4, 8 or 16. Lanes sharing an n read the same
|
||||
* weight words, so the wave issues 32/MT loads per step and broadcasts them to MT lanes each;
|
||||
* lanes sharing an m read the same activation words out of LDS. A lane therefore owns its own
|
||||
* accumulator from 0 to K and never exchanges a value with another lane: its chain is
|
||||
*
|
||||
* acc = 0; for k ascending: acc = dot2(pair k+1, dot2(pair k, acc))
|
||||
*
|
||||
* with pairs taken two k at a time, which is `s += a[k]*b[k]` in ascending k, summand for summand,
|
||||
* the loop r4d_gemm_bf16_nt_tiled's contract quotes and ref_gemm.h's quant_tile runs. There is no
|
||||
* wave reduction anywhere in this kernel, so nothing reassociates: at sk = 1 the output is
|
||||
* bit-identical to libref's, not merely within a tolerance.
|
||||
*
|
||||
* Rows past M and columns past N are clamped, not skipped -- a tail lane re-reads the last real row
|
||||
* and its result is dropped at the store -- so the k loop stays uniform and the loads stay
|
||||
* straight-line.
|
||||
*
|
||||
* ---- where the bytes come from --------------------------------------------------------------
|
||||
*
|
||||
* The activation is staged in LDS and widened on the way in: one row is M <= 16 elements wide per
|
||||
* k, so a tile is MT * 128 bf16 (4.25 KiB at MT = 16) and one 16-byte load a thread. Staging
|
||||
* converts bf16 -> f16 once per element with bf16x2_to_f16x2, which is exact, so the dot2 reads
|
||||
* f16 pairs straight out of LDS and the widening is paid N/MT times less often than it would be
|
||||
* read. The pitch is 68 dwords: 68 mod 32 = 4, so the eight lanes of a ds_read_b128 phase land on
|
||||
* banks 4 apart -- conflict-free -- and 68 * 4 = 272 keeps a 16-byte LDS read aligned.
|
||||
*
|
||||
* The weight is NOT staged. M is tiny, so a staged tile would be read by 32/MT lanes and then
|
||||
* thrown away; LDS staging buys reuse a skinny shape does not have. Weight bytes go straight from
|
||||
* global memory into registers, widened there by four v_cvt_pkrtz per eight values (one per dword,
|
||||
* so one convert per two dot2 products -- the price of the dot2 path being the widening the staged
|
||||
* row pays once per element), and live for the four products they feed.
|
||||
* Each wave keeps NT = 32/MT rows resident in L1 (NT lines of 128 B, 4 KiB at MT = 1, the worst
|
||||
* case), which is what makes 16-byte-per-lane strided reads across NT rows cost what they fetch.
|
||||
*
|
||||
* ---- the register budget --------------------------------------------------------------------
|
||||
*
|
||||
* A gfx11 SIMD has 1024 VGPRs for a wave32. The loop is one accumulator, four activation pairs,
|
||||
* four weight dwords, one 16-byte staging quad and a handful of pointers and counters: about 24
|
||||
* live VGPRs, so the kernel is nowhere near the 128 that R3D_WAVES(8) -- eight waves a SIMD,
|
||||
* 1024/8 -- asks for. The target is stated for the reason r3d_common.h gives: unstated, the
|
||||
* scheduler picks the occupancy itself, and this kernel's throughput is waves in flight, since
|
||||
* every wave is waiting on a memory load that takes hundreds of cycles. Eight waves a block of
|
||||
* 256 threads is the default, and `wv` is the axis a tuner walks.
|
||||
*
|
||||
* ---- split-K --------------------------------------------------------------------------------
|
||||
*
|
||||
* At M = 1 a wide N is the only parallelism there is, and N = 48 (a GDN a|b projection) gives three
|
||||
* waves on a 32-CU card. `sk` splits K into that many contiguous slabs, each owned by one
|
||||
* blockIdx.y, each writing an f32 partial to the caller's `scratch` arena; a second kernel on the
|
||||
* same stream adds the partials per output in ascending split order and narrows once.
|
||||
*
|
||||
* The order matters and is stated: summing sk per-slab partials is NOT the ascending sum libref
|
||||
* forms. Each partial is an ascending sum over its own slab, and the slab sums are then added in
|
||||
* ascending slab order, which brackets the products differently than a single running chain does.
|
||||
* sk = 1 is the bit-identical case; sk > 1 agrees to the last bits, which is the same contract
|
||||
* libr4d's tiled row states about its slices. The row is verified at every sk kbench measures.
|
||||
*
|
||||
* `sk == 0` means "the largest legal split for this K" off the axis's ladder {16, 8, 4, 2, 1},
|
||||
* legality being K % (sk * 8) == 0: a slice must end where the inner loop stops, on a group of the
|
||||
* eight k (four f16 pairs) a lane consumes per step, so a slice boundary never falls inside a
|
||||
* step. The staged tile is 128 k wide and its last tile is ragged, which is what lets a slice be
|
||||
* 8 k long, and the cap of 16 is the split the row's scratch hook sizes the arena for.
|
||||
*
|
||||
* ---- `nt` -----------------------------------------------------------------------------------
|
||||
*
|
||||
* RDNA3 has no global_load_tr_b128 (that is RDNA4) and no cache-swizzle field on a global load. So
|
||||
* `nt` is an axis that measures a knob the ISA does not special-case: nt = 1 issues the weight
|
||||
* reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache modifier
|
||||
* and no swizzle -- a plain stream -- and nt = 0 issues the same 16-byte reads through the generic
|
||||
* pointer, which lowers to flat_load_dwordx4. Nothing is invented here; the axis exists so kbench
|
||||
* can price the two lowerings and record that on this card they are the same stream.
|
||||
*/
|
||||
|
||||
/* hip_runtime.h first: it defines __forceinline__, which r3d_codecs.h's R3D_HD spells, and
|
||||
* r3d_common.h reaches the codecs before it reaches the runtime. */
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_launch.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kBlockThreads = 256; // eight waves, the default
|
||||
constexpr int kWaves = kBlockThreads / kWave;
|
||||
constexpr int kKTile = 128; // k a staged tile of a covers
|
||||
constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row
|
||||
constexpr int kMTMax = 16; // the band's upper bound
|
||||
|
||||
/* The split rule, in one place so the launch, the shim and the row's gemm_tune_valid agree.
|
||||
* `kUnit` is the k a lane's step consumes -- eight elements, four f16 pairs -- and a slice must be
|
||||
* whole steps, so a split is legal when K divides by sk * kUnit. The ladder is the row's `sk` axis
|
||||
* descending, and its top is the split the scratch hook sizes for: a wider split the arena cannot
|
||||
* hold is not a legal default. */
|
||||
constexpr int kUnit = 8;
|
||||
inline int pick_sk(long long K, int maxsk)
|
||||
{
|
||||
static const int kLadder[] = { 16, 8, 4, 2, 1 };
|
||||
for (int s : kLadder)
|
||||
if (s <= maxsk && K % ((long long)s * kUnit) == 0) return s;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* A 16-byte weight read. NT true is the address-space-1 form: global_load_b128, no cache modifier,
|
||||
* no swizzle, the plain stream the row's `nt` axis names. NT false goes through the generic
|
||||
* pointer, which the compiler lowers to flat_load_dwordx4. */
|
||||
template <bool NT>
|
||||
__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p)
|
||||
{
|
||||
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
|
||||
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p)
|
||||
{
|
||||
return *(const r3d_u32x4*)p;
|
||||
}
|
||||
|
||||
/* y[M,N] = a[M,K] @ b[N,K]^T, one output element a lane.
|
||||
*
|
||||
* `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the
|
||||
* narrowed bf16 the caller asked for. With sk > 1 every split writes its own f32 partial, dense
|
||||
* [sk][M][N], and gemm_split_reduce adds them. */
|
||||
template <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. */
|
||||
__shared__ uint32_t s_a[kMTMax * kAPitch];
|
||||
|
||||
const uint32_t tid = threadIdx.x;
|
||||
const uint32_t lane = tid & (kWave - 1);
|
||||
const uint32_t wave = tid / kWave;
|
||||
const uint32_t waves = blockDim.x / kWave;
|
||||
constexpr uint32_t kNT = kWave / MT; // weight rows a wave covers
|
||||
|
||||
const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * kNT + lane / MT;
|
||||
const uint32_t m = lane & (MT - 1);
|
||||
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
|
||||
const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1));
|
||||
|
||||
const int kbeg = (int)blockIdx.y * kslab;
|
||||
const int kend = kbeg + kslab < K ? kbeg + kslab : K;
|
||||
|
||||
const uint16_t* w = B + (size_t)n_real * w_ld;
|
||||
float acc = 0.0f;
|
||||
|
||||
for (int kt = kbeg; kt < kend; kt += kKTile) {
|
||||
const int kl = std::min(kKTile, kend - kt);
|
||||
|
||||
/* Stage: eight elements a unit, MT * (kl/8) units, 256 threads. A row past M re-reads the
|
||||
* last real row, whose products the store drops. */
|
||||
const int nu = (kl + 7) / 8;
|
||||
/* blockDim.x, not the 256-thread default: the wv axis launches one, two, four or eight
|
||||
* waves, and a stage loop that strides the block constant leaves units staged only for
|
||||
* the waves that exist -- wv = 1 stages 32 of MT*16 units and the k loop reads the rest of
|
||||
* the tile out of LDS that was never written. */
|
||||
for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) {
|
||||
const int r = i / nu, c = (i % nu) * 8;
|
||||
const int rr = r < M ? r : M - 1;
|
||||
const uint16_t* src = A + (size_t)rr * a_ld + kt + c;
|
||||
uint32_t* dst = s_a + (size_t)r * kAPitch + c / 2;
|
||||
if (c + 8 <= kl) {
|
||||
const r3d_u32x4 q = *(const __attribute__((address_space(1))) r3d_u32x4*)src;
|
||||
*(r3d_u32x4*)dst = r3d_u32x4{
|
||||
bf16x2_to_f16x2(q.x), bf16x2_to_f16x2(q.y),
|
||||
bf16x2_to_f16x2(q.z), bf16x2_to_f16x2(q.w) };
|
||||
} else {
|
||||
uint32_t p[4] = { 0, 0, 0, 0 };
|
||||
for (int e = 0; e < kl - c; e += 2) {
|
||||
const uint32_t lo = ldg_u16(src + e);
|
||||
const uint32_t hi = (e + 1 < kl) ? ldg_u16(src + e + 1) : 0u;
|
||||
p[e / 2] = bf16x2_to_f16x2(lo | (hi << 16));
|
||||
}
|
||||
for (int e = 0; e < (kl - c + 1) / 2; ++e) dst[e] = p[e];
|
||||
}
|
||||
}
|
||||
group_barrier();
|
||||
|
||||
const uint32_t* ap = s_a + (size_t)m * kAPitch;
|
||||
const int kf = kl & ~7;
|
||||
for (int k = 0; k < kf; k += 8) {
|
||||
const r3d_u32x4 aw = lds_a(ap + k / 2);
|
||||
const r3d_u32x4 b16 = ldw<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. */
|
||||
const r3d_u32x4 bw = r3d_u32x4{ bf16x2_to_f16x2(b16.x), bf16x2_to_f16x2(b16.y),
|
||||
bf16x2_to_f16x2(b16.z), bf16x2_to_f16x2(b16.w) };
|
||||
acc = dot4_f16x4(aw.x, aw.y, bw.x, bw.y, acc);
|
||||
acc = dot4_f16x4(aw.z, aw.w, bw.z, bw.w, acc);
|
||||
}
|
||||
/* The ragged end of the last slab, ascending. A split is legal only when its slab is whole
|
||||
* tiles, so this runs at sk = 1 with a K that is not a multiple of 128. */
|
||||
for (int k = kf; k < kl; ++k)
|
||||
acc = acc + bf16_to_f32((uint16_t)ldg_u16(A + (size_t)m_real * a_ld + kt + k))
|
||||
* bf16_to_f32((uint16_t)ldg_u16(w + kt + k));
|
||||
group_barrier(); // the next tile's stage must not race this one's reads
|
||||
}
|
||||
|
||||
const bool keep = (n0 < (uint32_t)N) && (m < (uint32_t)M);
|
||||
if (!keep) return;
|
||||
if constexpr (SPLIT) {
|
||||
/* Partial plane [sk][M][N]: split-major, so the reducer reads sk values M*N apart and this
|
||||
* store keeps the same [M][N] shape at every split. */
|
||||
Part[((size_t)blockIdx.y * M + m) * N + n0] = acc;
|
||||
} else {
|
||||
Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc); // narrowed once, here
|
||||
}
|
||||
}
|
||||
|
||||
/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one narrowing.
|
||||
*
|
||||
* This is the order libref's ascending sum produces at sk = 1 and not at sk > 1: each partial is
|
||||
* ascending over its own slab, and the slab sums bracket the products differently than one chain
|
||||
* does. The difference is in the last bits and is the split's, not a bug in it. */
|
||||
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_split_reduce(
|
||||
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
|
||||
{
|
||||
const int mn = M * N;
|
||||
const int stride = gridDim.x * kBlockThreads;
|
||||
for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) {
|
||||
const int m = i / N, n = i - m * N;
|
||||
const float* p = Part + (size_t)m * N + n;
|
||||
float v = p[0];
|
||||
for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N];
|
||||
Y[(size_t)m * y_ld + n] = f32_to_bf16(v);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* y[M,N] = a[M,K] @ b[N,K]^T, bf16 in and out, f32 accumulate, M <= 16.
|
||||
*
|
||||
* a [M][K] bf16, `a_ld` elements a row (0 = K)
|
||||
* b [N][K] bf16, row-major, k contiguous
|
||||
* y [M][N] bf16, `y_ld` elements a row (0 = N)
|
||||
*
|
||||
* `sk` splits K (0 = the largest legal split), `wv` is waves per block (0 = 8), `nt` picks the
|
||||
* weight load's lowering (see the file header), and `scratch` is the f32 partial arena,
|
||||
* sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null pointer, -2 a shape it
|
||||
* does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */
|
||||
extern "C" int r3d_gemm_nt_bf16_m16(long a, long b, long y, int M, int N, int K, int a_ld,
|
||||
int y_ld, int sk, int wv, int nt, long scratch, long stream)
|
||||
{
|
||||
if (!a || !b || !y) return -1;
|
||||
if (M < 1 || N < 1 || K < 1) return -2;
|
||||
if (M > kMTMax) return -2;
|
||||
if (!a_ld) a_ld = K;
|
||||
if (!y_ld) y_ld = N;
|
||||
if (sk == 0) sk = pick_sk(K, 16);
|
||||
if (sk < 1) return -2;
|
||||
if (K % ((long long)sk * kUnit)) return -2;
|
||||
if (sk > 1 && !scratch) return -1;
|
||||
if (wv <= 0) wv = kWaves;
|
||||
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2;
|
||||
|
||||
const int mt = M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax;
|
||||
const int kslab = K / sk;
|
||||
|
||||
#define R3D_M16_NT(MTV, NTV) \
|
||||
do { \
|
||||
const int nt_ = (N + (kWave / MTV) - 1) / (kWave / MTV); \
|
||||
const dim3 grid((nt_ + wv - 1) / wv, (unsigned)sk), block((unsigned)(wv * kWave)); \
|
||||
if (sk > 1) { \
|
||||
R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel<MTV, NTV, true>)), grid, block, \
|
||||
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
|
||||
(uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, K, kslab); \
|
||||
const int mn = M * N; \
|
||||
const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \
|
||||
R3D_KLAUNCH(gemm_split_reduce, dim3(nb), dim3(kBlockThreads), (hipStream_t)stream, \
|
||||
(const float*)scratch, (uint16_t*)y, M, N, y_ld, sk); \
|
||||
} else { \
|
||||
R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel<MTV, NTV, false>)), grid, block, \
|
||||
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
|
||||
(uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, K, kslab); \
|
||||
} \
|
||||
} while (0)
|
||||
#define R3D_M16_MT(MTV) do { if (nt) R3D_M16_NT(MTV, true); else R3D_M16_NT(MTV, false); } while (0)
|
||||
switch (mt) {
|
||||
case 1: R3D_M16_MT(1); break;
|
||||
case 2: R3D_M16_MT(2); break;
|
||||
case 4: R3D_M16_MT(4); break;
|
||||
case 8: R3D_M16_MT(8); break;
|
||||
default: R3D_M16_MT(16); break;
|
||||
}
|
||||
#undef R3D_M16_MT
|
||||
#undef R3D_M16_NT
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* ============================================================== the plugin ABI entry point
|
||||
*
|
||||
* gemm_nt's operand list is [a, b, y] and its parameters M, N, K, dtype (libref's pGemm/oGemm). */
|
||||
enum { G_A = 0, G_B, G_Y };
|
||||
|
||||
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
|
||||
static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
|
||||
extern "C" int r3d_rad_gemm_nt_bf16_m16(const RadArgs* a, RadStream s)
|
||||
{
|
||||
const RadTensor* A = r3d_opt(a, G_A);
|
||||
const RadTensor* B = r3d_opt(a, G_B);
|
||||
const RadTensor* Y = r3d_opt(a, G_Y);
|
||||
if (!A || !B || !Y) return R3D_NO(RAD_E_INVAL);
|
||||
R3D_NEED(dt_bf16(A));
|
||||
R3D_NEED(dt_bf16(B));
|
||||
R3D_NEED(dt_bf16(Y));
|
||||
|
||||
const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1));
|
||||
const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2));
|
||||
if (K < 1 || N < 1) return R3D_NO(RAD_E_SHAPE);
|
||||
/* The row count comes from the output, never from `M`, which is the band's upper bound. */
|
||||
const long long nel = r3d_numel(Y);
|
||||
if (nel < N || nel % N) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long M = nel / N;
|
||||
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
long long arows = 0, yrows = 0;
|
||||
const long long a_ld = r3d_rows_pitch(A, K, &arows);
|
||||
const long long y_ld = r3d_rows_pitch(Y, N, &yrows);
|
||||
if (a_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
|
||||
if (arows < M || yrows < M) return R3D_NO(RAD_E_SHAPE);
|
||||
/* The weight must be dense: every wave reads b[n][k] at n * K + k, and a pitch the launcher
|
||||
* does not carry cannot be described to it. */
|
||||
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
|
||||
/* 16-byte weight loads, at a row base and at a tile base, both multiples of 8 elements. */
|
||||
if (a_ld % 8) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
R3dGemmCfg c;
|
||||
r3d_cfg_gemm(a, &c);
|
||||
int wv = c.wv > 0 ? c.wv : kWaves;
|
||||
if (wv > kWaves) wv = kWaves;
|
||||
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return R3D_NO(RAD_E_SHAPE);
|
||||
int sk = c.sk > 0 ? c.sk : pick_sk(K, 16);
|
||||
if (sk > 16) return R3D_NO(RAD_E_SHAPE); // the scratch hook sizes for 16
|
||||
if (K % ((long long)sk * kUnit)) return R3D_NO(RAD_E_SHAPE);
|
||||
if (sk > 1) {
|
||||
const long long need = (long long)sk * M * N * 4;
|
||||
if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH);
|
||||
}
|
||||
|
||||
const int e = r3d_gemm_nt_bf16_m16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)N,
|
||||
(int)K, (int)a_ld, (int)y_ld, sk, wv, c.nt,
|
||||
(long)(uintptr_t)(sk > 1 ? a->scratch : nullptr),
|
||||
(long)(uintptr_t)s);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
|
||||
: e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
/* r3d_gemm_fp8a16_nt_m1.hip -- the same skinny shape against a block-scaled weight.
|
||||
*
|
||||
* y[M,N] = a[M,K] @ b[N,K]^T, b stored as E4M3 codes with one f32 scale per (pb1 x pb2) block,
|
||||
* f32 accumulate, narrowed once by the store. `a_scale`, when present, means the activation is
|
||||
* coded too -- quant_act_fp8's E4M3 codes with one f32 per (row, group) -- which is the fp8a8
|
||||
* form the row table names `fp8a8`.
|
||||
*
|
||||
* RDNA3 has no fp8 instruction: the builtins are declared for gfx11 and die at instruction
|
||||
* selection. So the codes are decoded in software, and the decode is free of cost in the sense
|
||||
* that matters here: E4M3 is four exponent and three mantissa bits, f16 is five and ten, so
|
||||
* e4m3x2_to_f16x2 is EXACT and the dot2 multiplies the numbers the checkpoint means. Nothing is
|
||||
* rounded between the code and the product, which is why this row's output is libref's to the bit
|
||||
* at sk = 1 and not merely inside fp8 quantisation noise.
|
||||
*
|
||||
* ---- the lane map --------------------------------------------------------------------------
|
||||
*
|
||||
* The same as r3d_gemm_bf16_nt_m16's: lane l owns the output (m = l % MT, n = n0 + l / MT) for the
|
||||
* template's MT = ceil(M) in {1,2,4,8,16}, walks k ascending and holds its own accumulator. One
|
||||
* difference is forced by the format, and it is the one that makes this kernel what it is: a lane
|
||||
* consumes sixteen codes per step, because that is what sixteen bytes are, and sixteen bytes is
|
||||
* one global_load_b128. Eight dot2 per step, so the weight stream is one 16-byte load per eight
|
||||
* matrix instructions -- the decode (eight v_perms and shifts, exact) sits between them and is the
|
||||
* reason this kernel's rate is not the bf16 row's.
|
||||
*
|
||||
* A lane owns one (m, n) pair, so a lane owns one scale per block: `n / pb1` picks b_scale's row
|
||||
* and the block index picks its column, and both are hoisted out of the block's sixteen-element
|
||||
* steps. The activation's scale, when the activation is coded, is `m`'s row at the same block
|
||||
* index. Lanes sharing an n agree on it, which is why no lane-to-lane exchange is needed.
|
||||
*
|
||||
* ---- where the scale multiplies -------------------------------------------------------------
|
||||
*
|
||||
* ref_gemm.h's quant_tile, and quant_dot beside it, is the spec, and the order it writes is the
|
||||
* order this kernel runs:
|
||||
*
|
||||
* for gi ascending: sub = 0
|
||||
* for k in the group, ascending: sub += a[k] * b[k] (from the CODES)
|
||||
* acc = acc + (sub * sa) * sb
|
||||
*
|
||||
* with sa = a_scale[m][gi] or 1, and sb = b_scale[n / pb1][gi]. The scale multiplies the finished
|
||||
* block, once, at the block's end -- not every product: scaling each product is equal in exact
|
||||
* arithmetic and differs in the last bits, which moves an fp8 code and so moves a token. And
|
||||
* `(sub * sa) * sb` is an order, not a formula: the parentheses are libref's, and the products are
|
||||
* summed from the raw codes with no scale folded into them. This kernel accumulates a block's
|
||||
* sub-sum into a register of its own, so the bracketing is the reference's, and the widening is
|
||||
* exact, so at sk = 1 the output is bit-identical to it.
|
||||
*
|
||||
* ---- the activation ---------------------------------------------------------------------------
|
||||
*
|
||||
* Staged in LDS per block of the weight's K, widened on the way in: bf16 -> f16 for fp8a16, E4M3 ->
|
||||
* f16 for fp8a8, both exact. One row of a is M <= 16 elements wide per k, so a staged block is
|
||||
* MT * 128 values, 4.25 KiB at MT = 16, and the pitch is 68 dwords: 68 mod 32 = 4, so a
|
||||
* ds_read_b128's eight lanes land on banks four apart, and 272 bytes a row keeps the 16-byte reads
|
||||
* aligned. The weight is not staged: with M <= 16 a staged tile has 32/MT readers, so staging
|
||||
* trades a wave's worth of L1 residency for a round trip through LDS and buys nothing.
|
||||
*
|
||||
* ---- split-K --------------------------------------------------------------------------------
|
||||
*
|
||||
* `sk` contiguous slices, one per blockIdx.y, each writing its f32 partial to `scratch` and a
|
||||
* second kernel adding them per output in ascending slice order. Each partial is a chain of
|
||||
* `(sub * sa) * sb` terms over its own slices of blocks, so at sk = 1 the chain is libref's
|
||||
* exactly; sk > 1 brackets the block terms by slice, which is the split's doing and agrees to the
|
||||
* last bits. Legality is K % (sk * group) == 0 -- a slice that ends mid-block cannot apply that
|
||||
* block's scale -- which is the row's gemm_tune_valid rule, unit = group.
|
||||
*
|
||||
* ---- `nt` -----------------------------------------------------------------------------------
|
||||
*
|
||||
* No transposed load on this ISA and no cache field on a global load. nt = 1 issues the weight
|
||||
* reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache
|
||||
* modifier and no swizzle; nt = 0 issues the same 16-byte reads through the generic pointer. The
|
||||
* axis measures the two lowerings, and on this card it measures the same stream twice.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD spells
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_launch.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kBlockThreads = 256;
|
||||
constexpr int kWaves = kBlockThreads / kWave;
|
||||
constexpr int kMTMax = 16;
|
||||
constexpr int kStep = 16; // codes a lane takes per step: one 16-byte load
|
||||
constexpr int kAPitch = 68; // dwords a staged activation row (128 values + 4)
|
||||
constexpr int kGroupMax = 128; // the stage is sized for one 128-wide block per row
|
||||
|
||||
/* A slice is legal when it is a whole number of scale blocks, so the split ladder is capped by
|
||||
* the scratch hook's widest split and stepped by the block the weight carries. */
|
||||
int pick_sk(long long K, int group, int maxsk)
|
||||
{
|
||||
static const int kLadder[] = { 16, 8, 4, 2, 1 };
|
||||
for (int s : kLadder)
|
||||
if (s <= maxsk && K % ((long long)s * group) == 0) return s;
|
||||
return 1;
|
||||
}
|
||||
|
||||
template <bool NT>
|
||||
__device__ __forceinline__ r3d_u32x4 ldc(const uint8_t* p) // 16 codes
|
||||
{
|
||||
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
|
||||
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p)
|
||||
{
|
||||
return *(const r3d_u32x4*)p;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ uint32_t ldg_u8(const uint8_t* p)
|
||||
{
|
||||
return *(const __attribute__((address_space(1))) uint8_t*)p;
|
||||
}
|
||||
|
||||
/* The weight's 16 codes as eight f16 pairs, exact.
|
||||
*
|
||||
* e4m3x2_to_f16x2 decodes the TWO codes in a dword's low half, so a 16-byte load -- four dwords,
|
||||
* sixteen codes -- is eight decodes, each fed the 16-bit pair it wants: the pairs straddle the
|
||||
* dwords, four dwords in, eight pairs out. Feeding the codec whole dwords decodes eight codes and
|
||||
* leaves the rest of the step multiplying registers that were never written, which is the quiet
|
||||
* version of this bug: the answer comes back a fraction of its size, not a NaN. */
|
||||
__device__ __forceinline__ void codes_to_f16x8(const r3d_u32x4 c, uint32_t* w)
|
||||
{
|
||||
const uint32_t d[4] = { c.x, c.y, c.z, c.w };
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j)
|
||||
w[j] = e4m3x2_to_f16x2((d[j >> 1] >> (16 * (j & 1))) & 0xffffu);
|
||||
}
|
||||
|
||||
/* y[M,N] = a[M,K] @ dequant(b)[N,K]^T. `A8` is the fp8a8 form: a carries E4M3 codes and a_scale
|
||||
* carries one f32 per (row, block); without it a is bf16 and read directly. */
|
||||
template <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,
|
||||
const uint8_t* __restrict__ B, const void* __restrict__ BScale, int bs16,
|
||||
uint16_t* __restrict__ Y, float* __restrict__ Part,
|
||||
int M, int N, int K, int group, int pb1, int a_ld, int y_ld, int kslab, int nkb)
|
||||
{
|
||||
__shared__ uint32_t s_a[kMTMax * kAPitch];
|
||||
|
||||
const uint32_t tid = threadIdx.x;
|
||||
const uint32_t lane = tid & (kWave - 1);
|
||||
const uint32_t wave = tid / kWave;
|
||||
const uint32_t waves = blockDim.x / kWave;
|
||||
constexpr uint32_t kNT = kWave / MT;
|
||||
|
||||
const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * kNT + lane / MT;
|
||||
const uint32_t m = lane & (MT - 1);
|
||||
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
|
||||
const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1));
|
||||
|
||||
const int kbeg = (int)blockIdx.y * kslab;
|
||||
const int kend = kbeg + kslab < K ? kbeg + kslab : K;
|
||||
|
||||
const uint8_t* w = B + (size_t)n_real * K;
|
||||
/* b_scale is the container's `weight_scale_inv`, and the op's shape hook writes it bf16 for the
|
||||
* whole quantised family -- `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})`; f32 belongs to the
|
||||
* separate `fp8a8f32` spelling. Both are read here; bf16 widens to f32 exactly, since every
|
||||
* bf16 value is representable in f32, so the widening is free and the products are unchanged. */
|
||||
const size_t bsrow = (size_t)(n_real / pb1) * nkb;
|
||||
const float* bsF = bs16 ? nullptr : (const float*)BScale + bsrow;
|
||||
const uint16_t* bsH = bs16 ? (const uint16_t*)BScale + bsrow : nullptr;
|
||||
const float* as = A8 ? AScale + (size_t)m_real * nkb : nullptr;
|
||||
|
||||
float acc = 0.0f;
|
||||
|
||||
/* One scale block per round: stage the block's activation, walk the block's k, fold the block's
|
||||
* scale in at the end. `kb` is the block's first k, which is where the scales are indexed. */
|
||||
for (int kb = kbeg; kb < kend; kb += group) {
|
||||
const int gl = std::min(group, kend - kb);
|
||||
const int gi = kb / group;
|
||||
|
||||
/* Stage gl elements of MT activation rows, widened to f16 pairs. Eight values a unit: a
|
||||
* 16-byte load for a bf16 row, an 8-byte one for a coded row, which is why the coded row's
|
||||
* pitch check is eight, not sixteen. A row past M re-reads the last real row. */
|
||||
constexpr int kUnit = 8;
|
||||
const int nu = (gl + kUnit - 1) / kUnit;
|
||||
for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) { // see the m16 unit's note on wv
|
||||
const int r = i / nu, c = (i % nu) * kUnit;
|
||||
const int rr = r < M ? r : M - 1;
|
||||
const int cnt = std::min(kUnit, gl - c);
|
||||
uint32_t* dst = s_a + (size_t)r * kAPitch + c / 2;
|
||||
if constexpr (A8) {
|
||||
const uint8_t* src = A + (size_t)rr * a_ld + kb + c; // codes: bytes and elements agree
|
||||
for (int e = 0; e < cnt; e += 8) {
|
||||
const uint8_t* sp = src + e;
|
||||
uint32_t q[2];
|
||||
if (cnt - e >= 8) {
|
||||
const r3d_u32x2 b8 =
|
||||
*(const __attribute__((address_space(1))) r3d_u32x2*)sp;
|
||||
q[0] = b8.x; q[1] = b8.y;
|
||||
} else {
|
||||
uint32_t pack[2] = { 0, 0 };
|
||||
for (int t = 0; t < cnt - e; ++t)
|
||||
pack[t >> 2] |= (uint32_t)ldg_u8(sp + t) << (8 * (t & 3));
|
||||
q[0] = pack[0]; q[1] = pack[1];
|
||||
}
|
||||
uint32_t p[4] = { e4m3x2_to_f16x2(q[0] & 0xffffu),
|
||||
e4m3x2_to_f16x2(q[0] >> 16),
|
||||
e4m3x2_to_f16x2(q[1] & 0xffffu),
|
||||
e4m3x2_to_f16x2(q[1] >> 16) };
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
if (e + 2 * t < gl) dst[e / 2 + t] = p[t];
|
||||
}
|
||||
} else {
|
||||
/* A is a byte pointer here because the coded form codes it: cast first, then the
|
||||
* row and k offsets are ELEMENT offsets, which for bf16 is twice the byte count. */
|
||||
const uint16_t* src = (const uint16_t*)A + (size_t)rr * a_ld + kb + c;
|
||||
for (int e = 0; e < cnt; e += 8) {
|
||||
uint32_t p[4];
|
||||
if (cnt - e >= 8) {
|
||||
const r3d_u32x4 b16 =
|
||||
*(const __attribute__((address_space(1))) r3d_u32x4*)(src + e);
|
||||
p[0] = bf16x2_to_f16x2(b16.x);
|
||||
p[1] = bf16x2_to_f16x2(b16.y);
|
||||
p[2] = bf16x2_to_f16x2(b16.z);
|
||||
p[3] = bf16x2_to_f16x2(b16.w);
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t) {
|
||||
const uint32_t lo = ldg_u16(src + e + 2 * t);
|
||||
const uint32_t hi = (e + 2 * t + 1 < gl)
|
||||
? ldg_u16(src + e + 2 * t + 1) : 0u;
|
||||
p[t] = bf16x2_to_f16x2(lo | (hi << 16));
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
if (e + 2 * t < gl) dst[e / 2 + t] = p[t];
|
||||
}
|
||||
}
|
||||
}
|
||||
group_barrier();
|
||||
|
||||
const uint32_t* ap = s_a + (size_t)m * kAPitch;
|
||||
float sub = 0.0f;
|
||||
const int gf = (gl / kStep) * kStep;
|
||||
for (int k = 0; k < gf; k += kStep) {
|
||||
const r3d_u32x4 a0 = lds_a(ap + k / 2);
|
||||
const r3d_u32x4 a1 = lds_a(ap + k / 2 + 4);
|
||||
uint32_t b[8];
|
||||
codes_to_f16x8(ldc<NT>(w + kb + k), b);
|
||||
sub = dot4_f16x4(a0.x, a0.y, b[0], b[1], sub);
|
||||
sub = dot4_f16x4(a0.z, a0.w, b[2], b[3], sub);
|
||||
sub = dot4_f16x4(a1.x, a1.y, b[4], b[5], sub);
|
||||
sub = dot4_f16x4(a1.z, a1.w, b[6], b[7], sub);
|
||||
}
|
||||
/* The last partial block, when K is not a whole block: ascending, two k at a time, each
|
||||
* code decoded on its own. The launcher refuses a K that is not a multiple of the block
|
||||
* (a ragged block would read past the scale plane), so this is a shape the kernel carries
|
||||
* for completeness and the row never issues. */
|
||||
for (int k = gf; k < gl; k += 2) {
|
||||
const uint32_t aw = ap[k / 2];
|
||||
const uint32_t c0 = ldg_u8(w + kb + k);
|
||||
const uint32_t c1 = (k + 1 < gl) ? ldg_u8(w + kb + k + 1) : 0u;
|
||||
const uint32_t pw = e4m3x2_to_f16x2(c0 | (c1 << 8));
|
||||
sub = dot2_f16x2(aw, pw, sub);
|
||||
}
|
||||
group_barrier(); // the next block's stage must not race this one's reads
|
||||
|
||||
/* The block's finished sub-sum, scaled once, in libref's parentheses. */
|
||||
const float sa = A8 ? as[gi] : 1.0f;
|
||||
acc = acc + (sub * sa) * (bs16 ? bf16_to_f32(bsH[gi]) : bsF[gi]);
|
||||
}
|
||||
|
||||
const bool keep = (n0 < (uint32_t)N) && (m < (uint32_t)M);
|
||||
if (!keep) return;
|
||||
if constexpr (SPLIT) {
|
||||
Part[((size_t)blockIdx.y * M + m) * N + n0] = acc;
|
||||
} else {
|
||||
Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc);
|
||||
}
|
||||
}
|
||||
|
||||
/* The split reduction, the m16 unit's, in the same order: v = ((p0 + p1) + p2) + ... ascending by
|
||||
* slice, then one narrowing. Ascending slice order is libref's ascending sum only at sk = 1; past
|
||||
* that the block terms are bracketed by slice, which is the split's cost and is stated as such. */
|
||||
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_reduce(
|
||||
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
|
||||
{
|
||||
const int mn = M * N;
|
||||
const int stride = gridDim.x * kBlockThreads;
|
||||
for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) {
|
||||
const int m = i / N, n = i - m * N;
|
||||
const float* p = Part + (size_t)m * N + n;
|
||||
float v = p[0];
|
||||
for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N];
|
||||
Y[(size_t)m * y_ld + n] = f32_to_bf16(v);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* y[M,N] = a[M,K] @ dequant(b)[N,K]^T over E4M3 codes, M <= 16, f32 accumulate, bf16 out.
|
||||
*
|
||||
* a [M][K] bf16 (fp8a16) or E4M3 codes (fp8a8, when `a_scale` is present)
|
||||
* a_scale [M][ceil(K/group)] f32, or 0
|
||||
* b [N][K] E4M3 codes, row-major, k contiguous
|
||||
* b_scale [ceil(N/pb1)][ceil(K/pb2)] bf16 (the container's weight_scale_inv) or f32, block-major
|
||||
* y [M][N] bf16, `y_ld` elements a row (0 = N)
|
||||
*
|
||||
* `group` is the code group along K (pb2, the checkpoint's block width); `pb1` the rows sharing a
|
||||
* scale row (0 = group). `sk` splits K (0 = the widest legal), `nt` the weight load's lowering,
|
||||
* `scratch` the f32 partial arena, sk * M * N * 4 bytes, required when the split is on. Returns 0,
|
||||
* -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 HIP failed. */
|
||||
extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M,
|
||||
int N, int K, int group, int pb1, int pb2, int a_ld, int y_ld,
|
||||
int sk, int nt, long scratch, int bs_dt, long stream)
|
||||
{
|
||||
if (!a || !b || !b_scale || !y) return -1;
|
||||
if (M < 1 || N < 1 || K < 1) return -2;
|
||||
if (M > kMTMax) return -2;
|
||||
if (group <= 0) group = R3D_FP8_BLOCK;
|
||||
if (pb1 <= 0) pb1 = group;
|
||||
if (pb2 == 0) pb2 = group;
|
||||
if (pb2 != group) return -2; // one block: the K block IS the code group
|
||||
if (group > kGroupMax) return -2;
|
||||
if (group % kStep) return -2; // a block must be whole lane steps
|
||||
if (K % group) return -2; // a ragged block reads past the scale plane
|
||||
const int nkb = K / group;
|
||||
if (!a_ld) a_ld = K;
|
||||
if (!y_ld) y_ld = N;
|
||||
const int a8 = a_scale != 0;
|
||||
if (a8 && (a_ld % 8)) return -3; // 8-byte code staging
|
||||
if (!a8 && (a_ld % 8)) return -3; // 16-byte widened staging
|
||||
if (sk == 0) sk = pick_sk(K, group, 16);
|
||||
if (sk < 1) return -2;
|
||||
if (K % ((long long)sk * group)) return -2;
|
||||
if (sk > 1 && !scratch) return -1;
|
||||
|
||||
const int bs16 = (bs_dt == RAD_BF16); /* anything else, 0 included, reads the plane as f32 */
|
||||
const int mt = M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax;
|
||||
const int kslab = K / sk;
|
||||
const int nrowb = (N + pb1 - 1) / pb1;
|
||||
if ((long long)nrowb * nkb <= 0) return -2;
|
||||
|
||||
#define R3D_Q_NT(MTV, A8V, NTV) \
|
||||
do { \
|
||||
const int nt_ = (N + (kWave / MTV) - 1) / (kWave / MTV); \
|
||||
const dim3 grid((nt_ + kWaves - 1) / kWaves, (unsigned)sk), dim3_blk(kBlockThreads); \
|
||||
if (sk > 1) { \
|
||||
R3D_KLAUNCH(R3D_KNAME((gemm_q_kernel<MTV, A8V, NTV, true>)), grid, dim3_blk, \
|
||||
(hipStream_t)stream, (const uint8_t*)a, (const float*)a_scale, \
|
||||
(const uint8_t*)b, (const void*)b_scale, bs16, (uint16_t*)y, \
|
||||
(float*)scratch, M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \
|
||||
const int mn = M * N; \
|
||||
const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \
|
||||
R3D_KLAUNCH(gemm_q_reduce, dim3(nb), dim3(kBlockThreads), (hipStream_t)stream, \
|
||||
(const float*)scratch, (uint16_t*)y, M, N, y_ld, sk); \
|
||||
} else { \
|
||||
R3D_KLAUNCH(R3D_KNAME((gemm_q_kernel<MTV, A8V, NTV, false>)), grid, dim3_blk, \
|
||||
(hipStream_t)stream, (const uint8_t*)a, (const float*)a_scale, \
|
||||
(const uint8_t*)b, (const void*)b_scale, bs16, (uint16_t*)y, \
|
||||
(float*)nullptr, M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \
|
||||
} \
|
||||
} while (0)
|
||||
#define R3D_Q_A8(MTV, A8V) do { if (nt) R3D_Q_NT(MTV, A8V, true); else R3D_Q_NT(MTV, A8V, false); } while (0)
|
||||
#define R3D_Q_MT(MTV) do { if (a8) R3D_Q_A8(MTV, true); else R3D_Q_A8(MTV, false); } while (0)
|
||||
switch (mt) {
|
||||
case 1: R3D_Q_MT(1); break;
|
||||
case 2: R3D_Q_MT(2); break;
|
||||
case 4: R3D_Q_MT(4); break;
|
||||
case 8: R3D_Q_MT(8); break;
|
||||
default: R3D_Q_MT(16); break;
|
||||
}
|
||||
#undef R3D_Q_MT
|
||||
#undef R3D_Q_A8
|
||||
#undef R3D_Q_NT
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* The declaration in r3d.h carries no scale dtype, and the weight's block scales are bf16 for the
|
||||
* whole quantised family (see the entry above), so the family needs a second spelling. `_ex` adds
|
||||
* `bs_dt`, the b_scale plane's RadDataType: RAD_BF16 reads it as bf16, anything else -- 0 included
|
||||
* -- reads it as f32, which is exactly what the entry below, and every caller written before the
|
||||
* bf16 discovery, asks for. The shim takes the dtype off the operand and calls `_ex`; the old entry
|
||||
* forwards, so a raw caller of the old name sees the behaviour it was written against. */
|
||||
extern "C" int r3d_gemm_nt_q_fp8(long a, long a_scale, long b, long b_scale, long y, int M, int N,
|
||||
int K, int group, int pb1, int pb2, int a_ld, int y_ld, int sk,
|
||||
int nt, long scratch, long stream)
|
||||
{
|
||||
return r3d_gemm_nt_q_fp8_ex(a, a_scale, b, b_scale, y, M, N, K, group, pb1, pb2, a_ld, y_ld, sk,
|
||||
nt, scratch, RAD_F32, stream);
|
||||
}
|
||||
|
||||
/* ============================================================== the plugin ABI entry point
|
||||
*
|
||||
* gemm_nt_q's operands are [a, a_scale, b, b_scale, y, a_sum?, b_ref?] and its parameters M, N, K,
|
||||
* group, dtype, pb1?, pb2?, split_n? (libref's pGemmQ/oGemmQ). */
|
||||
enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF };
|
||||
|
||||
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
|
||||
static int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
|
||||
/* The trace latch for this file: distinct GEMM shapes, printed once each. A static array and a
|
||||
* counter, no lock -- the flag is a diagnostic and a doubled line is a cosmetic cost, a lock in
|
||||
* the served path is not. */
|
||||
struct GemmPlanKey { long long M, N, K; unsigned a_rank, as_rank; long long a_ld, y_ld; };
|
||||
|
||||
static bool gemm_plan_once(long long M, long long N, long long K, unsigned a_rank,
|
||||
unsigned as_rank, long long a_ld, long long y_ld)
|
||||
{
|
||||
static GemmPlanKey seen[96];
|
||||
static int n = 0;
|
||||
for (int i = 0; i < n; ++i)
|
||||
if (seen[i].M == M && seen[i].N == N && seen[i].K == K && seen[i].a_rank == a_rank &&
|
||||
seen[i].as_rank == as_rank && seen[i].a_ld == a_ld && seen[i].y_ld == y_ld)
|
||||
return false;
|
||||
if (n < 96) seen[n++] = GemmPlanKey{M, N, K, a_rank, as_rank, a_ld, y_ld};
|
||||
return true;
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
|
||||
{
|
||||
const RadTensor* A = r3d_opt(a, Q_A);
|
||||
const RadTensor* AS = r3d_opt(a, Q_ASCALE);
|
||||
const RadTensor* B = r3d_opt(a, Q_B);
|
||||
const RadTensor* BS = r3d_opt(a, Q_BSCALE);
|
||||
const RadTensor* Y = r3d_opt(a, Q_Y);
|
||||
if (!A || !B || !BS || !Y) return R3D_NO(RAD_E_INVAL);
|
||||
/* The schemes this kernel decodes: E4M3 codes on the weight, bf16 activations (fp8a16) or
|
||||
* E4M3 codes with their own scale (fp8a8). E5M2 has no decoder here. */
|
||||
if (!r3d_is_e4m3(B)) return R3D_NO(RAD_E_DTYPE);
|
||||
/* The weight's block scales are bf16 for the whole quantised family -- the shape hook's
|
||||
* `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})` is the container's `weight_scale_inv`, and f32 is
|
||||
* the separate `fp8a8f32` spelling, which no row here claims (those bands stay with the
|
||||
* reference). Accept both; the kernel widens bf16 -> f32 at the load, exactly and for free. */
|
||||
const bool bs16 = r3d_is_bf16(BS);
|
||||
if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE);
|
||||
R3D_NEED(dt_bf16(Y));
|
||||
const bool a8 = AS != nullptr;
|
||||
if (a8) {
|
||||
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
|
||||
R3D_NEED(dt_f32(AS));
|
||||
} else {
|
||||
R3D_NEED(dt_bf16(A));
|
||||
}
|
||||
|
||||
const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1));
|
||||
const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2));
|
||||
if (K < 1 || N < 1) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long nel = r3d_numel(Y);
|
||||
if (nel < N || nel % N) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long M = nel / N; // never from the `M` parameter
|
||||
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* The block geometry, and the disagreement libref refuses: `group` is what the selector
|
||||
* matched on, and pb2 is the checkpoint's, and they describe the same bytes. */
|
||||
const long long group = r3d_geti_or(a, "group", R3D_FP8_BLOCK);
|
||||
const long long pb1 = r3d_geti_or(a, "pb1", group), pb2 = r3d_geti_or(a, "pb2", group);
|
||||
if (group != R3D_FP8_BLOCK) return R3D_NO(RAD_E_SHAPE);
|
||||
if (pb2 != 0 && pb2 != group) return R3D_NO(RAD_E_SHAPE);
|
||||
if (pb1 <= 0) return R3D_NO(RAD_E_SHAPE);
|
||||
if (K % group) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long nkb = (K + group - 1) / group, nrowb = (N + pb1 - 1) / pb1;
|
||||
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(BS) < nrowb * nkb) return R3D_NO(RAD_E_SHAPE);
|
||||
if (AS && r3d_numel(AS) < M * nkb) return R3D_NO(RAD_E_SHAPE);
|
||||
/* `a_sum` removes an activation zero point this grid does not have, and `b_ref` is an mxfp4
|
||||
* scale reference: libref refuses both beside these schemes (gemm_ntq_impl), so we do. */
|
||||
if (r3d_opt(a, Q_ASUM)) return R3D_NO(RAD_E_UNSUPPORTED);
|
||||
if (r3d_opt(a, Q_BREF)) return R3D_NO(RAD_E_UNSUPPORTED);
|
||||
|
||||
long long arows = 0, yrows = 0;
|
||||
const long long a_ld = r3d_rows_pitch(A, K, &arows);
|
||||
const long long y_ld = r3d_rows_pitch(Y, N, &yrows);
|
||||
if (a_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
|
||||
if (arows < M || yrows < M) return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_contig(B) || !r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE);
|
||||
if (AS && !r3d_contig(AS)) return R3D_NO(RAD_E_STRIDE);
|
||||
/* The scale planes have no pitch argument in the launcher, so they must be dense, and their
|
||||
* stated grid must be the one the kernel walks. */
|
||||
if (r3d_dim(BS, 1) != 0 && BS->shape[BS->rank - 1] != nkb && r3d_numel(BS) != nrowb * nkb)
|
||||
return R3D_NO(RAD_E_SHAPE);
|
||||
if ((a8 && (a_ld % 8)) || (!a8 && (a_ld % 8))) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
/* The plan's own numbers for the M<=16 band, under RAD_R3D_TRACE=1 and once per distinct
|
||||
* shape -- the same instrument the tiled row carries, in the row that serves the short steps.
|
||||
* It lives here because the served collapse begins at 15 prompt tokens, a step the tiled shim
|
||||
* never sees: the ladder's numbers below 17 are M=5..16 and the tiled row's line cannot speak
|
||||
* for them. M is derived off the activation's output the way the row derives it (line 430:
|
||||
* numel(y)/N, never the `M` parameter), and nothing is read that the checks above did not
|
||||
* already require. With the flag unset this is one cached getenv and a return: no copy, no
|
||||
* latch slot, no new operand read, no syscall. */
|
||||
if (r3d_trace_on() && gemm_plan_once(M, N, K, A->rank, AS ? AS->rank : 0u, a_ld, y_ld)) {
|
||||
std::fprintf(stderr, "[r3d] plan: gemm M=%lld (band M<=%d) N=%lld K=%lld group=%lld "
|
||||
"a rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld rows=%lld "
|
||||
"a_scale %s numel=%lld y rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld "
|
||||
"Mpad=%lld\n",
|
||||
M, kMTMax, N, K, group, (unsigned)A->rank, r3d_numel(A),
|
||||
r3d_dim(A, 0), r3d_dim(A, 1), a_ld, arows,
|
||||
AS ? "rank=2" : "absent (fp8a16, bf16 activations)",
|
||||
AS ? r3d_numel(AS) : 0LL, (unsigned)Y->rank, r3d_numel(Y), r3d_dim(Y, 0),
|
||||
r3d_dim(Y, 1), y_ld, (M + 15) / 16 * 16);
|
||||
r3d_trace_desc("gemm a", A);
|
||||
r3d_trace_desc("gemm y", Y);
|
||||
if (AS) r3d_trace_desc("gemm a_scale", AS);
|
||||
}
|
||||
|
||||
R3dGemmCfg c;
|
||||
r3d_cfg_gemm(a, &c);
|
||||
int sk = c.sk > 0 ? c.sk : pick_sk(K, (int)group, 16);
|
||||
if (sk > 16) return R3D_NO(RAD_E_SHAPE); // the scratch hook sizes for 16
|
||||
if (K % ((long long)sk * group)) return R3D_NO(RAD_E_SHAPE);
|
||||
if (sk > 1) {
|
||||
const long long need = (long long)sk * M * N * 4;
|
||||
if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH);
|
||||
}
|
||||
|
||||
const int e = r3d_gemm_nt_q_fp8_ex(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
|
||||
r3d_addr(Y), (int)M, (int)N, (int)K, (int)group, (int)pb1,
|
||||
(int)pb2, (int)a_ld, (int)y_ld, sk, c.nt,
|
||||
(long)(uintptr_t)(sk > 1 ? a->scratch : nullptr),
|
||||
(int)BS->dtype, /* bf16 weight_scale_inv or f32 */
|
||||
(long)(uintptr_t)s);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
|
||||
: e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
|
||||
}
|
||||
@@ -0,0 +1,678 @@
|
||||
/* r3d_gemm_fp8a8_gated.hip -- gemm_nt_q_gated: the gated MLP's GEMM, its gate and its quantiser in
|
||||
* one launch. 48 bands on one 2B model (N=12288 K=2048 group=128 dtype=fp8a8 act=silu, M=64 x47
|
||||
* and M=16), and the reason the [M, N] bf16 intermediate never exists.
|
||||
*
|
||||
* y[M,n] = gate(a[M,K] @ b[N,K]^T), quantised: n = N/2, gate half = b's rows [0, n),
|
||||
* up half = [n, N). `q` is E4M3 codes over y, `scale` one f32 per (row, `group` of n), and
|
||||
* `out_bf16`, when bound, is exactly the bf16 the codes were taken over.
|
||||
*
|
||||
* The law is ref_gemm_nt_q_gated and it is transcribed in its order:
|
||||
*
|
||||
* row[j] = quant_dot(ma, mb, SA, SB, m, j, K) over the FULL N, j ascending
|
||||
* gt = round_bf16(row[i]), up = round_bf16(row[n + i]) BOTH halves, before the gate
|
||||
* sg = 1 / (1 + exp(-gt)) the gate is the FIRST half
|
||||
* h = f32_to_bf16((act == silu ? gt * sg : sg) * up) the activation is not narrowed
|
||||
* fp8_row(h, n, group) amax -> scale[m, group], codes
|
||||
*
|
||||
* Both halves are narrowed before the gate because the unfused pair writes a bf16 [M, N] tensor and
|
||||
* re-reads it: the fused form must be byte-identical to the pair it replaces, so the narrowing that
|
||||
* the store performed is kept, and `out_bf16` is what the pair's tensor held. The activation itself
|
||||
* is NOT narrowed -- `gt * sg` is formed in f32 from the narrowed gate, and the product with `up`
|
||||
* rounds once, at the store.
|
||||
*
|
||||
* ---- the lane map: one lane owns a PAIR of dots -----------------------------------------------
|
||||
*
|
||||
* The gate couples column i with column n + i, and a wave covers 32 consecutive columns, so the
|
||||
* partner column is 192 waves away for the band's n = 6144: no lane-to-lane exchange reaches it, and
|
||||
* staging a whole row through LDS to reach it costs a round trip of the [M, N] tensor this op exists
|
||||
* to avoid. So the lane owns BOTH products of its column: it walks k ascending with two accumulators
|
||||
* and reads two weight rows, `i` and `n + i`. The weight traffic is unchanged -- the pair of rows is
|
||||
* exactly the traffic the unfused GEMM spent on the two columns -- and the coupling is free.
|
||||
*
|
||||
* A block covers ONE group of `group` output columns and RP = 256 / group rows, so a lane is
|
||||
*
|
||||
* i = blockIdx.x * group + (tid % group) m = blockIdx.y * RP + tid / group
|
||||
*
|
||||
* and a wave's 32 lanes are 32 consecutive columns of one group of one row, for group >= 32. That
|
||||
* alignment is what closes the epilogue inside the block: the group's amax is a wave max folded over
|
||||
* the group's group/32 waves in LDS, the scale is one store, the codes are one byte a lane. The
|
||||
* whole op -- product, gate, quantiser -- is one launch and no scratch, which is why the row is
|
||||
* concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`) and why the bf16 row of the
|
||||
* intermediate is not written, read, or allocated.
|
||||
*
|
||||
* ---- the two streams: fp8a8 at M <= 8 reads the codes, the rest stages them -------------------
|
||||
*
|
||||
* The band's served case is a decode: one row, the whole 12288 x 2048 operand, 42 calls a token.
|
||||
* The shape above is built for the band's declared ceiling (M = 64, 47 of the 48 bands) and serves
|
||||
* that height well; at M = 1 it spends 987 us on 24 MiB of codes, 25 GB/s, and the reason is not
|
||||
* the loads. It is the path a code takes: global -> LDS stage -> decode -> dot, with two
|
||||
* `group_barrier`s per k-block holding the block in step, and a decoder of ten VALU a code (RDNA3
|
||||
* has no fp8 instruction: r3d_codecs.h, and the builtins that look like one are rejected at
|
||||
* instruction selection on gfx1102).
|
||||
*
|
||||
* So the arm is chosen by the row count, in the launcher, from the same band key:
|
||||
*
|
||||
* M <= 8 and fp8a8 read the activation and both weight rows straight from memory, 16 bytes at
|
||||
* a time, decode them out of a 256-entry table the block builds once, and
|
||||
* multiply. No shared memory between a load and a dot, no barrier in the
|
||||
* k-loop, six loads in flight.
|
||||
* M >= 9, and every fp8a16 case the shape above, with the same table decoder in place of the
|
||||
* arithmetic one. At these heights the grid is 48 x M/2 blocks and occupancy,
|
||||
* not the window, is what feeds the stream; the stage pays for itself.
|
||||
*
|
||||
* Measured on the band, vram, GPU 2, nine launches timed on their own, best/median:
|
||||
*
|
||||
* M = 1 987.4 / 1154.9 -> 171.3 / 181.6 us (147 GB/s of codes; the card's 163 GB/s
|
||||
* M = 2 1120.6 / 1196.5 -> 166.2 / 177.1 us floor for 24 MiB is 154 us, and the same
|
||||
* M = 4 1417.3 / 1581.2 -> 221.0 / 229.6 us sixteen loads with no decode and no dot
|
||||
* M = 8 1874.0 / 2318.0 -> 403.4 / 412.3 us run in 139 us)
|
||||
* M = 16 2949.3 / 3226.1 -> 1055.0 / 1160.6 us
|
||||
* M = 32 5123.4 / 5405.1 -> 1660.6 / 1705.0 us
|
||||
* M = 64 8395.3 / 9051.0 -> 2786.5 / 2877.3 us
|
||||
*
|
||||
* The two numbers behind the shape, both from the band's own stream (24 MiB of codes, vram, 11
|
||||
* launches, this kernel's loop with the epilogue off): staged through LDS and decoded arithmetically
|
||||
* 497 us; read straight and decoded from the table 187 us; the read alone 139 us. The table alone
|
||||
* moves M = 64 from 8395 us to 2786 us -- two thirds of the tall arm's gain is the decoder, and it
|
||||
* costs nothing in registers (109 a lane, four waves a SIMD, zero spills).
|
||||
*
|
||||
* Two things in this file are load-bearing. The table's argument is a PAIR, not an index (see
|
||||
* build_e4m3_table). And the decoded pairs go from the table into the dot inline, never through an
|
||||
* array (see the tall arm's step_body).
|
||||
*
|
||||
* ---- where the scale multiplies -------------------------------------------------------------
|
||||
*
|
||||
* quant_dot, unchanged from r3d_gemm_fp8a16_nt_m1.hip: per group of k a sub-sum from zero over
|
||||
* ascending k of the CODES' products, then `acc = acc + (sub * sa) * sb` -- the parentheses are the
|
||||
* reference's, the scale multiplies the finished block once, and `sa` is `a_scale[m][gi]` (1 when
|
||||
* the activation carries no scale plane). Each lane's two chains are the two calls the unfused pair
|
||||
* makes, so the bracketing is the pair's, element for element.
|
||||
*
|
||||
* b_scale is bf16: this op's shape hook writes `o.t(RAD_BF16, {nb, kb})` with no f32 spelling, so
|
||||
* the plain entry reads the plane as bf16 and the `_ex` twin takes the dtype, as the fp8 GEMM's
|
||||
* does. bf16 -> f32 widening is exact, so an f32 plane carrying the same values must produce
|
||||
* bit-identical output; the driver tests exactly that.
|
||||
*
|
||||
* ---- the epilogue's one transcendental -------------------------------------------------------
|
||||
*
|
||||
* libref's sigmoid is `1.0f / (1.0f + (float)std::exp((double)(-x)))`. There is no f64 ALU on this
|
||||
* card (1:64, emulated), and the band asks for M*n = 393216 exponentials a layer, which is
|
||||
* attention's regime and not the sampler's. `expf` is the accurate device form, as in
|
||||
* r3d_gated_quant_fp8's kernel (r3d_quant_fp8.hip), not `__expf`; what it feeds is a bf16
|
||||
* narrowing, whose ulp is 2^-8 against the transcendental's ~1e-7, so the narrowing lands the same
|
||||
* bf16 everywhere but on a tie. The count of those ties is in the row's prose, measured.
|
||||
*
|
||||
* ---- what the launcher refuses ----------------------------------------------------------------
|
||||
*
|
||||
* M > 64 (the bands' ceiling, and past it the weight stream -- M reads of an [N, K] plane from L2 --
|
||||
* is the wall, which is a tiled kernel's problem, not this one's); N odd (the reference's own
|
||||
* `N & 1` test); a group that is not a power of two in [32, 256] (a wave must sit inside one group,
|
||||
* and the block is one group wide); group > n, where the reference defaults the QUANTISER's group to
|
||||
* n and leaves the weight's K block at the stated width: two widths this kernel reads as one, so it
|
||||
* refuses rather than serve a geometry whose two grids disagree; K % group != 0, because a ragged K
|
||||
* block reads past the scale plane; sk > 1, because no K slab closes an epilogue that needs the
|
||||
* whole row. Refusals are codes: -1 null, -2 shape, -3 pitch, -4 HIP.
|
||||
*
|
||||
* ---- relayout: none, and it is a claim ---------------------------------------------------------
|
||||
*
|
||||
* libref reads the gated weight [N, K] row-major; libr4d stores fp8a8 weights in WMMA fragment order
|
||||
* (`r4d.fp8.w.frag64`). The two readings are ~1.35 apart, a relative error, not noise, so this row
|
||||
* carries no relayout and says so: a row that inherits the fp8 GEMM's unrelayout scores 1.35 against
|
||||
* the per-op oracle and reads as a broken kernel. The stored order is the reading order here, which
|
||||
* is the library's rule for every row.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD spells
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_launch.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kBlockThreads = 256;
|
||||
constexpr int kWaves = kBlockThreads / kWave;
|
||||
constexpr int kStep = 16; // codes a lane takes per step: one 16-byte load
|
||||
constexpr int kWin = 64; // codes a lane takes per WINDOW: four loads per stream
|
||||
constexpr int kGroupMin = 32; // a wave's 32 columns must sit inside one group
|
||||
constexpr int kGroupMax = 256; // a block is one group wide, at 256 threads
|
||||
constexpr int kMMax = 64; // the bands' ceiling: 47 of the 48 are M = 64
|
||||
constexpr float kTopE4M3 = 448.0f; // q8_group's top for E4M3: the largest finite code
|
||||
|
||||
/* The E4M3 decoder as a table: 256 f16, one entry per code. The codec's arithmetic decode is ten
|
||||
* VALU a code (r3d_codecs.h -- RDNA3 has no fp8 instruction, and the builtins that look like one
|
||||
* are rejected at instruction selection), and this kernel decodes every weight code it multiplies,
|
||||
* twice over at RP = 2, which at M = 1 is every code in the operand. The table costs two
|
||||
* `ds_read_u16` and a pack a PAIR, and it is exact by construction: the entry for code c is the
|
||||
* dword the arithmetic path returns for c, computed by that path at the block's first instruction.
|
||||
* The unit test reads all 256 entries back and compares them with the codec. */
|
||||
__device__ __forceinline__ void build_e4m3_table(uint16_t* tab, uint32_t tid)
|
||||
{
|
||||
for (uint32_t u = tid; u < 128; u += kBlockThreads)
|
||||
/* The codec's argument is a PAIR, low code in the low byte; the entry is indexed by code.
|
||||
* Feeding it the index alone fills the even entries and decodes code 0 into every odd one,
|
||||
* so the kernel multiplies half the plane by zero -- the board's `codes256` case, whose
|
||||
* weight is the code enumeration, shows it: rel_l2 9.6e-01, not a NaN. */
|
||||
*(uint32_t*)&tab[2 * u] = e4m3x2_to_f16x2((u * 2) | ((u * 2 + 1) << 8));
|
||||
}
|
||||
|
||||
__device__ __forceinline__ uint32_t tab_pair(const uint16_t* tab, uint32_t pair)
|
||||
{
|
||||
const uint32_t lo = *(const uint16_t __attribute__((address_space(3))) *)(tab + (pair & 0xffu));
|
||||
const uint32_t hi = *(const uint16_t __attribute__((address_space(3))) *)(tab + (pair >> 8));
|
||||
return lo | (hi << 16);
|
||||
}
|
||||
|
||||
/* One step of the skinny arm: sixteen codes of activation and sixteen of weight, both coded, both
|
||||
* out of the same table. This is the whole of the reference's inner step -- `sub += a[k] * b[k]`,
|
||||
* k ascending -- with the pairs decoded as each dot consumes them. Four dot4, the pairs in order,
|
||||
* one accumulator; nothing about it depends on where the bytes came from. */
|
||||
__device__ __forceinline__ float dot_coded_step(const uint16_t* tab, const r3d_u32x4 a,
|
||||
const r3d_u32x4 c, float sub)
|
||||
{
|
||||
sub = dot4_f16x4(tab_pair(tab, a.x & 0xffffu), tab_pair(tab, a.x >> 16),
|
||||
tab_pair(tab, c.x & 0xffffu), tab_pair(tab, c.x >> 16), sub);
|
||||
sub = dot4_f16x4(tab_pair(tab, a.y & 0xffffu), tab_pair(tab, a.y >> 16),
|
||||
tab_pair(tab, c.y & 0xffffu), tab_pair(tab, c.y >> 16), sub);
|
||||
sub = dot4_f16x4(tab_pair(tab, a.z & 0xffffu), tab_pair(tab, a.z >> 16),
|
||||
tab_pair(tab, c.z & 0xffffu), tab_pair(tab, c.z >> 16), sub);
|
||||
sub = dot4_f16x4(tab_pair(tab, a.w & 0xffffu), tab_pair(tab, a.w >> 16),
|
||||
tab_pair(tab, c.w & 0xffffu), tab_pair(tab, c.w >> 16), sub);
|
||||
return sub;
|
||||
}
|
||||
|
||||
/* One step's sixteen codes into the accumulator: four dot4, the pairs decoded out of the table as
|
||||
* each dot consumes them. Materialising the eight pairs first and feeding the dots from the array
|
||||
* is what the register file cannot afford here: the scheduler hoists the sixteen table reads, so
|
||||
* all eight decoded pairs are live at once on top of the window's loads. Consuming a pair in the
|
||||
* dot that wants it keeps two registers live where the array keeps eight -- which is the
|
||||
* difference between this arm compiling at zero spills and spilling 374 bytes against the
|
||||
* 128-register budget a 256-thread block gets at four waves a SIMD. The order is unchanged: the
|
||||
* pairs ascend, four dot4 a step, into one accumulator. */
|
||||
__device__ __forceinline__ float dot_step(const uint16_t* tab, const r3d_u32x4 c,
|
||||
const r3d_u32x4 a0, const r3d_u32x4 a1, float sub)
|
||||
{
|
||||
sub = dot4_f16x4(a0.x, a0.y, tab_pair(tab, c.x & 0xffffu), tab_pair(tab, c.x >> 16), sub);
|
||||
sub = dot4_f16x4(a0.z, a0.w, tab_pair(tab, c.y & 0xffffu), tab_pair(tab, c.y >> 16), sub);
|
||||
sub = dot4_f16x4(a1.x, a1.y, tab_pair(tab, c.z & 0xffffu), tab_pair(tab, c.z >> 16), sub);
|
||||
sub = dot4_f16x4(a1.z, a1.w, tab_pair(tab, c.w & 0xffffu), tab_pair(tab, c.w >> 16), sub);
|
||||
return sub;
|
||||
}
|
||||
|
||||
|
||||
template <bool NT>
|
||||
__device__ __forceinline__ r3d_u32x4 ldc(const uint8_t* p) // 16 codes
|
||||
{
|
||||
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
|
||||
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p) { return *(const r3d_u32x4*)p; }
|
||||
|
||||
/* q8_group's clamp, with q8_group's comparisons: fminf/fmaxf replace a NaN with the bound, and a NaN
|
||||
* activation is a value the reference encodes as the format's NaN, not as +-top. */
|
||||
__device__ __forceinline__ float clamp_top(float c)
|
||||
{
|
||||
if (c > kTopE4M3) c = kTopE4M3;
|
||||
if (c < -kTopE4M3) c = -kTopE4M3;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* y[M,n] = gate(a @ b^T), with the quantiser. GROUP is the block's width in output columns AND the
|
||||
* weight's K block AND the quantiser's group: one `group` parameter, three grids, which is what the
|
||||
* op states: kb, nb and ng are derived from the one key. ACT is the gate, A8 the coded activation,
|
||||
* NT the weight load's lowering.
|
||||
*
|
||||
* The activation is staged in LDS per K block, widened to f16 pairs on the way in -- E4M3 -> f16 and
|
||||
* bf16 -> f16 are both exact over f16's normal range. A block stages RP * GROUP values, 512 bytes at
|
||||
* every supported GROUP, and a wave reads its row's 16 values per step as one broadcast ds_read: all
|
||||
* 32 lanes of a wave own the same m, so all 32 read the same address. The weight is not staged: a
|
||||
* lane streams two rows of it and no other lane reads them with it. */
|
||||
template <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,
|
||||
const uint8_t* __restrict__ B, const void* __restrict__ BScale, int bs16,
|
||||
uint8_t* __restrict__ Q, float* __restrict__ S, uint16_t* __restrict__ Y,
|
||||
int M, int N, int K, int a_ld, int q_ld, int y_ld, int nkb, int ng)
|
||||
{
|
||||
constexpr int RP = kBlockThreads / GROUP; // rows a block carries
|
||||
constexpr int AP = GROUP / 2; // dwords a staged activation row (f16 pairs)
|
||||
constexpr int WPG = GROUP / kWave; // waves covering one group of columns
|
||||
static_assert(RP >= 1 && WPG >= 1 && RP * WPG == kWaves, "a block is one group wide");
|
||||
|
||||
__shared__ uint32_t s_a[RP * AP];
|
||||
__shared__ float s_mx[kWaves];
|
||||
__shared__ uint16_t s_tab[256];
|
||||
|
||||
const uint32_t tid = threadIdx.x;
|
||||
const uint32_t lane = tid & (kWave - 1);
|
||||
const uint32_t wave = tid / kWave;
|
||||
|
||||
/* The block's decoder, filled before any lane reads it: 128 dwords, one per pair of codes, by
|
||||
* the codec's own arithmetic. The cost is 128 decodes a block -- at the band's M = 64 that is
|
||||
* 0.02% of the block's decodes, and at M = 1 it is paid once per block for 128 codes x 16 k
|
||||
* blocks of table reads. */
|
||||
build_e4m3_table(s_tab, tid);
|
||||
group_barrier();
|
||||
|
||||
const uint32_t gidx = blockIdx.x; // the group of output columns
|
||||
const uint32_t mloc = tid / GROUP; // this lane's row within the block
|
||||
const uint32_t i = gidx * GROUP + (tid % GROUP); // the fused column
|
||||
const uint32_t m = (uint32_t)blockIdx.y * RP + mloc;
|
||||
|
||||
const int n = N / 2;
|
||||
/* A ragged last group runs past n: the pair's rows are clamped, so no lane reads past the weight
|
||||
* plane, and its stores are guarded below. A row past M re-reads the last real row. */
|
||||
const int i_real = (int)(i < (uint32_t)n ? i : (uint32_t)(n - 1));
|
||||
const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1));
|
||||
|
||||
const uint8_t* wg = B + (size_t)i_real * K; // the gate's row
|
||||
const uint8_t* wu = B + (size_t)(n + i_real) * K; // the up's row, n rows further on
|
||||
/* b_scale is [ceil(N/group)][ceil(K/group)]: make_scales gives rblk = group (fewer scale rows
|
||||
* than operand rows is a block grid), so a row's scale row is its row index over the block. */
|
||||
const size_t bsg = (size_t)((uint32_t)i_real / GROUP) * (size_t)nkb;
|
||||
const size_t bsu = (size_t)((uint32_t)(n + i_real) / GROUP) * (size_t)nkb;
|
||||
const float* bsF = bs16 ? nullptr : (const float*)BScale;
|
||||
const uint16_t* bsH = bs16 ? (const uint16_t*)BScale : nullptr;
|
||||
const float* as = A8 ? AScale + (size_t)m_real * nkb : nullptr;
|
||||
|
||||
float acc_g = 0.0f, acc_u = 0.0f;
|
||||
|
||||
/* One scale block per round, `nkb` of them: stage the block's activation, walk the block's k
|
||||
* with two chains, fold the block's two scales in at the block's end. K is a multiple of GROUP,
|
||||
* which the launcher requires, so every block is whole and the staging loop has no tail. */
|
||||
/* The skinny arm's activation pointer: the row, in bytes. */
|
||||
const uint8_t* ar = (A8 && WIN) ? (const uint8_t*)A + (size_t)m_real * a_ld : nullptr;
|
||||
|
||||
for (int kb = 0; kb < K; kb += GROUP) {
|
||||
const int gi = kb / GROUP;
|
||||
/* The staged round, and the barrier around it, belong to the tall arms. At the skinny height
|
||||
* -- M <= 8, the threshold `R3D_GT_G` selects on, 16 KiB of activation at the band's K --
|
||||
* the whole activation is M*K bytes and the 48 column groups of a row all
|
||||
* read the same slice of it, so it lives in L1 from the first k-block on and staging it
|
||||
* through shared memory buys nothing but a barrier a block a k-block. The numbers: the
|
||||
* same stream read straight from memory 187 us, the same stream staged through LDS 497 us,
|
||||
* at 48 blocks, 24 MiB of codes, on a part of this family. */
|
||||
if constexpr (!WIN) {
|
||||
constexpr int kUnit = 8; // codes (fp8a8) or elements (bf16) a unit
|
||||
constexpr int nu = GROUP / kUnit;
|
||||
#pragma unroll
|
||||
for (int u = (int)tid; u < RP * nu; u += kBlockThreads) {
|
||||
const int r = u / nu, c = (u % nu) * kUnit;
|
||||
const int rm = (int)((uint32_t)blockIdx.y * RP + (uint32_t)r);
|
||||
const int rr = rm < M ? rm : M - 1;
|
||||
uint32_t* dst = s_a + (size_t)r * AP + c / 2;
|
||||
if constexpr (A8) {
|
||||
const r3d_u32x2 b8 = *(const __attribute__((address_space(1))) r3d_u32x2*)(
|
||||
A + (size_t)rr * a_ld + kb + c);
|
||||
dst[0] = e4m3x2_to_f16x2(b8.x & 0xffffu);
|
||||
dst[1] = e4m3x2_to_f16x2(b8.x >> 16);
|
||||
dst[2] = e4m3x2_to_f16x2(b8.y & 0xffffu);
|
||||
dst[3] = e4m3x2_to_f16x2(b8.y >> 16);
|
||||
} else {
|
||||
/* Cast to the element pointer FIRST: the row and k offsets are ELEMENT offsets,
|
||||
* which for bf16 is twice the byte count (r3d_gemm_fp8a16_nt_m1.hip). */
|
||||
const r3d_u32x4 b16 = *(const __attribute__((address_space(1))) r3d_u32x4*)(
|
||||
(const uint16_t*)A + (size_t)rr * a_ld + kb + c);
|
||||
dst[0] = bf16x2_to_f16x2(b16.x);
|
||||
dst[1] = bf16x2_to_f16x2(b16.y);
|
||||
dst[2] = bf16x2_to_f16x2(b16.z);
|
||||
dst[3] = bf16x2_to_f16x2(b16.w);
|
||||
}
|
||||
}
|
||||
group_barrier();
|
||||
|
||||
}
|
||||
|
||||
const uint32_t* ap = s_a + (size_t)mloc * AP;
|
||||
/* One chain at a time. The gate's product, k ascending into `sub_g`, then the up's into
|
||||
* `sub_u` -- the two chains are the two calls the unfused pair makes, they share nothing,
|
||||
* and each one's bracketing is that call's, element for element.
|
||||
*
|
||||
* Sequencing them, rather than interleaving them step by step, is what the register file
|
||||
* asks for. The window is eight 16-byte loads a stream; holding both streams' windows
|
||||
* live at once is 64 registers of loads on top of the decode's temporaries, the staged
|
||||
* activation's reads, the two accumulators and the block's pointers, and at 256 threads
|
||||
* (four waves a SIMD, 128 registers a lane) it spills 365 bytes. One chain's window is
|
||||
* 32 registers, and the arm compiles clean.
|
||||
*
|
||||
* On the band's stream -- 24 MiB of codes, vram, 11 launches, GPU 2, this kernel's loop
|
||||
* with the epilogue off: 16-byte step with the arithmetic decoder 584 us; table decoder,
|
||||
* same step 453 us; table, window 64 283 us; table, window 128 187 us; the same sixteen
|
||||
* loads with no decode and no dot 139 us. The op without the table decoder and the window
|
||||
* spends 1474 us a call. */
|
||||
float sub_g, sub_u;
|
||||
if constexpr (WIN) {
|
||||
/* The skinny arm, M <= 8 (the threshold `R3D_GT_G` selects on): read the codes, decode
|
||||
* them out of the block's table, multiply
|
||||
* them. No shared memory between the load and the dot, and no barrier in the k-loop --
|
||||
* the two chains, gate then up, k ascending inside each, the scales folded at the block's
|
||||
* end, the epilogue below untouched.
|
||||
*
|
||||
* Three loads a step, sixteen bytes each: the activation's sixteen codes, the gate's,
|
||||
* the up's. Six of them are in flight at the depth below, against the 163 GB/s the card
|
||||
* does; the tall arms feed the same stream with occupancy, at 32 waves a CU.
|
||||
*
|
||||
* On this band's stream (24 MiB of codes, vram, 11 launches, GPU 2, epilogue off):
|
||||
* the staged shape 497 us; the same codes read straight 187 us; the same sixteen loads
|
||||
* with no decode and no dot 139 us. The op without the table decoder and the window
|
||||
* spends 1474 us a call. */
|
||||
constexpr int kNS = GROUP / kStep; // steps a block
|
||||
constexpr int kD = 2; // loads a chain in flight
|
||||
auto chain = [&](const uint8_t* w, float sub) {
|
||||
auto ld = [&](int st) {
|
||||
return ldc<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. */
|
||||
r3d_u32x4 c0 = ld(0), c1 = ld(1);
|
||||
#pragma unroll
|
||||
for (int st = 0; st < kNS; st += kD) {
|
||||
__builtin_amdgcn_sched_barrier(0);
|
||||
const r3d_u32x4 a0 = ldc<NT>(ar + kb + (st + 0) * kStep);
|
||||
const r3d_u32x4 a1 = ldc<NT>(ar + kb + (st + 1) * kStep);
|
||||
const r3d_u32x4 n0 = ld(st + kD + 0), n1 = ld(st + kD + 1);
|
||||
sub = dot_coded_step(s_tab, a0, c0, sub);
|
||||
sub = dot_coded_step(s_tab, a1, c1, sub);
|
||||
c0 = n0;
|
||||
c1 = n1;
|
||||
}
|
||||
return sub;
|
||||
};
|
||||
sub_g = chain(wg, 0.0f);
|
||||
sub_u = chain(wu, 0.0f);
|
||||
} else {
|
||||
/* The tall arms: one 16-code step a round, both streams in the same round.
|
||||
* At M >= 8 the block grid is 48 x M/2 blocks, the wave slots are full, and the stream
|
||||
* is fed by occupancy -- 109 registers a lane, four waves a SIMD, 32 waves a CU. The
|
||||
* window is a skinny-arm fix: it buys its loads per lane at 32 registers, which on
|
||||
* this arm is a fifth wave a SIMD given up, and on the 47 bands at M = 64 that is the
|
||||
* whole op. Measured: windowed at M = 64 costs more than it saves. */
|
||||
sub_g = 0.0f;
|
||||
sub_u = 0.0f;
|
||||
/* The round's unroll depth is a register decision, and at group = 32 it is the whole
|
||||
* decision: the block is two steps wide, so `unroll 2` is a full unroll, the scheduler
|
||||
* takes all thirty-two table reads of the two chains and hoists them above the dots,
|
||||
* and the arm lands at 128 registers with 12 spilled (the same arm at group >= 64, in
|
||||
* the same file, is 106 to 112 with none). Left as a loop the body is one step. */
|
||||
/* Inline, from the table into the dot, on purpose. Materialising the eight decoded
|
||||
* pairs into an array on the way -- the shape the arithmetic decoder above feeds --
|
||||
* puts the plane about a third away from the reference at every tall height (M = 7:
|
||||
* rel_l2 6.6e-01; M = 64: -nan), with the table itself exact on the device, entry by
|
||||
* entry and pair by pair. The array form is the one that miscomputes here; do not
|
||||
* restore it as a tidy-up. */
|
||||
auto step_body = [&](int k) {
|
||||
const r3d_u32x4 a0 = lds_a(ap + k / 2);
|
||||
const r3d_u32x4 a1 = lds_a(ap + k / 2 + 4);
|
||||
sub_g = dot_step(s_tab, ldc<NT>(wg + kb + k), a0, a1, sub_g);
|
||||
sub_u = dot_step(s_tab, ldc<NT>(wu + kb + k), a0, a1, sub_u);
|
||||
};
|
||||
if constexpr (GROUP <= 32) {
|
||||
#pragma unroll 1
|
||||
for (int k = 0; k < GROUP; k += kStep) step_body(k);
|
||||
} else {
|
||||
#pragma unroll 2
|
||||
for (int k = 0; k < GROUP; k += kStep) step_body(k);
|
||||
}
|
||||
}
|
||||
if constexpr (!WIN)
|
||||
group_barrier(); // the next block's stage must not race this one's reads
|
||||
|
||||
/* The two finished sub-sums, each scaled once, in libref's parentheses. */
|
||||
const float sa = A8 ? as[gi] : 1.0f;
|
||||
acc_g = acc_g + (sub_g * sa) * (bs16 ? bf16_to_f32(bsH[bsg + gi]) : bsF[bsg + gi]);
|
||||
acc_u = acc_u + (sub_u * sa) * (bs16 ? bf16_to_f32(bsH[bsu + gi]) : bsF[bsu + gi]);
|
||||
}
|
||||
|
||||
/* ---- the epilogue: narrow both halves, gate, quantise the group -------------------------- */
|
||||
const float gt = bf16_to_f32(f32_to_bf16(acc_g));
|
||||
const float up = bf16_to_f32(f32_to_bf16(acc_u));
|
||||
const float sg = 1.0f / (1.0f + expf(-gt));
|
||||
const uint16_t h = f32_to_bf16((ACT == R3D_ACT_SILU ? gt * sg : sg) * up);
|
||||
|
||||
const bool keep = (i < (uint32_t)n) && (m < (uint32_t)M);
|
||||
if (keep && Y) Y[(size_t)m * y_ld + i] = h;
|
||||
/* A column past n, and a row past M, contribute 0.0f: padding takes no part in the amax and
|
||||
* takes no store, which is quant_act_fp8's rule for a ragged row. */
|
||||
const float am = keep ? fabsf(bf16_to_f32(h)) : 0.0f;
|
||||
|
||||
float mx = wave_max(am); // fmaxf skips a NaN, as `if (m > amax)` does
|
||||
if (lane == 0) s_mx[wave] = mx;
|
||||
group_barrier();
|
||||
mx = s_mx[mloc * WPG];
|
||||
#pragma unroll
|
||||
for (int w = 1; w < WPG; ++w) mx = fmaxf(mx, s_mx[mloc * WPG + w]);
|
||||
|
||||
const float sc = mx > 0.0f ? mx * (1.0f / kTopE4M3) : 1.0f;
|
||||
/* One store per (row, group): the group's WPG waves all hold the same max, so the first writes
|
||||
* and the rest stand down. `scale` is dense -- the launcher takes no pitch for it -- so a row is
|
||||
* `ng` scales and the group index is the block's. */
|
||||
if (keep && lane == 0 && (wave % WPG) == 0) S[(size_t)m * ng + gidx] = sc;
|
||||
|
||||
if (keep) {
|
||||
const float inv = 1.0f / sc;
|
||||
Q[(size_t)m * q_ld + i] = f32_to_e4m3(clamp_top(bf16_to_f32(h) * inv));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* y[M,n] = gate(a[M,K] @ dequant(b)[N,K]^T), E4M3 codes out, n = N/2 inside.
|
||||
*
|
||||
* a [M][K] E4M3 codes (fp8a8, with `a_scale`) or bf16 (fp8a16)
|
||||
* a_scale [M][ceil(K/group)] f32, dense, or 0
|
||||
* b [N][K] E4M3 codes, row-major, k contiguous: gate rows [0,n), up rows
|
||||
* [n,N)
|
||||
* b_scale [ceil(N/group)][ceil(K/group)] bf16 (the op's stated dtype) or f32, block-major
|
||||
* q [M][n] E4M3 codes, `q_ld` elements a row (0 = n)
|
||||
* scale [M][ceil(n/group)] f32, DENSE (no pitch is taken)
|
||||
* out_bf16 [M][n] bf16, `y_ld` elements a row (0 = n), optional: the pre-gate...
|
||||
* the gated bf16 tensor the codes were taken over
|
||||
*
|
||||
* `group` is the weight's K block, the weight's row block and the output quantiser's group at once,
|
||||
* which is what the op's single key states; 0 takes the checkpoint's 128. `act` is R3D_ACT_SILU
|
||||
* (down_proj's input) or R3D_ACT_SIGMOID (a gated attention o_proj's). `sk` is accepted as 0/1 and
|
||||
* refused above it: the epilogue needs a whole row. `nt` selects the weight load's lowering.
|
||||
* `scratch` is unused -- the op needs no arena, which is what keeps the row concurrent.
|
||||
*
|
||||
* Returns 0, -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 HIP
|
||||
* failed. */
|
||||
extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale, long q, long scale,
|
||||
long out_bf16, int M, int N, int K, int group, int act,
|
||||
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
|
||||
int bs_dt, long stream)
|
||||
{
|
||||
if (!a || !b || !b_scale || !q || !scale) return -1;
|
||||
if (M < 1 || N < 2 || (N & 1) || K < 1) return -2;
|
||||
if (M > kMMax) return -2;
|
||||
if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return -2;
|
||||
const int n = N / 2;
|
||||
if (group <= 0) group = R3D_FP8_BLOCK;
|
||||
if (group > n) return -2; // two grids, one key: see the header
|
||||
if (group < kGroupMin || group > kGroupMax || (group & (group - 1))) return -2;
|
||||
if (K % group) return -2; // a ragged block reads past the scales
|
||||
const int nkb = K / group, ng = (n + group - 1) / group;
|
||||
if (!a_ld) a_ld = K;
|
||||
if (!q_ld) q_ld = n;
|
||||
if (!y_ld) y_ld = n;
|
||||
if (a_ld % 8) return -3; // 8-code (and 8-element) staging
|
||||
if (sk == 0) sk = 1;
|
||||
if (sk > 1) return -2; // no K slab closes this epilogue
|
||||
(void)scratch;
|
||||
|
||||
const int bs16 = (bs_dt == RAD_BF16); /* anything else, 0 included, reads the plane as f32 */
|
||||
const int a8 = a_scale != 0;
|
||||
const int rp = kBlockThreads / group;
|
||||
const dim3 grid((unsigned)ng, (unsigned)((M + rp - 1) / rp)), blk(kBlockThreads);
|
||||
|
||||
/* The skinny arms -- the decode's height -- take the windowed stream; the tall arms keep
|
||||
* the step. One number, two kernels, and the band key that names them is the same one.
|
||||
*
|
||||
* M <= 8 is the shipped threshold and it is a tunable, not a fact. With the table decoder in both
|
||||
* arms, N=12288 K=2048 group=128 vram: at M=8 skinny 402 against staged 754, at M=16 skinny 955
|
||||
* against staged 1030 -- so the crossover is above 16; M=9..15 is unmeasured. Decode lives at M=1
|
||||
* and a draft's verify at M<=8, which is what the threshold is chosen for; a prefill at 9..16 rows
|
||||
* would take the skinny arm on the M=16 numbers, for about 7%. */
|
||||
#define R3D_GT_G(G, A, A8, NTV) \
|
||||
do { \
|
||||
if (A8 && M <= 8) R3D_GT_W(G, A, A8, NTV, true); \
|
||||
else R3D_GT_W(G, A, A8, NTV, false); \
|
||||
} while (0)
|
||||
#define R3D_GT_W(G, A, A8, NTV, WV) \
|
||||
R3D_KLAUNCH(R3D_KNAME((gated_kernel<G, A, A8, NTV, WV>)), grid, blk, (hipStream_t)stream, \
|
||||
(const uint8_t*)a, (const float*)a_scale, (const uint8_t*)b, \
|
||||
(const void*)b_scale, bs16, (uint8_t*)q, (float*)scale, (uint16_t*)out_bf16, \
|
||||
M, N, K, a_ld, q_ld, y_ld, nkb, ng)
|
||||
#define R3D_GT_NT(G, A, A8) do { if (nt) R3D_GT_G(G, A, A8, true); else R3D_GT_G(G, A, A8, false); } while (0)
|
||||
#define R3D_GT_A8(G, A) do { if (a8) R3D_GT_NT(G, A, true); else R3D_GT_NT(G, A, false); } while (0)
|
||||
#define R3D_GT_ACT(G) do { if (act == R3D_ACT_SILU) R3D_GT_A8(G, R3D_ACT_SILU); \
|
||||
else R3D_GT_A8(G, R3D_ACT_SIGMOID); } while (0)
|
||||
#define R3D_GT(G) do { switch (group) { case G: R3D_GT_ACT(G); break; default: break; } } while (0)
|
||||
R3D_GT(32);
|
||||
R3D_GT(64);
|
||||
R3D_GT(128);
|
||||
R3D_GT(256);
|
||||
#undef R3D_GT
|
||||
#undef R3D_GT_ACT
|
||||
#undef R3D_GT_A8
|
||||
#undef R3D_GT_NT
|
||||
#undef R3D_GT_W
|
||||
#undef R3D_GT_G
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* The declaration in r3d.h carries no scale dtype, and this op's shape hook states bf16 -- the hook
|
||||
* has no f32 spelling at all -- so the plain entry reads bf16 and the `_ex` twin above carries the
|
||||
* key. A caller with an f32 scale plane (the `fp8a8f32` reading of the unfused GEMM) lands on `_ex`
|
||||
* with RAD_F32; the kernel widens bf16 -> f32 exactly, so the two agree to the bit. */
|
||||
extern "C" int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, long q, long scale,
|
||||
long out_bf16, int M, int N, int K, int group, int act,
|
||||
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
|
||||
long stream)
|
||||
{
|
||||
return r3d_gemm_nt_q_gated_ex(a, a_scale, b, b_scale, q, scale, out_bf16, M, N, K, group, act,
|
||||
a_ld, q_ld, y_ld, sk, nt, scratch, RAD_BF16, stream);
|
||||
}
|
||||
|
||||
/* ============================================================== the plugin ABI entry point
|
||||
*
|
||||
* gemm_nt_q_gated's operands are [a, a_scale, b, b_scale, q, scale, out_bf16?] and its parameters
|
||||
* M, N, K, group, dtype, act (libref's pGemmQGated/oGemmQGated: `act` REQUIRED, `a_scale` REQUIRED,
|
||||
* `out_bf16` optional). The shape hook declines every scheme but fp8a8, so the row binds fp8a8 and
|
||||
* the shim reads the coded activation off the operands. */
|
||||
enum { G_A = 0, G_ASCALE, G_B, G_BSCALE, G_Q, G_SCALE, G_OB };
|
||||
|
||||
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
|
||||
static int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
static int dt_e4m3(const RadTensor* t) { return r3d_is_e4m3(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
|
||||
extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
|
||||
{
|
||||
const RadTensor* A = r3d_opt(a, G_A);
|
||||
const RadTensor* AS = r3d_opt(a, G_ASCALE);
|
||||
const RadTensor* B = r3d_opt(a, G_B);
|
||||
const RadTensor* BS = r3d_opt(a, G_BSCALE);
|
||||
const RadTensor* Q = r3d_opt(a, G_Q);
|
||||
const RadTensor* SC = r3d_opt(a, G_SCALE);
|
||||
const RadTensor* OB = r3d_opt(a, G_OB);
|
||||
if (!A || !B || !BS || !Q || !SC) return R3D_NO(RAD_E_INVAL);
|
||||
if (!r3d_is_e4m3(B)) return R3D_NO(RAD_E_DTYPE);
|
||||
R3D_NEED(dt_e4m3(Q));
|
||||
R3D_NEED(dt_f32(SC));
|
||||
if (OB) R3D_NEED(dt_bf16(OB));
|
||||
/* The activation: E4M3 codes with a per-(row, group) f32 scale (fp8a8, the scheme this op's
|
||||
* shape hook and every band states), or bf16 with no scale (fp8a16, which the hook declines, so
|
||||
* no band arrives: the kernel carries the path because the launcher does, and the shim accepts
|
||||
* it on the operands). E5M2 has no decoder here. */
|
||||
const bool a8 = AS != nullptr;
|
||||
if (a8) {
|
||||
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
|
||||
R3D_NEED(dt_f32(AS));
|
||||
} else {
|
||||
R3D_NEED(dt_bf16(A));
|
||||
}
|
||||
/* b_scale is bf16 -- `o.t(RAD_BF16, {nb, kb})` is this op's own line in the hook, and the
|
||||
* container's `weight_scale_inv` for the whole quantised family. f32 is accepted because the
|
||||
* widening is exact and the kernel reads both: the driver's bf16/f32 pair must agree element
|
||||
* for element. */
|
||||
const bool bs16 = r3d_is_bf16(BS);
|
||||
if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
/* `act` is required by the schema (P_STR, not P_STRO): an implementation may compile one gate,
|
||||
* and an optional parameter would let the row resolve for the other. libref's default is -1 and
|
||||
* it refuses it; so does this shim, with no `mode` integer spelling to fall back on. */
|
||||
const int act = r3d_act_code(a, "act", nullptr, -1);
|
||||
if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return R3D_NO(RAD_E_INVAL);
|
||||
|
||||
const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1));
|
||||
const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2));
|
||||
if (K < 1 || N < 2 || (N & 1)) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long n = N / 2;
|
||||
|
||||
/* Rows come from `q`, never from the `M` parameter, which is the band's upper bound. libref
|
||||
* reads numel(q) / n; on a plane whose pitch exceeds n that counts the padding, so the shape's
|
||||
* own row count clamps it. A dense plane -- every case the fixture draws -- reads the same
|
||||
* number either way. */
|
||||
const long long qnel = r3d_numel(Q);
|
||||
if (qnel < n || qnel % n) return R3D_NO(RAD_E_SHAPE);
|
||||
long long M = qnel / n;
|
||||
if (Q->rank >= 2 && r3d_dim(Q, (int)Q->rank - 2) < M) M = r3d_dim(Q, (int)Q->rank - 2);
|
||||
if (M < 1 || M > kMMax) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* The group: the weight's K block, the weight's row block and the quantiser's group, from the
|
||||
* one key the op states. The reference defaults 0 to `group`-as-stated for the grids and
|
||||
* `g > n` to n for the quantiser alone; this kernel reads one width, so a group wider than the
|
||||
* fused width is refused rather than served on a grid the two sides do not share. */
|
||||
const long long group = r3d_geti_or(a, "group", R3D_FP8_BLOCK);
|
||||
if (group < kGroupMin || group > kGroupMax || (group & (group - 1))) return R3D_NO(RAD_E_SHAPE);
|
||||
if (group > n) return R3D_NO(RAD_E_SHAPE);
|
||||
if (K % group) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long nkb = K / group, nb = (N + group - 1) / group, ng = (n + group - 1) / group;
|
||||
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(BS) < nb * nkb) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(SC) < M * ng) return R3D_NO(RAD_E_SHAPE);
|
||||
if (AS && r3d_numel(AS) < M * nkb) return R3D_NO(RAD_E_SHAPE);
|
||||
if (OB && r3d_numel(OB) < M * n) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
long long arows = 0, qrows = 0, srows = 0, yrows = 0;
|
||||
const long long a_ld = r3d_rows_pitch(A, K, &arows);
|
||||
const long long q_ld = r3d_rows_pitch(Q, n, &qrows);
|
||||
const long long y_ld = OB ? r3d_rows_pitch(OB, n, &yrows) : n;
|
||||
if (a_ld < 0 || q_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
|
||||
/* `yrows` is only a promise when the plane is there. `r3d_rows_pitch` leaves the count at zero
|
||||
* for a null operand, and an absent optional output is a null operand by contract (r3d_args.h),
|
||||
* so testing `yrows` unconditionally reads "the row is missing" from "the caller asked for no
|
||||
* bf16 mirror". */
|
||||
if (arows < M || qrows < M || (OB && yrows < M)) return R3D_NO(RAD_E_SHAPE);
|
||||
if (a_ld % 8) return R3D_NO(RAD_E_STRIDE); // 8-code / 8-element staging
|
||||
/* The scale planes travel without a pitch argument, so they must be dense, and `scale`'s grid
|
||||
* must be the one the kernel walks: `ng` scales a row. */
|
||||
if (!r3d_contig(B) || !r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE);
|
||||
if (AS && !r3d_contig(AS)) return R3D_NO(RAD_E_STRIDE);
|
||||
if (r3d_rows_pitch(SC, ng, &srows) != ng) return R3D_NO(RAD_E_STRIDE);
|
||||
if (srows < M) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_dim(BS, 1) != 0 && BS->shape[BS->rank - 1] != nkb && r3d_numel(BS) != nb * nkb)
|
||||
return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
R3dGemmCfg c;
|
||||
r3d_cfg_gemm(a, &c);
|
||||
/* Split-K is the axis this kernel cannot honour: a K slab produces a partial product, and the
|
||||
* epilogue needs the finished row -- its bf16 narrowing, the gate's partner column, the group's
|
||||
* amax. A caller that states sk > 1 is refused here, at the row, not answered slowly. */
|
||||
if (c.sk > 1) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
const int e = r3d_gemm_nt_q_gated_ex(
|
||||
r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(Q), r3d_addr(SC),
|
||||
r3d_addr(OB), (int)M, (int)N, (int)K, (int)group, act, (int)a_ld, (int)q_ld, (int)y_ld, 1,
|
||||
c.nt, 0L, (int)BS->dtype, (long)(uintptr_t)s);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
|
||||
: e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,431 @@
|
||||
/* r3d_gemm_inta8.hip -- gemm_nt_q at dtype=w4a8 and w8a8: the symmetric int4 and int8 weight
|
||||
* grids at decode heights, one kernel per grid.
|
||||
*
|
||||
* The grids, libref's descriptions: int8 activations in quant_act_i8's step order against
|
||||
* signed weight codes (I4, two a byte, or I8, one a byte) with one f16 scale per (row, 128 of
|
||||
* K), an f32 activation scale per row, and no zero point -- the dequant is code times scale,
|
||||
* so there is no a_sum to carry and no bias to take off. The group sub-sum is formed on the
|
||||
* integer grid and scaled once per group, the reference's order:
|
||||
*
|
||||
* sub = sum over the group of a * code, an exact integer
|
||||
* acc += (sub * a_scale[m]) * scale[n, g]
|
||||
*
|
||||
* ---- exactness, and why the dots may run in f16 --------------------------------------------------
|
||||
*
|
||||
* A lane's 64 products are |a * code| <= 127 * 7 (w4a8) or 127 * 127 (w8a8), and the group's
|
||||
* 128 of them sum to 113,792 (w4a8) or 2,064,512 (w8a8): both under 2^24, the f32 mantissa, so
|
||||
* the lane partial and the pair fold are exact, and the group terms land in the accumulator
|
||||
* in the reference's ascending order. The codes widen to f16 through a sign extension, which
|
||||
* is exact for both grids; the activations widen through the i8 codec the w2a8 arm uses.
|
||||
*
|
||||
* The activation is the step order: within each sixteen-byte step the middle two dwords are
|
||||
* exchanged, so the staging reads through the same position map the w2a8 arm does, and a
|
||||
* weight row's codes are plain row-major, two a byte at I4 and one a byte at I8.
|
||||
*
|
||||
* ---- the tile --------------------------------------------------------------------------------------
|
||||
*
|
||||
* One workgroup serves kWaves weight rows; a wavefront takes one row, lane l owns rows
|
||||
* l & (MT-1) and k-lane l / MT, and the chunk is 2048 / MT codes: a multiple of the 128
|
||||
* group at every MT, so a chunk carries CG = 16 / MT whole groups and the group's scale is
|
||||
* one read. The lane's 64 codes are 32 bytes at I4, two 16-byte loads, and 64 at I8, four.
|
||||
* The lane's 64 sit in the group's two halves the w2a8 arm folds with one shfl_xor(MT), and
|
||||
* the group's term -- scaled by the activation's row scale and the weight's group scale --
|
||||
* goes to shared, where the row's owner lane sums the chunk's groups in ascending order.
|
||||
*
|
||||
* M > 16 is the tiled row's; the w2a8 arm serves the 2- and 4-bit container grids there, and
|
||||
* the 8-bit grid at prefill heights is declared out of this unit.
|
||||
*
|
||||
* ---- refusals --------------------------------------------------------------------------------------
|
||||
*
|
||||
* Every structural violation is a refusal, in the shim: the dtypes of all five operands,
|
||||
* K % 128, the band's M, the b row pitch's 16-byte alignment, the a and y pitches. There is
|
||||
* no data that is a refusal: both grids have no reserved value.
|
||||
*/
|
||||
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_codecs.h"
|
||||
#include "r3d_launch.h"
|
||||
#include "r3d_args.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kWave = 32;
|
||||
constexpr int kWaves = 8;
|
||||
constexpr int kBlockThreads = kWaves * kWave;
|
||||
constexpr int kMTMax = 16;
|
||||
constexpr int kGroup = 128;
|
||||
constexpr int kTileQuads = 512; /* MT rows x CHUNK/4 f16, constant over MT */
|
||||
|
||||
/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse.
|
||||
* Applied to the four columns of one dword it leaves them four contiguous bytes and turns
|
||||
* the map on the DWORD index into a swap of bits 0 and 1 -- the middle two dwords of a
|
||||
* 16-byte step exchanged. */
|
||||
__device__ __forceinline__ int64_t dword_pos(int64_t d)
|
||||
{
|
||||
return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1));
|
||||
}
|
||||
|
||||
/* The LDS swizzle, at the granularity the tile is touched: a quad of four f16, two dwords,
|
||||
* moved as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low
|
||||
* four bits with bits 4..7 -- a bijection on 16-quad groups. */
|
||||
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
|
||||
|
||||
/* Four int8 codes -> two f16x2 dwords. Exact: an integer of |a| <= 127 needs no rounding. */
|
||||
__device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi)
|
||||
{
|
||||
lo = f16x2_pack((float)(int32_t)(int8_t)(w & 0xffu), (float)(int32_t)(int8_t)((w >> 8) & 0xffu));
|
||||
hi = f16x2_pack((float)(int32_t)(int8_t)((w >> 16) & 0xffu),
|
||||
(float)(int32_t)(int8_t)((w >> 24) & 0xffu));
|
||||
}
|
||||
|
||||
/* Four signed int4 codes (two bytes, the low code in the low nibble) -> two f16x2 dwords.
|
||||
* Exact: the sign extension lands on an integer, and f16 steps by 1/8 at exponent 2^-3.
|
||||
* A nibble n is the value (n & 7) - (n & 8): 0..7 pass through and 8..15 land on -8..-1.
|
||||
* The gfx1102 backend folds the bias-8 spelling ((n ^ 8) - 8) to n ^ 16 once it has proven
|
||||
* the nibble range, so the sign is kept as a bit term. */
|
||||
__device__ __forceinline__ void i4x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi)
|
||||
{
|
||||
const uint32_t n0 = w & 0xFu;
|
||||
const uint32_t n1 = (w >> 4) & 0xFu;
|
||||
const uint32_t n2 = (w >> 8) & 0xFu;
|
||||
const uint32_t n3 = (w >> 12) & 0xFu;
|
||||
const int32_t c0 = (int32_t)((n0 & 7u) - (n0 & 8u));
|
||||
const int32_t c1 = (int32_t)((n1 & 7u) - (n1 & 8u));
|
||||
const int32_t c2 = (int32_t)((n2 & 7u) - (n2 & 8u));
|
||||
const int32_t c3 = (int32_t)((n3 & 7u) - (n3 & 8u));
|
||||
lo = f16x2_pack((float)c0, (float)c1);
|
||||
hi = f16x2_pack((float)c2, (float)c3);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float dot4_f16x4(uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1,
|
||||
float acc)
|
||||
{
|
||||
const _Float16* fa = (const _Float16*)&a0;
|
||||
const _Float16* fb = (const _Float16*)&b0;
|
||||
acc = fmaf(fa[0], fb[0], acc);
|
||||
acc = fmaf(fa[1], fb[1], acc);
|
||||
const _Float16* fa1 = (const _Float16*)&a1;
|
||||
const _Float16* fb1 = (const _Float16*)&b1;
|
||||
acc = fmaf(fa1[0], fb1[0], acc);
|
||||
acc = fmaf(fa1[1], fb1[1], acc);
|
||||
return acc;
|
||||
}
|
||||
|
||||
template <int MT, int CDT>
|
||||
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
|
||||
gemm_inta8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa,
|
||||
const uint8_t* __restrict__ b, int b_rb, const uint16_t* __restrict__ sb,
|
||||
int sb_rb, uint16_t* __restrict__ y, int M, int N, int K, int chunk,
|
||||
int a_pitch, int y_pitch)
|
||||
{
|
||||
constexpr int KL = kWave / MT; /* k-lanes per activation row */
|
||||
constexpr int CG = (2048 / MT) / kGroup; /* groups per chunk: 16 / MT */
|
||||
constexpr int CL = 64; /* codes per lane per chunk */
|
||||
constexpr int NLOAD = (CL * CDT) / 128; /* 16-byte loads: the lane's window */
|
||||
|
||||
__shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/4 f16, swizzled */
|
||||
__shared__ float sT[kWaves * 16]; /* warp*16 + m*CG + j */
|
||||
__shared__ float sSa[MT];
|
||||
|
||||
const int lane = threadIdx.x & (kWave - 1);
|
||||
const int warp = (int)(threadIdx.x / kWave);
|
||||
const int n = blockIdx.x * kWaves + warp;
|
||||
const bool live = n < N;
|
||||
if ((int)blockIdx.x * kWaves >= N) return;
|
||||
|
||||
const int m = lane & (MT - 1);
|
||||
const int kl = lane / MT;
|
||||
const int row_bytes = b_rb; /* the codes' byte pitch, from the shim */
|
||||
const int cq = (CDT == 4) ? (chunk >> 1) : chunk; /* the chunk's code bytes */
|
||||
const int nchunk = K / chunk;
|
||||
|
||||
if (lane < MT) sSa[lane] = lane < M ? sa[lane] : 0.0f;
|
||||
__syncthreads();
|
||||
|
||||
float acc = 0.0f;
|
||||
for (int ch = 0; ch < nchunk; ++ch) {
|
||||
/* Stage the chunk's activation rows, widened and step-unpermuted on the way in. Cells
|
||||
* are four codes: MT * CHUNK/4 = 512 of them at every MT, two per thread. */
|
||||
for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) {
|
||||
const int r = i / (chunk >> 2), c = i % (chunk >> 2);
|
||||
uint32_t w = 0;
|
||||
if (r < M)
|
||||
w = *(const uint32_t*)(a + (long long)r * a_pitch +
|
||||
dword_pos((int64_t)ch * (chunk >> 2) + c));
|
||||
const int q = r * (chunk >> 2) + c;
|
||||
uint32_t lo, hi;
|
||||
i8x4_to_f16x2(w, lo, hi);
|
||||
sA[p_ix(q)] = make_uint2(lo, hi);
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
if (live) {
|
||||
/* 64 codes: 32 bytes at I4, 64 at I8. The lane's codes are kl * 64 within the
|
||||
* chunk, and the row pitch keeps every 16-byte load aligned. */
|
||||
const uint8_t* bp = b + (long long)n * row_bytes + (int64_t)ch * cq +
|
||||
kl * (CL / 2) * (CDT / 4);
|
||||
uint4 qw[NLOAD];
|
||||
#pragma unroll
|
||||
for (int L = 0; L < NLOAD; ++L)
|
||||
__builtin_memcpy(&qw[L], bp + 16 * L, 16);
|
||||
/* One value per quad: I4 the two-byte window as a 16-bit element, I8 the dword.
|
||||
* The I4 window is taken as a half at its own address; shifting a dword array by
|
||||
* a byte amount miscompiles on the gfx1102 backend. */
|
||||
uint32_t wd[(CL >> 2)];
|
||||
if (CDT == 4) {
|
||||
uint16_t wq[CL / 2];
|
||||
#pragma unroll
|
||||
for (int L = 0; L < NLOAD; ++L)
|
||||
__builtin_memcpy(&wq[8 * L], &qw[L], 16);
|
||||
#pragma unroll
|
||||
for (int v = 0; v < (CL >> 2); ++v)
|
||||
wd[v] = wq[v];
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int L = 0; L < NLOAD; ++L)
|
||||
{ wd[4 * L + 0] = qw[L].x; wd[4 * L + 1] = qw[L].y;
|
||||
wd[4 * L + 2] = qw[L].z; wd[4 * L + 3] = qw[L].w; }
|
||||
}
|
||||
|
||||
const int qb = m * (chunk >> 2) + kl * (CL >> 2);
|
||||
/* 16 quads, decoded before the dot. */
|
||||
uint32_t cb[(CL >> 2)][2];
|
||||
#pragma unroll
|
||||
for (int v = 0; v < (CL >> 2); ++v) {
|
||||
if (CDT == 4) i4x4_to_f16x2(wd[v] & 0xFFFFu, cb[v][0], cb[v][1]);
|
||||
else i8x4_to_f16x2(wd[v], cb[v][0], cb[v][1]);
|
||||
}
|
||||
float p = 0.0f; /* the lane's half-group, an exact integer */
|
||||
#pragma unroll
|
||||
for (int v = 0; v < (CL >> 2); ++v) {
|
||||
const uint2 av = sA[p_ix(qb + v)];
|
||||
p = dot4_f16x4(av.x, av.y, cb[v][0], cb[v][1], p);
|
||||
}
|
||||
|
||||
/* Fold the pair: lanes l and l^MT are the same row, the two halves of one group. */
|
||||
const float isg = p + __shfl_xor(p, MT);
|
||||
|
||||
const int g = ch * CG + (kl >> 1);
|
||||
const float sc = f16_to_f32(sb[(long long)n * sb_rb + g]);
|
||||
const float term = (isg * sSa[m]) * sc; /* the reference's parentheses */
|
||||
/* One slot per (row, group-in-chunk): MT*CG is 16 at every MT. The group's two
|
||||
* half-lanes write the same value, which is what the pair fold above is for. */
|
||||
sT[warp * 16 + m * CG + (kl >> 1)] = term;
|
||||
}
|
||||
__syncthreads();
|
||||
/* The chunk's groups, in ascending order, into the lane that owns the row's answer:
|
||||
* the reference walks g in ascending order and f32 adds are not associative, so the
|
||||
* order is part of the answer, not a detail. */
|
||||
if (live && kl == 0) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CG; ++j)
|
||||
if (m < M) acc += sT[warp * 16 + m * CG + j];
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
if (live && kl == 0 && m < M) y[(long long)m * y_pitch + n] = f32_to_bf16(acc);
|
||||
}
|
||||
|
||||
int mt_for(int M)
|
||||
{
|
||||
int mt = 1;
|
||||
while (mt < M && mt < kMTMax) mt *= 2;
|
||||
return mt;
|
||||
}
|
||||
|
||||
#define R3D_INTA8_LAUNCH(MT, CDT) \
|
||||
do { \
|
||||
const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads); \
|
||||
R3D_KLAUNCH(R3D_KNAME((gemm_inta8_kernel<MT, CDT>)), grid, block, (hipStream_t)stream, \
|
||||
(const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb, (const uint16_t*)b_scale, \
|
||||
(int)sb_rb, (uint16_t*)y, M, N, K, chunk, a_ld, y_ld); \
|
||||
} while (0)
|
||||
|
||||
extern "C" int r3d_gemm_nt_q_w4a8_m16(long a, long a_scale, long b, long b_scale, long y,
|
||||
int M, int N, int K, int a_ld, int y_ld, long long b_rb,
|
||||
long long sb_rb, long stream)
|
||||
{
|
||||
if (!a || !a_scale || !b || !b_scale || !y) return -1;
|
||||
if (M < 1 || N < 1 || K < 1) return -2;
|
||||
if (M > kMTMax) return -2;
|
||||
if (K % kGroup) return -2;
|
||||
const int mt = mt_for(M);
|
||||
const int chunk = 2048 / mt;
|
||||
if (K % chunk) return -2;
|
||||
if (!a_ld) a_ld = K;
|
||||
if (!y_ld) y_ld = N;
|
||||
if (a_ld % 4) return -3;
|
||||
if (y_ld < N) return -3;
|
||||
if (!b_rb) b_rb = K / 2;
|
||||
if (b_rb < K / 2) return -3;
|
||||
if (b_rb & 15) return -5;
|
||||
if (!sb_rb) sb_rb = K / kGroup;
|
||||
if (sb_rb < K / kGroup) return -3;
|
||||
if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5;
|
||||
|
||||
switch (mt) {
|
||||
case 1: R3D_INTA8_LAUNCH(1, 4); break;
|
||||
case 2: R3D_INTA8_LAUNCH(2, 4); break;
|
||||
case 4: R3D_INTA8_LAUNCH(4, 4); break;
|
||||
case 8: R3D_INTA8_LAUNCH(8, 4); break;
|
||||
default: R3D_INTA8_LAUNCH(16, 4); break;
|
||||
}
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale, long y,
|
||||
int M, int N, int K, int a_ld, int y_ld, long long b_rb,
|
||||
long long sb_rb, long stream)
|
||||
{
|
||||
if (!a || !a_scale || !b || !b_scale || !y) return -1;
|
||||
if (M < 1 || N < 1 || K < 1) return -2;
|
||||
if (M > kMTMax) return -2;
|
||||
if (K % kGroup) return -2;
|
||||
const int mt = mt_for(M);
|
||||
const int chunk = 2048 / mt;
|
||||
if (K % chunk) return -2;
|
||||
if (!a_ld) a_ld = K;
|
||||
if (!y_ld) y_ld = N;
|
||||
if (a_ld % 4) return -3;
|
||||
if (y_ld < N) return -3;
|
||||
if (!b_rb) b_rb = K;
|
||||
if (b_rb < K) return -3;
|
||||
if (b_rb & 15) return -5;
|
||||
if (!sb_rb) sb_rb = K / kGroup;
|
||||
if (sb_rb < K / kGroup) return -3;
|
||||
if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5;
|
||||
|
||||
switch (mt) {
|
||||
case 1: R3D_INTA8_LAUNCH(1, 8); break;
|
||||
case 2: R3D_INTA8_LAUNCH(2, 8); break;
|
||||
case 4: R3D_INTA8_LAUNCH(4, 8); break;
|
||||
case 8: R3D_INTA8_LAUNCH(8, 8); break;
|
||||
default: R3D_INTA8_LAUNCH(16, 8); break;
|
||||
}
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
#undef R3D_INTA8_LAUNCH
|
||||
|
||||
/* ================================================================== the shims
|
||||
*
|
||||
* gemm_nt_q's slots, as the two shims take them: 0 a (I8, step order), 1 a_scale (f32, one
|
||||
* per row), 2 b (I4 or I8 codes), 3 b_scale (f16, one per (row, 128 of K)), 4 y (bf16),
|
||||
* 5 a_sum (absent: symmetric), 6 b_ref (absent).
|
||||
*/
|
||||
|
||||
extern "C" int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s)
|
||||
{
|
||||
if (!a) return R3D_NO(RAD_E_INVAL);
|
||||
const char* dt = r3d_gets(a, "dtype");
|
||||
if (dt && std::strcmp(dt, "w4a8") != 0) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
const RadTensor* A = r3d_opt(a, 0);
|
||||
const RadTensor* AS = r3d_opt(a, 1);
|
||||
const RadTensor* B = r3d_opt(a, 2);
|
||||
const RadTensor* BS = r3d_opt(a, 3);
|
||||
const RadTensor* Y = r3d_opt(a, 4);
|
||||
const RadTensor* ASUM = r3d_opt(a, 5);
|
||||
const RadTensor* BREF = r3d_opt(a, 6);
|
||||
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
|
||||
return R3D_NO(RAD_E_INVAL);
|
||||
if (r3d_has(ASUM) || r3d_has(BREF)) return R3D_NO(RAD_E_DTYPE); /* symmetric: nothing to remove */
|
||||
|
||||
if (!r3d_is_i8(A)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (B->dtype != RAD_I4) return R3D_NO(RAD_E_DTYPE);
|
||||
if (BS->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
|
||||
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
|
||||
if (K % kGroup) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long ynel = r3d_numel(Y);
|
||||
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long M = ynel / N;
|
||||
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(AS) < M) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(BS) < N * (K / kGroup)) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long ap = r3d_row_pitch(A);
|
||||
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
|
||||
long long yrows = 0;
|
||||
const long long yp = r3d_rows_pitch(Y, N, &yrows);
|
||||
if (yp < N) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
const long long bbr = r3d_row_pitch(B) / 2; /* I4 counts elements, two a byte */
|
||||
const int rc = r3d_gemm_nt_q_w4a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
|
||||
r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp,
|
||||
bbr, (long long)r3d_row_pitch(BS), (long)s);
|
||||
if (rc == -1) return R3D_NO(RAD_E_INVAL);
|
||||
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
|
||||
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
|
||||
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
|
||||
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_gemm_nt_q_w8a8_m16(const RadArgs* a, RadStream s)
|
||||
{
|
||||
if (!a) return R3D_NO(RAD_E_INVAL);
|
||||
const char* dt = r3d_gets(a, "dtype");
|
||||
if (dt && std::strcmp(dt, "w8a8") != 0) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
const RadTensor* A = r3d_opt(a, 0);
|
||||
const RadTensor* AS = r3d_opt(a, 1);
|
||||
const RadTensor* B = r3d_opt(a, 2);
|
||||
const RadTensor* BS = r3d_opt(a, 3);
|
||||
const RadTensor* Y = r3d_opt(a, 4);
|
||||
const RadTensor* ASUM = r3d_opt(a, 5);
|
||||
const RadTensor* BREF = r3d_opt(a, 6);
|
||||
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
|
||||
return R3D_NO(RAD_E_INVAL);
|
||||
if (r3d_has(ASUM) || r3d_has(BREF)) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
if (!r3d_is_i8(A)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (B->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE);
|
||||
if (BS->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
|
||||
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
|
||||
if (K % kGroup) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long ynel = r3d_numel(Y);
|
||||
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long M = ynel / N;
|
||||
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(AS) < M) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(BS) < N * (K / kGroup)) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long ap = r3d_row_pitch(A);
|
||||
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
|
||||
long long yrows = 0;
|
||||
const long long yp = r3d_rows_pitch(Y, N, &yrows);
|
||||
if (yp < N) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
const int rc = r3d_gemm_nt_q_w8a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
|
||||
r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp,
|
||||
(long long)r3d_row_pitch(B), (long long)r3d_row_pitch(BS),
|
||||
(long)s);
|
||||
if (rc == -1) return R3D_NO(RAD_E_INVAL);
|
||||
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
|
||||
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
|
||||
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
|
||||
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -0,0 +1,738 @@
|
||||
/* r3d_gemm_mxfp4a8.hip -- gemm_nt_q at dtype=mxfp4a8: an OCP-MXFP4 weight against an fp8
|
||||
* activation, at both heights.
|
||||
*
|
||||
* y[M,N] = a[M,K] @ b[N,K]^T, a in E4M3 with one f32 scale per (row, 128 of K), b in e2m1
|
||||
* with one e8m0 scale per (row, 32 of K). f32 accumulate, one bf16 narrowing at the store.
|
||||
* There is no zero point: the scale is symmetric.
|
||||
*
|
||||
* ---- the format, and the fold it gives ----------------------------------------------------------------
|
||||
*
|
||||
* OCP MXFP4 stores a weight row as e2m1 codes, two per byte, element 2j in the LOW nibble of
|
||||
* byte j, with one e8m0 exponent per 32 K elements: a u8 plane [N, K/32] behind the u8 codes
|
||||
* plane [N, K/2]. e8m0 value e means the factor 2^(e-127); e = 0 and e = 255 are reserved
|
||||
* (zero, NaN) and a plane carrying either is refused, the reference's answer for the same
|
||||
* bytes.
|
||||
*
|
||||
* The fold this kernel runs, per 32-block:
|
||||
*
|
||||
* 1. the code for element k is e4m3(mag) at d = 0 -- the e2m1 magnitude is EXACT in e4m3,
|
||||
* because all eight magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} are e4m3 grid points. The
|
||||
* unpack is a 4-bit lookup on the nibble through the eight e4m3 magnitude bytes
|
||||
* {0x00, 0x30, 0x38, 0x3C, 0x40, 0x44, 0x48, 0x4C}, the sign bit of the code on the
|
||||
* sign bit of the byte.
|
||||
* 2. the code products run on dot2_f16x2. A product is at most 6 x 448 = 2688, in f16's
|
||||
* range (65504), and an eight-term partial is under 21504, in f16's grid: the dot's
|
||||
* only rounding is the instruction's own.
|
||||
* 3. the per-block factor 2^(e-127) is applied in the epilogue: the 32-block partial, an
|
||||
* f32, is multiplied by the factor -- a power of two, exact in f32 short of the
|
||||
* under/overflow edge -- and added to the running f32 sum. One multiply and one add per
|
||||
* block per output element, no per-element scale traffic.
|
||||
* 4. the store narrows once, to bf16.
|
||||
*
|
||||
* The e2m1 magnitude is exact, the products are exact, and the two roundings a block sees are
|
||||
* the dot's fused rounding and the store: the row's distance from the reference is the store's
|
||||
* ulp, nothing else.
|
||||
*
|
||||
* The RDNA4 sibling folds the e8 into the table through a d-indexed row, because its WMMA
|
||||
* path needs one scale per row; this library's dot2 path folds per block in the epilogue, and
|
||||
* the table is the eight fixed magnitude bytes, no index.
|
||||
*
|
||||
* ---- the tiled row (M >= 17) -------------------------------------------------------------------------
|
||||
*
|
||||
* The 128x128 tile, 8x8 f32 accumulators a lane, k ascending in 32-code chunks. The chunk IS
|
||||
* the OCP 32-block: the lane's e8 bytes for its eight tile columns enter as one byte per row
|
||||
* at staging, through LDS, and the chunk's partials flush at the chunk's end:
|
||||
*
|
||||
* total[i][j] += acc[i][j] * 2^(e8[n_c + j][blk] - 127); acc[i][j] = 0;
|
||||
*
|
||||
* `acc` is the 32-block partial, `total` the running f32 sum over blocks in ascending k. The
|
||||
* activation stages exactly as the fp8a8 tiled row's: E4M3 through the LDS table, the f32
|
||||
* scale per (row, 128 of K) folded at staging; 32 divides 128, so a chunk sits inside one
|
||||
* group and never straddles one.
|
||||
*
|
||||
* ---- the m16 row (M <= 16) ----------------------------------------------------------------------------
|
||||
*
|
||||
* One wave per weight row, the w2a8 row's shape: lane l owns row m = l % MT and k-lane
|
||||
* kl = l / MT, a chunk is CHUNK = 2048/MT codes, and every lane takes 64 of them -- two OCP
|
||||
* 32-blocks, the lane's blocks 2*kl and 2*kl+1 of the chunk. Each lane sums its two blocks in
|
||||
* k, scales each by the block's e8, and the group's four block terms are formed in ascending
|
||||
* block order by one shfl_xor pair and written to LDS, where the kl == 0 lane adds them to the
|
||||
* accumulator in ascending block order: the reference's ascending-k accumulation, at the
|
||||
* 32-block granularity the format fixes.
|
||||
*
|
||||
* ---- refusals -----------------------------------------------------------------------------------------
|
||||
*
|
||||
* Every structural violation is a refusal, in the shim: the dtypes of all seven operands (the
|
||||
* codes as fp4_e2m1 or raw bytes, the e8 plane as e8m0 or u8, `b_ref` the e8 plane again and
|
||||
* ignored), K % 32 and K % 128, the codes plane's extent and 16-byte row alignment, the e8
|
||||
* plane's [N, K/32] extent, the pitches, the band's M. A reserved e8 (0, 255) is a data
|
||||
* violation, and it is refused where the data is readable: the shim scans the e8 plane once
|
||||
* per (pointer, size) pair, on a plane the host can see, and answers E_INVAL. A plane the
|
||||
* host cannot see is not scanned, and the kernel's e8 guard -- reserved values take the scale
|
||||
* zero -- keeps its output finite.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_args.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_codecs.h"
|
||||
#include "r3d_fp8_dequant.h"
|
||||
#include "r3d_tiling.h"
|
||||
#include "r3d_launch.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kBlockThreads = 256;
|
||||
constexpr int kWaves = 8;
|
||||
constexpr int kTM = 128; /* rows a tile */
|
||||
constexpr int kTN = 128; /* columns a tile */
|
||||
constexpr int kKC = 32; /* k a chunk: one OCP 32-block */
|
||||
constexpr int kMX = 32; /* K per e8m0 exponent: the OCP MX block */
|
||||
constexpr int kGroup = 128; /* the activation's scale group */
|
||||
constexpr int kMMin = 17; /* the tiled row's floor: the m16 row's ceiling plus one */
|
||||
constexpr int kMTMax = 16;
|
||||
constexpr int kTileQuads = 512; /* MT * CHUNK/4, constant over MT: 2048 codes, 4 KiB of f16 */
|
||||
|
||||
/* The eight e2m1 magnitudes, as e4m3 bytes: 0, .5, 1, 1.5 in the low word, 2, 3, 4, 6 in the
|
||||
* high. Every one is exact, which is the whole point of the fold. */
|
||||
#define R3D_MXFP4_MAG_LO 0x3c383000u
|
||||
#define R3D_MXFP4_MAG_HI 0x4c484440u
|
||||
|
||||
/* Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) as eight e4m3
|
||||
* bytes in k order (word 0 = elements 0..3, word 1 = 4..7). Even and odd nibbles each run
|
||||
* through the magnitude bytes by a v_perm_b32 on the 3-bit magnitude, bit 3 of the code shifts
|
||||
* onto the e4m3 sign, and two more v_perm_b32 interleave the halves. The table is the fixed
|
||||
* d = 0 row: no index, because the per-block factor is applied in the epilogue, not folded
|
||||
* here. */
|
||||
__device__ __forceinline__ void mxfp4_unpack8(uint32_t wv, uint32_t* lo, uint32_t* hi)
|
||||
{
|
||||
const uint32_t ev = wv & 0x0F0F0F0Fu; /* low nibble of each byte -> even elements */
|
||||
const uint32_t od = (wv >> 4) & 0x0F0F0F0Fu; /* high nibble -> odd elements */
|
||||
const uint32_t be = __builtin_amdgcn_perm(R3D_MXFP4_MAG_HI, R3D_MXFP4_MAG_LO, ev & 0x07070707u)
|
||||
| ((ev & 0x08080808u) << 4);
|
||||
const uint32_t bo = __builtin_amdgcn_perm(R3D_MXFP4_MAG_HI, R3D_MXFP4_MAG_LO, od & 0x07070707u)
|
||||
| ((od & 0x08080808u) << 4);
|
||||
*lo = __builtin_amdgcn_perm(bo, be, 0x05010400u);
|
||||
*hi = __builtin_amdgcn_perm(bo, be, 0x07030602u);
|
||||
}
|
||||
|
||||
/* The e8m0 factor: 2^(e-127). The reserved values take the scale zero -- e = 0 is the
|
||||
* format's zero, e = 255 its NaN -- so a plane that carries one computes a zero block and
|
||||
* stays finite; the refusal for such a plane is the shim's, where the bytes are readable. */
|
||||
__device__ __forceinline__ float e8_scale(uint8_t e)
|
||||
{
|
||||
return (e == 0 || e == 255) ? 0.0f : ldexpf(1.0f, (int)e - 127);
|
||||
}
|
||||
|
||||
/* Four e4m3 bytes (one dword, low byte first) as two f16x2, through the block's table. The
|
||||
* table entries are f16 bit patterns, so the words are moves, not conversions. */
|
||||
__device__ __forceinline__ void e4m3x4_to_f16x2(const uint16_t* tbl, uint32_t w, uint32_t* o)
|
||||
{
|
||||
o[0] = (uint32_t)tbl[w & 0xffu] | ((uint32_t)tbl[(w >> 8) & 0xffu] << 16);
|
||||
o[1] = (uint32_t)tbl[(w >> 16) & 0xffu] | ((uint32_t)tbl[(w >> 24) & 0xffu] << 16);
|
||||
}
|
||||
|
||||
/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. NOT
|
||||
* f16x2_pack, which truncates. */
|
||||
__device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc)
|
||||
{
|
||||
const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16);
|
||||
const _Float16 a = __builtin_bit_cast(_Float16, lo16);
|
||||
const _Float16 b = __builtin_bit_cast(_Float16, hi16);
|
||||
const _Float16 s = (_Float16)sc;
|
||||
const _Float16 rl = a * s, rh = b * s;
|
||||
return (uint32_t)__builtin_bit_cast(uint16_t, rl)
|
||||
| ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16);
|
||||
}
|
||||
|
||||
/* Eight codes -> eight f16, through the table. gfx11 has no E4M3 convert, so the 256-entry
|
||||
* f16 table stands in for the instruction. */
|
||||
__device__ __forceinline__ void codes8(const uint2 c, const uint16_t* tbl, uint32_t* w)
|
||||
{
|
||||
r3d_e4m3x8_ld(tbl, c, w);
|
||||
}
|
||||
|
||||
template <int NT>
|
||||
__device__ __forceinline__ uint2 loadc8s(const uint8_t* p)
|
||||
{
|
||||
typedef uint32_t __attribute__((ext_vector_type(2))) u8v;
|
||||
u8v v;
|
||||
if (NT) v = __builtin_nontemporal_load((const u8v*)p);
|
||||
else __builtin_memcpy(&v, p, 8);
|
||||
uint2 r;
|
||||
__builtin_memcpy(&r, &v, 8);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ================================================================== the tiled row */
|
||||
|
||||
struct ActQ {
|
||||
const float* scale; /* a_scale, f32: [M][ceil(K/group)] */
|
||||
long long row; /* elements a row */
|
||||
int gmode; /* 1: one scale per (row, group) */
|
||||
};
|
||||
|
||||
struct MxWQ {
|
||||
const uint8_t* codes; /* e2m1, two per byte, [N][K/2] */
|
||||
const uint8_t* e8; /* e8m0, one per 32, [N][K/32] */
|
||||
long long code_row; /* bytes a codes row */
|
||||
long long e8_row; /* bytes an e8 row */
|
||||
};
|
||||
|
||||
/*
|
||||
* The tile: 128 rows x 128 columns of y, 256 threads, eight waves, eight outputs a side a
|
||||
* lane -- 64 f32 accumulators a lane for the 32-block partials, 64 more for the running
|
||||
* sum, grid (N/kTN) x ceil(M/kTM). k is walked in chunks of 32; the activation arrives as
|
||||
* E4M3 codes, decodes through the block's table and leaves staging as f16 with its scale
|
||||
* folded in, and the weight arrives as e2m1 nibbles, unpacks to e4m3 and leaves staging as
|
||||
* f16 UNSIGNED by the block: its scale is the e8, and the e8 is applied at the chunk's end,
|
||||
* where the chunk's partials meet it.
|
||||
*/
|
||||
template <int NT>
|
||||
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
|
||||
mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __restrict__ y,
|
||||
int M, int N, int K, int a_ld, int y_ld)
|
||||
{
|
||||
__shared__ __align__(16) uint16_t sA[kTM * kKC];
|
||||
__shared__ __align__(16) uint16_t sB[kTN * kKC];
|
||||
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
|
||||
__shared__ uint8_t sE8[kTN]; /* the chunk's e8, one per tile row */
|
||||
|
||||
const int tid = (int)threadIdx.x;
|
||||
r3d_e4m3_f16_init(sTbl, tid, kBlockThreads);
|
||||
|
||||
const int m0 = (int)blockIdx.y * kTM;
|
||||
const int n0 = (int)blockIdx.x * kTN;
|
||||
const int rg = tid >> 4, cg = tid & 15;
|
||||
|
||||
float acc[8][8];
|
||||
float total[8][8];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) { acc[i][j] = 0.0f; total[i][j] = 0.0f; }
|
||||
|
||||
const int m_r = m0 + rg * 8, n_c = n0 + cg * 8;
|
||||
|
||||
for (int k0 = 0; k0 < K; k0 += kKC) {
|
||||
const int g = k0 / kGroup;
|
||||
const int blk = k0 / kMX; /* the chunk is one 32-block */
|
||||
|
||||
#pragma unroll
|
||||
for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) {
|
||||
const int mm = j / (kKC / 8), c8 = j % (kKC / 8);
|
||||
const int m = m0 + mm, k = k0 + c8 * 8;
|
||||
uint4 staged = make_uint4(0, 0, 0, 0);
|
||||
if (m < M) {
|
||||
const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)];
|
||||
uint32_t w[4];
|
||||
codes8(loadc8s<NT>(a + (long long)m * a_ld + k), sTbl, w);
|
||||
staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa),
|
||||
fold_pair(w[2], sa), fold_pair(w[3], sa));
|
||||
}
|
||||
*(uint4*)&sA[srow(mm, c8, kKC)] = staged;
|
||||
}
|
||||
for (int nn = tid; nn < kTN; nn += kBlockThreads) {
|
||||
const int n = n0 + nn;
|
||||
uint4 st[4] = { make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0),
|
||||
make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0) };
|
||||
/* The e8 for the column, written even past N: a row the tile does not serve keeps
|
||||
* the scale zero, so the flush multiplies a staged zero by a defined value. */
|
||||
sE8[nn] = (n < N) ? h.e8[(long long)n * h.e8_row + blk] : 0;
|
||||
if (n < N) {
|
||||
/* 32 codes, 16 bytes, one load: k0 is a multiple of 32, the row a multiple of
|
||||
* 64 bytes, so the load is aligned. */
|
||||
uint4 cv;
|
||||
__builtin_memcpy(&cv, h.codes + (long long)n * h.code_row + (k0 >> 1), 16);
|
||||
const uint32_t d[4] = { cv.x, cv.y, cv.z, cv.w };
|
||||
uint32_t w[16];
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
uint32_t lo, hi;
|
||||
mxfp4_unpack8(d[q], &lo, &hi);
|
||||
e4m3x4_to_f16x2(sTbl, lo, w + 4 * q);
|
||||
e4m3x4_to_f16x2(sTbl, hi, w + 4 * q + 2);
|
||||
}
|
||||
st[0] = make_uint4(w[0], w[1], w[2], w[3]);
|
||||
st[1] = make_uint4(w[4], w[5], w[6], w[7]);
|
||||
st[2] = make_uint4(w[8], w[9], w[10], w[11]);
|
||||
st[3] = make_uint4(w[12], w[13], w[14], w[15]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) *(uint4*)&sB[srow(nn, q, kKC)] = st[q];
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
/* The chunk's e8 for the lane's eight columns, held in registers: the flush reads it
|
||||
* and nothing else does. The index is tile-local -- sE8 is this tile's 128 rows, and a
|
||||
* global column index reads past it on every tile past the first. */
|
||||
float e8s[8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) e8s[j] = e8_scale(sE8[cg * 8 + j]);
|
||||
|
||||
#pragma unroll
|
||||
for (int kc = 0; kc < kKC; kc += 2) {
|
||||
uint32_t af[8], bf[8];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i)
|
||||
af[i] = *(const uint32_t*)&sA[srow_pair(rg * 8 + i, kc, kKC)];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j)
|
||||
bf[j] = *(const uint32_t*)&sB[srow_pair(cg * 8 + j, kc, kKC)];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]);
|
||||
}
|
||||
/* The 32-block boundary: the partial scales by the block's factor, the sum keeps the
|
||||
* blocks in ascending k, and the partial resets for the next block. */
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
total[i][j] += acc[i][j] * e8s[j];
|
||||
acc[i][j] = 0.0f;
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
/* y is bf16: one narrowing, 16-byte runs of eight columns. Rows past M write nothing. */
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const int m = m_r + i;
|
||||
if (m >= M) break;
|
||||
uint16_t* row = (uint16_t*)y + (long long)m * y_ld;
|
||||
if (n_c + 8 <= N) {
|
||||
uint32_t p[4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j)
|
||||
p[j] = (uint32_t)f32_to_bf16(total[i][2 * j]) |
|
||||
((uint32_t)f32_to_bf16(total[i][2 * j + 1]) << 16);
|
||||
*(uint4*)(row + n_c) = make_uint4(p[0], p[1], p[2], p[3]);
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j)
|
||||
if (n_c + j < N) row[n_c + j] = f32_to_bf16(total[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the m16 row */
|
||||
|
||||
/* The LDS swizzle, at the granularity the tile is touched: a quad of four codes, two dwords,
|
||||
* moved as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low four
|
||||
* bits with bits 4..7 -- a bijection on 16-quad groups. */
|
||||
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
|
||||
|
||||
template <int MT>
|
||||
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
|
||||
gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__ sa, int sa_stride,
|
||||
const uint8_t* __restrict__ b, const uint8_t* __restrict__ e8,
|
||||
int e8_row, uint16_t* __restrict__ y, int M, int N, int K, int chunk,
|
||||
int a_pitch, int y_pitch)
|
||||
{
|
||||
constexpr int KL = kWave / MT; /* k-lanes per activation row */
|
||||
constexpr int CL = 64; /* codes per lane per chunk: two 32-blocks */
|
||||
constexpr int BPR = (2048 / MT) / kMX; /* 32-blocks a row of the chunk: 64/MT */
|
||||
|
||||
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
|
||||
__shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/2 f16, swizzled */
|
||||
__shared__ float sB[kWaves * 64]; /* the chunk's block terms: warp*64 + m*BPR + bl */
|
||||
|
||||
const int lane = threadIdx.x & (kWave - 1);
|
||||
const int warp = (int)(threadIdx.x / kWave);
|
||||
const int n = blockIdx.x * kWaves + warp;
|
||||
const bool live = n < N;
|
||||
if ((int)blockIdx.x * kWaves >= N) return;
|
||||
|
||||
const int m = lane & (MT - 1);
|
||||
const int kl = lane / MT;
|
||||
const int nchunk = K / chunk;
|
||||
|
||||
r3d_e4m3_f16_init(sTbl, threadIdx.x, kBlockThreads);
|
||||
|
||||
float acc = 0.0f;
|
||||
for (int ch = 0; ch < nchunk; ++ch) {
|
||||
__syncthreads();
|
||||
/* The chunk's activation rows, decoded and scaled on the way in. Cells are four codes:
|
||||
* MT * CHUNK/4 = 512 of them at every MT, two per thread. The scale is per (row, 128
|
||||
* of K); a cell's four codes sit in one group, so one scalar a cell. */
|
||||
for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) {
|
||||
const int r = i / (chunk >> 2), c = i % (chunk >> 2);
|
||||
uint32_t lo = 0, hi = 0;
|
||||
if (r < M) {
|
||||
const int64_t k0 = (int64_t)ch * (chunk >> 2) * 4 + c * 4;
|
||||
const uint32_t w = *(const uint32_t*)(a + (long long)r * a_pitch + k0);
|
||||
const float s = sa[(long long)r * sa_stride + k0 / kGroup];
|
||||
uint32_t w2[2];
|
||||
e4m3x4_to_f16x2(sTbl, w, w2);
|
||||
lo = fold_pair(w2[0], s);
|
||||
hi = fold_pair(w2[1], s);
|
||||
}
|
||||
const int q = r * (chunk >> 2) + c;
|
||||
sA[p_ix(q)] = make_uint2(lo, hi);
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
if (live) {
|
||||
/* 64 codes, 32 bytes: two 16-byte loads, aligned by the row pitch and k0 % 32 == 0. */
|
||||
const uint8_t* bp = b + (long long)n * (K >> 1) + (int64_t)ch * (chunk >> 1)
|
||||
+ kl * (CL >> 1);
|
||||
uint4 qw0 = make_uint4(0, 0, 0, 0), qw1 = make_uint4(0, 0, 0, 0);
|
||||
__builtin_memcpy(&qw0, bp, 16);
|
||||
__builtin_memcpy(&qw1, bp + 16, 16);
|
||||
const uint32_t w8[8] = { qw0.x, qw0.y, qw0.z, qw0.w, qw1.x, qw1.y, qw1.z, qw1.w };
|
||||
|
||||
const int qb = m * (chunk >> 2) + kl * (CL >> 2);
|
||||
float p0 = 0.0f, p1 = 0.0f; /* the lane's two 32-block partials */
|
||||
#pragma unroll
|
||||
for (int v = 0; v < 8; ++v) { /* dwords 0..3: block 2*kl, 4..7: 2*kl+1 */
|
||||
uint32_t elo, ehi;
|
||||
mxfp4_unpack8(w8[v], &elo, &ehi);
|
||||
float& p = (v < 4) ? p0 : p1;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 2; ++e) {
|
||||
uint32_t w2[2];
|
||||
e4m3x4_to_f16x2(sTbl, e ? ehi : elo, w2);
|
||||
const uint2 av = sA[p_ix(qb + 2 * v + e)];
|
||||
p = dot4_f16x4(av.x, av.y, w2[0], w2[1], p);
|
||||
}
|
||||
}
|
||||
|
||||
/* The lane's two blocks, scaled by their e8. The pair (kl, kl^1) owns the group's
|
||||
* four blocks -- kl even the lower two, kl odd the upper two -- so one exchange
|
||||
* forms the group in ascending block order. */
|
||||
const int blk0 = ch * (chunk / kMX) + 2 * kl;
|
||||
const float q0f = p0 * e8_scale(e8[(long long)n * e8_row + blk0]);
|
||||
const float q1f = p1 * e8_scale(e8[(long long)n * e8_row + blk0 + 1]);
|
||||
const float o0f = __shfl_xor(q0f, MT);
|
||||
const float o1f = __shfl_xor(q1f, MT);
|
||||
const bool lo = !(kl & 1);
|
||||
const float t0 = lo ? q0f : o0f;
|
||||
const float t1 = lo ? q1f : o1f;
|
||||
const float t2 = lo ? o0f : q0f;
|
||||
const float t3 = lo ? o1f : q1f;
|
||||
|
||||
/* One slot per (row, 32-block-in-chunk): MT*BPR is 64 at every MT. The group's two
|
||||
* half-lanes write the same four values. */
|
||||
const int j = kl >> 1;
|
||||
const int bb = warp * 64 + m * BPR + 4 * j;
|
||||
sB[bb + 0] = t0;
|
||||
sB[bb + 1] = t1;
|
||||
sB[bb + 2] = t2;
|
||||
sB[bb + 3] = t3;
|
||||
}
|
||||
__syncthreads();
|
||||
/* The chunk's block terms, in ascending block order, into the lane that owns the row's
|
||||
* answer: the reference walks k in ascending order and f32 adds are not associative, so
|
||||
* the order is part of the answer, not a detail. */
|
||||
if (live && kl == 0) {
|
||||
#pragma unroll
|
||||
for (int bl = 0; bl < BPR; ++bl)
|
||||
if (m < M) acc += sB[warp * 64 + m * BPR + bl];
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
if (live && kl == 0 && m < M) y[(long long)m * y_pitch + n] = f32_to_bf16(acc);
|
||||
}
|
||||
|
||||
/* ================================================================== the launchers */
|
||||
|
||||
static int mt_for(int M)
|
||||
{
|
||||
int mt = 1;
|
||||
while (mt < M && mt < kMTMax) mt *= 2;
|
||||
return mt;
|
||||
}
|
||||
|
||||
extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y,
|
||||
int M, int N, int K, int group, int a_ld, int y_ld,
|
||||
long long e8_row, long stream)
|
||||
{
|
||||
if (!a || !a_scale || !b || !b_scale || !y) return -1;
|
||||
if (M < 1 || N < 1 || K < 1) return -2;
|
||||
if (M > kMTMax) return -2;
|
||||
if (group != kGroup) return -2;
|
||||
if (K % kGroup) return -2; /* the activation's scale group */
|
||||
if (K % kMX) return -2; /* the weight's 32-block */
|
||||
const int mt = mt_for(M);
|
||||
const int chunk = 2048 / mt;
|
||||
if (K % chunk) return -2;
|
||||
if (!a_ld) a_ld = K;
|
||||
if (!y_ld) y_ld = N;
|
||||
if (a_ld < K) return -3;
|
||||
if (a_ld % 4) return -3; /* four codes a dword, staged whole */
|
||||
if (y_ld < N) return -3;
|
||||
if (!e8_row) e8_row = K / kMX;
|
||||
if (e8_row < K / kMX) return -3;
|
||||
if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5;
|
||||
|
||||
const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads);
|
||||
#define R3D_MXFP4A8_M16(MT) \
|
||||
do { \
|
||||
R3D_KLAUNCH(R3D_KNAME((gemm_mxfp4a8_m16_kernel<MT>)), grid, block, (hipStream_t)stream, \
|
||||
(const uint8_t*)a, (const float*)a_scale, K / kGroup, (const uint8_t*)b, \
|
||||
(const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \
|
||||
y_ld); \
|
||||
} while (0)
|
||||
switch (mt) {
|
||||
case 1: R3D_MXFP4A8_M16(1); break;
|
||||
case 2: R3D_MXFP4A8_M16(2); break;
|
||||
case 4: R3D_MXFP4A8_M16(4); break;
|
||||
case 8: R3D_MXFP4A8_M16(8); break;
|
||||
default: R3D_MXFP4A8_M16(16); break;
|
||||
}
|
||||
#undef R3D_MXFP4A8_M16
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
#define L_MX(why, a1, v1, a2, v2) \
|
||||
do { \
|
||||
if (r3d_trace_on()) \
|
||||
std::fprintf(stderr, "[r3d] %s:%d %s: %s = %lld, %s = %lld\n", \
|
||||
__FILE__, __LINE__, (why), (a1), (long long)(v1), (a2), \
|
||||
(long long)(v2)); \
|
||||
return R3D_NO(-3); \
|
||||
} while (0)
|
||||
|
||||
int launch_mxfp4a8_tiled(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K,
|
||||
int group, int a_ld, long long b_row, int as_ld, long long e8_row,
|
||||
int y_ld, int nt, long stream)
|
||||
{
|
||||
if (!av || !asv || !bvc || !bsv || !yv) return -1;
|
||||
if (M < kMMin || N < 1 || K < 1) return -2;
|
||||
if (group != kGroup) return -2; /* kKC 32 divides the group 128 */
|
||||
if (K % kGroup) return -2; /* a ragged k-block reads past the scale planes */
|
||||
if (K > (1 << 24)) return -2;
|
||||
if (nt < 0 || nt > 1) return -2;
|
||||
if (a_ld % 8) L_MX("a pitch: 8-byte code loads, 8 codes a lane", "a_ld", a_ld, "K", K);
|
||||
if (b_row & 15) L_MX("b row pitch: 16-byte code loads", "b_row", b_row, "K", K);
|
||||
if (as_ld < (K + kGroup - 1) / kGroup) L_MX(
|
||||
"a_scale: one per (row, group)", "as_ld", as_ld, "ceil(K/group)",
|
||||
(K + kGroup - 1) / kGroup);
|
||||
if (y_ld % 8) L_MX("y pitch: 16-byte bf16 store runs", "y_ld", y_ld, "N", N);
|
||||
if (a_ld < K) L_MX("a pitch shorter than K", "a_ld", a_ld, "K", K);
|
||||
if (!b_row) b_row = K >> 1;
|
||||
if (b_row < (K >> 1)) L_MX("b row pitch shorter than K/2", "b_row", b_row, "K", K);
|
||||
if (!e8_row) e8_row = K / kMX;
|
||||
if (e8_row < K / kMX) L_MX("e8 row pitch shorter than K/32", "e8_row", e8_row, "K", K);
|
||||
if (y_ld < N) L_MX("y pitch shorter than N", "y_ld", y_ld, "N", N);
|
||||
if ((av & 7) || (asv & 3) || (bvc & 15) || (bsv & 1) || (yv & 7)) return -5;
|
||||
|
||||
const dim3 blk(kBlockThreads);
|
||||
const dim3 grd((unsigned)((N + kTN - 1) / kTN), (unsigned)((M + kTM - 1) / kTM));
|
||||
ActQ aq{(const float*)(uintptr_t)asv, (long long)as_ld, 1};
|
||||
MxWQ h{(const uint8_t*)(uintptr_t)bvc, (const uint8_t*)(uintptr_t)bsv, b_row, e8_row};
|
||||
hipStream_t s = (hipStream_t)(uintptr_t)stream;
|
||||
if (nt) mxfp4a8_tiled_kernel<1><<<grd, blk, 0, s>>>(
|
||||
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
|
||||
else mxfp4a8_tiled_kernel<0><<<grd, blk, 0, s>>>(
|
||||
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y,
|
||||
int M, int N, int K, int group, int a_ld,
|
||||
long long b_row, int as_ld, long long e8_row,
|
||||
int y_ld, int nt, long stream)
|
||||
{
|
||||
return launch_mxfp4a8_tiled(a, a_scale, b_codes, b_scale, y, M, N, K, group, a_ld, b_row,
|
||||
as_ld, e8_row, y_ld, nt, stream);
|
||||
}
|
||||
|
||||
/* ================================================================== the shims
|
||||
*
|
||||
* gemm_nt_q's slots, as the two shims take them: 0 a (E4M3), 1 a_scale (f32, one per (row,
|
||||
* 128 of K)), 2 b (the e2m1 codes -- fp4_e2m1, or the raw u8 bytes, two a byte), 3 b_scale (the
|
||||
* e8 plane, e8m0 or u8, one per 32 of K), 4 y (bf16), 5 a_sum (absent: symmetric), 6 b_ref (the
|
||||
* e8 plane again, accepted and ignored).
|
||||
*/
|
||||
|
||||
/* The reserved-e8 scan: one pass per (pointer, size) pair for the process's life. The plane is
|
||||
* the weight's, its address stable across the launches a pass makes, and a second scan of the
|
||||
* same bytes buys nothing. The scan needs the host to see the plane -- the mapped tier's form,
|
||||
* the placement the row's operands take; a plane the host cannot see is not scanned, and the
|
||||
* kernel's e8 guard carries the reserved values there. */
|
||||
struct E8ScanKey { const void* p; long long n; };
|
||||
static bool e8_scan_once(const void* p, long long n)
|
||||
{
|
||||
static E8ScanKey seen[16];
|
||||
static int ns = 0;
|
||||
for (int i = 0; i < ns; ++i)
|
||||
if (seen[i].p == p && seen[i].n == n) return true;
|
||||
if (ns < 16) seen[ns++] = E8ScanKey{ p, n };
|
||||
void* dev = nullptr;
|
||||
if (hipHostGetDevicePointer(&dev, (void*)p, 0) != hipSuccess) return true;
|
||||
const uint8_t* e8 = (const uint8_t*)p;
|
||||
for (long long i = 0; i < n; ++i)
|
||||
if (e8[i] == 0 || e8[i] == 255) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s)
|
||||
{
|
||||
if (!a) return R3D_NO(RAD_E_INVAL);
|
||||
const char* dt = r3d_gets(a, "dtype");
|
||||
if (dt && std::strcmp(dt, "mxfp4a8") != 0) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
const RadTensor* A = r3d_opt(a, 0);
|
||||
const RadTensor* AS = r3d_opt(a, 1);
|
||||
const RadTensor* B = r3d_opt(a, 2);
|
||||
const RadTensor* BS = r3d_opt(a, 3);
|
||||
const RadTensor* Y = r3d_opt(a, 4);
|
||||
const RadTensor* ASUM = r3d_opt(a, 5);
|
||||
const RadTensor* BREF = r3d_opt(a, 6);
|
||||
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
|
||||
return R3D_NO(RAD_E_INVAL);
|
||||
if (r3d_has(ASUM)) return R3D_NO(RAD_E_DTYPE); /* symmetric: no zero point */
|
||||
/* `b_ref` is the reference's per-row exponent, derived from `b_scale`: it changes no
|
||||
* product, so beside an e2m1 weight its dtype is checked and its value ignored. */
|
||||
if (r3d_has(BREF) && BREF->dtype != RAD_E8M0 && BREF->dtype != RAD_U8)
|
||||
return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (B->dtype != RAD_FP4E2M1 && B->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e2m1, two a byte */
|
||||
if (BS->dtype != RAD_E8M0 && BS->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e8m0, one per 32 */
|
||||
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
|
||||
/* The `group` key names the band; the blocks the kernel reads -- 128 for the activation's
|
||||
* scale, 32 for the weight's e8 -- are the format's, so the key is not checked. */
|
||||
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
|
||||
if (K % kGroup || K % kMX) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long ynel = r3d_numel(Y);
|
||||
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long M = ynel / N;
|
||||
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(AS) < M * (K / kGroup)) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long bbytes = B->dtype == RAD_FP4E2M1 ? r3d_numel(B) / 2 : r3d_numel(B);
|
||||
if (bbytes < N * (K / 2)) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(BS) < N * (K / kMX)) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long ap = r3d_row_pitch(A);
|
||||
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE);
|
||||
const long long as_p = r3d_row_pitch(AS);
|
||||
if (as_p < K / kGroup) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE);
|
||||
long long yrows = 0;
|
||||
const long long yp = r3d_rows_pitch(Y, N, &yrows);
|
||||
if (yp < N) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
if (!e8_scan_once(r3d_p(BS), N * (K / kMX))) return R3D_NO(RAD_E_INVAL);
|
||||
|
||||
const int rc = r3d_gemm_nt_q_mxfp4a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
|
||||
r3d_addr(Y), (int)M, (int)N, (int)K, kGroup,
|
||||
(int)ap, (int)yp, (long long)r3d_row_pitch(BS),
|
||||
(long)s);
|
||||
if (rc == -1) return R3D_NO(RAD_E_INVAL);
|
||||
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
|
||||
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
|
||||
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
|
||||
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
|
||||
{
|
||||
if (!a) return R3D_NO(RAD_E_INVAL);
|
||||
const char* dt = r3d_gets(a, "dtype");
|
||||
if (dt && std::strcmp(dt, "mxfp4a8") != 0) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
const RadTensor* A = r3d_opt(a, 0);
|
||||
const RadTensor* AS = r3d_opt(a, 1);
|
||||
const RadTensor* B = r3d_opt(a, 2);
|
||||
const RadTensor* BS = r3d_opt(a, 3);
|
||||
const RadTensor* Y = r3d_opt(a, 4);
|
||||
const RadTensor* ASUM = r3d_opt(a, 5);
|
||||
const RadTensor* BREF = r3d_opt(a, 6);
|
||||
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
|
||||
return R3D_NO(RAD_E_INVAL);
|
||||
if (r3d_has(ASUM)) return R3D_NO(RAD_E_DTYPE); /* symmetric: no zero point */
|
||||
if (r3d_has(BREF) && BREF->dtype != RAD_E8M0 && BREF->dtype != RAD_U8)
|
||||
return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (B->dtype != RAD_FP4E2M1 && B->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE);
|
||||
if (BS->dtype != RAD_E8M0 && BS->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
/* The band's keys, from the schema: N, K, group. The codes plane is [N, K/2], so a band that
|
||||
* names no N or K is answered by the operand, with the /2 restored. */
|
||||
const long long M_band = r3d_geti_or(a, "M", 0);
|
||||
const long long N0 = r3d_geti_or(a, "N", 0), K0 = r3d_geti_or(a, "K", 0);
|
||||
const long long N = N0 > 0 ? N0 : r3d_dim(B, 0);
|
||||
/* A band that names no K is answered by the codes plane: [N, K] of fp4_e2m1, [N, K/2] of
|
||||
* raw bytes. The `group` key names the band; the blocks the kernel reads are the
|
||||
* format's, so the key is not checked. */
|
||||
const long long K = K0 > 0 ? K0
|
||||
: (B->dtype == RAD_FP4E2M1 ? r3d_dim(B, 1) : 2 * r3d_dim(B, 1));
|
||||
if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE);
|
||||
if (K > (1 << 24)) return R3D_NO(RAD_E_INVAL);
|
||||
if (K % kGroup || K % kMX) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
long long a_rows = 0;
|
||||
const long long ap = r3d_rows_pitch(A, K, &a_rows);
|
||||
if (ap < K || a_rows < 1) return R3D_NO(RAD_E_STRIDE);
|
||||
if (ap % 8) return R3D_NO(RAD_E_STRIDE); /* 8-byte code loads, 8 codes a lane */
|
||||
/* THE STEP'S M IS THE ACTIVATION'S ROW COUNT. The band key M is an upper bound: a step
|
||||
* shorter than the band is the step the engine runs, and the key keeps its job as the
|
||||
* ceiling the plan promised not to exceed. */
|
||||
const long long M = a_rows;
|
||||
if (M_band > 0 && M > M_band) return R3D_NO(RAD_E_SHAPE);
|
||||
if (M < kMMin) return R3D_NO(RAD_E_UNSUPPORTED); /* the m16 row serves M <= 16 */
|
||||
|
||||
const long long ynel = r3d_numel(Y);
|
||||
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
|
||||
if (ynel / N < M) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(AS) < M * (K / kGroup)) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long bbytes = B->dtype == RAD_FP4E2M1 ? r3d_numel(B) / 2 : r3d_numel(B);
|
||||
if (bbytes < N * (K / 2)) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(BS) < N * (K / kMX)) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long as_p = r3d_row_pitch(AS);
|
||||
if (as_p < K / kGroup) return R3D_NO(RAD_E_STRIDE);
|
||||
/* The codes plane's pitch, in bytes: fp4_e2m1 counts elements, two to a byte. */
|
||||
const long long cp0 = r3d_row_pitch(B);
|
||||
const long long cp = B->dtype == RAD_FP4E2M1 ? cp0 / 2 : cp0;
|
||||
if (cp < K / 2) return R3D_NO(RAD_E_STRIDE);
|
||||
if (cp & 15) return R3D_NO(RAD_E_ALIGN);
|
||||
const long long e8p = r3d_row_pitch(BS);
|
||||
if (e8p < K / kMX) return R3D_NO(RAD_E_STRIDE);
|
||||
long long yrows = 0;
|
||||
const long long yp = r3d_rows_pitch(Y, N, &yrows);
|
||||
if (yp < N) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_aligned(r3d_p(A), 8) || !r3d_aligned(r3d_p(AS), 4) ||
|
||||
!r3d_aligned(r3d_p(B), 16) || !r3d_aligned(r3d_p(Y), 8))
|
||||
return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
if (!e8_scan_once(r3d_p(BS), N * (K / kMX))) return R3D_NO(RAD_E_INVAL);
|
||||
|
||||
const int nt = (int)r3d_geti_or(a, "nt", 0);
|
||||
const int rc = r3d_gemm_nt_q_mxfp4a8_tiled(r3d_addr(A), r3d_addr(AS), r3d_addr(B),
|
||||
r3d_addr(BS), r3d_addr(Y), (int)M, (int)N,
|
||||
(int)K, kGroup, (int)ap, cp, (int)as_p, e8p,
|
||||
(int)yp, nt, (long)s);
|
||||
if (rc == -1) return R3D_NO(RAD_E_INVAL);
|
||||
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
|
||||
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
|
||||
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
|
||||
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -0,0 +1,576 @@
|
||||
/* r3d_gemm_nt_q_w2a8.hip -- gemm_nt_q at dtype=w2a8: the vocabulary projection, decode-sized.
|
||||
*
|
||||
* y[M,N] = a[M,K] @ b[N,K]^T over a 2-bit unsigned weight code with an f16 scale and an unsigned
|
||||
* integer zero per (row, group of K), an int8 activation with one f32 scale per ROW, and the int8
|
||||
* code sums `a_sum` the zero is removed with. f32 accumulate, bf16 store.
|
||||
*
|
||||
* This is the band that gates the server. MiniCPM5-2B's `output.weight` is N=130560, K=2048,
|
||||
* group=128, dtype=w2a8, and its stored form is the container's joined `rad.planes` operand: a
|
||||
* scale plane and a zero plane behind ONE operand (b_scale). libref declines w2a8 in
|
||||
* `gemm_q_shape`, so kbench has no case for the op the engine needs most -- the fixture cannot
|
||||
* draw the dtype, which is why this row's evidence is a driver that builds the joined operand with
|
||||
* `rad_planes_relayout` and compares every element against `ref_gemm_nt_q`'s own body. libref reads
|
||||
* the form in `gemm_zp`, so a host row serves it, at 135 GFLOP of CPU work per token; and a
|
||||
* placement without a reader is refused, because nothing in the loaded set can READ the joined form.
|
||||
* `r3d_layout_gemm_q_w2a8` below is that reader: it DESCRIBES the container's bytes (that is what
|
||||
* RadLayoutFn in rad_abi.h is), and the row carries no relayout and no repacking.
|
||||
*
|
||||
* ---- the law, and the order inside it ---------------------------------------------------------
|
||||
*
|
||||
* gemm_zp, the ZP_I8_ROW arm, is the spec, and this kernel runs its order:
|
||||
*
|
||||
* q[k] = rad_load_bits(row n of b, 2, k) bits [2k,2k+2) of byte k/4
|
||||
* is(g) = SUM_{k in group g} (int)a[m][i8_step_pos(k)] * (int)q[k] integers: exact
|
||||
* sub(g) = (float)is(g) - (float)z[n][g] * a_sum[g*mpad + m] mpad = ceil(M/16)*16 = 16
|
||||
* acc = acc + (sub(g) * sa[m]) * sb[n][g] g ASCENDING
|
||||
* y[m,n] = bf16(acc)
|
||||
*
|
||||
* `a_sum` is per row and per group and group-major, `sa` is one f32 per ROW (ZP_I8_ROW: quant_act_i8
|
||||
* scales a whole row, not a group), and `(sub * sa) * sb` is a parenthesised order, not a formula.
|
||||
*
|
||||
* The activation is in quant_act_i8's step order: column c sits at byte
|
||||
* i8_step_pos(c) = (c & ~12) | ((c & 4) << 1) | ((c & 8) >> 1), bits 2 and 3 of c swapped, the map
|
||||
* its own inverse. Swapping bits 2 and 3 of a column is swapping bits 0 and 1 of its DWORD index,
|
||||
* so a dword's four columns stay four contiguous bytes: staging reads a's dwords in a permuted
|
||||
* dword order, one 4-byte load per four codes, and nothing straddles a dword.
|
||||
*
|
||||
* `is` is a sum of integers, every partial sum under 2^24, so it is exact in f32 and its bracketing
|
||||
* is free. `sub`, the products and the g-ascending accumulation are float, and their order is the
|
||||
* reference's, so the store is bit-identical to the host row: bit-equality element by element is
|
||||
* the test, not a tolerance, because nothing else on this machine can draw the operands.
|
||||
*
|
||||
* ---- U2 to f16 through a bias, and the bias removed with a_sum ---------------------------------
|
||||
*
|
||||
* There is no int8 dot on this ISA. `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a`
|
||||
* and the RDNA3 matrix ops `__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are all undeclared in AMD
|
||||
* clang 24.0.0git for gfx1102. So the codes widen to f16 and the dot runs on dot2_f16x2, whose
|
||||
* hardware form folds a pair into an f32 accumulator. Every product is
|
||||
* an integer and every partial sum is an integer, and "products and partials are integers below
|
||||
* 2^24" is a true statement about f32 and a false statement about this instruction: v_fdot2_f32_f16
|
||||
* carries a little under 24 bits of mantissa on integer operands -- about 22, from the ratio of the
|
||||
* worst error to its magnitude -- so any kernel that pushes integers through a pair-dot inherits a
|
||||
* tail once its partials reach 2^20. The instrument at the end of this file (one 64-code dot per
|
||||
* lane, the f32 it produces beside the exact integer it should have produced) shows: bias 1024,
|
||||
* 71027 of 262144 dots off, by up to 1/8. Bias 128, 70115 of 262144 off, by up to 1/64. The bias is 128 because the tail grows with the magnitude, and 128 is
|
||||
* the largest power of two that keeps a lane's partial sum under 2^21; shrinking it is a smaller
|
||||
* tail, not no tail. What the tail costs is one bit of the bf16 answer: 0.1-0.2% of outputs land one
|
||||
* bf16 ulp off and nothing else, rel_l2 5.0e-3 at the band, no non-finite anywhere. That is this
|
||||
* row's exactness, written out here because the law below is exact integers and the row reads like a
|
||||
* bit-exact one. It is not, and the row's prose says so.
|
||||
* The row without the dot unit -- four f32 words a quad in the tile, four __fmaf_rn per quad -- is
|
||||
* not in this file. Its arithmetic is exact: a probe of 262144 samples of the four fmas with no
|
||||
* tile, zero inexact dots, worst error exactly zero. Its staging is the defect: the f32 tile,
|
||||
* written through a vector pointer at -O2, comes up with content that was never written, and
|
||||
* typing the array `uint4` rules aliasing out, so the defect is in the tile staging and not in the
|
||||
* arithmetic.
|
||||
* At the band this row is not memory-bound. r3d_vocab_bf16.hip streams the same n_vocab x n_embd
|
||||
* head in 535 MB of bf16 in 3.29 ms at M=1, 163 GB/s, two thirds of the card's DRAM. The 66.8 MB
|
||||
* of codes this row reads has a streaming floor near 0.41 ms, not the 3.0 ms of one 22 GB/s pass
|
||||
* this row measures, so this row runs 6-10x above its own floor and the headroom is in its loop --
|
||||
* the group-term plane and the two barriers a chunk -- not in the memory system. An f32 row costs
|
||||
* nothing to run, and the tail goes with it.
|
||||
* The trick that pays for the widening is that f16 bits of (128 + x) are 0x5800 + 8x for 0 <= x < 8,
|
||||
* so a 2-bit code becomes an f16 with a mask, two shifts and an add -- no table, no compare per
|
||||
* code -- and the dot returns is' = SUM a[k]*(128 + q[k]) = is + 128*SUM a. SUM a over the group is
|
||||
* the plane the op already carries: a_sum[g*mpad + m], the very number the zero is removed with.
|
||||
* 128 * a_sum scales an integer-valued f32 by a power of two, so it is exact, is = is' - 128*a_sum
|
||||
* is exact, and the reference's own sub = (float)is - (float)z*a_sum follows unchanged. The de-bias
|
||||
* costs one exact f32 subtraction per (m, group) and is why a row with no int8 instruction on it is
|
||||
* memory-bound at the band instead of unpack-bound.
|
||||
*
|
||||
* ---- the lane map ------------------------------------------------------------------------------
|
||||
*
|
||||
* One warp per weight row n; a block of 8 waves covers 8 rows. MT, the template's row count, is the
|
||||
* power of two that covers M, and KL = 32/MT is the number of k-lanes per activation row. A chunk
|
||||
* is CHUNK = 2048/MT codes, so the staged tile is always MT*CHUNK/2 = 1024 dwords = 4 KiB: the
|
||||
* tile shrinks with the row count exactly as the row count grows, which is what keeps the block
|
||||
* resident at M=16. A chunk holds CHUNK/128 = 16/MT groups and every lane takes 64 codes -- one
|
||||
* 16-byte load of codes (four bytes, sixteen codes each, U2 being four codes a byte), thirty-two
|
||||
* dwords of activation from LDS and thirty-two dot2 in sixteen dot4_f16x4 -- so lane l owns row
|
||||
* m = l % MT, k-lane kl = l / MT, and group ch*(16/MT) + kl/2, whose two halves are the pair
|
||||
* (l, l^MT): the group folds with ONE shfl_xor, in integers.
|
||||
*
|
||||
* Each lane's group index ascends with the chunk index, so `acc += term` in the lane IS the
|
||||
* reference's ascending g loop over the groups that lane owns; the groups the other k-lanes own are
|
||||
* added by kl-1 ordered broadcasts per chunk, in ascending kl, which is ascending g. At M=16, where
|
||||
* a chunk is one group, there is no cross-lane float work at all. Reassociating the g sum is what
|
||||
* would break bit-equality, and the map is built so that no lane ever has to.
|
||||
*
|
||||
* LDS is touched a quad at a time (two dwords, 8 bytes), swizzled as `p_ix` below; unswizzled the
|
||||
* wavefront's 32 quads for one u all sit in the same bank pair.
|
||||
*
|
||||
* ---- refusals (codes; RAD_R3D_TRACE=1 prints the line) -----------------------------------------
|
||||
*
|
||||
* The shim mirrors gemm_ntq_impl's and gemm_zp's checks and declines two things the reference
|
||||
* accepts, each named at its site: M > 16 (the band is 16, the tile is 16 rows, mpad is the
|
||||
* reference's 16-row pad; the prefill vocab projection is `logits_gemm` and is a tiled bf16 row,
|
||||
* not a wider loop bound here), and a zero plane stored sub-byte (U2/U4/U5), where the kernel reads
|
||||
* a zero a byte at a time -- a sub-byte zero plane needs the bit-extract path,
|
||||
* `rad_load_bits(zb, bits, g)` is ten lines. w2a8's practical form, and this container's, is U8.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_codecs.h"
|
||||
#include "r3d_launch.h"
|
||||
#include "r3d_args.h"
|
||||
|
||||
#include "rad_planes.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kBlockThreads = 256;
|
||||
constexpr int kWaves = kBlockThreads / kWave; /* 8 weight rows per block */
|
||||
constexpr int kMTMax = 16; /* the band's M */
|
||||
constexpr int kTileQuads = 512; /* MT * CHUNK/4, constant over MT: 512 quads, 4 KiB */
|
||||
constexpr int kGroup = 128; /* the block size w2a8 is stored at */
|
||||
constexpr int kMpad = 16; /* the reference's (M+15)/16*16, M <= 16 */
|
||||
|
||||
/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse. Applying
|
||||
* it to the four columns of one dword leaves them four contiguous bytes and turns the map on the
|
||||
* DWORD index into a swap of bits 0 and 1 -- the middle two dwords of a 16-byte step exchanged.
|
||||
* The byte a dword starts at is therefore 4 * dword_pos(d): NOT 4 * step_pos(d), which swaps the
|
||||
* wrong pair of bits and reads the step's dwords unexchanged. */
|
||||
[[maybe_unused]] [[maybe_unused]] __device__ __forceinline__ int64_t step_pos(int64_t c)
|
||||
{
|
||||
return (c & ~(int64_t)12) | ((c & 4) << 1) | ((c & 8) >> 1);
|
||||
}
|
||||
__device__ __forceinline__ int64_t dword_pos(int64_t d)
|
||||
{
|
||||
return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1));
|
||||
}
|
||||
|
||||
/* The LDS swizzle, at the granularity the tile is touched: a quad of four codes, two dwords, moved
|
||||
* as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low four bits with
|
||||
* bits 4..7 -- a bijection on 16-quad groups, so on any tile whose quad count is a multiple of 16.
|
||||
* A wavefront reads q = m*(CHUNK/4) + kl*16 + u for fixed u; CHUNK/4 is a multiple of 16 at every
|
||||
* MT, so q ^ (q >> 4) mod 16 is u ^ (4m + kl) mod 16 over the 32 lanes -- 16 distinct values, each
|
||||
* one 8-byte access spanning two banks: 32 banks, no conflict. The swizzle must leave bit 0 of the
|
||||
* quad index alone: the two dwords of a quad are adjacent only then, and the scalar form that
|
||||
* XORs bits 5..9 of the dword index does not. */
|
||||
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
|
||||
|
||||
/* Four int8 codes -> two f16x2 dwords. Exact: an integer of |a| <= 127 needs no rounding. */
|
||||
__device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi)
|
||||
{
|
||||
lo = f16x2_pack((float)(int32_t)(int8_t)(w & 0xffu), (float)(int32_t)(int8_t)((w >> 8) & 0xffu));
|
||||
hi = f16x2_pack((float)(int32_t)(int8_t)((w >> 16) & 0xffu),
|
||||
(float)(int32_t)(int8_t)((w >> 24) & 0xffu));
|
||||
}
|
||||
|
||||
/* Four U2 codes (one byte) -> two f16x2 dwords, BIASED by 128: each half is the f16 bits of
|
||||
* (128 + code). An f16 at exponent 2^7 steps its mantissa by 1/8, so 128 + code is 0x5800 + 8*code
|
||||
* and stays an integer. The dot therefore returns is + 128 * the group's code sum, which the
|
||||
* epilogue takes off with the group's a_sum.
|
||||
*
|
||||
* The bias is 128 and not 1024 because of where the dot unit's precision runs out. a * (B + q) is an
|
||||
* integer the size of 128 * B, and a lane's 64 of them sum to 64 * 128 * (B + 3): at B = 1024 that is
|
||||
* 2^23, at B = 128 it is 2^20. The unit keeps a little under 24 bits of mantissa on integers, so the
|
||||
* tail scales with the magnitude -- 71027 of 262144 dots off by up to 1/8 at B = 1024, 70115 off by
|
||||
* up to 1/64 at B = 128, in the probe below. 128 is the largest power of two that keeps a lane's
|
||||
* partial sum under 2^21, which is as close as a pair-dot gets; the header carries the rest. */
|
||||
__device__ __forceinline__ void u2x4_biased(uint32_t w, uint32_t& lo, uint32_t& hi)
|
||||
{
|
||||
lo = 0x58005800u + ((w & 3u) << 3) + (((w >> 2) & 3u) << 19);
|
||||
hi = 0x58005800u + (((w >> 4) & 3u) << 3) + (((w >> 6) & 3u) << 19);
|
||||
}
|
||||
|
||||
template <int MT>
|
||||
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
|
||||
gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int sa_stride,
|
||||
const uint8_t* __restrict__ b, const uint16_t* __restrict__ sb, int sb_rb,
|
||||
const uint8_t* __restrict__ zq, int z_rb, const float* __restrict__ asum,
|
||||
int asum_stride, uint16_t* __restrict__ y, int M, int N, int K, int chunk,
|
||||
int a_pitch, int y_pitch)
|
||||
{
|
||||
constexpr int KL = kWave / MT; /* k-lanes per activation row */
|
||||
constexpr int CG = (2048 / MT) / kGroup; /* groups per chunk */
|
||||
constexpr int CL = (2048 / MT) / KL; /* codes per lane per chunk: 64 */
|
||||
|
||||
/* The tile: one quad of four codes per slot, two f16x2 dwords, typed as the quad the staging
|
||||
* writes and the dot reads. The tile is a `uint2[]` and not a `uint32_t[]` reached through a
|
||||
* vector pointer: the f32 variant of this row, written through `*(uint4*)&sA[]` at -O2, comes
|
||||
* up with content that was never written. */
|
||||
__shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/2 f16, swizzled */
|
||||
__shared__ float sT[kWaves * 16]; /* each warp's chunk terms: warp*16 + m*CG + j */
|
||||
__shared__ float sSa[MT];
|
||||
|
||||
const int lane = threadIdx.x & (kWave - 1);
|
||||
const int warp = (int)(threadIdx.x / kWave);
|
||||
const int n = blockIdx.x * kWaves + warp;
|
||||
/* A wavefront past the last row sits the chunk out, but it stages: the tile is block-wide, so
|
||||
* the warps that have no row to serve still write the rows their lanes own. Only a block whose
|
||||
* EIGHT rows are all past the last row leaves, which is a block-uniform test and cannot strand
|
||||
* a barrier; a guard on the row would, because the tail block's dead warps own tile rows and
|
||||
* staging them from never-written memory corrupts the tile. The store is guarded by `live`
|
||||
* below, so a dead wavefront writes nothing. */
|
||||
const bool live = n < N;
|
||||
if ((int)blockIdx.x * kWaves >= N) return;
|
||||
|
||||
const int m = lane & (MT - 1);
|
||||
const int kl = lane / MT;
|
||||
const int row_bytes = K >> 2; /* rad_enc_row_bytes(RAD_U2, K), K % 16 == 0 */
|
||||
const int cq = chunk >> 2; /* the chunk's code bytes */
|
||||
const int nchunk = K / chunk;
|
||||
|
||||
if (lane < MT) sSa[lane] = lane < M ? sa[(long long)lane * sa_stride] : 0.0f;
|
||||
__syncthreads();
|
||||
|
||||
float acc = 0.0f;
|
||||
for (int ch = 0; ch < nchunk; ++ch) {
|
||||
/* Stage the chunk's activation rows, widened and step-unpermuted on the way in. Cells are
|
||||
* four codes: MT * CHUNK/4 = 512 of them at every MT, two per thread. */
|
||||
for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) {
|
||||
const int r = i / (chunk >> 2), c = i % (chunk >> 2);
|
||||
uint32_t w = 0;
|
||||
if (r < M)
|
||||
w = *(const uint32_t*)(a + (long long)r * a_pitch +
|
||||
dword_pos((int64_t)ch * (chunk >> 2) + c));
|
||||
const int q = r * (chunk >> 2) + c;
|
||||
uint32_t lo, hi;
|
||||
i8x4_to_f16x2(w, lo, hi);
|
||||
sA[p_ix(q)] = make_uint2(lo, hi);
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
uint4 qw = make_uint4(0, 0, 0, 0);
|
||||
if (live)
|
||||
qw = *(const uint4*)(b + (long long)n * row_bytes + (long long)ch * cq + kl * (CL >> 2));
|
||||
const uint32_t w4[4] = { qw.x, qw.y, qw.z, qw.w };
|
||||
|
||||
if (live) {
|
||||
const int qb = m * (chunk >> 2) + kl * (CL >> 2);
|
||||
float p = 0.0f; /* the lane's half-group, an exact integer */
|
||||
#pragma unroll
|
||||
for (int v = 0; v < 4; ++v) { /* four bytes, four quads, sixteen codes */
|
||||
#pragma unroll
|
||||
for (int b = 0; b < 4; ++b) {
|
||||
uint32_t ql, qh;
|
||||
u2x4_biased((w4[v] >> (8 * b)) & 0xffu, ql, qh);
|
||||
const uint2 av = sA[p_ix(qb + 4 * v + b)];
|
||||
p = dot4_f16x4(av.x, av.y, ql, qh, p);
|
||||
}
|
||||
}
|
||||
/* Fold the pair: lanes l and l^MT are the same row, the two halves of one group. */
|
||||
const float isg = p + __shfl_xor(p, MT);
|
||||
|
||||
const int g = ch * CG + (kl >> 1);
|
||||
const float as = asum[(long long)g * asum_stride + m];
|
||||
const float is = isg - 128.0f * as; /* exact: the de-bias */
|
||||
const float iz = (float)zq[(long long)n * z_rb + g];
|
||||
const float sc = f16_to_f32(sb[(long long)n * (sb_rb >> 1) + g]);
|
||||
const float term = ((is - iz * as) * sSa[m]) * sc; /* gemm_zp's parentheses */
|
||||
/* One slot per (row, group-in-chunk): MT*CG is 16 at every MT, so this is 64 bytes.
|
||||
* The group's two half-lanes write the same value, which is why the pair fold above is
|
||||
* a fold and not a broadcast. */
|
||||
sT[warp * 16 + m * CG + (kl >> 1)] = term;
|
||||
}
|
||||
__syncthreads();
|
||||
/* Group ch*CG + j, for j ascending, into the lane that owns the row's answer. The reference
|
||||
* walks g in ascending order and f32 adds are not associative, so the order is part of the
|
||||
* answer, not a detail. The group gather is the one place in the kernel that crosses
|
||||
* k-lanes; it is a barrier and four LDS reads at 64 bytes, which is cheaper than a shuffle
|
||||
* round-trip. */
|
||||
if (live && kl == 0) {
|
||||
|
||||
/* A chunk carries CG groups, and group ch*CG + j lives in the two k-lanes 2j and 2j+1:
|
||||
* they hold the same group's two halves, which is what the fold above combined. Every
|
||||
* lane adds all CG of them in ascending j, so each lane of a row ends on the same
|
||||
* partial sum, built in the same order the reference walks its groups in -- f32 adds are
|
||||
* not associative, and a lane that finished its own group last rounds the tail
|
||||
* differently. Reading a lane's `acc` would not do: by j = 2 it has already added a
|
||||
* group of its own. */
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CG; ++j)
|
||||
if (m < M) acc += sT[warp * 16 + m * CG + j];
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
if (live && kl == 0 && m < M) y[(long long)m * y_pitch + n] = f32_to_bf16(acc);
|
||||
}
|
||||
|
||||
int mt_for(int M) { return M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax; }
|
||||
|
||||
} // namespace
|
||||
|
||||
/* ================================================================== the launcher
|
||||
*
|
||||
* Codes: 0, -1 a required pointer is null, -2 a shape it does not read, -3 a pitch it cannot read,
|
||||
* -4 HIP. `nt` is the threads argument every libr3d launcher takes and this kernel ignores: the
|
||||
* work is one warp per weight row, and the wavefront count is the grid.
|
||||
*
|
||||
* `b_scale` is the joined operand's base. The launcher reads the two planes out of its own header
|
||||
* (rad_planes.h's rad_planes_find) and passes each plane's base, row pitch in bytes and the row
|
||||
* count down, so the kernel reads the container's bytes where they lie. */
|
||||
|
||||
/* The instrument behind the measurement in the header: the dot on its own, one 64-code sample per
|
||||
* lane, the f32 it produces beside the exact integer it should have produced. The driver runs it as
|
||||
* `dot [n]`; the bias is sized from it, and it shows the f32 path to be exact. Two extern "C"
|
||||
* symbols, no row, no cost at serve time. */
|
||||
extern "C" __global__ void __launch_bounds__(256) probe_dot_kernel(const int8_t* a,
|
||||
const uint8_t* codes,
|
||||
float* out, long long* exact)
|
||||
{
|
||||
const int g = blockIdx.x * 32 + (int)(threadIdx.x / kWave) * 4 + (int)(threadIdx.x & 3);
|
||||
const int lane4 = (int)(threadIdx.x & 31) & 3;
|
||||
(void)lane4;
|
||||
const uint32_t* w4 = (const uint32_t*)(codes + (long long)g * 16);
|
||||
float p = 0.0f;
|
||||
long long ex = 0;
|
||||
#pragma unroll
|
||||
for (int v = 0; v < 4; ++v) {
|
||||
#pragma unroll
|
||||
for (int b = 0; b < 4; ++b) {
|
||||
const uint32_t aw = *(const uint32_t*)(a + (long long)g * 64 + 4 * (4 * v + b));
|
||||
uint32_t ql, qh;
|
||||
u2x4_biased((w4[v] >> (8 * b)) & 0xffu, ql, qh);
|
||||
uint32_t lo, hi;
|
||||
i8x4_to_f16x2(aw, lo, hi);
|
||||
p = dot4_f16x4(lo, hi, ql, qh, p);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j)
|
||||
ex += (long long)(int)(int8_t)((aw >> (8 * j)) & 0xffu) *
|
||||
(long long)(128 + ((w4[v] >> (8 * b + 2 * j)) & 3u));
|
||||
}
|
||||
}
|
||||
out[g] = p;
|
||||
exact[g] = ex;
|
||||
}
|
||||
|
||||
extern "C" int r3d_w2a8_probe_launch(const int8_t* a, const uint8_t* codes, float* out,
|
||||
long long* exact, int n)
|
||||
{
|
||||
probe_dot_kernel<<<(n + 31) / 32, 256, 0, 0>>>(a, codes, out, exact);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -1;
|
||||
}
|
||||
|
||||
extern "C" int r3d_gemm_nt_q_w2a8(long a, long a_scale, long b, long b_scale, long a_sum, long y,
|
||||
int M, int N, int K, int group, int a_ld, int y_ld, int nt,
|
||||
long stream)
|
||||
{
|
||||
(void)nt;
|
||||
if (!a || !a_scale || !b || !b_scale || !a_sum || !y) return -1;
|
||||
if (M < 1 || N < 1 || K < 1) return -2;
|
||||
if (M > kMTMax) return -2; /* the row says the same: C_LE("M", 16) */
|
||||
if (group != kGroup) return -2; /* the tile is 128-wide: chunk = 128*16/MT */
|
||||
if (K % kGroup) return -2;
|
||||
if (K % 16) return -2; /* the step order is a 16-byte step */
|
||||
const int mt = mt_for(M);
|
||||
const int chunk = 2048 / mt;
|
||||
if (K % chunk) return -2; /* ragged chunk: the tile would read past K */
|
||||
const int G = K / group;
|
||||
if (G < 1) return -2;
|
||||
if (!a_ld) a_ld = K;
|
||||
if (!y_ld) y_ld = N;
|
||||
if (a_ld % 4) return -3; /* four codes a dword, staged whole */
|
||||
if (((uintptr_t)b & 15u) || ((uintptr_t)a & 3u)) return -3;
|
||||
|
||||
const RadPlanesHeader* h = rad_planes_header((const void*)(uintptr_t)b_scale);
|
||||
if (!h) return -2; /* not the joined form: rad.planes is expected */
|
||||
const RadPlanesEntry* es = nullptr;
|
||||
const RadPlanesEntry* ez = nullptr;
|
||||
const void* sp = rad_planes_find((const void*)(uintptr_t)b_scale, "scale", &es);
|
||||
const void* zp = rad_planes_find((const void*)(uintptr_t)b_scale, "zero", &ez);
|
||||
if (!sp || !zp || !es || !ez) return -2;
|
||||
if (es->dtype != RAD_F16) return -2; /* this kernel reads an f16 scale */
|
||||
if (ez->dtype != RAD_U8) return -2; /* ...and a byte-wide zero; see the header */
|
||||
if (es->rows != N || es->cols != G || ez->rows != N || ez->cols != G) return -2;
|
||||
if ((es->row_bytes & 1) || es->row_bytes < 2 * G || ez->row_bytes < G) return -3;
|
||||
|
||||
#define R3D_W2A8_LAUNCH(MT) \
|
||||
do { \
|
||||
const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads); \
|
||||
R3D_KLAUNCH(R3D_KNAME((gemm_w2a8_kernel<MT>)), grid, block, (hipStream_t)stream, \
|
||||
(const int8_t*)a, (const float*)a_scale, 1, (const uint8_t*)b, \
|
||||
(const uint16_t*)sp, (int)es->row_bytes, (const uint8_t*)zp, (int)ez->row_bytes, \
|
||||
(const float*)a_sum, kMpad, (uint16_t*)y, M, N, K, chunk, a_ld, y_ld); \
|
||||
} while (0)
|
||||
|
||||
switch (mt) {
|
||||
case 1: R3D_W2A8_LAUNCH(1); break;
|
||||
case 2: R3D_W2A8_LAUNCH(2); break;
|
||||
case 4: R3D_W2A8_LAUNCH(4); break;
|
||||
case 8: R3D_W2A8_LAUNCH(8); break;
|
||||
default: R3D_W2A8_LAUNCH(16); break;
|
||||
}
|
||||
#undef R3D_W2A8_LAUNCH
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* ================================================================== the shim
|
||||
*
|
||||
* gemm_nt_q's slots, as gemm_ntq_impl takes them: 0 a (i8, step order), 1 a_scale (f32, one per
|
||||
* row), 2 b (the u2 codes), 3 b_scale (the joined scale+zero), 4 y (bf16), 5 a_sum (f32, group
|
||||
* major, mpad = 16 columns). */
|
||||
extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
|
||||
{
|
||||
if (!a) return R3D_NO(RAD_E_INVAL);
|
||||
const char* dt = r3d_gets(a, "dtype");
|
||||
if (dt && std::strcmp(dt, "w2a8") != 0) return R3D_NO(RAD_E_DTYPE); /* the row is w2a8 only */
|
||||
|
||||
const RadTensor* A = r3d_opt(a, 0);
|
||||
const RadTensor* AS = r3d_opt(a, 1);
|
||||
const RadTensor* B = r3d_opt(a, 2);
|
||||
const RadTensor* BS = r3d_opt(a, 3);
|
||||
const RadTensor* Y = r3d_opt(a, 4);
|
||||
const RadTensor* ASUM = r3d_opt(a, 5);
|
||||
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y) || !r3d_p(ASUM))
|
||||
return R3D_NO(RAD_E_INVAL);
|
||||
|
||||
if (A->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE); /* quant_act_i8's codes */
|
||||
if (B->dtype != RAD_U2) return R3D_NO(RAD_E_DTYPE); /* the grid's codes */
|
||||
if (Y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_is_f32(AS) || !r3d_is_f32(ASUM)) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
|
||||
const long long group = r3d_geti_or(a, "group", 0);
|
||||
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
|
||||
if (group != kGroup) return R3D_NO(RAD_E_SHAPE); /* no defaulting: gemm_zp refuses 0 */
|
||||
if (K % group || K % 16) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long G = K / group;
|
||||
|
||||
const long long ynel = r3d_numel(Y);
|
||||
if (N < 1 || ynel % N) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long M = ynel / N;
|
||||
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); /* DECLINE, in the header: the band is
|
||||
* 16 and the tile is 16 rows; the
|
||||
* prefill vocab projection is
|
||||
* logits_gemm, a tiled bf16 row. */
|
||||
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (r3d_numel(AS) < M) return R3D_NO(RAD_E_INVAL); /* gemm_zp's code for this one */
|
||||
if (r3d_numel(ASUM) < G * kMpad) return R3D_NO(RAD_E_INVAL);
|
||||
|
||||
const long long ap = r3d_row_pitch(A);
|
||||
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); /* step order read four codes a dword */
|
||||
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); /* gemm_zp: contiguous codes only */
|
||||
long long yrows = 0;
|
||||
const long long yp = r3d_rows_pitch(Y, N, &yrows);
|
||||
if (yp < N) return R3D_NO(RAD_E_STRIDE);
|
||||
if (!r3d_contig(ASUM)) return R3D_NO(RAD_E_STRIDE);
|
||||
|
||||
const RadPlanesHeader* h = rad_planes_header(r3d_p(BS));
|
||||
if (!h) return R3D_NO(RAD_E_DTYPE); /* the joined form is the operand */
|
||||
const RadPlanesEntry* es = nullptr;
|
||||
const RadPlanesEntry* ez = nullptr;
|
||||
const void* sp = rad_planes_find(r3d_p(BS), "scale", &es);
|
||||
const void* zp = rad_planes_find(r3d_p(BS), "zero", &ez);
|
||||
if (!sp || !zp || !es || !ez) return R3D_NO(RAD_E_DTYPE);
|
||||
if (es->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE);
|
||||
if (ez->dtype != RAD_U8)
|
||||
return R3D_NO(RAD_E_DTYPE); /* DECLINE: a sub-byte zero plane needs the bit-extract path;
|
||||
* rad_load_bits(zb, bits, g) is 10 lines. U8 is w2a8's form. */
|
||||
if (es->rows != N || es->cols != G || ez->rows != N || ez->cols != G) return R3D_NO(RAD_E_SHAPE);
|
||||
if ((es->row_bytes & 1) || es->row_bytes < 2 * G || ez->row_bytes < G) return R3D_NO(RAD_E_STRIDE);
|
||||
|
||||
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
const int rc = r3d_gemm_nt_q_w2a8(
|
||||
r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(ASUM), r3d_addr(Y), (int)M,
|
||||
(int)N, (int)K, (int)group, (int)ap, (int)yp, 0, (long)s);
|
||||
/* The launcher's codes are its own (r3d_launch.h's set: null, shape, pitch, HIP); the row speaks
|
||||
* RAD codes, and the shim is where the two are named. Same mapping as the gated row's. */
|
||||
if (rc == 0) return RAD_OK;
|
||||
return R3D_NO(rc == -1 ? RAD_E_INVAL : rc == -2 ? RAD_E_SHAPE
|
||||
: rc == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
|
||||
}
|
||||
|
||||
/* ================================================================== the layout hook
|
||||
*
|
||||
* The scoped exception to libr3d's "no layout hooks, no repacking" rule, transcribed from libref's
|
||||
* `ref_layout_gemm_q` with the checks and their order unchanged:
|
||||
*
|
||||
* if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
|
||||
* const ZpGrid* zg = zp_grid(dtype); group = param "group";
|
||||
* if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
|
||||
* transform empty, or beginning "givens";
|
||||
* sel_roles(enc, sel, n, "scale", "zero") && enc->n_planes >= 3;
|
||||
* plane[0]: role "codes", dtype == zg->codes, block {1,1};
|
||||
* scale: RAD_PLANE_TILED, RAD_F16, block {1, group};
|
||||
* zero: RAD_PLANE_TILED, zero_dt(...), block {1, group};
|
||||
* return rad_planes_layout(enc, sel, planes, n, out);
|
||||
*
|
||||
* zp_grid, zero_dt and sel_roles are libref-internal statics, inlined below for w2a8: the grid is
|
||||
* { "w2a8", RAD_U2, ZP_I8_ROW }, zero_dt is U8|U2|U4|U5, and the practical form is U8 (the kernel
|
||||
* declines a sub-byte zero, at its site, with the fix named). The answer is rad_planes.h's own:
|
||||
* the tag is "rad.planes", the dtype the first plane's, the shape the byte count. NOTHING HERE
|
||||
* MOVES A BYTE: this hook is the reader the mapped tier needs and the row's relayout is null.
|
||||
*/
|
||||
/* The writer for the joined operand this hook names: codes, scale and zero as the plan's one
|
||||
* `rad.planes` weight, assembled by rad_planes_relayout -- header, entries, each plane's rows,
|
||||
* copied. The ABI's contract is that a query answering RAD_OK is a promise the loader keeps on the
|
||||
* row's word: "out describes the stored form, and relayout will produce it" (rad_abi.h), and a
|
||||
* weight with no hook is the only kind that can be read where it lies, which is why a joined weight
|
||||
* is placed in VRAM and a plain one can stay on the mapped tier. Nothing here transforms a code:
|
||||
* the bytes written are the bytes stored. */
|
||||
extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n_planes, void* dst,
|
||||
int64_t dst_bytes)
|
||||
{
|
||||
(void)p; (void)n_p;
|
||||
if (operand != 3) return RAD_E_UNSUPPORTED;
|
||||
return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes);
|
||||
}
|
||||
|
||||
/* A layout query answers in the engine's own vocabulary and leaves no trace, and a model that will
|
||||
* not load says only that two rows want one weight in two forms. This prints the question and the
|
||||
* answer -- operand, band dtype, planes offered, code returned -- under RAD_R3D_TRACE=1. */
|
||||
static int r3d_layout_trace(const char* who, int operand, const char* dt, int n_planes, int rc) {
|
||||
if (r3d_trace_on())
|
||||
std::fprintf(stderr, "[r3d] %s: operand %d dtype %s planes %d -> %d\n", who, operand,
|
||||
dt ? dt : "(none)", n_planes, rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n, RadLayout* out)
|
||||
{
|
||||
if (n < 2 || operand != 3) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_UNSUPPORTED);
|
||||
const char* dt = r3d_pgets(p, n_p, "dtype");
|
||||
/* The plan this hook describes -- the (scale, zero) pair joined on operand 3 -- is a statement
|
||||
* about the CONTAINER, not about the code width, and the engine forces every row that reads one
|
||||
* weight to answer with one form. So both packed grids come through, and the width a row can
|
||||
* unpack is the SHIM's business: gemm_nt_q_w2a8_m16 reads U2 and nothing else,
|
||||
* gemm_nt_q_w2a8_tiled reads U2 and U4, and each says so at its own line. */
|
||||
if (!dt || (std::strcmp(dt, "w2a8") != 0 && std::strcmp(dt, "w4a8_asym") != 0))
|
||||
return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the packed grids */
|
||||
const long long group = r3d_pgeti_or(p, n_p, "group", 0);
|
||||
if (group <= 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
if (!enc || !rad_enc_is(enc, "affine")) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
|
||||
return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
if (!enc || enc->n_planes < 3 || !sel) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
|
||||
/* sel_roles(enc, sel, n, "scale", "zero"): one role per selected plane, in order. */
|
||||
if (n != 2) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
const char* want = i == 0 ? "scale" : "zero";
|
||||
if (sel[i] < 0 || sel[i] >= enc->n_planes) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
if (std::strncmp(enc->plane[sel[i]].role, want, RAD_ENC_STR) != 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
}
|
||||
/* The codes plane is the one this operand does NOT take: the weight's role "codes", the grid's
|
||||
* dtype, block {1,1}. libref finds it by role over enc->plane, not by sel. */
|
||||
int codes = -1;
|
||||
for (int i = 0; i < enc->n_planes; ++i)
|
||||
if (std::strncmp(enc->plane[i].role, "codes", RAD_ENC_STR) == 0) { codes = i; break; }
|
||||
if (codes < 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
if (enc->plane[codes].block[0] != 1 || enc->plane[codes].block[1] != 1) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
const RadEncPlane& q = enc->plane[sel[i]];
|
||||
const RadTensor& t = planes[i];
|
||||
if (q.kind != RAD_PLANE_TILED) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
if (q.block[0] != 1 || q.block[1] != group) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
|
||||
if (i == 0) {
|
||||
if (t.dtype != RAD_F16) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the scale is f16 */
|
||||
} else {
|
||||
const uint32_t zd = t.dtype;
|
||||
const bool ok = zd == RAD_U8 || zd == RAD_U2 || zd == RAD_U4 || zd == RAD_U5;
|
||||
if (!ok) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* zero_dt: never signed */
|
||||
}
|
||||
}
|
||||
return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, rad_planes_layout(enc, sel, planes, n, out));
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/* r3d_launch.h -- the two lines a libr3d unit needs to launch a kernel.
|
||||
*
|
||||
* R3D_KLAUNCH is the triple-chevron form, which the engine services on its own queues because the
|
||||
* stream it hands a launch is the one hipLaunchKernel accepts (docs/PLUGIN.md §5). It is written as
|
||||
* a macro so a test can define it and drive the same sources through a host SIMT emulator; a build
|
||||
* does not, and gets the chevron.
|
||||
*
|
||||
* R3D_DYN_LDS declares a kernel's dynamic LDS, sized by the launch: `extern __shared__` in a build.
|
||||
* RDNA3 gives a workgroup the same 64 KiB RDNA4 does, so a tile sized for libr4d fits here too.
|
||||
*
|
||||
* R3D_KNAME names a kernel in a context where commas would split a macro argument, the way
|
||||
* HIP_KERNEL_NAME does for hipLaunchKernelGGL.
|
||||
*/
|
||||
#ifndef R3D_LAUNCH_H
|
||||
#define R3D_LAUNCH_H
|
||||
#define R3D_KNAME(...) __VA_ARGS__
|
||||
#ifndef R3D_KLAUNCH
|
||||
#define R3D_KLAUNCH(kernel, grid, block, stream, ...) kernel<<<grid, block, 0, stream>>>(__VA_ARGS__)
|
||||
#endif
|
||||
#ifndef R3D_DYN_LDS
|
||||
#define R3D_DYN_LDS(type, name) extern __shared__ type name[]
|
||||
#endif
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,289 @@
|
||||
/* r3d_plugin.h -- what libr3d's translation units share.
|
||||
*
|
||||
* The row table (r3d_rows.cpp) and the operand descriptions (r3d_shapes.cpp) are pure host C++ and
|
||||
* include only this file and the ABI; the launch shims include r3d.h and so <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.
|
||||
*
|
||||
* Nothing in this header may include r3d.h.
|
||||
*/
|
||||
#ifndef RAD_R3D_PLUGIN_H
|
||||
#define RAD_R3D_PLUGIN_H
|
||||
|
||||
#include "r3d_args.h"
|
||||
|
||||
/* ================================================================== the priority ladder
|
||||
*
|
||||
* The selector ranks candidate rows by an integer priority (spec §2.1); where two rows of one op
|
||||
* can match a geometry, it decides which serves. Each group states the reason for its order.
|
||||
* Values are spaced by ten so a row can be slipped between two without renumbering.
|
||||
*
|
||||
* libr3d ships one row per (op, dtype) pair far more often than libr4d does: on RDNA3 there is no
|
||||
* matrix instruction whose fragment layout, tile shape or operand width a kernel has to design
|
||||
* around, so the dot2 kernel that serves bf16 serves f16 with a template argument, and there is
|
||||
* nothing to specialise a second row for. Where two rows of one op do exist, the reason is the
|
||||
* geometry, and it is written next to the pair.
|
||||
*/
|
||||
enum {
|
||||
/* The common case: this op, these dtypes, one row. Nothing competes with it. */
|
||||
R3D_PRIO_ONLY = 50,
|
||||
|
||||
/* `attn_paged` is banded on q_len, and the decode row's bound (q_len <= 16) is a bucket
|
||||
* boundary, not a partition: a speculative verify at 8 query tokens matches the prefill row
|
||||
* too, and the decode kernel -- split-KV, one head group a workgroup, no query tile -- is the
|
||||
* faster one there. Decode therefore outranks prefill, as it does in libr4d. */
|
||||
R3D_PRIO_ATTN_DECODE = 70,
|
||||
R3D_PRIO_ATTN_PREFILL = 60,
|
||||
|
||||
/* The skinny bf16 GEMM's band is M <= 16 and the tiled one's starts at M >= 16, so the two
|
||||
* meet at exactly 16 rows and the skinny kernel wins there (it keeps the whole weight stream
|
||||
* in flight with one wave a row and has no LDS staging to pay for). The overlap is deliberate:
|
||||
* a caller that wants the tiled kernel at 16 rows asks with M=17, the same convention libr4d
|
||||
* uses at its own m64/tiled boundary. */
|
||||
R3D_PRIO_GEMM_M16 = 60,
|
||||
R3D_PRIO_GEMM_TILED = 40,
|
||||
|
||||
/* The vocab is a GEMM whose N is the vocabulary: one row, M <= 16, split-K across the whole
|
||||
* card. The tiled GEMM has no row for these N, so this priority only decides against a future
|
||||
* tiled vocab row. */
|
||||
R3D_PRIO_VOCAB_M1 = 60,
|
||||
|
||||
/* An fp8 weight row and an int8 weight row never compete: no dtype string reaches both, and a
|
||||
* container's encoding picks which is legal. */
|
||||
R3D_PRIO_GEMM_FP8 = 60,
|
||||
|
||||
/* The sampler stages are one row each, on one dtype (f32 logits), so there is nothing to rank.
|
||||
* The name is here so a second row for a stage -- an i8 logits form, say -- has a ladder to
|
||||
* join. */
|
||||
R3D_PRIO_SAMPLE = 50
|
||||
};
|
||||
|
||||
/* ================================================================== the dtype codes a C
|
||||
* launcher takes
|
||||
*
|
||||
* The launchers in r3d.h take a dtype as an int, because a `__global__`'s dtype has to be a runtime
|
||||
* value for the ops that are one kernel over several (cast, fill, dequant) and a compile-time one
|
||||
* everywhere else. These are the codes; they are libr3d's own, not rad_types.h's RAD_DT_* (a
|
||||
* launcher's argument list is a private contract between a shim and its kernel, and the kernel
|
||||
* switch reads better over a dense 0..n than over the ABI's sparse enum). Every shim translates. */
|
||||
enum {
|
||||
R3D_DT_BF16 = 0,
|
||||
R3D_DT_F16 = 1,
|
||||
R3D_DT_F32 = 2,
|
||||
R3D_DT_I32 = 3,
|
||||
R3D_DT_I64 = 4,
|
||||
R3D_DT_U8 = 5, /* byte codes: fp8 e4m3, read with the codec */
|
||||
R3D_DT_I8 = 6,
|
||||
R3D_DT_E5M2 = 7,
|
||||
R3D_DT_N = 8
|
||||
};
|
||||
|
||||
/* A RadTensor's dtype to the code above, or -1 for one libr3d has no kernel for. */
|
||||
static inline int r3d_dt_code(uint32_t dt) {
|
||||
switch (dt) {
|
||||
case RAD_BF16: return R3D_DT_BF16;
|
||||
case RAD_F16: return R3D_DT_F16;
|
||||
case RAD_F32: return R3D_DT_F32;
|
||||
case RAD_I32:
|
||||
case RAD_U32: return R3D_DT_I32;
|
||||
case RAD_I64: return R3D_DT_I64;
|
||||
case RAD_F8E4M3: return R3D_DT_U8;
|
||||
case RAD_F8E5M2: return R3D_DT_E5M2;
|
||||
case RAD_I8: return R3D_DT_I8;
|
||||
case RAD_U8: return R3D_DT_U8;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/* The bytes an element of that code occupies. */
|
||||
static inline int r3d_dt_size(int code) {
|
||||
static const int kSize[R3D_DT_N] = { 2, 2, 4, 4, 8, 1, 1, 1 };
|
||||
return (code >= 0 && code < R3D_DT_N) ? kSize[code] : 0;
|
||||
}
|
||||
|
||||
/* The activation an `act` parameter names, as the kernels' template argument. */
|
||||
enum { R3D_ACT_SILU = 0, R3D_ACT_SIGMOID = 1, R3D_ACT_GELU = 2 };
|
||||
|
||||
/* rope's `mode`, same numbering as libref's kModes. libr3d's kernel implements neox and gptj; the
|
||||
* rows' constraints say so, so a model that needs mrope is not routed here. */
|
||||
enum { R3D_ROPE_NEOX = 0, R3D_ROPE_GPTJ = 1 };
|
||||
|
||||
/* ================================================================== the row table's entry points
|
||||
*
|
||||
* Declared here so r3d_rows.cpp, which is host code built without ROCm, can name them; each is
|
||||
* defined beside its kernel, in the unit named below, and is documented there. A shim is a
|
||||
* `RadLaunchFn`: operands read with r3d_args.h, dtype from the tensor, row count from the operand.
|
||||
* A shape hook is a `RadShapeFn`: the extent and content domain of one operand (r3d_shapes.cpp).
|
||||
*/
|
||||
extern "C" {
|
||||
|
||||
/* --- r3d_model_bf16.hip --- */
|
||||
int r3d_rad_rmsnorm (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_layernorm (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_add (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_mul (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_cast (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_silu (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_gelu (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sigmoid (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_act_mul (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_softmax (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_scale (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_fill (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_rope (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_kv_store (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_embed_lookup (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_gather_rows (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_scatter_rows (const RadArgs* a, RadStream s);
|
||||
|
||||
/* --- r3d_quant_fp8.hip --- */
|
||||
int r3d_rad_quant_act_fp8 (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_quant_act_i8 (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_quant_act_i8g (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_gated_quant_fp8 (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_dequant (const RadArgs* a, RadStream s);
|
||||
|
||||
/* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */
|
||||
int r3d_rad_gemm_nt_bf16_m16 (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_gemm_nt_q_fp8 (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_gemm_nt_q_i8 (const RadArgs* a, RadStream s);
|
||||
|
||||
/* --- r3d_shapes.cpp --- */
|
||||
int r3d_shape_rmsnorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_layernorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_add (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_mul (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_act_mul (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_cast (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_silu (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_gelu (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_sigmoid (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_softmax (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_scale (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_fill (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_rope (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_kv_store (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_embed_lookup (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_gather_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_scatter_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_quant_act_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_quant_act_i8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_quant_act_i8g (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_gated_quant_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_dequant (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_gemm_nt (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_gemm_nt_q (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
|
||||
/* --- r3d_attn_paged_h128.hip, r3d_vocab_bf16.hip, r3d_sample_f32.hip --- */
|
||||
extern "C" int r3d_shape_silu_mul (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_attn_paged (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_gemm_nt_q_gated (const RadParam*, int, int, RadOpdDesc*);
|
||||
/* The vocab projection at w2a8, decode. The layout hook is this library's scoped exception to
|
||||
* "no layout hooks" (the other two are the fp8 weight's and the logits head's, below): it repacks
|
||||
* nothing, it presents the container's `scale` and `zero` planes as the single joined `b_scale`
|
||||
* operand the way rad_planes stores them, transcribed from
|
||||
* ref_layout_gemm_q. Without it the plan has a placement with no reader. */
|
||||
extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadEncoding*,
|
||||
const int* sel, const RadTensor* planes, int n_planes,
|
||||
RadLayout*);
|
||||
extern "C" int r3d_shape_dflash_select (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_row_topk (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_argmax (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_temp (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_topk (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_topp (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_minp (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_typical (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_xtc (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_pick (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_penalties (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_dry (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_ngram_ban (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_mask (const RadParam*, int, int, RadOpdDesc*);
|
||||
extern "C" int r3d_shape_sample_logprobs (const RadParam*, int, int, RadOpdDesc*);
|
||||
|
||||
/* --- r3d_sample_f32.hip: the draw spine (row_topk, argmax, temp, topk, pick, the four narrowings)
|
||||
and r3d_model_bf16.hip's pre-filters (penalties, dry, ngram_ban, mask, logprobs) --- */
|
||||
int r3d_rad_gemm_nt_q_w2a8 (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_gemm_nt_q_gated (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_dflash_select (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_row_topk (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_argmax (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_temp (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_topk (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_pick (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_topp (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_minp (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_typical (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_xtc (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_penalties (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_dry (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_ngram_ban (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_mask (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_sample_logprobs (const RadArgs* a, RadStream s);
|
||||
|
||||
/* --- r3d_model_bf16.hip: the fused MLP activation and the fused norm-quantiser --- */
|
||||
/* The paged attention's two entry points, banded on q_len: the decode kernel is split-KV over the
|
||||
* cache with one head group a workgroup, the prefill kernel stages a 16-token query tile. */
|
||||
int r3d_rad_attn_decode_h128 (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_attn_prefill_h128 (const RadArgs* a, RadStream s);
|
||||
|
||||
/* --- r3d_vocab_bf16.hip: the vocabulary projection, both heights. The shape hook is a
|
||||
* transcription of ref_logits_gemm_shape -- three plain tensors, nothing joined -- so the band the
|
||||
* engine declares is the band kbench fills, which is the opposite of the w2a8 row's null hook: there
|
||||
* the describable byte count is the trap, here it is the point. */
|
||||
/* --- r3d_gemm_fp8a8_tiled.hip: the quantised GEMM above the decode heights, and the reader for
|
||||
* the container's fp8 weight: codes and per-128x128 scale as two planes behind `b_scale`. The
|
||||
* reference's own gemm_nt_q hook answers nothing for this dtype -- ref_layout_gemm_q reads zp_grid,
|
||||
* and zp_grid has no fp8a8 entry -- which is why the row carries its own. */
|
||||
int r3d_rad_gemm_nt_q_fp8_tiled (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_gemm_nt_q_w2a8_tiled (const RadArgs* a, RadStream s);
|
||||
extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*,
|
||||
const int*, const RadTensor*, int, RadLayout*);
|
||||
|
||||
/* --- r3d_gemm_mxfp4a8.hip: the OCP-MXFP4 weight against the fp8 activation, both heights. The
|
||||
* weight is two plain u8 planes -- e2m1 codes [N, K/2] and the e8m0 scale [N, K/32] -- so the row
|
||||
* reads them in place and carries no layout hook; the shape hook is its own because the weight's
|
||||
* two planes are not the fp8 grid's E4M3 codes and block scale. */
|
||||
int r3d_rad_gemm_nt_q_mxfp4a8_m16 (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s);
|
||||
|
||||
/* --- r3d_gemm_inta8.hip: the symmetric int4 and int8 weight grids at decode heights. The weight
|
||||
* is signed codes (I4, two a byte, or I8, one a byte) against a plain f16 scale per (row, 128 of
|
||||
* K) -- no zero point and no a_sum, so both planes are read in place and the rows carry no layout
|
||||
* hook. */
|
||||
int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s);
|
||||
int r3d_rad_gemm_nt_q_w8a8_m16(const RadArgs* a, RadStream s);
|
||||
int r3d_shape_gemm_nt_q_w4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
int r3d_shape_gemm_nt_q_w8a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
|
||||
/* The three writers that go with the three plane hooks, one per row, each delegating to
|
||||
* rad_planes_relayout: the loader converts a quantised weight into the joined operand the plan names
|
||||
* at load, and only the row that reads it can say how. See abi/rad_abi.h. */
|
||||
extern "C" int r3d_relayout_logits_head(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, void*, int64_t);
|
||||
extern "C" int r3d_relayout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*,
|
||||
const int*, const RadTensor*, int, void*, int64_t);
|
||||
extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadEncoding*,
|
||||
const int*, const RadTensor*, int, void*, int64_t);
|
||||
|
||||
int r3d_rad_logits_gemm_bf16 (const RadArgs* a, RadStream s);
|
||||
/* The head's reader: `output.weight` at a llama_dense_fp8 checkpoint is E4M3 codes and a bf16 scale
|
||||
* per 128x128 block, stored as two container planes behind the one `lm_head` operand, and the mapped
|
||||
* tier will not place a weight a loaded library cannot read in place. Transcribed from
|
||||
* ref_layout_head (libref's own logits row carries that hook), with the statics it uses inlined
|
||||
* beside it. It moves no byte: a round-trip through its relayout writer (above) reproduces the
|
||||
* planes byte for byte, and that writer exists for the round-trip, not for a move. */
|
||||
extern "C" int r3d_layout_logits_head(const RadParam*, int, int, const RadEncoding*,
|
||||
const int*, const RadTensor*, int, RadLayout*);
|
||||
int r3d_rad_gemm_nt_bf16_tiled (const RadArgs* a, RadStream s);
|
||||
int r3d_shape_logits_gemm_bf16 (const RadParam*, int, int, RadOpdDesc*);
|
||||
|
||||
int r3d_rad_silu_mul (const RadArgs* a, RadStream s);
|
||||
int r3d_rad_rmsnorm_quant_fp8 (const RadArgs* a, RadStream s);
|
||||
int r3d_shape_rmsnorm_quant_fp8 (const RadParam*, int, int, RadOpdDesc*);
|
||||
|
||||
} /* extern "C" */
|
||||
|
||||
#endif /* RAD_R3D_PLUGIN_H */
|
||||
@@ -0,0 +1,929 @@
|
||||
/* r3d_quant_fp8.hip -- the activation quantisers and the dequantise that reads a container's own
|
||||
* codes.
|
||||
*
|
||||
* The arithmetic is libref's, transcribed. The group core is `q8_group`: an amax over
|
||||
* the group's consecutive columns, `sc = amax * (1.0f / top)` -- a MULTIPLY by the reciprocal, not a
|
||||
* divide -- codes `v * (1/sc)` clamped to +-top and encoded by the codec, and scale 1 for an
|
||||
* all-zero group, whose reciprocal would be an infinity. The five bodies are libref's
|
||||
* quant_act_fp8, quant_act_i8, quant_act_i8g, gated_quant_fp8 and dequant, loop order and rounding
|
||||
* points as written. The clamp is required and not defensive: `amax * (1/scale)` is
|
||||
* 448 exactly and can round an ulp above once the reciprocal is rounded, and a code out of range
|
||||
* encodes as NaN, which then spreads through every row that reads it.
|
||||
*
|
||||
* RDNA3 has no fp8 instruction (r3d_common.h), so both directions are the software codecs in
|
||||
* r3d_codecs.h, which are bit-exact mirrors of rad_plugin.h's; the absmax is a butterfly
|
||||
* (r3d_xor_max), which reproduces a `__shfl_xor` loop bit for bit, and a max is exact and
|
||||
* order-free, so the bracketing is q8_group's ascending one whatever the lane mapping.
|
||||
*
|
||||
* No kernel here carries a layout hook, and the codes are the bytes their consumer reads, which is
|
||||
* the reason a container converted on this card is readable anywhere. Four of the five planes are
|
||||
* plain row-major with one f32 scale per (row, group), because a dot2 GEMM reads codes in the order
|
||||
* they are stored. The fifth is the op whose NAME carries the order: libref stores quant_act_i8's
|
||||
* codes in the int8 WMMA's step order (`i8_step_pos`, the middle two dwords of every 16-byte step
|
||||
* exchanged) because that is what the w4a8, w8a8 and w2a8 GEMMs read, so this kernel stores them
|
||||
* that way too and its n is a multiple of 16; quant_act_i8g is the row-major int8 plane, and it is
|
||||
* the one this library's i8a8 GEMM consumes. The two are not interchangeable.
|
||||
*
|
||||
* The store address costs nothing either way: a lane owns FOUR CONSECUTIVE COLUMNS, so its codes are
|
||||
* one dword, a wave's are 128 contiguous bytes, and a wave covers exactly one 128-column group;
|
||||
* `i8_step_pos` preserves c % 4, so it permutes a wave's 128 bytes without splitting a lane. The
|
||||
* launchers therefore refuse `n % 4` -- and quant_act_i8 `n % 16` -- and a ragged last group
|
||||
* (n % group != 0) is written zero-padded: padding is a zero code and takes no part in the amax.
|
||||
*
|
||||
* Group widths: the rows ask for 128, the checkpoint's weight-scale block width, and the kernels
|
||||
* also serve any other power of two from 4 to 512, so a selftest can drive a narrow group and a
|
||||
* future row on a 64-wide grid needs no new kernel. A group is a power of two because the amax
|
||||
* butterfly is over the lanes covering it, GROUP/4 of them.
|
||||
*/
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_args.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_launch.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kThreads = 256;
|
||||
constexpr uint32_t kWaves = kThreads / kWave;
|
||||
|
||||
enum : uint32_t {
|
||||
kColsPerLane = 4, /* one dword of codes a lane */
|
||||
kWaveCols = kWave * kColsPerLane /* 128: the columns a wave covers */
|
||||
};
|
||||
|
||||
/* The largest code each quantiser saturates at. E4M3 has no infinity, so 448 is the largest finite
|
||||
* value, and the scale is a dequant multiplier like the checkpoint's weight_scale_inv: the GEMM
|
||||
* multiplies the activation's scale by the weight's block scale and never divides. */
|
||||
constexpr float kTopE4M3 = 448.0f;
|
||||
constexpr float kTopI8 = 127.0f;
|
||||
|
||||
/* The floor quant_act_i8's amax is raised to before its DIVIDE by 127, where quant_act_fp8
|
||||
* multiplies by a reciprocal, so the two quantisers round one ulp apart here; that is libref's
|
||||
* spelling and the GEMMs read the scale as it is. */
|
||||
constexpr float kI8Floor = 1e-8f;
|
||||
|
||||
/* The LDS code-sum accumulator's width, in groups, as in libr4d's r4d_quant_act_i8. */
|
||||
enum : uint32_t { kI8MaxGroups = 256 };
|
||||
|
||||
/* A bf16 element of a row: a whole-register 16-bit load (r3d_common.h) widened by a shift. */
|
||||
__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
|
||||
return bf16_to_f32((uint16_t)ldg_u16(p + i));
|
||||
}
|
||||
|
||||
/* q8_group's clamp, in q8_group's order and with q8_group's comparisons, at the codec's top -- 448
|
||||
* for E4M3, 127 for int8. fminf/fmaxf are NOT the same function here: they replace a NaN with the
|
||||
* bound, and a NaN in an activation is a value the reference encodes as the format's NaN, not as
|
||||
* +-top. */
|
||||
__device__ __forceinline__ float clamp_top(float c, float top) {
|
||||
if (c > top) c = top;
|
||||
if (c < -top) c = -top;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* The four codes a lane's four columns produce, in column order: byte 0 is column c0. */
|
||||
__device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) {
|
||||
const uint32_t lo = e4m3x2_pack(clamp_top(v[0] * inv, kTopE4M3), clamp_top(v[1] * inv, kTopE4M3));
|
||||
const uint32_t hi = e4m3x2_pack(clamp_top(v[2] * inv, kTopE4M3), clamp_top(v[3] * inv, kTopE4M3));
|
||||
return lo | (hi << 16);
|
||||
}
|
||||
|
||||
/* The same four codes as int8, at the same rounding points: clamp to +-127, then the codec's
|
||||
* round-to-nearest-even. quant_act_i8g's store; quant_act_i8's is the same bytes at a permuted
|
||||
* address. */
|
||||
__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
|
||||
const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8));
|
||||
const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8));
|
||||
const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8));
|
||||
const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8));
|
||||
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
|
||||
}
|
||||
|
||||
/* q8_group's scale from the group's amax: the reciprocal of `top` MULTIPLIED, not a divide -- the
|
||||
* one place the two int8 quantisers and the fp8 one agree, and the reason the per-row
|
||||
* quant_act_i8 spells its scale as a divide and is a separate body. */
|
||||
__device__ __forceinline__ float group_scale(float am, float top) {
|
||||
return am > 0.0f ? am * (1.0f / top) : 1.0f;
|
||||
}
|
||||
|
||||
/* The map libref uses, verbatim: where a row's column c is stored in the step-ordered int8 plane.
|
||||
* Bits 2 and 3 of c exchanged = the middle two dwords of every 16-byte step swapped, which is the
|
||||
* order the int8 WMMA reads an A fragment. The map is its own inverse, and it preserves c % 4, so a
|
||||
* lane's four columns stay contiguous and its store stays one dword. */
|
||||
__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) {
|
||||
return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1);
|
||||
}
|
||||
|
||||
/* block_sum's twin for a maximum -- r3d_common.h has the sum. A max needs no order argument at all:
|
||||
* it is exact, so the wave partials combine in any order -- but it is spelled the same way, so a
|
||||
* reader sees one reduction shape in this library and not two. `lds` holds kWaves floats. */
|
||||
__device__ __forceinline__ float block_max(float v, float* lds) {
|
||||
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
|
||||
v = wave_max(v);
|
||||
if (lane == 0) lds[wave] = v;
|
||||
__syncthreads();
|
||||
float t = lds[0];
|
||||
#pragma unroll
|
||||
for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]);
|
||||
return t;
|
||||
}
|
||||
|
||||
/* ================================================================== quant_act_fp8
|
||||
*
|
||||
* Per-(row, group) symmetric E4M3 of an activation, over q8_group. One workgroup
|
||||
* a row, a wave a group, a lane four columns -- libr4d's layout, because the reason for
|
||||
* it (one dword a lane, 128 contiguous bytes a wave) is the store and not the instruction set.
|
||||
*
|
||||
* GROUP is the group's width. At 128 a wave covers one group and the amax is r3d_xor_max<32>. A
|
||||
* narrower group is covered by GROUP/4 lanes of the wave and the butterfly is over those lanes, so
|
||||
* one wave quantises 128/GROUP groups in a pass; a wider one is covered by one wave in sub-blocks
|
||||
* of 128 whose maxima are fmaxf'd. All three are q8_group's bracketing.
|
||||
*
|
||||
* Rows are dim 0, so a rank-3 activation ([tokens, heads, width], a GDN block's out-projection
|
||||
* input) is one row per token, as libref reads it: its consuming GEMM's K is heads*width, and one
|
||||
* row per head would put scales on a grid that GEMM does not read.
|
||||
*/
|
||||
template <int GROUP>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
|
||||
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n,
|
||||
uint32_t ngrp, uint32_t x_ld, uint32_t s_ld) {
|
||||
constexpr int kSub = GROUP >= (int)kWaveCols ? GROUP / (int)kWaveCols : 1;
|
||||
constexpr int kPer = GROUP < (int)kWaveCols ? (int)kWaveCols / GROUP : 1;
|
||||
constexpr int kLanes = GROUP < (int)kWaveCols ? (int)(GROUP / kColsPerLane) : (int)kWave;
|
||||
static_assert(kLanes >= 1 && kLanes <= (int)kWave, "a group spans at most one wave");
|
||||
|
||||
const uint32_t row = blockIdx.x;
|
||||
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
|
||||
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
|
||||
uint8_t* __restrict__ qr = q + (size_t)row * n;
|
||||
|
||||
const uint32_t nunit = (ngrp + kPer - 1) / kPer;
|
||||
for (uint32_t u = wave; u < nunit; u += kWaves) {
|
||||
const uint32_t g0 = u * kPer, cbase = g0 * GROUP;
|
||||
float v[kSub][kColsPerLane];
|
||||
float am = 0.0f;
|
||||
#pragma unroll
|
||||
for (int sb = 0; sb < kSub; ++sb) {
|
||||
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < kColsPerLane; ++j) {
|
||||
const uint32_t c = c0 + (uint32_t)j;
|
||||
/* Past the row's end a lane contributes 0.0f, so padding is a zero code and takes
|
||||
* no part in the amax. n is a multiple of 4, so a lane's four columns are all in
|
||||
* the row or all outside it: the ragged edge never splits a lane. */
|
||||
v[sb][j] = c < n ? ld_bf(xr, c) : 0.0f;
|
||||
}
|
||||
float m = 0.0f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < kColsPerLane; ++j) m = fmaxf(m, fabsf(v[sb][j]));
|
||||
am = fmaxf(am, r3d_xor_max<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. */
|
||||
if ((lane & (kLanes - 1)) == 0) {
|
||||
const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes;
|
||||
if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc;
|
||||
}
|
||||
const float inv = 1.0f / sc;
|
||||
#pragma unroll
|
||||
for (int sb = 0; sb < kSub; ++sb) {
|
||||
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
|
||||
if (c0 < n) *(uint32_t*)(qr + c0) = e4m3_codes4(v[sb], inv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== quant_act_i8g
|
||||
*
|
||||
* The same group core at int8, q8_group called with top 127. One scale
|
||||
* per (row, group), `sc = amax * (1.0f / 127)` -- the reciprocal MULTIPLIED, as in the fp8 path, so
|
||||
* this is quant_act_fp8 with a different codec and not quant_act_i8 at a finer granularity -- codes
|
||||
* clamp(v * (1/sc), +-127) to nearest even, stored ROW-MAJOR, and scale 1 for an all-zero group.
|
||||
*
|
||||
* The row-major store is the point of the op: libr3d's only int8 GEMM is the i8a8 one, and a dot2
|
||||
* GEMM reads a row in the order it is stored. The step-ordered plane belongs to quant_act_i8, whose
|
||||
* consumers are libr4d's WMMA GEMMs, and the two are not interchangeable.
|
||||
*
|
||||
* Same lane mapping and same ragged rules as quant_act_fp8_kernel, so the two bodies read as one
|
||||
* shape with the codec swapped.
|
||||
*/
|
||||
template <int GROUP>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8g_kernel(
|
||||
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n,
|
||||
uint32_t ngrp, uint32_t x_ld, uint32_t s_ld) {
|
||||
constexpr int kSub = GROUP >= (int)kWaveCols ? GROUP / (int)kWaveCols : 1;
|
||||
constexpr int kPer = GROUP < (int)kWaveCols ? (int)kWaveCols / GROUP : 1;
|
||||
constexpr int kLanes = GROUP < (int)kWaveCols ? (int)(GROUP / kColsPerLane) : (int)kWave;
|
||||
static_assert(kLanes >= 1 && kLanes <= (int)kWave, "a group spans at most one wave");
|
||||
|
||||
const uint32_t row = blockIdx.x;
|
||||
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
|
||||
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
|
||||
uint8_t* __restrict__ qr = q + (size_t)row * n;
|
||||
|
||||
const uint32_t nunit = (ngrp + kPer - 1) / kPer;
|
||||
for (uint32_t u = wave; u < nunit; u += kWaves) {
|
||||
const uint32_t g0 = u * kPer, cbase = g0 * GROUP;
|
||||
float v[kSub][kColsPerLane];
|
||||
float am = 0.0f;
|
||||
#pragma unroll
|
||||
for (int sb = 0; sb < kSub; ++sb) {
|
||||
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < kColsPerLane; ++j) {
|
||||
const uint32_t c = c0 + (uint32_t)j;
|
||||
v[sb][j] = c < n ? ld_bf(xr, c) : 0.0f; /* padding is a zero code, as above */
|
||||
}
|
||||
float m = 0.0f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < kColsPerLane; ++j) m = fmaxf(m, fabsf(v[sb][j]));
|
||||
am = fmaxf(am, r3d_xor_max<kLanes>(m));
|
||||
}
|
||||
const float sc = group_scale(am, kTopI8);
|
||||
if ((lane & (kLanes - 1)) == 0) {
|
||||
const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes;
|
||||
if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc;
|
||||
}
|
||||
const float inv = 1.0f / sc;
|
||||
#pragma unroll
|
||||
for (int sb = 0; sb < kSub; ++sb) {
|
||||
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
|
||||
if (c0 < n) *(uint32_t*)(qr + c0) = i8_codes4(v[sb], inv); /* row-major */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* x [M][n] bf16, `x_ld` elements a row (0 = n)
|
||||
* q [M][n] E4M3, DENSE: the launcher takes no code pitch, so the plane is
|
||||
* row-major with no hole in it, rounded up to 4 bytes for the padding
|
||||
* s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group))
|
||||
*
|
||||
* A launcher checks what a `__global__` cannot and issues one kernel: 0, -1 a null pointer, -2 a bad
|
||||
* extent (including a group with no instantiation), -3 a pitch that does not describe the operand,
|
||||
* -4 the HIP launch failed. It allocates nothing and synchronises on nothing. */
|
||||
extern "C" int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld,
|
||||
int s_ld, long stream) {
|
||||
if (!x || !q || !s) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (n % (int)kColsPerLane) return -3; /* a lane owns four columns; see the kernel */
|
||||
if (group < 4 || group > 512 || (group & (group - 1))) return -2;
|
||||
const int ngrp = (n + group - 1) / group;
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!s_ld) s_ld = ngrp;
|
||||
if (x_ld < n || s_ld < ngrp) return -3;
|
||||
|
||||
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
|
||||
const dim3 grid((unsigned)M), block(kThreads);
|
||||
#define R3D_QAF(G) \
|
||||
R3D_KLAUNCH(R3D_KNAME(quant_act_fp8_kernel<G>), grid, block, st, (const uint16_t*)x, \
|
||||
(uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)ngrp, (uint32_t)x_ld, \
|
||||
(uint32_t)s_ld)
|
||||
switch (group) {
|
||||
case 4: R3D_QAF(4); break;
|
||||
case 8: R3D_QAF(8); break;
|
||||
case 16: R3D_QAF(16); break;
|
||||
case 32: R3D_QAF(32); break;
|
||||
case 64: R3D_QAF(64); break;
|
||||
case 128: R3D_QAF(128); break;
|
||||
case 256: R3D_QAF(256); break;
|
||||
case 512: R3D_QAF(512); break;
|
||||
default: return -2;
|
||||
}
|
||||
#undef R3D_QAF
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* ================================================================== quant_act_i8
|
||||
*
|
||||
* The activation of the w4a8, w8a8 and w2a8 GEMMs, ONE SCALE PER ROW,
|
||||
* max(amax, 1e-8) / 127, codes x * (1/scale) rounded to nearest even by the int8 codec.
|
||||
*
|
||||
* The codes go out in libref's STEP ORDER, `i8_step_pos`: the middle two
|
||||
* dwords of every 16-byte step exchanged, which is why this op's n is a multiple of 16 and not of
|
||||
* 4. That order is what the op MEANS -- the w4a8, w8a8 and w2a8 GEMMs read the plane that way, and
|
||||
* kbench compares the plane element by element -- so it is kept on a card that has no WMMA, and the
|
||||
* row-major int8 plane is a separate op, quant_act_i8g below, which is the one this library's i8a8
|
||||
* GEMM consumes. The permutation is per-lane and preserves c % 4, so a lane's four codes stay
|
||||
* contiguous and the store stays one dword; a wave's 128 bytes are a permutation of the same 128.
|
||||
*
|
||||
* One divergence from the reference's arithmetic, and it is inert: libref reduces a row with
|
||||
* std::max and this with fmaxf. They agree on every input the op can see -- std::max(a, NaN) is a, so
|
||||
* the reference's amax is never a NaN, and fmaxf drops the NaN the same way; an all-NaN row has amax
|
||||
* 0 in both and scale 1e-8/127.
|
||||
*
|
||||
* ASUM, when present, also takes each row's code sums per `group` columns, group-major
|
||||
* [n/group][Mpad] with Mpad = ceil(M/16)*16: an asymmetric weight grid needs sum_k a_k to subtract
|
||||
* z_g * sum_k a_k from a group's dot product once instead of N times, and it reads whole 16-row
|
||||
* tiles. The sums are integers, so the LDS accumulator's atomic adds are exact and their order is
|
||||
* free. Rows M..Mpad-1 are not written; the caller zeroes them, as libref does.
|
||||
*/
|
||||
template <bool ASUM>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel(
|
||||
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s,
|
||||
float* __restrict__ asum, uint32_t n, uint32_t group, uint32_t x_ld, uint32_t s_ld,
|
||||
uint32_t mpad) {
|
||||
__shared__ float red[kWaves];
|
||||
__shared__ int gs[kI8MaxGroups];
|
||||
|
||||
const uint32_t row = blockIdx.x;
|
||||
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
|
||||
uint8_t* __restrict__ qr = q + (size_t)row * n;
|
||||
const uint32_t ngrp = ASUM ? n / group : 0;
|
||||
|
||||
float am = 0.0f;
|
||||
for (uint32_t c = threadIdx.x * kColsPerLane; c < n; c += kThreads * kColsPerLane) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < kColsPerLane; ++j) {
|
||||
const uint32_t cc = c + (uint32_t)j;
|
||||
if (cc < n) am = fmaxf(am, fabsf(ld_bf(xr, cc)));
|
||||
}
|
||||
}
|
||||
const float scale = fmaxf(block_max(am, red), kI8Floor) / kTopI8;
|
||||
const float inv = 1.0f / scale;
|
||||
if (threadIdx.x == 0) s[(size_t)row * s_ld] = scale;
|
||||
if (ASUM) {
|
||||
for (uint32_t g = threadIdx.x; g < ngrp; g += kThreads) gs[g] = 0;
|
||||
__syncthreads(); /* the zeroing has to land before the atomics */
|
||||
}
|
||||
|
||||
for (uint32_t c = threadIdx.x * kColsPerLane; c < n; c += kThreads * kColsPerLane) {
|
||||
uint32_t w = 0;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < kColsPerLane; ++j) {
|
||||
const uint32_t cc = c + (uint32_t)j;
|
||||
const int8_t code = (cc < n) ? f32_to_i8_rtne(ld_bf(xr, cc) * inv) : (int8_t)0;
|
||||
w |= (uint32_t)(uint8_t)code << (8 * j);
|
||||
/* n % group == 0 and group % 4 == 0, so a lane's four columns are in one group. The
|
||||
* sum is over column order, and the map is its own inverse, so summing the codes of
|
||||
* columns [gi*group, (gi+1)*group) here is libref reading qr[i8_step_pos(i)] --
|
||||
* same bytes, same groups. */
|
||||
if (ASUM && cc < n) atomicAdd(&gs[cc / group], (int)code);
|
||||
}
|
||||
*(uint32_t*)(qr + i8_step_pos(c)) = w; /* the step order, one dword a lane */
|
||||
}
|
||||
if (ASUM) {
|
||||
__syncthreads();
|
||||
for (uint32_t g = threadIdx.x; g < ngrp; g += kThreads)
|
||||
asum[(size_t)g * mpad + row] = (float)gs[g];
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* x [M][n] bf16, `x_ld` elements a row (0 = n)
|
||||
* q [M][n] i8, DENSE, in libref's STEP ORDER (i8_step_pos: bits 2 and 3 of the
|
||||
* column exchanged), so n is a multiple of 16, not of 4
|
||||
* s [M] f32, ONE scale a row, written at element pitch `s_ld` (0 = 1). A
|
||||
* plane with more room than rows is legal and filled in libref's flat
|
||||
* order -- the row's scale at s[r], the tail the caller's -- because
|
||||
* that is what libref does with whatever capacity it is handed, and a
|
||||
* byte comparison of the tail then agrees.
|
||||
* asum [n/group][Mpad] f32, optional, group-major, Mpad = ceil(M/16)*16
|
||||
*
|
||||
* `group` sizes asum and is ignored without it, as libref ignores it: it is the width of the code
|
||||
* sums, not the granularity of the scale, which is the whole row. */
|
||||
extern "C" int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n, int group,
|
||||
int x_ld, int s_ld, long stream) {
|
||||
if (!x || !q || !s) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (n % 16) return -3; /* a whole 16-byte step; see i8_step_pos */
|
||||
uint32_t mpad = 0;
|
||||
if (asum) {
|
||||
if (group < (int)kColsPerLane || group % (int)kColsPerLane || n % group) return -2;
|
||||
if (n / group > (int)kI8MaxGroups) return -2;
|
||||
mpad = (uint32_t)((M + 15) / 16 * 16);
|
||||
} else {
|
||||
group = n;
|
||||
}
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!s_ld) s_ld = 1;
|
||||
if (x_ld < n || s_ld < 1) return -3;
|
||||
|
||||
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
|
||||
const dim3 grid((unsigned)M), block(kThreads);
|
||||
if (asum)
|
||||
R3D_KLAUNCH(R3D_KNAME(quant_act_i8_kernel<true>), grid, block, st, (const uint16_t*)x,
|
||||
(uint8_t*)q, (float*)s, (float*)asum, (uint32_t)n, (uint32_t)group,
|
||||
(uint32_t)x_ld, (uint32_t)s_ld, mpad);
|
||||
else
|
||||
R3D_KLAUNCH(R3D_KNAME(quant_act_i8_kernel<false>), grid, block, st, (const uint16_t*)x,
|
||||
(uint8_t*)q, (float*)s, (float*)nullptr, (uint32_t)n, (uint32_t)group,
|
||||
(uint32_t)x_ld, (uint32_t)s_ld, mpad);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* x [M][n] bf16, `x_ld` elements a row (0 = n)
|
||||
* q [M][n] i8, DENSE and ROW-MAJOR: the plane this library's i8a8 GEMM reads
|
||||
* s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group))
|
||||
*
|
||||
* `group` is the scale's width and is clamped to n when absent, as libref clamps it: `group >= n`
|
||||
* and `group` absent are both one scale a row. Codes clamp to +-127 before
|
||||
* the codec, in q8_group's order. 0, -1, -2 a bad extent or an uninstantiated group, -3 a pitch
|
||||
* that does not describe the operand, -4 the HIP launch failed. */
|
||||
extern "C" int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group,
|
||||
long long x_ld, long long s_ld, long stream) {
|
||||
if (!x || !q || !s) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (n % (int)kColsPerLane) return -3; /* a lane owns four columns; see the kernel */
|
||||
if (group < 4 || group > 512 || (group & (group - 1))) return -2;
|
||||
const int ngrp = (n + group - 1) / group;
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!s_ld) s_ld = ngrp;
|
||||
if (x_ld < n || s_ld < ngrp) return -3;
|
||||
|
||||
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
|
||||
const dim3 grid((unsigned)M), block(kThreads);
|
||||
#define R3D_QAI8G(G) \
|
||||
R3D_KLAUNCH(R3D_KNAME(quant_act_i8g_kernel<G>), grid, block, st, (const uint16_t*)x, \
|
||||
(uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)ngrp, (uint32_t)x_ld, \
|
||||
(uint32_t)s_ld)
|
||||
switch (group) {
|
||||
case 4: R3D_QAI8G(4); break;
|
||||
case 8: R3D_QAI8G(8); break;
|
||||
case 16: R3D_QAI8G(16); break;
|
||||
case 32: R3D_QAI8G(32); break;
|
||||
case 64: R3D_QAI8G(64); break;
|
||||
case 128: R3D_QAI8G(128); break;
|
||||
case 256: R3D_QAI8G(256); break;
|
||||
case 512: R3D_QAI8G(512); break;
|
||||
default: return -2;
|
||||
}
|
||||
#undef R3D_QAI8G
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* ================================================================== gated_quant_fp8
|
||||
*
|
||||
* act(gate) * up, then quant_act_fp8's quantiser, in one pass. `gate_up` is
|
||||
* [M, 2n], gate in the first n and up in the second, which is what a fused gate_up projection
|
||||
* writes; the product is what gets quantised, and `out_bf16`, when bound, receives it.
|
||||
*
|
||||
* The product is narrowed to bf16 and read back before the absmax. That is the op and not an
|
||||
* optimisation: the unfused pair writes a bf16 [M, n] tensor and quantises those bytes, so the
|
||||
* codes are taken over the narrowed value and out_bf16 holds exactly the value they came from.
|
||||
* Within the product the rounding points are libref's: sg = 1/(1+exp(-gate)) in f32, then
|
||||
* (gate*sg) for silu -- MULTIPLIED, not divided, which is a different f32 -- then * up, then one
|
||||
* bf16 narrowing. `expf` is the accurate form and not __expf (r3d_common.h); it is the one value in
|
||||
* this unit the reference evaluates in double, so a code can move by one where the bf16 narrowing
|
||||
* lands on a tie. Every other number here is bit-for-bit.
|
||||
*
|
||||
* No row reduction, so no first pass and no barrier: a wave a group, a lane four columns.
|
||||
*/
|
||||
template <int GROUP, int ACT>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void gated_quant_fp8_kernel(
|
||||
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q,
|
||||
float* __restrict__ s, uint32_t n, uint32_t ngrp, uint32_t s_ld) {
|
||||
constexpr int kSub = GROUP >= (int)kWaveCols ? GROUP / (int)kWaveCols : 1;
|
||||
constexpr int kPer = GROUP < (int)kWaveCols ? (int)kWaveCols / GROUP : 1;
|
||||
constexpr int kLanes = GROUP < (int)kWaveCols ? (int)(GROUP / kColsPerLane) : (int)kWave;
|
||||
|
||||
const uint32_t row = blockIdx.x;
|
||||
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
|
||||
const uint16_t* __restrict__ gr = gu + (size_t)row * (2 * n);
|
||||
uint16_t* __restrict__ yr = y ? y + (size_t)row * n : nullptr;
|
||||
uint8_t* __restrict__ qr = q + (size_t)row * n;
|
||||
|
||||
const uint32_t nunit = (ngrp + kPer - 1) / kPer;
|
||||
for (uint32_t u = wave; u < nunit; u += kWaves) {
|
||||
const uint32_t g0 = u * kPer, cbase = g0 * GROUP;
|
||||
float v[kSub][kColsPerLane];
|
||||
float am = 0.0f;
|
||||
#pragma unroll
|
||||
for (int sb = 0; sb < kSub; ++sb) {
|
||||
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < kColsPerLane; ++j) {
|
||||
const uint32_t c = c0 + (uint32_t)j;
|
||||
if (c < n) {
|
||||
const float gt = ld_bf(gr, c);
|
||||
const float up = ld_bf(gr, n + c);
|
||||
const float sg = 1.0f / (1.0f + expf(-gt));
|
||||
const uint16_t h = f32_to_bf16((ACT == R3D_ACT_SILU ? gt * sg : sg) * up);
|
||||
if (yr) yr[c] = h;
|
||||
v[sb][j] = bf16_to_f32(h);
|
||||
} else {
|
||||
v[sb][j] = 0.0f; /* padding: see quant_act_fp8_kernel */
|
||||
}
|
||||
}
|
||||
float m = 0.0f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < kColsPerLane; ++j) m = fmaxf(m, fabsf(v[sb][j]));
|
||||
am = fmaxf(am, r3d_xor_max<kLanes>(m));
|
||||
}
|
||||
const float sc = group_scale(am, kTopE4M3);
|
||||
if ((lane & (kLanes - 1)) == 0) { /* the ragged guard, as above */
|
||||
const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes;
|
||||
if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc;
|
||||
}
|
||||
const float inv = 1.0f / sc;
|
||||
#pragma unroll
|
||||
for (int sb = 0; sb < kSub; ++sb) {
|
||||
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
|
||||
if (c0 < n) *(uint32_t*)(qr + c0) = e4m3_codes4(v[sb], inv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* gu [M][2n] bf16, gate first then up, DENSE (the launcher takes no pitch)
|
||||
* y [M][n] bf16, the product, optional, dense
|
||||
* q [M][n] E4M3, dense
|
||||
* s [M][ceil(n/group)] f32, dense
|
||||
*
|
||||
* `act` is R3D_ACT_SILU (down_proj's input) or R3D_ACT_SIGMOID (a gated attention o_proj's). */
|
||||
extern "C" int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16, int M, int n,
|
||||
int group, int act, long stream) {
|
||||
if (!gate_up || !q || !s) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (n % (int)kColsPerLane) return -3;
|
||||
if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return -2;
|
||||
if (group < 4 || group > 512 || (group & (group - 1))) return -2;
|
||||
const int ngrp = (n + group - 1) / group;
|
||||
|
||||
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
|
||||
const dim3 grid((unsigned)M), block(kThreads);
|
||||
#define R3D_GQ(G, A) \
|
||||
R3D_KLAUNCH(R3D_KNAME(gated_quant_fp8_kernel<G, A>), grid, block, st, (const uint16_t*)gate_up, \
|
||||
(uint16_t*)out_bf16, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)ngrp, \
|
||||
(uint32_t)ngrp)
|
||||
#define R3D_GQ_ACT(A) \
|
||||
switch (group) { \
|
||||
case 4: R3D_GQ(4, A); break; \
|
||||
case 8: R3D_GQ(8, A); break; \
|
||||
case 16: R3D_GQ(16, A); break; \
|
||||
case 32: R3D_GQ(32, A); break; \
|
||||
case 64: R3D_GQ(64, A); break; \
|
||||
case 128: R3D_GQ(128, A); break; \
|
||||
case 256: R3D_GQ(256, A); break; \
|
||||
case 512: R3D_GQ(512, A); break; \
|
||||
default: return -2; \
|
||||
}
|
||||
/* The gate is a template argument, so the multiply below is one instruction and not a branch in
|
||||
* the inner loop; the switch is over the group widths, each with its own lane mapping. */
|
||||
if (act == R3D_ACT_SILU) { R3D_GQ_ACT(R3D_ACT_SILU); }
|
||||
else { R3D_GQ_ACT(R3D_ACT_SIGMOID); }
|
||||
#undef R3D_GQ_ACT
|
||||
#undef R3D_GQ
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* ================================================================== dequant
|
||||
*
|
||||
* y = code * scale, the read of a container's own quantised weight. Elementwise,
|
||||
* so there is no reduction and no order to match; the code decodes exactly (E4M3's four exponent
|
||||
* bits and three mantissa bits are a subset of f16's, and of f32's; E5M2 is f16's top byte,
|
||||
* rad_plugin.h; int8 is exact in f32), the product is one f32 multiply per element, and the
|
||||
* store narrows it to bf16 -- the width every consumer of a dequantised weight on this card reads,
|
||||
* which is why the launcher names the codes' dtype and not the output's.
|
||||
*
|
||||
* The scale stream is [M, ceil(n/group)] and the shim requires it to carry every group, so the
|
||||
* clamp below never fires on a well-formed call; libref clamps a short stream's index to its last
|
||||
* scale instead of reading off the end, and a kernel row refuses that geometry instead.
|
||||
*/
|
||||
template <int QDT>
|
||||
__device__ __forceinline__ float code_value(uint8_t b) {
|
||||
if (QDT == R3D_DT_U8) return e4m3_to_f32(b);
|
||||
if (QDT == R3D_DT_E5M2) return f16_to_f32((uint16_t)b << 8);
|
||||
return (float)(int8_t)b;
|
||||
}
|
||||
|
||||
template <int QDT>
|
||||
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void dequant_kernel(
|
||||
const uint8_t* __restrict__ q, const float* __restrict__ s, uint16_t* __restrict__ y,
|
||||
uint32_t n, uint32_t group, uint32_t ngrp, uint32_t s_ld, uint32_t y_ld) {
|
||||
const uint32_t row = blockIdx.x;
|
||||
const uint8_t* __restrict__ qr = q + (size_t)row * n;
|
||||
const float* __restrict__ sr = s + (size_t)row * s_ld;
|
||||
uint16_t* __restrict__ yr = y + (size_t)row * y_ld;
|
||||
|
||||
for (uint32_t c = threadIdx.x * kColsPerLane; c < n; c += kThreads * kColsPerLane) {
|
||||
const uint32_t gi = min(c / group, ngrp - 1u);
|
||||
const float sc = ldg_f32(sr + gi);
|
||||
/* n is a multiple of 4 and the plane is dense, so a lane's four codes are one dword. */
|
||||
const uint32_t w = ldg_u32((const uint32_t*)(qr + c));
|
||||
/* One 8-byte store a lane: bf16x2_rne is software RTNE, because gfx11 has no
|
||||
* v_cvt_pk_bf16_f32 (r3d_common.h), and the narrowing is the store's single round. */
|
||||
uint32_t* yp = (uint32_t*)(yr + c);
|
||||
yp[0] = bf16x2_rne(code_value<QDT>((uint8_t)(w & 0xffu)) * sc,
|
||||
code_value<QDT>((uint8_t)(w >> 8)) * sc);
|
||||
yp[1] = bf16x2_rne(code_value<QDT>((uint8_t)(w >> 16)) * sc,
|
||||
code_value<QDT>((uint8_t)(w >> 24)) * sc);
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* q [M][n] codes, DENSE: E4M3, E5M2 or i8, one byte apiece
|
||||
* s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group))
|
||||
* y [M][n] bf16, `y_ld` elements a row (0 = n)
|
||||
*
|
||||
* `y` is bf16: the launcher describes the codes' dtype and not the output's, because a dequantised
|
||||
* weight here is read by a bf16 dot2 GEMM, which is the same reason r3d.h gives this launcher one
|
||||
* dtype argument. An f32 plane is r3d_cast's, which carries two. */
|
||||
extern "C" int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s_ld,
|
||||
int y_ld, long stream) {
|
||||
if (!q || !s || !y) return -1;
|
||||
if (M <= 0 || n <= 0 || group < 1) return -2;
|
||||
if (n % (int)kColsPerLane) return -3;
|
||||
if (q_dt != R3D_DT_U8 && q_dt != R3D_DT_E5M2 && q_dt != R3D_DT_I8) return -2;
|
||||
const int ngrp = (n + group - 1) / group;
|
||||
if (!s_ld) s_ld = ngrp;
|
||||
if (!y_ld) y_ld = n;
|
||||
if (s_ld < ngrp || y_ld < n) return -3;
|
||||
|
||||
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
|
||||
const dim3 grid((unsigned)M), block(kThreads);
|
||||
#define R3D_DQ(D) \
|
||||
R3D_KLAUNCH(R3D_KNAME(dequant_kernel<D>), grid, block, st, (const uint8_t*)q, (const float*)s, \
|
||||
(uint16_t*)y, (uint32_t)n, (uint32_t)group, (uint32_t)ngrp, (uint32_t)s_ld, \
|
||||
(uint32_t)y_ld)
|
||||
switch (q_dt) {
|
||||
case R3D_DT_U8: R3D_DQ(R3D_DT_U8); break;
|
||||
case R3D_DT_E5M2: R3D_DQ(R3D_DT_E5M2); break;
|
||||
case R3D_DT_I8: R3D_DQ(R3D_DT_I8); break;
|
||||
default: return -2;
|
||||
}
|
||||
#undef R3D_DQ
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* ================================================================== the plugin ABI entry points
|
||||
*
|
||||
* Three things every shim here reads off the operands and not off the parameters:
|
||||
*
|
||||
* * the dtype. A row's `dtype` constraint is a necessary condition on the geometry, not a promise
|
||||
* about the tensors, and an f32 activation read as bf16 is a value that passes every other
|
||||
* check.
|
||||
* * the row count. `M` is the band's upper bound, so the args carry a bound and the operand
|
||||
* carries the call.
|
||||
* * the pitch. r3d_rows_pitch() answers in elements, or -1 for an inner axis that is strided.
|
||||
*
|
||||
* The code planes are dense: none of the four launchers takes a code pitch, because a dot2 GEMM
|
||||
* reads codes row-major and the engine hands them over in the order it stores them. A plane with a
|
||||
* hole in it is a stride refusal and not a slow path. */
|
||||
|
||||
/* bf16 is the only activation width these kernels read. An f32 activation is r3d_cast's problem,
|
||||
* which takes the dtypes as arguments; a quantiser with a dtype switch in its inner loop is the
|
||||
* wrong shape for an op whose whole point is the store. */
|
||||
static inline int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
static inline int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
/* The codes' dtype picks the codec, so it is checked exactly and never as "some byte". */
|
||||
static inline int dt_e4m3(const RadTensor* t) { return r3d_is_e4m3(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
static inline int dt_i8(const RadTensor* t) { return r3d_is_i8(t) ? RAD_OK : RAD_E_DTYPE; }
|
||||
|
||||
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
|
||||
|
||||
/* A launcher checked the geometry and answered with a code; translate it to a RAD status. */
|
||||
static inline int r3d_launch_status(int e) {
|
||||
switch (e) {
|
||||
case 0: return RAD_OK;
|
||||
case -1: return RAD_E_INVAL;
|
||||
case -2: return RAD_E_SHAPE;
|
||||
case -3: return RAD_E_STRIDE;
|
||||
default: return RAD_E_DEVICE;
|
||||
}
|
||||
}
|
||||
|
||||
/* The group must be a power of two from 4 to 512: the amax butterfly is over the lanes covering a
|
||||
* group, GROUP/4 of them, and the kernels are instantiated for those widths. libref clamps
|
||||
* `group <= 0 || group > n` to n, so "one scale a row" arrives as 0 and leaves as n;
|
||||
* a width with no instantiation is refused and not rounded, because a rounded group would quantise
|
||||
* on a grid the weight's scales are not on. */
|
||||
static inline int r3d_group_of(long long g, long long n) {
|
||||
if (g <= 0 || g > n) g = n;
|
||||
return (g >= 4 && g <= 512 && (g & (g - 1)) == 0) ? (int)g : 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ quant_act_fp8 */
|
||||
|
||||
enum { QAF_X = 0, QAF_Q, QAF_S };
|
||||
|
||||
extern "C" int r3d_rad_quant_act_fp8(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* x = r3d_opt(a, QAF_X);
|
||||
const RadTensor* q = r3d_opt(a, QAF_Q);
|
||||
const RadTensor* sc = r3d_opt(a, QAF_S);
|
||||
if (!x || !q || !sc) return R3D_NO(RAD_E_INVAL);
|
||||
R3D_NEED(dt_bf16(x));
|
||||
R3D_NEED(dt_e4m3(q));
|
||||
R3D_NEED(dt_f32(sc));
|
||||
|
||||
const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1));
|
||||
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
|
||||
const int group = r3d_group_of(r3d_geti_or(a, "group", R3D_ACT_GROUP), n);
|
||||
if (!group) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long ngrp = (n + group - 1) / group;
|
||||
|
||||
long long rows = 0, qrows = 0, srows = 0;
|
||||
const long long x_ld = r3d_rows_pitch(x, n, &rows);
|
||||
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
|
||||
const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows);
|
||||
if (x_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE);
|
||||
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
|
||||
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
|
||||
if (srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
return r3d_launch_status(r3d_quant_act_fp8(r3d_addr(x), r3d_addr(q), r3d_addr(sc), (int)rows,
|
||||
(int)n, group, (int)x_ld, (int)s_ld,
|
||||
(long)(uintptr_t)stream));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ quant_act_i8 */
|
||||
|
||||
enum { QAI_X = 0, QAI_Q, QAI_S, QAI_ASUM };
|
||||
|
||||
extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* x = r3d_opt(a, QAI_X);
|
||||
const RadTensor* q = r3d_opt(a, QAI_Q);
|
||||
const RadTensor* sc = r3d_opt(a, QAI_S);
|
||||
const RadTensor* as = r3d_opt(a, QAI_ASUM); /* the asymmetric grid's code sums */
|
||||
if (!x || !q || !sc) return R3D_NO(RAD_E_INVAL);
|
||||
R3D_NEED(dt_bf16(x));
|
||||
R3D_NEED(dt_i8(q));
|
||||
R3D_NEED(dt_f32(sc));
|
||||
if (r3d_has(as)) R3D_NEED(dt_f32(as)); /* a slot with no bytes is the operand being absent */
|
||||
|
||||
const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1));
|
||||
if (n <= 0 || n % 16) return R3D_NO(RAD_E_SHAPE); /* a whole 16-byte step: see i8_step_pos */
|
||||
|
||||
/* One scale a row: this op's scale granularity IS the row (the amax runs over the whole row,
|
||||
* and the store is `stt(s, rowoff(s, r, 1), scale)`, a FLAT stream at element pitch 1), and
|
||||
* libref lists `group` as the width of the row SUMS, not of the scale. A plane with more
|
||||
* elements than rows is therefore accepted and filled in libref's order: the row's scale
|
||||
* lands at s[r], the plane's first M elements, and the rest of it stays the caller's. That
|
||||
* is exactly the plane the row's operand description gives --
|
||||
* [M, ceil(n/group)], quant_act_i8g's width, of which this op writes the first column -- and
|
||||
* refusing it would be the shim tightening its own row past the reference: libref requires
|
||||
* numel(s) >= rows and nothing more, and the bytes it never touches compare equal. */
|
||||
|
||||
long long rows = 0, qrows = 0, srows = 0;
|
||||
const long long x_ld = r3d_rows_pitch(x, n, &rows);
|
||||
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
|
||||
const long long s_ld = r3d_rows_pitch(sc, 1, &srows);
|
||||
if (x_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE);
|
||||
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
|
||||
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
|
||||
if (srows < rows || r3d_numel(sc) < rows) return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
/* `group` sizes asum only, and is not read without it. n % group == 0, because a sum is over
|
||||
* whole columns of a row, and the LDS accumulator is 256 groups wide. */
|
||||
int group = 0;
|
||||
if (as) {
|
||||
group = (int)r3d_geti_or(a, "group", R3D_W8_GROUP);
|
||||
if (group < (int)kColsPerLane || group % kColsPerLane || n % group)
|
||||
return R3D_NO(RAD_E_SHAPE);
|
||||
if (n / group > (long long)kI8MaxGroups) return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_contig(as)) return R3D_NO(RAD_E_STRIDE);
|
||||
const long long mpad = ((rows + 15) / 16) * 16;
|
||||
if (r3d_numel(as) < (n / group) * mpad) return R3D_NO(RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
return r3d_launch_status(r3d_quant_act_i8(
|
||||
r3d_addr(x), r3d_addr(q), r3d_addr(sc), r3d_addr(as), (int)rows, (int)n, group, (int)x_ld,
|
||||
(int)s_ld, (long)(uintptr_t)stream));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ quant_act_i8g */
|
||||
|
||||
/* The int8 plane at group granularity, and the one this library's i8a8 GEMM reads. Operands are
|
||||
* libref's oQuantFp8 shape -- {x, q, scale} -- with the int8 codes' dtype. */
|
||||
enum { QAG_X = 0, QAG_Q, QAG_S };
|
||||
|
||||
extern "C" int r3d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* x = r3d_opt(a, QAG_X);
|
||||
const RadTensor* q = r3d_opt(a, QAG_Q);
|
||||
const RadTensor* sc = r3d_opt(a, QAG_S);
|
||||
if (!x || !q || !sc) return R3D_NO(RAD_E_INVAL);
|
||||
R3D_NEED(dt_bf16(x));
|
||||
R3D_NEED(dt_i8(q));
|
||||
R3D_NEED(dt_f32(sc));
|
||||
|
||||
const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1));
|
||||
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
|
||||
/* libref's clamp of `group`: absent, zero or wider than the row is one
|
||||
* scale a row, so the default here is 0 and the clamp turns it into n. A width the kernels have
|
||||
* no instantiation for is refused, not rounded to one. */
|
||||
const int group = r3d_group_of(r3d_geti_or(a, "group", 0), n);
|
||||
if (!group) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long ngrp = (n + group - 1) / group;
|
||||
|
||||
long long rows = 0, qrows = 0, srows = 0;
|
||||
const long long x_ld = r3d_rows_pitch(x, n, &rows);
|
||||
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
|
||||
const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows);
|
||||
if (x_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE);
|
||||
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
|
||||
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
|
||||
if (srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
return r3d_launch_status(r3d_quant_act_i8g(x->data, q->data, sc->data, (int)rows, (int)n, group,
|
||||
x_ld, s_ld, (long)(uintptr_t)stream));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gated_quant_fp8 */
|
||||
|
||||
enum { GQT_GU = 0, GQT_Q, GQT_S, GQT_Y };
|
||||
|
||||
extern "C" int r3d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* gu = r3d_opt(a, GQT_GU);
|
||||
const RadTensor* q = r3d_opt(a, GQT_Q);
|
||||
const RadTensor* sc = r3d_opt(a, GQT_S);
|
||||
const RadTensor* y = r3d_opt(a, GQT_Y); /* the product, for a bf16 consumer */
|
||||
if (!gu || !q || !sc) return R3D_NO(RAD_E_INVAL);
|
||||
R3D_NEED(dt_bf16(gu));
|
||||
R3D_NEED(dt_e4m3(q));
|
||||
R3D_NEED(dt_f32(sc));
|
||||
if (r3d_has(y)) R3D_NEED(dt_bf16(y)); /* the same: an empty slot is no operand at all */
|
||||
|
||||
/* "silu" (down_proj's input) or "sigmoid" (a gated attention o_proj's), `mode` the integer
|
||||
* spelling of the same choice, `act` winning where both are given. libref's `act` enumerates
|
||||
* those two, so a gelu-gated feed-forward is not this row's: it asks for a gate the oracle has
|
||||
* no definition for here. */
|
||||
const int act = r3d_act_code(a, "act", "mode", R3D_ACT_SILU);
|
||||
if (act < 0) return R3D_NO(RAD_E_UNSUPPORTED);
|
||||
|
||||
const long long n = r3d_geti_or(a, "n", r3d_dim(q, (int)q->rank - 1));
|
||||
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
|
||||
const int group = r3d_group_of(r3d_geti_or(a, "group", R3D_ACT_GROUP), n);
|
||||
if (!group) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long ngrp = (n + group - 1) / group;
|
||||
|
||||
/* The fused gate_up projection writes the plane dense, gate half first, [M, 2n] with no hole: a
|
||||
* sliced gate is r3d_act_mul_bf16's, which takes the two pitches. */
|
||||
long long rows = 0, qrows = 0, srows = 0, yrows = 0;
|
||||
const long long gu_ld = r3d_rows_pitch(gu, 2 * n, &rows);
|
||||
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
|
||||
const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows);
|
||||
const long long y_ld = y ? r3d_rows_pitch(y, n, &yrows) : n;
|
||||
if (gu_ld < 0 || q_ld < 0 || s_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
|
||||
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
|
||||
if (gu_ld != 2 * n) return R3D_NO(RAD_E_SHAPE);
|
||||
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
|
||||
if (s_ld != ngrp || srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE);
|
||||
if (y && (y_ld != n || yrows < rows || r3d_numel(y) < rows * n)) return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
return r3d_launch_status(r3d_gated_quant_fp8(
|
||||
r3d_addr(gu), r3d_addr(q), r3d_addr(sc), r3d_addr(y), (int)rows, (int)n, group, act,
|
||||
(long)(uintptr_t)stream));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ dequant */
|
||||
|
||||
enum { DQT_Q = 0, DQT_S, DQT_Y };
|
||||
|
||||
extern "C" int r3d_rad_dequant(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* q = r3d_opt(a, DQT_Q);
|
||||
const RadTensor* sc = r3d_opt(a, DQT_S);
|
||||
const RadTensor* y = r3d_opt(a, DQT_Y);
|
||||
if (!q || !sc || !y) return R3D_NO(RAD_E_INVAL);
|
||||
/* The codes' dtype IS the encoding, so it is read off the tensor: E4M3 and E5M2 are one byte
|
||||
* apiece and nothing in the bytes tells them apart. A plain u8 plane carries no encoding, so it
|
||||
* is not accepted under the E4M3 code. */
|
||||
if (q->dtype == RAD_U8) return R3D_NO(RAD_E_DTYPE);
|
||||
const int q_dt = r3d_dt_code(q->dtype);
|
||||
if (q_dt != R3D_DT_U8 && q_dt != R3D_DT_E5M2 && q_dt != R3D_DT_I8)
|
||||
return R3D_NO(RAD_E_DTYPE);
|
||||
R3D_NEED(dt_f32(sc));
|
||||
R3D_NEED(dt_bf16(y)); /* the launcher has no output dtype; see above */
|
||||
|
||||
const long long n = r3d_geti_or(a, "n", r3d_dim(y, (int)y->rank - 1));
|
||||
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* Rows come off `y`, as in ref_dequant: `y` is the plane the consumer reads. */
|
||||
long long rows = 0, qrows = 0, srows = 0;
|
||||
const long long y_ld = r3d_rows_pitch(y, n, &rows);
|
||||
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
|
||||
if (y_ld < 0 || q_ld < 0) return R3D_NO(RAD_E_STRIDE);
|
||||
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
|
||||
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* The scale stream's extent gives the group count and `group` each group's width, as libref
|
||||
* reads them; with no `group`, the stream is taken as one scale per group of ceil(n/ngrp). */
|
||||
const long long ngrp_param = r3d_numel(sc) / rows > 0 ? r3d_numel(sc) / rows : 1;
|
||||
long long group = r3d_geti_or(a, "group", 0);
|
||||
if (group <= 0) group = (n + ngrp_param - 1) / ngrp_param;
|
||||
if (group < 1 || group > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long ngrp = (n + group - 1) / group;
|
||||
const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows);
|
||||
if (s_ld < 0 || srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4) || !r3d_aligned(r3d_p(y), 8))
|
||||
return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
return r3d_launch_status(r3d_dequant(r3d_addr(q), r3d_addr(sc), r3d_addr(y), (int)rows, (int)n,
|
||||
(int)group, q_dt, (int)s_ld, (int)y_ld,
|
||||
(long)(uintptr_t)stream));
|
||||
}
|
||||
+1839
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,932 @@
|
||||
/* r3d_sample_pre_f32.hip -- the sampler's pre-filters: the five stages that edit the logits row
|
||||
* before the candidate set is built. `sample_logprobs`, `sample_penalties`, `sample_dry`,
|
||||
* `sample_ngram_ban` and `sample_mask`; the draw spine -- argmax, temp, top-k, the narrowings and
|
||||
* the pick -- is `r3d_sample_f32.hip`, and the only things shared are statics.
|
||||
*
|
||||
* The arithmetic is libref's, transcribed: the reference's sampler is the law, and
|
||||
* `abi/rad_sample.h` is the wire format for every scalar, one 96-byte row per sampled position. The order of the
|
||||
* arithmetic is transcription where the order can be seen, and there is a lot of it here: the
|
||||
* penalties law (sign-dependent repetition, the count times the frequency, presence once per
|
||||
* distinct token, all of it at the token's FIRST occurrence in the window), DRY's longest-suffix
|
||||
* repeat per continuation token with its repeated-multiplication penalty, the n-gram ban's
|
||||
* windowed prefix search and its whitelist exemption, and the mask's bit-per-token rule.
|
||||
*
|
||||
* ============================== what each stage reads, and why the shapes differ ==============
|
||||
*
|
||||
* The row is 130560 f32 at the band and there are 2048 of them: the logits plane is 1.02 GiB and
|
||||
* one pass over it is ~3.6 ms on this card (RX 7600, 16 CUs). That number sorts the five into two
|
||||
* shapes, and the shape is decided by how many of the row's columns the stage touches -- which is
|
||||
* what the reference touches, not what it could:
|
||||
*
|
||||
* HISTORY STAGES -- penalties, dry, ngram_ban. A row's window is 64 tokens, so a row has at most
|
||||
* 64 columns to touch. libref touches exactly those, and so does this file: one block a row of 64
|
||||
* threads, each position a thread, the window read straight from L2 (4096 integer reads a row,
|
||||
* which is why the quadratic scans are free and why there is no LDS copy of the history). These
|
||||
* kernels move kilobytes a row. Micro-optimising the scans would be optimising the part that is
|
||||
* not the cost.
|
||||
*
|
||||
* ROW STAGES -- mask, logprobs. A mask writes every disallowed column of the row and logprobs
|
||||
* summarises every column of it, so these read and write the plane and are the bandwidth rows of
|
||||
* the unit: 256 threads a row, a thread a run of columns, so each lane's traffic is one
|
||||
* contiguous segment.
|
||||
*
|
||||
* `sample_logprobs` is where the pass count is the whole argument. libref reads the row three
|
||||
* times -- a max, then a sum of `exp(v - max)`, then a third scan to insert every element into a
|
||||
* k-list -- so at the band it reads 3.06 GiB where one pass reads 1.02. One pass cannot know the
|
||||
* row's max before it has seen the row, so each lane keeps a running max and a running DOUBLE sum
|
||||
* of `exp(v - its own max)`, rescaling its sum when its max rises (one double multiply per rise,
|
||||
* a handful per lane), and the butterfly merges pairs of (max, sum) by
|
||||
*
|
||||
* m = max(a, b); sum = a.sum * exp(a.mx - m) + b.sum * exp(b.mx - m)
|
||||
*
|
||||
* which is the reference's sum shifted by a constant per lane. Each term is the reference's term
|
||||
* to a fraction of an f64 ulp, the merged sum lands on the reference's to ~1e-15 relative, and the
|
||||
* stored value is f32 -- 6e-8 is the granularity of what the plane holds, so the rescaling is
|
||||
* below the store's own rounding. The lane shuffles carry the max (32-bit) and the k-list (one
|
||||
* 8-byte pattern an entry at a time); the sum is merged in LDS, by wave and then across waves, and
|
||||
* the reason is in sample_logprobs_kernel's comment: a double can cross lanes soundly only by
|
||||
* moving bits, never by value. `r3d_lanes_check` at the end of the file is the control that keeps
|
||||
* that true, and `r3d_selftest.cpp` runs it. The `exp`
|
||||
* is `exp(double)`, the reference's own width: libref's sum adds double exps and the row is the
|
||||
* logit distribution, so this is the file's one fp64-heavy kernel and it is the slow path by law,
|
||||
* not by oversight -- consumer RDNA3 is 1:64 on doubles. At the band (M=2048,
|
||||
* n_vocab=130560, k=21) the plane's one read is 3.6 ms at 266 GiB/s, a read that also sums
|
||||
* `exp(double)` is 30.4 ms, this kernel is 38.9 ms, and libref's three reads of that plane are
|
||||
* 2.988 GiB against this kernel's 0.996.
|
||||
*
|
||||
* The k-list is per lane too, k deep, kept in the reference's order -- descending by value, ties
|
||||
* to the LOWER column, which is `topk_next`'s total order and the narrowing stages' -- and merged
|
||||
* pairwise in the same butterfly, so the block's list is the reference's list. `k` at the band is
|
||||
* 21; the pool is 64 deep, and a request above that is refused rather than silently truncated.
|
||||
*
|
||||
* ============================== agreement, and where this file declines ==============================
|
||||
*
|
||||
* Maxima are strict `>` with the max as the first argument, which is `std::max`'s law and is how a
|
||||
* NaN is kept out of the row's max: a NaN never compares greater, so it is never adopted, at the
|
||||
* first element or anywhere later. A NaN in the sum propagates, because the reference's
|
||||
* `exp(NaN - mx)` is NaN and it is added.
|
||||
*
|
||||
* A row whose parameters turn the stage off is left bit for bit as it was -- the flag test is the
|
||||
* reference's, and for penalties the identity test (rep 1, freq 0, pres 0) is too.
|
||||
*
|
||||
* Declines, all of them RAD_E_UNSUPPORTED from the shim and none of them reachable from a row that
|
||||
* carries the constraints its rows do: a history plane wider than 2^31/8 columns is not a plane;
|
||||
* `k` above 64 for logprobs (the pool's depth, and far above any k the engine requests); and for
|
||||
* ngram_ban a `whitelist` plane, which the kernel implements -- the whitelist is exempted before
|
||||
* the -inf writes, as the reference removes it from the banned set -- so the only decline is the
|
||||
* `ngram` plane's dtype and the mask and whitelist's, which must be 32-bit words.
|
||||
*/
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_args.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_launch.h"
|
||||
|
||||
#include <rad_sample.h>
|
||||
|
||||
#include <cfloat>
|
||||
|
||||
/* ================================================================== shared helpers (statics)
|
||||
*
|
||||
* The headers are frozen, so a unit that needs a helper carries its own copy and keeps it static: a
|
||||
* non-static one collides at link with the same helper in another unit and takes the library down.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kThreads = 256; /* 8 waves: the row stages */
|
||||
constexpr uint32_t kPre = 64; /* 2 waves: the history stages, a position a thread */
|
||||
constexpr uint32_t kWave = 32;
|
||||
constexpr uint32_t kWaves = kThreads / kWave;
|
||||
constexpr int kKMax = 64; /* the k-list pool's depth, per lane */
|
||||
|
||||
/* The row's summary accumulates `exp` in DOUBLE, because that is where the reference's sum lives.
|
||||
* The width is a switch, because the width is the cost: at the band the double exp is 30 ms of the
|
||||
* kernel's 38 ms against a 3.7 ms plane read, and an f32 exp widened to double --
|
||||
* `expf`, terms accurate to an f32 ulp, summed in double -- lands the row's sum on the reference's
|
||||
* to ~1e-10 relative against a stored f32 granularity of 6e-8. Define R3D_LP_EXP_F32 to build the
|
||||
* fast exp; the default is the reference's arithmetic. */
|
||||
#ifdef R3D_LP_EXP_F32
|
||||
__device__ __forceinline__ double dexp(double x) { return (double)expf((float)x); }
|
||||
#else
|
||||
__device__ __forceinline__ double dexp(double x) { return exp(x); }
|
||||
#endif
|
||||
|
||||
/* A whole-register load of an index plane: the history, the n-gram pair, the bitmask words. */
|
||||
__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) {
|
||||
return (int32_t)ldg_u32((const uint32_t*)p);
|
||||
}
|
||||
__device__ __forceinline__ uint32_t ldg_u8(const uint8_t* p) { return *(const uint8_t*)p; }
|
||||
|
||||
/* Lane partners of the accumulator's pieces. */
|
||||
template <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. */
|
||||
|
||||
/* The law, verbatim. The window both history stages read, clamped to the row's own row
|
||||
* of the plane; `last_n` 0 disables the stage, a negative keeps the whole span, a positive keeps
|
||||
* its TAIL. The window law IS the history law: the window, and the rule that a token is penalised
|
||||
* at its first occurrence in it. */
|
||||
__device__ __forceinline__ bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax,
|
||||
int64_t* ho_out, int64_t* hl_out) {
|
||||
if (last_n == 0) return false;
|
||||
int64_t hl = sp.hist_len;
|
||||
int64_t ho = sp.hist_off < 0 ? 0 : sp.hist_off;
|
||||
if (ho > hmax) ho = hmax;
|
||||
if (hl > hmax - ho) hl = hmax - ho;
|
||||
if (last_n > 0 && hl > last_n) {
|
||||
ho += hl - last_n;
|
||||
hl = last_n;
|
||||
}
|
||||
*ho_out = ho;
|
||||
*hl_out = hl;
|
||||
return hl > 0;
|
||||
}
|
||||
|
||||
/* The law, verbatim, including the stop short of overflow: repeated multiplication, so
|
||||
* every implementation lands on the same float. */
|
||||
__device__ __forceinline__ float dry_penalty(float multiplier, float base, int64_t e) {
|
||||
float pen = multiplier;
|
||||
if (base == 1.0f) return pen;
|
||||
const float lim = FLT_MAX / base;
|
||||
for (int64_t i = 0; i < e; ++i) {
|
||||
if (pen > lim) break;
|
||||
pen *= base;
|
||||
}
|
||||
return pen;
|
||||
}
|
||||
|
||||
/* The k-list's order: descending by value, ties to the lower column. `above(x, y)` is "x comes
|
||||
* first", the reference's comparator and `topk_next`'s chain. */
|
||||
struct Cand { float v; int32_t i; };
|
||||
__device__ __forceinline__ bool above(Cand x, Cand y) {
|
||||
return x.v > y.v || (x.v == y.v && x.i < y.i);
|
||||
}
|
||||
|
||||
/* ================================================================== sample_logprobs
|
||||
*
|
||||
* The law. The row's summary: its max, the sum of exp(v - max) in double, and the k
|
||||
* largest as (id, logit) pairs descending, ids as floats with `vocab_off` added, an unfilled slot
|
||||
* id -1 and logit -infinity. Rows without RAD_SP_LOGPROBS are not written at all.
|
||||
*
|
||||
* One pass over the row, per the file's header: the max, the sum and the k-list are three
|
||||
* independent accumulations of the same read, and the sum is rescaled into the row's final max at
|
||||
* the merge, which is a per-lane shift of the reference's terms.
|
||||
*/
|
||||
struct Acc {
|
||||
float mx;
|
||||
double sum;
|
||||
Cand c[kKMax];
|
||||
int n;
|
||||
};
|
||||
|
||||
/* A lane's running state over its own elements. A new maximum rescales the sum it has so far; the
|
||||
* reference never rescales (it knows the max up front) and the rescale is the price of the read. */
|
||||
__device__ __forceinline__ void acc_push(Acc& a, int k, uint32_t col, float v) {
|
||||
if (v > a.mx) {
|
||||
if (a.mx != -INFINITY) a.sum *= dexp((double)a.mx - (double)v);
|
||||
a.mx = v;
|
||||
}
|
||||
a.sum += dexp((double)v - (double)a.mx);
|
||||
/* The reference's insertion: an element that is not above the k-th is dropped, and the insert
|
||||
* point is the first slot the element beats (with a NaN, no slot, so the tail: insert, then the
|
||||
* pop leaves the list exactly as it was). */
|
||||
if (a.n == k && !above(Cand{ v, (int32_t)col }, a.c[a.n - 1])) return;
|
||||
int pos = 0;
|
||||
while (pos < a.n && !above(Cand{ v, (int32_t)col }, a.c[pos])) ++pos;
|
||||
if (pos >= k) return;
|
||||
for (int j = (a.n < k ? a.n : k - 1); j > pos; --j) a.c[j] = a.c[j - 1];
|
||||
a.c[pos] = Cand{ v, (int32_t)col };
|
||||
if (a.n < k) ++a.n;
|
||||
}
|
||||
|
||||
/* The butterfly's merge of two lanes' states: the max is strict, the sum is the two shifted sums,
|
||||
* and the lists merge on the same order. Ties in the merge (two equal values at equal columns
|
||||
* cannot happen -- the column is the lane's -- and a NaN is not above anything, so a NaN list
|
||||
* entry stays in the lane that read it). */
|
||||
__device__ __forceinline__ Acc acc_merge(const Acc& a, const Acc& b, int k) {
|
||||
Acc r;
|
||||
r.mx = a.mx > b.mx ? a.mx : b.mx;
|
||||
r.sum = (a.mx == -INFINITY ? 0.0 : a.sum * dexp((double)a.mx - (double)r.mx)) +
|
||||
(b.mx == -INFINITY ? 0.0 : b.sum * dexp((double)b.mx - (double)r.mx));
|
||||
int i = 0, j = 0;
|
||||
r.n = 0;
|
||||
while (r.n < k && (i < a.n || j < b.n)) {
|
||||
const bool take_b = (i >= a.n) || (j < b.n && above(b.c[j], a.c[i]));
|
||||
r.c[r.n++] = take_b ? b.c[j++] : a.c[i++];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
template <int THR>
|
||||
__global__ __launch_bounds__(THR) void sample_logprobs_kernel(
|
||||
const float* __restrict__ lg, const RadSampleParams* __restrict__ pr,
|
||||
float* __restrict__ st, uint32_t n, uint32_t k, uint32_t lg_ld, uint32_t st_ld,
|
||||
int32_t voff) {
|
||||
const uint32_t row = blockIdx.x;
|
||||
if (!(pr[row].flags & RAD_SP_LOGPROBS)) return;
|
||||
|
||||
Acc a;
|
||||
a.mx = -INFINITY;
|
||||
a.sum = 0.0;
|
||||
a.n = 0;
|
||||
const float* __restrict__ lr = lg + (size_t)row * lg_ld;
|
||||
for (uint32_t c = threadIdx.x; c < n; c += THR) acc_push(a, (int)k, c, ldg_f32(lr + c));
|
||||
|
||||
/* The k-list and the max meet their partners in the wave's 32-bit lane shuffles, five rounds.
|
||||
*
|
||||
* The participation mask of a 64-bit shuffle on this ROCm is an `unsigned long long`, and on
|
||||
* wave32 it is `0xFFFFFFFFull`: `~0ull` names lanes 32..63, which a wave of 32 does not have.
|
||||
* `r3d_lanes_check` at the end of this file is the control that proves the lane helpers, and
|
||||
* `r3d_selftest.cpp` runs it and checks every lane of every wave.
|
||||
*
|
||||
* The SUM does not go through a lane shuffle: it meets its partners in LDS, the machinery
|
||||
* `block_sum` already trusts. A double can cross lanes soundly -- lanes_check_kernel below is
|
||||
* exact in all 256 lanes of all 8 waves for three forms of it -- but only by moving the value's
|
||||
* *bits*, never by value: a cast to an integer type converts by value, so
|
||||
*
|
||||
* d += (double)r3d_xor_lane_u64<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. */
|
||||
#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. */ \
|
||||
const unsigned long long packed = \
|
||||
(unsigned long long)__float_as_uint(a.c[j].v) | \
|
||||
((unsigned long long)(uint32_t)a.c[j].i << 32); \
|
||||
const unsigned long long got = __shfl_xor_sync(0xFFFFFFFFull, packed, M); \
|
||||
b.c[j] = Cand{ __uint_as_float((uint32_t)got), (int32_t)(uint32_t)(got >> 32) }; \
|
||||
} \
|
||||
b.sum = 0.0; \
|
||||
const float mx = a.mx > b.mx ? a.mx : b.mx; /* no lane's max is a NaN: a NaN is never \
|
||||
adopted by the strict test above */ \
|
||||
a = acc_merge(a, b, (int)k); \
|
||||
a.mx = mx; \
|
||||
}
|
||||
R3D_ACC_XOR(16)
|
||||
R3D_ACC_XOR(8)
|
||||
R3D_ACC_XOR(4)
|
||||
R3D_ACC_XOR(2)
|
||||
R3D_ACC_XOR(1)
|
||||
#undef R3D_ACC_XOR
|
||||
|
||||
/* The wave's sum, in LDS: the wave's max first, then every lane's sum shifted into it, in lane
|
||||
* order. An empty lane (a row narrower than the block) has max -infinity and sum 0 and
|
||||
* contributes nothing, which is the reference's own arithmetic on an empty span. */
|
||||
__shared__ float s_mx[kThreads];
|
||||
__shared__ double s_sum[kThreads];
|
||||
__shared__ float w_mx[kWaves];
|
||||
__shared__ double w_sum[kWaves];
|
||||
__shared__ int w_n[kWaves];
|
||||
__shared__ Cand w_c[kWaves][kKMax];
|
||||
s_mx[threadIdx.x] = a.mx;
|
||||
s_sum[threadIdx.x] = a.sum;
|
||||
__syncthreads();
|
||||
|
||||
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
|
||||
if (lane == 0) {
|
||||
const uint32_t b = wave * kWave;
|
||||
float m = s_mx[b];
|
||||
for (uint32_t l = 1; l < kWave; ++l)
|
||||
if (s_mx[b + l] > m) m = s_mx[b + l];
|
||||
double s = 0.0;
|
||||
for (uint32_t l = 0; l < kWave; ++l)
|
||||
s += s_mx[b + l] == -INFINITY ? 0.0
|
||||
: s_sum[b + l] * dexp((double)s_mx[b + l] - (double)m);
|
||||
w_mx[wave] = m;
|
||||
w_sum[wave] = s;
|
||||
w_n[wave] = a.n;
|
||||
for (int j = 0; j < k; ++j) w_c[wave][j] = a.c[j];
|
||||
}
|
||||
__syncthreads();
|
||||
if (threadIdx.x != 0) return;
|
||||
/* The eight wave partials, in wave order: the row's max, the row's sum, the row's k-list. */
|
||||
float m = w_mx[0];
|
||||
double s = w_sum[0];
|
||||
int n_list = w_n[0];
|
||||
Cand list[kKMax];
|
||||
for (int j = 0; j < k; ++j) list[j] = w_c[0][j];
|
||||
for (uint32_t w = 1; w < kWaves; ++w) {
|
||||
const float mm = w_mx[w] > m ? w_mx[w] : m;
|
||||
s = (m == -INFINITY ? 0.0 : s * dexp((double)m - (double)mm)) +
|
||||
(w_mx[w] == -INFINITY ? 0.0 : w_sum[w] * dexp((double)w_mx[w] - (double)mm));
|
||||
m = mm;
|
||||
Acc x, y;
|
||||
x.mx = m; x.sum = 0.0; x.n = n_list;
|
||||
for (int j = 0; j < k; ++j) x.c[j] = list[j];
|
||||
y.mx = w_mx[w]; y.sum = 0.0; y.n = w_n[w];
|
||||
for (int j = 0; j < k; ++j) y.c[j] = w_c[w][j];
|
||||
const Acc t = acc_merge(x, y, (int)k);
|
||||
n_list = t.n;
|
||||
for (int j = 0; j < k; ++j) list[j] = t.c[j];
|
||||
}
|
||||
|
||||
float* __restrict__ sr = st + (size_t)row * st_ld;
|
||||
sr[0] = m;
|
||||
sr[1] = (float)s;
|
||||
for (uint32_t j = 0; j < k; ++j) {
|
||||
const bool have_j = j < (uint32_t)n_list;
|
||||
sr[2 + 2 * j] = have_j ? (float)(list[j].i + voff) : -1.0f;
|
||||
sr[3 + 2 * j] = have_j ? list[j].v : -INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== sample_penalties
|
||||
*
|
||||
* The law. llama.cpp's ordering, at the token's first occurrence in the window:
|
||||
*
|
||||
* repetition logit = logit > 0 ? logit / rep : logit * rep
|
||||
* frequency logit -= count * freq
|
||||
* presence logit -= pres
|
||||
*
|
||||
* The repetition penalty is sign-dependent because dividing a negative logit would raise it. The
|
||||
* count carries the multiplicity, which is why the update runs once per distinct token, and the
|
||||
* scan for it is the reference's own: walk the window from the front, stop at an earlier
|
||||
* occurrence, count the ones from here on.
|
||||
*
|
||||
* Columns are global ids less `vocab_off`, so a token on another rank's shard is skipped here and
|
||||
* penalised there. Each distinct token is one column and one thread, so the writes cannot race.
|
||||
*/
|
||||
__global__ __launch_bounds__(kPre) void sample_penalties_kernel(
|
||||
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist,
|
||||
uint32_t n, uint32_t lg_ld, uint32_t hmax, int32_t voff) {
|
||||
const uint32_t row = blockIdx.x;
|
||||
const RadSampleParams& sp = pr[row];
|
||||
if (!(sp.flags & RAD_SP_PENALTY)) return;
|
||||
const float rep = sp.rep_penalty, freq = sp.freq_penalty, pres = sp.pres_penalty;
|
||||
if (rep == 1.0f && freq == 0.0f && pres == 0.0f) return;
|
||||
|
||||
int64_t ho = 0, hl = 0;
|
||||
if (!hist_window(sp, sp.penalty_last_n, (int64_t)hmax, &ho, &hl)) return;
|
||||
|
||||
const int32_t* __restrict__ hr = hist + (size_t)row * hmax + ho;
|
||||
float* __restrict__ lr = lg + (size_t)row * lg_ld;
|
||||
for (uint32_t i = threadIdx.x; i < (uint32_t)hl; i += kPre) {
|
||||
const int32_t tok = ldg_i32(hr + i);
|
||||
const int64_t col = (int64_t)tok - voff;
|
||||
if (tok < 0 || col < 0 || col >= n) continue;
|
||||
bool first = true;
|
||||
int64_t count = 0;
|
||||
for (int64_t j = 0; j < hl; ++j) {
|
||||
if (ldg_i32(hr + j) != tok) continue;
|
||||
if (j < (int64_t)i) { first = false; break; }
|
||||
++count;
|
||||
}
|
||||
if (!first) continue;
|
||||
float v = lr[col];
|
||||
v = v > 0.0f ? v / rep : v * rep;
|
||||
v -= (float)count * freq;
|
||||
v -= pres;
|
||||
lr[col] = v;
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== sample_dry
|
||||
*
|
||||
* The law, DRY's rule (llama.cpp's llama_sampler_dry_apply): for every earlier position
|
||||
* j, n_j is how long a suffix of the window also ends at j, capped at the breaker limit; the token
|
||||
* at j+1 would extend that repeat and is penalised by multiplier * base^(n - allowed), once, by the
|
||||
* LONGEST repeat it follows. A token that is itself a whole-sequence breaker is never penalised,
|
||||
* and only lengths at or above `allowed` count.
|
||||
*
|
||||
* A thread a position, the window read from L2. The map the reference keeps is here a maximum over
|
||||
* the threads that share a token, applied by the thread holding the token's first occurrence, so
|
||||
* one column is written once.
|
||||
*/
|
||||
__global__ __launch_bounds__(kPre) void sample_dry_kernel(
|
||||
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist,
|
||||
const uint8_t* __restrict__ brk, uint32_t n, uint32_t lg_ld, uint32_t hmax, int32_t voff) {
|
||||
const uint32_t row = blockIdx.x;
|
||||
const RadSampleParams& sp = pr[row];
|
||||
if (!(sp.flags & RAD_SP_DRY) || !(sp.dry_multiplier > 0.0f)) return;
|
||||
const int64_t allowed = sp.dry_allowed_length > 0 ? sp.dry_allowed_length : 2;
|
||||
|
||||
int64_t ho = 0, hl = 0;
|
||||
if (!hist_window(sp, sp.dry_penalty_last_n, (int64_t)hmax, &ho, &hl)) return;
|
||||
if (hl <= allowed) return;
|
||||
const int64_t cap = sp.dry_rep_limit > 0 && sp.dry_rep_limit < hl ? sp.dry_rep_limit : hl;
|
||||
if (cap < allowed) return;
|
||||
|
||||
const int32_t* __restrict__ hr = hist + (size_t)row * hmax + ho;
|
||||
const uint8_t* __restrict__ br = brk ? brk + (size_t)row * hmax + ho : nullptr;
|
||||
float* __restrict__ lr = lg + (size_t)row * lg_ld;
|
||||
const auto tok_at = [&](int64_t i) { return ldg_i32(hr + i); };
|
||||
const auto exempt = [&](int64_t i) { return br && ldg_u8(br + i) != 0u; };
|
||||
const float base = sp.dry_base > 0.0f ? sp.dry_base : 1.75f;
|
||||
|
||||
for (uint32_t j = threadIdx.x; j + 1u < (uint32_t)hl; j += kPre) {
|
||||
const int64_t lim = ((int64_t)j + 1 < cap) ? (int64_t)j + 1 : cap;
|
||||
int64_t m = 0;
|
||||
while (m < lim && tok_at(j - m) == tok_at(hl - 1 - m)) ++m;
|
||||
if (m < allowed || exempt((int64_t)j + 1)) continue;
|
||||
const int32_t tok = tok_at((int64_t)j + 1);
|
||||
const int64_t col = (int64_t)tok - voff;
|
||||
if (tok < 0 || col < 0 || col >= n) continue;
|
||||
/* The longest repeat any position attributes to this token, and the first thread that
|
||||
* carries it pays for it. Equal tokens at equal lengths: the lowest j, so one writer. */
|
||||
int64_t longest = m;
|
||||
bool first = true;
|
||||
for (int64_t q = 0; q + 1 < hl; ++q) {
|
||||
if (tok_at(q + 1) != tok) continue;
|
||||
const int64_t limq = (q + 1 < cap) ? q + 1 : cap;
|
||||
int64_t mq = 0;
|
||||
while (mq < limq && tok_at(q - mq) == tok_at(hl - 1 - mq)) ++mq;
|
||||
if (mq < allowed || exempt(q + 1)) continue;
|
||||
if (mq > longest) longest = mq;
|
||||
if (q < (int64_t)j) { first = false; break; }
|
||||
}
|
||||
if (!first) continue;
|
||||
const float v = lr[col];
|
||||
lr[col] = v - dry_penalty(sp.dry_multiplier, base, longest - allowed);
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== sample_ngram_ban
|
||||
*
|
||||
* The law, the windowed no-repeat-ngram ban. With the row's window s[0, hl):
|
||||
*
|
||||
* search_start = max(0, hl - w); search_end = hl - n + 1; prefix = s[hl - n + 1, hl)
|
||||
* for idx in [search_start, search_end): s[idx, idx + n - 1) == prefix => ban s[idx + n - 1]
|
||||
*
|
||||
* The window is on the START index, so the n-gram that straddles the window's edge is searched. A
|
||||
* banned token's logit becomes -infinity, and the whitelist is removed from the banned set before
|
||||
* any -inf is written, so a whitelisted column is never touched. n == 1 bans every token in the
|
||||
* window, the prefix being empty. A row whose n is 0 is left bit for bit as it was.
|
||||
*
|
||||
* A thread a search index. Several indices can ban the same token; the write is the same -infinity
|
||||
* from every one of them, so the race writes one value.
|
||||
*/
|
||||
__global__ __launch_bounds__(kPre) void sample_ngram_ban_kernel(
|
||||
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist,
|
||||
const int32_t* __restrict__ ngram, const int32_t* __restrict__ wl, uint32_t n, uint32_t lg_ld,
|
||||
uint32_t hmax, uint32_t words, int32_t voff) {
|
||||
const uint32_t row = blockIdx.x;
|
||||
const RadSampleParams& sp = pr[row];
|
||||
const int32_t* __restrict__ nr = ngram + (size_t)row * 2;
|
||||
const int64_t nn = ldg_i32(nr);
|
||||
const int64_t win_req = ldg_i32(nr + 1);
|
||||
if (nn <= 0) return;
|
||||
|
||||
int64_t ho = 0, hl = 0;
|
||||
if (!hist_window(sp, -1, (int64_t)hmax, &ho, &hl)) return; /* the whole staged span */
|
||||
if (hl < nn) return;
|
||||
const int64_t win = (win_req > 0 && win_req < hl) ? win_req : hl;
|
||||
const int64_t search_start = hl - win;
|
||||
const int64_t search_end = hl - nn + 1;
|
||||
if (search_end <= search_start) return;
|
||||
|
||||
const int32_t* __restrict__ hr = hist + (size_t)row * hmax + ho;
|
||||
const int32_t* __restrict__ wr = wl ? wl + (size_t)row * words : nullptr;
|
||||
float* __restrict__ lr = lg + (size_t)row * lg_ld;
|
||||
const auto tok_at = [&](int64_t i) { return ldg_i32(hr + i); };
|
||||
const auto exempt = [&](int64_t col) {
|
||||
if (!wr) return false;
|
||||
const uint32_t word = (uint32_t)ldg_i32(wr + col / 32);
|
||||
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
|
||||
};
|
||||
const int64_t plen = nn - 1, p0 = hl - plen;
|
||||
|
||||
for (uint32_t idx = search_start + threadIdx.x; idx < (uint32_t)search_end; idx += kPre) {
|
||||
bool match = true;
|
||||
for (int64_t j = 0; j < plen; ++j) {
|
||||
if (tok_at((int64_t)idx + j) != tok_at(p0 + j)) { match = false; break; }
|
||||
}
|
||||
if (!match) continue;
|
||||
const int32_t tok = tok_at((int64_t)idx + plen);
|
||||
const int64_t col = (int64_t)tok - voff;
|
||||
if (tok < 0 || col < 0 || col >= n) continue;
|
||||
if (exempt(col)) continue;
|
||||
lr[col] = -INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== sample_mask
|
||||
*
|
||||
* The law. A set bit means allowed; an unset column's logit becomes -infinity. This is
|
||||
* the dense row stage: a row of 130560 columns and a bitmask of 4080 words, so a thread takes a
|
||||
* word and the 32 columns under it, which is one contiguous 128-byte segment a lane. A word that
|
||||
* is all ones is skipped whole, and a word that is all zeros is a run of eight 16-byte stores;
|
||||
* either way the row is written in the order the plane is laid out.
|
||||
*
|
||||
* `mask_row` is the row's own row of the bitmask plane, and the reference skips a row index
|
||||
* outside the plane, -1 included (the shape hook caps `idx_max` at M so a fixture draws a real
|
||||
* row); the shim bounds the plane to at least M rows, which is the same test at the geometry the
|
||||
* op's descriptor describes.
|
||||
*/
|
||||
__global__ __launch_bounds__(kThreads) void sample_mask_kernel(
|
||||
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ bm,
|
||||
uint32_t n, uint32_t lg_ld, uint32_t words, uint32_t mask_rows) {
|
||||
const uint32_t row = blockIdx.x;
|
||||
const RadSampleParams& sp = pr[row];
|
||||
if (!(sp.flags & RAD_SP_MASK)) return;
|
||||
const int64_t mrow = sp.mask_row;
|
||||
if (mrow < 0 || (uint64_t)mrow >= mask_rows) return;
|
||||
|
||||
const int32_t* __restrict__ br = bm + (size_t)mrow * words;
|
||||
float* __restrict__ lr = lg + (size_t)row * lg_ld;
|
||||
for (uint32_t w = threadIdx.x; w < words; w += kThreads) {
|
||||
const uint32_t bits = (uint32_t)ldg_i32(br + w);
|
||||
if (bits == 0xffffffffu) continue; /* nothing banned in these 32 */
|
||||
const uint32_t c0 = 32u * w;
|
||||
const uint32_t cnt = n - c0 < 32u ? n - c0 : 32u; /* the row's last word is partial */
|
||||
if (bits == 0u) {
|
||||
for (uint32_t c = 0; c < cnt; ++c) lr[c0 + c] = -INFINITY;
|
||||
continue;
|
||||
}
|
||||
for (uint32_t c = 0; c < cnt; ++c)
|
||||
if (((bits >> c) & 1u) == 0u) lr[c0 + c] = -INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ shim helpers */
|
||||
|
||||
static inline int sp_is_word(const RadTensor* t) {
|
||||
return t && (t->dtype == RAD_U32 || t->dtype == RAD_I32 || t->dtype == RAD_F32);
|
||||
}
|
||||
|
||||
/* The params plane: [M, 24] words. The dtype test is not decoration -- a 16-bit view of the plane
|
||||
* passes a byte-count check and then misreads every row, sampling with the top half of one row's
|
||||
* temp and the bottom of the next. */
|
||||
static inline int params_ok(const RadTensor* t, long long M) {
|
||||
if (!t || !t->data) return RAD_E_INVAL;
|
||||
if (!sp_is_word(t)) return RAD_E_DTYPE;
|
||||
if (r3d_numel(t) * 4 < M * (long long)sizeof(RadSampleParams)) return RAD_E_SHAPE;
|
||||
if (!r3d_contig(t)) return RAD_E_STRIDE;
|
||||
if (!r3d_aligned(r3d_p(t), 8)) return RAD_E_ALIGN; /* seed and pos are 8-byte fields */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static inline int logits_ok(const RadTensor* t) {
|
||||
if (!t || !t->data) return RAD_E_INVAL;
|
||||
if (!r3d_is_f32(t)) return RAD_E_DTYPE;
|
||||
if (!r3d_aligned(r3d_p(t), 4)) return RAD_E_ALIGN;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The history plane: i32 [M, max_hist], contiguous, its width the reference's `hmax`. */
|
||||
static inline int hist_ok(const RadTensor* t, long long M, long long* hmax) {
|
||||
if (!t || !t->data) return RAD_E_INVAL;
|
||||
if (!r3d_is_i32(t)) return RAD_E_DTYPE;
|
||||
if (!r3d_contig(t)) return RAD_E_STRIDE;
|
||||
if (!r3d_aligned(r3d_p(t), 4)) return RAD_E_ALIGN;
|
||||
const long long w = r3d_numel(t) / M;
|
||||
if (w <= 0 || w > 0x7fffffffLL) return RAD_E_SHAPE;
|
||||
*hmax = w;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static inline int r3d_launch_status(int rc) {
|
||||
if (rc == 0) return RAD_OK;
|
||||
switch (rc) {
|
||||
case -1: return RAD_E_INVAL;
|
||||
case -2: return RAD_E_SHAPE;
|
||||
case -3: return RAD_E_STRIDE;
|
||||
default: return RAD_E_DEVICE;
|
||||
}
|
||||
}
|
||||
|
||||
/* The logits row count, from the plane and never from the band's M. */
|
||||
static inline int logits_rows(const RadArgs* a, const RadTensor* lg, long long* n_vocab,
|
||||
long long* rows, long long* lg_ld) {
|
||||
/* The reference reads the width off the band, falling back to the plane's last dimension, and
|
||||
* a rank-1 plane has no last dimension to read: the width is absent, which is E_SHAPE. */
|
||||
*n_vocab = r3d_geti_or(a, "n_vocab",
|
||||
lg->rank >= 2 ? r3d_dim(lg, (int)lg->rank - 1) : 0);
|
||||
if (*n_vocab <= 0 || *n_vocab > 0x7fffffffLL) return RAD_E_SHAPE;
|
||||
*lg_ld = r3d_rows_pitch(lg, *n_vocab, rows);
|
||||
if (*lg_ld < 0) return RAD_E_STRIDE;
|
||||
if (*rows <= 0 || *rows > 0x7fffffffLL) return RAD_E_SHAPE;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
#define R3D_NEED(x) \
|
||||
do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
|
||||
|
||||
/* ================================================================== launchers
|
||||
*
|
||||
* lg [M][n_vocab] f32, INOUT for the four editing stages, read-only for logprobs
|
||||
* params [M] 24 words a row, the per-row scalars
|
||||
* hist [M][max_hist] i32, global token ids, `hist_off`/`hist_len` windowing it
|
||||
* stats [M][2 + 2k] f32
|
||||
* bitmask [rows][(n_vocab+31)/32] i32, a set bit meaning allowed
|
||||
*
|
||||
* 0, -1 null, -2 bad extent, -3 pitch, -4 the HIP launch failed. No allocation, no synchronisation.
|
||||
*/
|
||||
|
||||
extern "C" int r3d_sample_logprobs(long lg, long params, long stats, int M, int n_vocab, int k,
|
||||
long long lg_ld, long long stats_ld, int vocab_off,
|
||||
long stream) {
|
||||
if (!lg || !params || !stats) return -1;
|
||||
if (M <= 0 || n_vocab <= 0 || k <= 0) return -2;
|
||||
if (k > kKMax) return -2;
|
||||
if (!lg_ld) lg_ld = n_vocab;
|
||||
if (!stats_ld) stats_ld = 2 + 2 * (long long)k;
|
||||
if (lg_ld < n_vocab || stats_ld < 2 + 2 * (long long)k) return -3;
|
||||
R3D_KLAUNCH(R3D_KNAME(sample_logprobs_kernel<kThreads>), dim3((uint32_t)M), dim3(kThreads),
|
||||
(hipStream_t)(uintptr_t)stream, (const float*)(uintptr_t)lg,
|
||||
(const RadSampleParams*)(uintptr_t)params, (float*)(uintptr_t)stats,
|
||||
(uint32_t)n_vocab, (uint32_t)k, (uint32_t)lg_ld, (uint32_t)stats_ld,
|
||||
(int32_t)vocab_off);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r3d_sample_penalties(long lg, long params, long hist, int M, int n_vocab,
|
||||
long long lg_ld, long long hist_ld, int vocab_off,
|
||||
long stream) {
|
||||
if (!lg || !params || !hist) return -1;
|
||||
if (M <= 0 || n_vocab <= 0) return -2;
|
||||
if (!lg_ld) lg_ld = n_vocab;
|
||||
if (!hist_ld) return -2; /* the window is clamped to the plane's width */
|
||||
if (lg_ld < n_vocab || hist_ld <= 0) return -3;
|
||||
R3D_KLAUNCH(R3D_KNAME(sample_penalties_kernel), dim3((uint32_t)M), dim3(kPre),
|
||||
(hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg,
|
||||
(const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)hist,
|
||||
(uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hist_ld, (int32_t)vocab_off);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r3d_sample_dry(long lg, long params, long hist, long breakers, int M, int n_vocab,
|
||||
long long lg_ld, long long hist_ld, int vocab_off, long stream) {
|
||||
if (!lg || !params || !hist) return -1;
|
||||
if (M <= 0 || n_vocab <= 0) return -2;
|
||||
if (!lg_ld) lg_ld = n_vocab;
|
||||
if (!hist_ld) return -2;
|
||||
if (lg_ld < n_vocab || hist_ld <= 0) return -3;
|
||||
R3D_KLAUNCH(R3D_KNAME(sample_dry_kernel), dim3((uint32_t)M), dim3(kPre),
|
||||
(hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg,
|
||||
(const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)hist,
|
||||
(const uint8_t*)(uintptr_t)breakers, (uint32_t)n_vocab, (uint32_t)lg_ld,
|
||||
(uint32_t)hist_ld, (int32_t)vocab_off);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r3d_sample_ngram_ban(long lg, long params, long hist, long ngram, long whitelist,
|
||||
int M, int n_vocab, long long lg_ld, long long hist_ld,
|
||||
int vocab_off, long stream) {
|
||||
if (!lg || !params || !hist || !ngram) return -1;
|
||||
if (M <= 0 || n_vocab <= 0) return -2;
|
||||
if (!lg_ld) lg_ld = n_vocab;
|
||||
if (!hist_ld) return -2;
|
||||
if (lg_ld < n_vocab || hist_ld <= 0) return -3;
|
||||
const uint32_t words = (uint32_t)((n_vocab + 31) / 32);
|
||||
R3D_KLAUNCH(R3D_KNAME(sample_ngram_ban_kernel), dim3((uint32_t)M), dim3(kPre),
|
||||
(hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg,
|
||||
(const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)hist,
|
||||
(const int32_t*)(uintptr_t)ngram, (const int32_t*)(uintptr_t)whitelist,
|
||||
(uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hist_ld, words, (int32_t)vocab_off);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r3d_sample_mask(long lg, long params, long bitmask, int M, int n_vocab,
|
||||
long long lg_ld, int mask_rows, long stream) {
|
||||
if (!lg || !params || !bitmask) return -1;
|
||||
if (M <= 0 || n_vocab <= 0) return -2;
|
||||
if (!lg_ld) lg_ld = n_vocab;
|
||||
if (lg_ld < n_vocab) return -3;
|
||||
if (mask_rows < M) return -3; /* a plane that cannot address row M-1 is not that plane */
|
||||
const uint32_t words = (uint32_t)((n_vocab + 31) / 32);
|
||||
/* mask_rows is the bitmask plane's own row count, which is what the reference compares
|
||||
* mask_row against, and the shim reads it off the operand. It is M at the geometry the shape
|
||||
* hook draws and the engine builds, and larger when a caller hands a plane of its own, in which
|
||||
* case a row addressing past M is masked, as the reference masks it. The grid stays M: rows
|
||||
* past the logits plane's row count have no logits to mask. */
|
||||
R3D_KLAUNCH(R3D_KNAME(sample_mask_kernel), dim3((uint32_t)M), dim3(kThreads),
|
||||
(hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg,
|
||||
(const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)bitmask,
|
||||
(uint32_t)n_vocab, (uint32_t)lg_ld, words, (uint32_t)mask_rows);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* ================================================================== shims
|
||||
*
|
||||
* libref's operand lists: {logits, params, history[, breakers]} for the history stages,
|
||||
* {logits, params, ngram, whitelist?} for the ban, {logits, params, bitmask} for the mask and
|
||||
* {logits, params, stats} for logprobs. M is the logits plane's row count.
|
||||
*/
|
||||
|
||||
extern "C" int r3d_rad_sample_logprobs(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* lg = r3d_opt(a, 0);
|
||||
const RadTensor* pr = r3d_opt(a, 1);
|
||||
const RadTensor* st = r3d_opt(a, 2);
|
||||
R3D_NEED(logits_ok(lg));
|
||||
const long long k = r3d_geti_or(a, "k", 0);
|
||||
if (k <= 0) return R3D_NO(RAD_E_SHAPE);
|
||||
/* The pool is 64 deep per lane, which is above every k the engine requests. A row carrying
|
||||
* C_LE("k", 64) is what keeps a request above it out of the band. */
|
||||
if (k > kKMax) return R3D_NO(RAD_E_UNSUPPORTED);
|
||||
long long n_vocab = 0, rows = 0, lg_ld = 0;
|
||||
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
|
||||
R3D_NEED(params_ok(pr, rows));
|
||||
if (!st || !st->data) return R3D_NO(RAD_E_INVAL);
|
||||
if (!r3d_is_f32(st)) return R3D_NO(RAD_E_DTYPE);
|
||||
long long srows = 0;
|
||||
const long long st_ld = r3d_rows_pitch(st, 2 + 2 * k, &srows);
|
||||
if (st_ld < 0) return R3D_NO(RAD_E_STRIDE);
|
||||
if (srows < rows) return R3D_NO(RAD_E_SHAPE);
|
||||
return r3d_launch_status(r3d_sample_logprobs(
|
||||
r3d_addr(lg), r3d_addr(pr), r3d_addr(st), (int)rows, (int)n_vocab, (int)k, lg_ld, st_ld,
|
||||
(int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream));
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_sample_penalties(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* lg = r3d_opt(a, 0);
|
||||
const RadTensor* pr = r3d_opt(a, 1);
|
||||
const RadTensor* hi = r3d_opt(a, 2);
|
||||
R3D_NEED(logits_ok(lg));
|
||||
long long n_vocab = 0, rows = 0, lg_ld = 0;
|
||||
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
|
||||
R3D_NEED(params_ok(pr, rows));
|
||||
long long hmax = 0;
|
||||
R3D_NEED(hist_ok(hi, rows, &hmax));
|
||||
return r3d_launch_status(r3d_sample_penalties(
|
||||
r3d_addr(lg), r3d_addr(pr), r3d_addr(hi), (int)rows, (int)n_vocab, lg_ld, hmax,
|
||||
(int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream));
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_sample_dry(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* lg = r3d_opt(a, 0);
|
||||
const RadTensor* pr = r3d_opt(a, 1);
|
||||
const RadTensor* hi = r3d_opt(a, 2);
|
||||
const RadTensor* brk = r3d_opt(a, 3);
|
||||
R3D_NEED(logits_ok(lg));
|
||||
long long n_vocab = 0, rows = 0, lg_ld = 0;
|
||||
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
|
||||
R3D_NEED(params_ok(pr, rows));
|
||||
long long hmax = 0;
|
||||
R3D_NEED(hist_ok(hi, rows, &hmax));
|
||||
long long baddr = 0;
|
||||
if (brk && brk->data) {
|
||||
/* One byte a history position, the exemption matching the history position for position. */
|
||||
if (!r3d_is_u8(brk)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_contig(brk)) return R3D_NO(RAD_E_STRIDE);
|
||||
if (r3d_numel(brk) < rows * hmax) return R3D_NO(RAD_E_SHAPE);
|
||||
baddr = r3d_addr(brk);
|
||||
}
|
||||
return r3d_launch_status(r3d_sample_dry(
|
||||
r3d_addr(lg), r3d_addr(pr), r3d_addr(hi), baddr, (int)rows, (int)n_vocab, lg_ld, hmax,
|
||||
(int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream));
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_sample_ngram_ban(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* lg = r3d_opt(a, 0);
|
||||
const RadTensor* pr = r3d_opt(a, 1);
|
||||
const RadTensor* hi = r3d_opt(a, 2);
|
||||
const RadTensor* ng = r3d_opt(a, 3);
|
||||
const RadTensor* wl = r3d_opt(a, 4);
|
||||
R3D_NEED(logits_ok(lg));
|
||||
long long n_vocab = 0, rows = 0, lg_ld = 0;
|
||||
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
|
||||
R3D_NEED(params_ok(pr, rows));
|
||||
long long hmax = 0;
|
||||
R3D_NEED(hist_ok(hi, rows, &hmax));
|
||||
if (!ng || !ng->data) return R3D_NO(RAD_E_INVAL);
|
||||
if (!r3d_is_i32(ng)) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_contig(ng) || r3d_numel(ng) < 2 * rows) return R3D_NO(RAD_E_SHAPE);
|
||||
const long long words = (n_vocab + 31) / 32;
|
||||
long long waddr = 0;
|
||||
if (wl && wl->data) {
|
||||
if (wl->dtype != RAD_I32 && wl->dtype != RAD_U32) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_contig(wl)) return R3D_NO(RAD_E_STRIDE);
|
||||
if (r3d_numel(wl) < rows * words) return R3D_NO(RAD_E_SHAPE);
|
||||
waddr = r3d_addr(wl);
|
||||
}
|
||||
return r3d_launch_status(r3d_sample_ngram_ban(
|
||||
r3d_addr(lg), r3d_addr(pr), r3d_addr(hi), r3d_addr(ng), waddr, (int)rows, (int)n_vocab,
|
||||
lg_ld, hmax, (int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream));
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_sample_mask(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* lg = r3d_opt(a, 0);
|
||||
const RadTensor* pr = r3d_opt(a, 1);
|
||||
const RadTensor* bm = r3d_opt(a, 2);
|
||||
R3D_NEED(logits_ok(lg));
|
||||
long long n_vocab = 0, rows = 0, lg_ld = 0;
|
||||
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
|
||||
R3D_NEED(params_ok(pr, rows));
|
||||
if (!bm || !bm->data) return R3D_NO(RAD_E_INVAL);
|
||||
if (bm->dtype != RAD_I32 && bm->dtype != RAD_U32) return R3D_NO(RAD_E_DTYPE);
|
||||
if (!r3d_contig(bm)) return R3D_NO(RAD_E_STRIDE);
|
||||
const long long words = (n_vocab + 31) / 32;
|
||||
if (words <= 0 || r3d_numel(bm) < rows * words) return R3D_NO(RAD_E_SHAPE);
|
||||
/* The plane's own row count is the bound the reference tests, and the plane may be longer than
|
||||
* the logits: a caller that hands a plane of its own gets its rows. */
|
||||
const long long mask_rows = r3d_numel(bm) / words;
|
||||
return r3d_launch_status(r3d_sample_mask(r3d_addr(lg), r3d_addr(pr), r3d_addr(bm), (int)rows,
|
||||
(int)n_vocab, lg_ld, (int)mask_rows,
|
||||
(long)(uintptr_t)stream));
|
||||
}
|
||||
|
||||
/* ================================================================== the lane helpers, proved
|
||||
*
|
||||
* Every wave-sum in libr3d is a butterfly over lane shuffles, and the arithmetic that rides on a
|
||||
* lane shuffle is invisible to a codec sweep: a helper that hands back a stale half of a 64-bit
|
||||
* value reads as a few percent of a perplexity, in a model nobody suspects. This file
|
||||
* has one of the shapes in it -- the logprobs k-list crosses lanes as 8-byte values -- so it also
|
||||
* carries the control that checks the helpers, on the card, one entry per lane per wave.
|
||||
*
|
||||
* On this box (gfx1102, -O2 and -O3, wave32) the control is exact in **all 256 lanes of all 8
|
||||
* waves**: seeds at wave-local lanes 6, 9, 19 and 25, five butterfly rounds, and every form of the
|
||||
* 64-bit exchange -- `r3d_xor_lane_u64` (two 32-bit shuffles of the halves), the same shape written
|
||||
* as a `__shfl_xor_sync` per half, and one shuffle of the 64-bit value -- with the lane's value
|
||||
* derived from `threadIdx.x`, loaded from a plane, and accumulated in a grid-stride loop.
|
||||
* `r3d_xor_lane_u64` is sound; the form it must not be written in converts by value:
|
||||
*
|
||||
* d += (double)r3d_xor_lane_u64<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.
|
||||
*/
|
||||
__device__ __forceinline__ double d_from_bits(unsigned long long b) {
|
||||
double d;
|
||||
__builtin_memcpy(&d, &b, sizeof d);
|
||||
return d;
|
||||
}
|
||||
__device__ __forceinline__ unsigned long long bits_of(double d) {
|
||||
unsigned long long b;
|
||||
__builtin_memcpy(&b, &d, sizeof b);
|
||||
return b;
|
||||
}
|
||||
|
||||
__global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ out) {
|
||||
/* kThreads and kWave are this file's anonymous-namespace names and are ambiguous out here, so
|
||||
* the control spells its own geometry. */
|
||||
constexpr uint32_t kLWave = 32, kLBlock = 256;
|
||||
/* Seeds at wave-local lanes 6, 9, 19, 25: a wave with four non-zero lanes and an expected sum
|
||||
* of 0.08945 + 1 + 0.5971 + 0.9768, in the butterfly's own order. Every wave carries them, so
|
||||
* every wave is checked. */
|
||||
const uint32_t lane = threadIdx.x & (kLWave - 1);
|
||||
const double seed = (lane == 6) ? 0.08945 : (lane == 9) ? 1.0 : (lane == 19) ? 0.5971
|
||||
: (lane == 25) ? 0.9768 : 0.0;
|
||||
__shared__ double s_d[kLBlock];
|
||||
__shared__ float s_f[kLBlock];
|
||||
s_d[threadIdx.x] = seed;
|
||||
s_f[threadIdx.x] = (float)seed;
|
||||
__syncthreads();
|
||||
|
||||
/* Form 0: the 32-bit butterfly every wave-sum in the library is built from, over a value read
|
||||
* out of LDS so it is a memory operand and not a constant. */
|
||||
float f = s_f[threadIdx.x];
|
||||
f += r3d_xor_lane<16>(f);
|
||||
f += r3d_xor_lane<8>(f);
|
||||
f += r3d_xor_lane<4>(f);
|
||||
f += r3d_xor_lane<2>(f);
|
||||
f += r3d_xor_lane<1>(f);
|
||||
out[0 * kLBlock + threadIdx.x] = (double)f;
|
||||
|
||||
/* Form 1: the halves form over a value derived from the lane index. The pattern goes to the
|
||||
* helper and back through bits_of/d_from_bits: a cast between double and an integer type
|
||||
* converts the value, which is what this control guards against. */
|
||||
double d = seed;
|
||||
#define R3D_L64(N) d += d_from_bits(r3d_xor_lane_u64<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. */
|
||||
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. */
|
||||
d = s_d[threadIdx.x];
|
||||
#define R3D_S64(N) d += d_from_bits(__shfl_xor_sync(0xFFFFFFFFull, bits_of(d), N));
|
||||
R3D_S64(16) R3D_S64(8) R3D_S64(4) R3D_S64(2) R3D_S64(1)
|
||||
#undef R3D_S64
|
||||
out[3 * kLBlock + threadIdx.x] = d;
|
||||
}
|
||||
|
||||
/* Four forms x 256 lanes of doubles (8 KiB, which the caller owns: this launcher allocates nothing,
|
||||
* as every launcher in this file does). 0, -1 null, -4 the launch failed. r3d_selftest.cpp dlsyms
|
||||
* this by name and compares every lane against a host emulation of the same five rounds. */
|
||||
extern "C" int r3d_lanes_check(long out, long stream) {
|
||||
if (!out) return -1;
|
||||
R3D_KLAUNCH(R3D_KNAME(lanes_check_kernel), dim3(1), dim3(256),
|
||||
(hipStream_t)(uintptr_t)stream, (double*)(uintptr_t)out);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,836 @@
|
||||
/* r3d_shapes.cpp -- the extent and content domain of each operand of an op at a geometry.
|
||||
*
|
||||
* This is libr3d's side of the `RadShapeFn` hook: the component that reads an operand is the one
|
||||
* that knows its extent. The hand-written table in `tools/` describes the ops it was written
|
||||
* against; a row that exists only here is invisible to it, and a tool that cannot size an operand
|
||||
* cannot call the op cold. So correctness checks, benchmarks and the coverage census reach these
|
||||
* rows through this hook.
|
||||
*
|
||||
* The authority for every extent is the shim, not the prose or the row table. Each `r3d_rad_*`
|
||||
* entry point unpacks `RadArgs.t[i]` into extents and pitches; if a shim passes `x->shape[1]` as
|
||||
* `n`, that is what the operand is. Each group names its unit, and a change to a shim's contract
|
||||
* must be mirrored here.
|
||||
*
|
||||
* Content matters as much as size. A token id gathers a row of a codebook, a KV slot indexes
|
||||
* n_blocks * block_size positions, a block-table entry indexes n_blocks. Drawn from the wrong
|
||||
* range, such an operand tests the kernel's out-of-range handling instead of its arithmetic, and a
|
||||
* scatter whose indices collide is a race the parallel rerun rightly reports as a failure.
|
||||
* `RAD_FILL_INDEX` with an explicit `idx_max` states each range, and `RAD_OPD_F_IDX_UNIQUE` marks
|
||||
* the scatters that need distinct destinations.
|
||||
*
|
||||
* ============================================================ rows with no description
|
||||
*
|
||||
* A decline is a real answer: the caller skips and counts the case, where an invented extent
|
||||
* yields a meaningless pass. These rows carry a null `opd_shape`:
|
||||
*
|
||||
* gemm_nt_q at a quantised `a` whose scale plane the row does not name
|
||||
* Not present in libr3d: both quantised rows state their activation dtype in `dtype`, so
|
||||
* `a` is bf16 against an fp8 weight (fp8a16) or i8 against an i8 weight (i8a8), and both are
|
||||
* described below. The case is listed here because it is the one libr4d declines, and a
|
||||
* reader comparing the two files will look for the difference.
|
||||
*
|
||||
* rope at a multi-component mode
|
||||
* mrope, imrope and axial take one position per component, component-major, and the
|
||||
* component count comes from the `sections` string. libr3d's kernel implements neox and gptj
|
||||
* and its row's constraints say so, so a geometry with `sections` set is never routed here.
|
||||
*
|
||||
* No tuned axis is read here: this plugin's axes (split counts, wave counts, the streaming mode)
|
||||
* change how a kernel walks its operands, not their extents. An axis that did would be read from
|
||||
* `p`, where the core appends the chosen point.
|
||||
*
|
||||
* Pure host code (no r3d.h, no HIP), like r3d_rows.cpp, so the tables compile and can be read
|
||||
* without ROCm.
|
||||
*/
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#include "r3d_plugin.h"
|
||||
|
||||
namespace {
|
||||
|
||||
/* ==================================================================== building a description
|
||||
*
|
||||
* Each op builds its whole operand list in schema order and hands out the one asked for, so the
|
||||
* count can be checked by eye against the schema in r3d_rows.cpp (the tool also checks it against
|
||||
* `RadOpSchema::n_operands`).
|
||||
*/
|
||||
|
||||
/* A plain operand of up to four extents. A trailing 0 ends the shape; zero is never a legal
|
||||
* extent (`pick` refuses one), so it cannot be mistaken for a real one. */
|
||||
RadOpdDesc opd(uint32_t dt, int64_t d0, int64_t d1 = 0, int64_t d2 = 0, int64_t d3 = 0) {
|
||||
RadOpdDesc d{};
|
||||
d.dtype = dt;
|
||||
d.fill = RAD_FILL_NORMAL;
|
||||
/* -1 is "draw"; set explicitly though the caller pre-initialises it. */
|
||||
d.idx_const = -1;
|
||||
const int64_t e[4] = { d0, d1, d2, d3 };
|
||||
for (int i = 0; i < 4 && e[i] != 0; ++i) d.shape[d.rank++] = e[i];
|
||||
return d;
|
||||
}
|
||||
|
||||
/* An index operand. `idx_max` is the exclusive upper bound of the draw; 0 means the previous
|
||||
* operand's leading extent (the ABI default, right for a gather from the operand before it).
|
||||
* `konst >= 0` fills every element with that value. Always i32: every index libr3d reads is signed
|
||||
* 32-bit. */
|
||||
RadOpdDesc opd_idx(int64_t d0, int64_t idx_max, int64_t konst = -1, uint32_t flags = 0,
|
||||
int64_t d1 = 0) {
|
||||
RadOpdDesc d = opd((uint32_t)RAD_I32, d0, d1);
|
||||
d.fill = RAD_FILL_INDEX;
|
||||
d.idx_max = idx_max;
|
||||
d.idx_const = konst;
|
||||
d.flags = flags;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* An optional operand this description does not pass. One entry per schema operand is still
|
||||
* emitted, so absence needs a spelling; to the ABI it means a null RadTensor. */
|
||||
RadOpdDesc opd_none() {
|
||||
RadOpdDesc d{};
|
||||
d.idx_const = -1;
|
||||
d.flags = RAD_OPD_F_ABSENT;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* Restricts the fill to (0, 1); `RAD_FILL_SIGMOID` is the ABI's only such draw. A scale plane drawn
|
||||
* from a normal is as likely to be negative as positive, and a negative descale inverts the sign of
|
||||
* an entire quantised block. */
|
||||
RadOpdDesc in_unit(RadOpdDesc d) { d.fill = RAD_FILL_SIGMOID; return d; }
|
||||
|
||||
/* Hands out operand `operand` of a list after checking the whole list, so a geometry missing a
|
||||
* parameter declines every operand rather than describing a few and declining the rest. A
|
||||
* non-positive extent means a needed parameter was absent or zero: RAD_E_UNSUPPORTED, not
|
||||
* RAD_E_SHAPE, which would read as a tool bug. An index outside the list is a bug here or in the
|
||||
* schema, reported as RAD_E_SHAPE. */
|
||||
int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) {
|
||||
if (!out || !list || n <= 0) return RAD_E_INVAL;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (list[i].flags & RAD_OPD_F_ABSENT) continue;
|
||||
if (list[i].rank == 0 || list[i].rank > RAD_MAX_RANK) return RAD_E_UNSUPPORTED;
|
||||
for (uint32_t d = 0; d < list[i].rank; ++d)
|
||||
if (list[i].shape[d] <= 0) return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (operand < 0 || operand >= n) return RAD_E_SHAPE;
|
||||
*out = list[operand];
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#define R3D_PICK(list) return pick(out, operand, (list), (int)(sizeof(list) / sizeof((list)[0])))
|
||||
|
||||
/* ==================================================================== parameters
|
||||
*
|
||||
* `M` and the other ranged parameters read as the band's bound, not any one step's row count (as
|
||||
* in every shim here): buffers must hold the whole band the kernel was selected for.
|
||||
*
|
||||
* Not r3d_pgeti_or(): that reads RAD_P_INT only, which suits a launch (every range has collapsed
|
||||
* by then), but this hook can see ranges still open. rad_param_getdim (ABI, shared with libr4d)
|
||||
* reads a RAD_P_RANGE as its high bound.
|
||||
*/
|
||||
int64_t gi(const RadParam* p, int n_p, const char* k, int64_t dflt) {
|
||||
return rad_param_getdim(p, n_p, k, dflt);
|
||||
}
|
||||
|
||||
const char* gs(const RadParam* p, int n_p, const char* k) {
|
||||
return rad_param_gets(p, n_p, k, nullptr);
|
||||
}
|
||||
|
||||
/* The activation dtype, from `dtype` and its attention spellings; bf16 when the geometry names
|
||||
* none. A quantisation-scheme string ("fp8a16", "w8a16") is not a dtype and lands on bf16, which
|
||||
* is what the quantised rows use it to mean: the scheme picks the weight's dtype, the row states
|
||||
* the activation's. */
|
||||
uint32_t act_dt(const RadParam* p, int n_p) {
|
||||
const char* s = gs(p, n_p, "dtype");
|
||||
if (!s) s = gs(p, n_p, "q_dtype");
|
||||
const uint32_t dt = rad_dtype_parse(s);
|
||||
return dt == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : dt;
|
||||
}
|
||||
|
||||
/* The scale-stream group count, matching the quantisers' launches: `group` <= 0 or wider than the
|
||||
* row is one scale per row, otherwise ceil(n / group). */
|
||||
int64_t scale_groups(int64_t n, int64_t group) {
|
||||
int64_t g = group;
|
||||
if (g <= 0 || g > n) g = n;
|
||||
return g > 0 ? (n + g - 1) / g : 0;
|
||||
}
|
||||
|
||||
/* ==================================================================== elementwise and norms
|
||||
* r3d_model_bf16.hip
|
||||
*/
|
||||
|
||||
} /* namespace */
|
||||
|
||||
extern "C" {
|
||||
|
||||
/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. The gain is described at its full width; the
|
||||
* form with no gain at all is a hand case, since a null optional operand is not a fill domain. */
|
||||
int r3d_shape_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const RadOpdDesc list[] = { opd(D, M, n), opd(D, n), opd(D, M, n) }; /* x, w, y */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The two-pass form. `b` is optional and passed: the biased form covers strictly more code, and a
|
||||
* null optional operand is not a fill domain a tool can draw. */
|
||||
int r3d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const RadOpdDesc list[] = { opd(D, M, n), opd(D, n), opd(D, n), opd(D, M, n) }; /* x,w,b,y */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* add / mul share a schema and a description. `b` is described at full extent; the row-broadcast
|
||||
* form is not described, since a buffer of n elements against M rows cannot be told from a shape
|
||||
* bug by a tool that sizes by shape alone. */
|
||||
static int binary_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd(D, M, n) }; /* a, b, y */
|
||||
return pick(out, operand, list, 3);
|
||||
}
|
||||
|
||||
int r3d_shape_add(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return binary_shape(p, n_p, operand, out);
|
||||
}
|
||||
int r3d_shape_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return binary_shape(p, n_p, operand, out);
|
||||
}
|
||||
|
||||
/* y = act(gate) * up over two [M, n] operands. The fused [M, 2n] form is the one the model
|
||||
* issues; describing it here would be a second spelling of a geometry the row's `n` is about, so
|
||||
* the two halves are described as the kernel sees them. */
|
||||
int r3d_shape_act_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return binary_shape(p, n_p, operand, out);
|
||||
}
|
||||
|
||||
/* x -> y, one dtype to another. Operand dtypes come from `from` and `to`; an unparseable spelling
|
||||
* falls back to f32, the widest it could mean. */
|
||||
int r3d_shape_cast(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
uint32_t from = rad_dtype_parse(gs(p, n_p, "from"));
|
||||
uint32_t to = rad_dtype_parse(gs(p, n_p, "to"));
|
||||
if (from == (uint32_t)RAD_DT_INVALID) from = (uint32_t)RAD_F32;
|
||||
if (to == (uint32_t)RAD_DT_INVALID) to = (uint32_t)RAD_F32;
|
||||
const RadOpdDesc list[] = { opd(from, M, n), opd(to, M, n) }; /* x, y */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The unary activations and softmax: x and y at the same extent. */
|
||||
static int unary_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n) }; /* x, y */
|
||||
return pick(out, operand, list, 2);
|
||||
}
|
||||
|
||||
int r3d_shape_silu(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return unary_shape(p, n_p, operand, out);
|
||||
}
|
||||
int r3d_shape_gelu(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return unary_shape(p, n_p, operand, out);
|
||||
}
|
||||
int r3d_shape_sigmoid(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return unary_shape(p, n_p, operand, out);
|
||||
}
|
||||
int r3d_shape_softmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return unary_shape(p, n_p, operand, out);
|
||||
}
|
||||
|
||||
/* y = x * s. `s` is one element, broadcast over everything; a row of them would be a different op. */
|
||||
int r3d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const RadOpdDesc list[] = { opd(D, M, n), opd(D, 1), opd(D, M, n) }; /* x, s, y */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* y = value. The only operand is the output, so a case's whole content is the kernel's. */
|
||||
int r3d_shape_fill(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const RadOpdDesc list[] = { opd(D, M, n) };
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* ==================================================================== the model's odds and ends
|
||||
* r3d_model_bf16.hip
|
||||
*/
|
||||
|
||||
/* In-place rotary over a fused qkv row: n_head q heads, then n_head_kv each of k and v. The
|
||||
* positions are drawn over the row count, which for a single step is its own positions; a step
|
||||
* crossing a context boundary is a hand case, since a fill cannot spell "contiguous from an
|
||||
* arbitrary start". */
|
||||
int r3d_shape_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t hd = gi(p, n_p, "head_dim", 0);
|
||||
const int64_t nh = gi(p, n_p, "n_head", 0);
|
||||
const int64_t nkv = gi(p, n_p, "n_head_kv", nh);
|
||||
if (M <= 0 || hd <= 0 || nh <= 0) return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc list[] = {
|
||||
opd((uint32_t)RAD_BF16, M, (nh + 2 * nkv) * hd), /* qkv, INOUT */
|
||||
opd_idx(M, 0) /* positions */
|
||||
};
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* K and V into a paged cache. Two blocks of slack over the tokens, so the slot mapping is not a
|
||||
* dense prefix and the block index matters. Only the cache takes `kv_dtype`: k and v are bf16
|
||||
* activations whatever the cache stores. */
|
||||
int r3d_shape_kv_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t hd = gi(p, n_p, "head_dim", 0);
|
||||
const int64_t kvh = gi(p, n_p, "n_head_kv", 0);
|
||||
const int64_t bs = gi(p, n_p, "block_size", 0);
|
||||
if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t nb = (M + bs - 1) / bs + 2;
|
||||
const uint32_t kv = rad_dtype_parse(gs(p, n_p, "kv_dtype"));
|
||||
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : kv;
|
||||
const RadOpdDesc list[] = {
|
||||
opd((uint32_t)RAD_BF16, M, kvh, hd), /* k */
|
||||
opd((uint32_t)RAD_BF16, M, kvh, hd), /* v */
|
||||
opd_idx(M, nb * bs, -1, RAD_OPD_F_IDX_UNIQUE), /* slot_mapping */
|
||||
opd(KV, nb, kvh, bs, 2 * hd) /* kv_cache, INOUT */
|
||||
};
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* x[r] = wte[ids[r] - vocab_offset]. Ids are global, so the draw's bound is `vocab_offset + n_vocab`:
|
||||
* under a shard the draw crosses the slice boundary and exercises the zero-row path. */
|
||||
int r3d_shape_embed_lookup(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t ne = gi(p, n_p, "n_embd", 0);
|
||||
const int64_t nv = gi(p, n_p, "n_vocab", 0);
|
||||
const int64_t vo = gi(p, n_p, "vocab_offset", 0);
|
||||
if (M <= 0 || ne <= 0 || nv <= 0 || vo < 0) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const RadOpdDesc list[] = {
|
||||
opd_idx(M, vo + nv), /* tokens */
|
||||
opd(D, nv, ne), /* wte */
|
||||
opd(D, M, ne) /* x */
|
||||
};
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The source is 4x the gathered height so the gather is not the identity, which would pass while
|
||||
* broken; `idx` draws over those 4M rows. */
|
||||
int r3d_shape_gather_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const RadOpdDesc list[] = { opd(D, 4 * M, n), opd_idx(M, 0), opd(D, M, n) }; /* x, idx, y */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* Onto exactly M rows a scatter is a permutation, which a kernel ignoring `idx` could pass, so the
|
||||
* destination is 4x the scattered height and unnamed rows must come back unchanged. The indices are
|
||||
* distinct: two rows drawing one destination is a race. */
|
||||
int r3d_shape_scatter_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const RadOpdDesc list[] = {
|
||||
opd(D, M, n), opd_idx(M, 4 * M, -1, RAD_OPD_F_IDX_UNIQUE), opd(D, 4 * M, n)
|
||||
}; /* v, idx, x (INOUT) */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* ================================================================== quantisation
|
||||
* r3d_quant_fp8.hip
|
||||
*/
|
||||
|
||||
/* Codes row-major at [M, n], one f32 scale per (row, `group` of n). `dtype` names the input; the
|
||||
* output's dtype is in the op name. */
|
||||
int r3d_shape_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
|
||||
const RadOpdDesc list[] = {
|
||||
opd(D, M, n), opd((uint32_t)RAD_F8E4M3, M, n), opd((uint32_t)RAD_F32, M, ng)
|
||||
}; /* x, q, scale */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The int8 twin, with the optional row-sum plane beside it. `asum` is described whenever `group`
|
||||
* divides n, so a case checks the row sums as well; it is group-major, the layout libref's
|
||||
* quant_act_i8 writes. */
|
||||
/* The per-row int8: one scale per row, in a [M, 1] plane (the reference writes it at pitch 1, so a
|
||||
* plane with more room is legal and this states the tightest one), and the optional `asum` described
|
||||
* whenever `group` divides n, so a case exercises the row sums too. `q` is in the step order --
|
||||
* described by its extent, because a description states a plane's size and content domain, not a
|
||||
* permutation; the row's `shape` prose names the order. */
|
||||
int r3d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), g = gi(p, n_p, "group", 0);
|
||||
const RadOpdDesc list[] = {
|
||||
opd(D, M, n),
|
||||
opd((uint32_t)RAD_I8, M, n),
|
||||
opd((uint32_t)RAD_F32, M, 1),
|
||||
(g > 0 && n % g == 0) ? opd((uint32_t)RAD_F32, n / g, (M + 15) / 16 * 16) : opd_none()
|
||||
}; /* x, q, scale, asum */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The per-group int8, the activation the i8a8 GEMM reads: the fp8 quantiser's extents at int8 codes
|
||||
* and a 127 denominator. */
|
||||
int r3d_shape_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
|
||||
const RadOpdDesc list[] = {
|
||||
opd(D, M, n), opd((uint32_t)RAD_I8, M, n), opd((uint32_t)RAD_F32, M, ng)
|
||||
}; /* x, q, scale */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The gated form: gate_up is [M, 2n] with the gate first, and what is quantised is
|
||||
* act(gate) * up over n columns. */
|
||||
int r3d_shape_gated_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
|
||||
const RadOpdDesc list[] = {
|
||||
opd(D, M, 2 * n),
|
||||
opd((uint32_t)RAD_F8E4M3, M, n),
|
||||
opd((uint32_t)RAD_F32, M, ng),
|
||||
opd((uint32_t)RAD_BF16, M, n)
|
||||
}; /* gate_up, q, scale, out_bf16 */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* y = code * scale. `dtype` names the code: E4M3 and E5M2 are the checkpoint's fp8, i8 the int8
|
||||
* twin. The scale is a dequant multiplier, so its draw is restricted to (0, 1) -- a normal draw is
|
||||
* as likely to be negative, and a negative scale inverts a whole block. */
|
||||
int r3d_shape_dequant(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t g = gi(p, n_p, "group", 0);
|
||||
const uint32_t qd = rad_dtype_parse(gs(p, n_p, "dtype"));
|
||||
const uint32_t Q = qd == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_I8 : qd;
|
||||
const RadOpdDesc list[] = {
|
||||
opd(Q, M, n), in_unit(opd((uint32_t)RAD_F32, M, scale_groups(n, g))),
|
||||
opd((uint32_t)RAD_BF16, M, n)
|
||||
}; /* q, scale, y */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* ================================================================== gemm
|
||||
* r3d_gemm_bf16_nt_m16.hip, r3d_gemm_bf16_nt_tiled.hip, r3d_gemm_fp8a16_nt_m1.hip
|
||||
*/
|
||||
|
||||
/* y[M,N] = a[M,K] @ b[N,K]^T. Both operands are k-contiguous, which is what the transposed spelling
|
||||
* in the op's name means and why neither is described as [K, N]. */
|
||||
int r3d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
|
||||
const RadOpdDesc list[] = { opd(D, M, K), opd(D, N, K), opd(D, M, N) }; /* a, b, y */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The vocabulary projection, transcribed from ref_logits_gemm_shape: x [M, n_embd] and the head
|
||||
* [n_vocab, n_embd] in the activation's dtype, the logits in f32 -- the dtype the schema states, not
|
||||
* the one a GEMM would narrow to, because every sampler stage downstream reads f32 and a prefill
|
||||
* band's plane is 1.07 GB of it at M=2048. The reference's own logits row answers a placement
|
||||
* question (`ref_layout_head`: where the head lives) and so carries a layout hook; this row has
|
||||
* nothing to place, it reads the head where it is stored, which is why the hook it declares is the
|
||||
* shape and nothing else. A hook is the right thing to write *because* all three operands are
|
||||
* describable: the extents the hook names are the ones that get filled, which is the opposite of
|
||||
* the joined w2a8 plane, where a describable byte count is a container header waiting to be filled
|
||||
* with random bytes. */
|
||||
int r3d_shape_logits_gemm_bf16(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), nv = gi(p, n_p, "n_vocab", 0), ne = gi(p, n_p, "n_embd", 0);
|
||||
if (M <= 0 || nv <= 0 || ne <= 0) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const RadOpdDesc list[] = { opd(D, M, ne), opd(D, nv, ne), opd(RAD_F32, M, nv) };
|
||||
R3D_PICK(list); /* x, lm_head, logits */
|
||||
}
|
||||
|
||||
/* The quantised GEMM. `dtype` names the scheme, and the scheme fixes which operands are coded:
|
||||
*
|
||||
* fp8a16 a bf16, b the checkpoint's E4M3 [N][K], b_scale one f32 per 128x128 block (the
|
||||
* container's `weight_scale_inv`, whose dtype the container states: f32 at fp8a8f32,
|
||||
* bf16 as DeepSeek's own scales are).
|
||||
* fp8a8 a E4M3 against a_scale, one f32 per (row, `group` of K) -- quant_act_fp8's output
|
||||
* feeding the GEMM, which is the reason the two rows state the same group.
|
||||
* i8a8 i8 codes on both axes with an f32 scale per (row, `group`).
|
||||
*
|
||||
* `b_scale`'s plane is block-major [ceil(N/pb), ceil(K/pb)] for fp8 and row-major [N, ceil(K/group)]
|
||||
* for i8: the two checkpoints spell it differently and both are the bytes on disk. */
|
||||
int r3d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
|
||||
if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED;
|
||||
int64_t group = gi(p, n_p, "group", 0);
|
||||
if (group <= 0) group = R3D_FP8_BLOCK; /* the block every block-scaled checkpoint uses */
|
||||
const int64_t kb = (K + group - 1) / group, nb = (N + group - 1) / group;
|
||||
const char* q = gs(p, n_p, "dtype");
|
||||
const bool i8a8 = q && !std::strcmp(q, "i8a8");
|
||||
const bool a8 = q && (!std::strcmp(q, "fp8a8") || i8a8);
|
||||
|
||||
RadOpdDesc list[R3D_GEMM_Q_NOPERAND];
|
||||
list[0] = opd(i8a8 ? (uint32_t)RAD_I8 : (a8 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16),
|
||||
M, K); /* a */
|
||||
list[1] = a8 ? in_unit(opd((uint32_t)RAD_F32, M, kb)) : opd_none(); /* a_scale */
|
||||
list[2] = opd(i8a8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3, N, K); /* b */
|
||||
list[3] = in_unit(opd((uint32_t)RAD_F32, i8a8 ? N : nb, kb)); /* b_scale */
|
||||
list[4] = opd((uint32_t)RAD_BF16, M, N); /* y */
|
||||
list[5] = opd_none(); /* a_sum */
|
||||
list[6] = opd_none(); /* b_ref */
|
||||
return pick(out, operand, list, R3D_GEMM_Q_NOPERAND);
|
||||
}
|
||||
|
||||
/* The OCP-MXFP4 grid, libref's description for the dtype: the weight is e2m1, two a byte, with
|
||||
* one e8m0 exponent per 32 of K, so the weight's planes are [N, K] of fp4_e2m1 and [N, K/32] of
|
||||
* e8m0; `b_ref` is the same exponent plane, accepted beside an e2m1 weight and ignored. The
|
||||
* activation is the fp8a8 row's -- E4M3 against one f32 per (row, 128 of K), drawn in (0, 1) as
|
||||
* a quantiser's is. Both zero-point operands are absent: the scale is symmetric. */
|
||||
int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
|
||||
if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED;
|
||||
if (K % 128) return RAD_E_UNSUPPORTED; /* the activation's scale group and the 32-block */
|
||||
const char* q = gs(p, n_p, "dtype");
|
||||
if (!q || std::strcmp(q, "mxfp4a8") != 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t kb = K / 128;
|
||||
RadOpdDesc list[R3D_GEMM_Q_NOPERAND];
|
||||
list[0] = opd((uint32_t)RAD_F8E4M3, M, K); /* a */
|
||||
RadOpdDesc as = opd((uint32_t)RAD_F32, M, kb); /* a_scale */
|
||||
as.fill = RAD_FILL_SIGMOID; /* a quantiser's (0, 1) */
|
||||
list[1] = as;
|
||||
list[2] = opd((uint32_t)RAD_FP4E2M1, N, K); /* b: e2m1, two a byte */
|
||||
/* The e8m0 scale, filled with 127: the factor 2^0. A normal draw of the u8 grid is an exponent
|
||||
* as high as 227, a factor 2^100, and the plane would scale the output past the finiteness
|
||||
* bound the run checks; 127 is the checkpoint's own cluster and no reserved value. */
|
||||
RadOpdDesc e8 = opd((uint32_t)RAD_E8M0, N, K / 32); /* b_scale: e8m0 */
|
||||
e8.fill = RAD_FILL_INDEX;
|
||||
e8.idx_const = 127;
|
||||
list[3] = e8;
|
||||
list[4] = opd((uint32_t)RAD_BF16, M, N); /* y */
|
||||
list[5] = opd_none(); /* a_sum */
|
||||
list[6] = e8; /* b_ref: the e8 plane */
|
||||
return pick(out, operand, list, R3D_GEMM_Q_NOPERAND);
|
||||
}
|
||||
|
||||
/* The symmetric int4 / int8 weight grids, libref's descriptions: int8 activations in the step
|
||||
* order against signed codes (I4, two a byte, or I8, one a byte) with one f16 scale per (row,
|
||||
* 128 of K) and one f32 activation scale per row, drawn in (0, 1) as a quantiser's is. There is
|
||||
* no zero point and no a_sum: the dequant is code times scale. */
|
||||
static int shape_inta8(const RadParam* p, int n_p, int operand, RadOpdDesc* out, const char* q,
|
||||
uint32_t bdt)
|
||||
{
|
||||
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
|
||||
if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED;
|
||||
if (K % 128) return RAD_E_UNSUPPORTED; /* the weight's scale group */
|
||||
const char* d = gs(p, n_p, "dtype");
|
||||
if (!d || std::strcmp(d, q) != 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t kb = K / 128;
|
||||
RadOpdDesc list[R3D_GEMM_Q_NOPERAND];
|
||||
list[0] = opd((uint32_t)RAD_I8, M, K); /* a, step order */
|
||||
RadOpdDesc as = opd((uint32_t)RAD_F32, M, 1); /* a_scale, per row */
|
||||
as.fill = RAD_FILL_SIGMOID;
|
||||
list[1] = as;
|
||||
list[2] = opd(bdt, N, K); /* b: the signed codes */
|
||||
list[3] = opd((uint32_t)RAD_F16, N, kb); /* b_scale */
|
||||
list[4] = opd((uint32_t)RAD_BF16, M, N); /* y */
|
||||
list[5] = opd_none(); /* a_sum */
|
||||
list[6] = opd_none(); /* b_ref */
|
||||
return pick(out, operand, list, R3D_GEMM_Q_NOPERAND);
|
||||
}
|
||||
|
||||
int r3d_shape_gemm_nt_q_w4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
{
|
||||
return shape_inta8(p, n_p, operand, out, "w4a8", (uint32_t)RAD_I4);
|
||||
}
|
||||
|
||||
int r3d_shape_gemm_nt_q_w8a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
{
|
||||
return shape_inta8(p, n_p, operand, out, "w8a8", (uint32_t)RAD_I8);
|
||||
}
|
||||
|
||||
} /* extern "C" */
|
||||
|
||||
|
||||
/* ==================================================================== r3d_sample_f32.hip, r3d_attn_paged_h128.hip
|
||||
*
|
||||
* The vocabulary and the sampler. The schemas in r3d_rows.cpp are transcribed from libref and
|
||||
* checked against it, and these are the other half of that transcription. Every extent, dtype,
|
||||
* fill domain and flag below is libref's: a description that differs from libref's is a case
|
||||
* kbench skips, with one line saying so, and a row that is never exercised is a row that is not
|
||||
* tested.
|
||||
*
|
||||
* The sampler's `params` operand is one plane with one fill domain, `RAD_FILL_SAMPLE_PARAMS`: the
|
||||
* ABI's `RadSampleParams`, 96 bytes, 24 f32 words a row, whose fields the stages read by name. The
|
||||
* history window and the mask-row count are placed *inside* that plane by `fill_chunk` and
|
||||
* `idx_max`, so the draw produces a window that fits the plane and a `mask_row` that is a row of
|
||||
* the bitmask plane (or -1, the unconstrained row sharing a short plane). Both are the stage's
|
||||
* parameters to obey, not this file's invention.
|
||||
*/
|
||||
|
||||
/* The sampler's parameter plane: [M, 24] f32, one RadSampleParams a row. */
|
||||
RadOpdDesc opd_params(int64_t M, int64_t hist, int64_t mask_rows) {
|
||||
RadOpdDesc d = opd((uint32_t)RAD_F32, M, 24);
|
||||
d.fill = (uint32_t)RAD_FILL_SAMPLE_PARAMS;
|
||||
d.fill_chunk = hist;
|
||||
d.idx_max = mask_rows;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* The widths libref's shapes choose, and the reasons it gives for them: the history window is what
|
||||
* a deployment sizes the plane to, 64 is plausible; the candidate width is narrower than the
|
||||
* vocabulary and wide enough for the narrowing stages. */
|
||||
enum { kHist = 64, kCand = 64 };
|
||||
|
||||
/* `n_vocab` rows of f32 logits, and the parameter plane, the pair every vocabulary-width stage
|
||||
* opens with. */
|
||||
int sample_vocab(const RadParam* p, int n_p, int64_t* M, int64_t* nv) {
|
||||
*M = gi(p, n_p, "M", 0);
|
||||
*nv = gi(p, n_p, "n_vocab", 0);
|
||||
return (*M > 0 && *nv > 0) ? RAD_OK : RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* silu(gate) * up over one fused projection: the operand is [M, 2n] and the output [M, n]. */
|
||||
int r3d_shape_silu_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const RadOpdDesc list[] = { opd(D, M, 2 * n), opd(D, M, n) }; /* gate_up (gate first), y */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The fused add + norm + quantiser. `residual` is INOUT and the sum it holds is the bf16 one the
|
||||
* variance reads, so x and residual are the same shape by the op's meaning, not by convenience;
|
||||
* `out_bf16`, optional, is what the codes were taken over, and it exists so a test can read the
|
||||
* value the quantiser saw. */
|
||||
int r3d_shape_rmsnorm_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
|
||||
const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd(D, n),
|
||||
opd((uint32_t)RAD_F8E4M3, M, n), opd((uint32_t)RAD_F32, M, ng),
|
||||
opd((uint32_t)RAD_BF16, M, n) };
|
||||
R3D_PICK(list); /* x, residual, w, q, scale, out_bf16 */
|
||||
}
|
||||
|
||||
/* Paged attention. The context is deeper than the query: one sequence whose context is its query
|
||||
* length is the smallest geometry, and the one that exercises nothing -- no deep paging, no KV
|
||||
* split, no window -- so `ctx`, when a harness passes it, wins, and is never below the query.
|
||||
* `q_len` is the ranged parameter; a decode row and a 2048-token prefill chunk are different
|
||||
* kernels (docs/OPS.md). */
|
||||
int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "q_len", 0);
|
||||
const int64_t hd = gi(p, n_p, "head_dim", 0);
|
||||
const int64_t bs = gi(p, n_p, "block_size", 16);
|
||||
const int64_t gqa = gi(p, n_p, "gqa", 1);
|
||||
const int64_t nh = gi(p, n_p, "n_head", gqa);
|
||||
if (M <= 0 || hd <= 0 || bs <= 0 || gqa <= 0 || nh <= 0 || nh % gqa) return RAD_E_UNSUPPORTED;
|
||||
const int64_t kvh = nh / gqa;
|
||||
const int64_t S = 1;
|
||||
/* `ctx`, as the reference spells it -- and it is NOT the band's `max_ctx`, which is why a
|
||||
* geometry that wants a context deeper than its query chunk has to name `ctx`. When no case
|
||||
* names it, the context is the query chunk. */
|
||||
int64_t ctx = gi(p, n_p, "ctx", 0);
|
||||
if (ctx < M) ctx = M;
|
||||
const int64_t max_blocks = (ctx + bs - 1) / bs;
|
||||
|
||||
const uint32_t Q = act_dt(p, n_p);
|
||||
const uint32_t kv = rad_dtype_parse(gs(p, n_p, "kv_dtype"));
|
||||
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? Q : kv;
|
||||
|
||||
const RadOpdDesc list[] = {
|
||||
opd(Q, S * M, nh, hd), /* q */
|
||||
opd(KV, max_blocks, kvh, bs, 2 * hd), /* kv_cache */
|
||||
opd_idx(S, max_blocks, -1, 0, max_blocks), /* block_table: indexes blocks,
|
||||
may repeat -- a page table */
|
||||
opd_idx(S, 0, ctx), /* seqused: a constant, not a draw */
|
||||
opd_none(), /* k_descale: no per-(seq,head) */
|
||||
opd_none(), /* v_descale */
|
||||
opd_none(), /* cu_seqlens: the rectangular
|
||||
reading at one sequence */
|
||||
opd(Q, S * M, nh, hd) /* out */
|
||||
};
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* Exact per-row top-R. `pairs` is described because its packing is checked: an int32 id's bits in
|
||||
* the first slot beside its value, so the plane is f32 to hold the value. */
|
||||
int r3d_shape_row_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), R = gi(p, n_p, "R", 0);
|
||||
if (M <= 0 || N <= 0 || R <= 0) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const RadOpdDesc list[] = {
|
||||
opd(D, M, N), opd((uint32_t)RAD_I32, M, R), opd((uint32_t)RAD_F32, M, R),
|
||||
opd((uint32_t)RAD_F32, M, R, 2)
|
||||
}; /* x, idx, val, pairs */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
int r3d_shape_sample_argmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc list[] = {
|
||||
opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0), opd((uint32_t)RAD_I32, M)
|
||||
}; /* logits, params, token */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
int r3d_shape_sample_temp(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0) };
|
||||
R3D_PICK(list); /* logits INOUT, params */
|
||||
}
|
||||
|
||||
/* DFlash2's candidate walk, slot for slot from libref's shape hook. `cand` and `anchor` hold token
|
||||
* ids bounded by n_vocab so the codebook gather stays inside the plane, and cand/unary/hp carry one
|
||||
* row per (sequence, step), M * steps. */
|
||||
/* The gated MLP band, slot for slot from libref's shape hook: n = N/2, the weight's scales per
|
||||
* (ceil(N/group), ceil(K/group)) in **bf16** (the container's `weight_scale_inv`, which writes
|
||||
* `o.t(RAD_BF16, {nb, kb})`), the output's codes per (M, n) and its scales per (M, ceil(n/group)).
|
||||
* The row's set is fp8a8 only, group a power of two in [32, 256], no wider than n, and K a whole
|
||||
* number of groups -- a hook that describes a shape the kernel refuses is the bug class this file
|
||||
* exists to prevent. */
|
||||
int r3d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t N = gi(p, n_p, "N", 0);
|
||||
const int64_t K = gi(p, n_p, "K", 0);
|
||||
const int64_t group = gi(p, n_p, "group", 0);
|
||||
const char* q = gs(p, n_p, "dtype");
|
||||
if (!q || std::strcmp(q, "fp8a8") != 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t n = N / 2;
|
||||
if (M <= 0 || M > 64 || N <= 1 || (N & 1) || K <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
|
||||
if (group != 32 && group != 64 && group != 128 && group != 256) return RAD_E_UNSUPPORTED;
|
||||
if (group > n || (K % group)) return RAD_E_UNSUPPORTED;
|
||||
const int64_t kb = (K + group - 1) / group, nb = (N + group - 1) / group;
|
||||
const int64_t ng = (n + group - 1) / group;
|
||||
const RadOpdDesc list[] = {
|
||||
opd((uint32_t)RAD_F8E4M3, M, K), /* a */
|
||||
opd((uint32_t)RAD_F32, M, kb), /* a_scale */
|
||||
opd((uint32_t)RAD_F8E4M3, N, K), /* b: gate rows [0,n), up rows [n,N) */
|
||||
opd((uint32_t)RAD_BF16, nb, kb), /* b_scale: the container's form */
|
||||
opd((uint32_t)RAD_F8E4M3, M, n), /* q */
|
||||
opd((uint32_t)RAD_F32, M, ng), /* scale */
|
||||
opd((uint32_t)RAD_BF16, M, n), /* out_bf16, optional */
|
||||
};
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
int r3d_shape_dflash_select(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t steps = gi(p, n_p, "steps", 0);
|
||||
const int64_t K = gi(p, n_p, "top_k", 0);
|
||||
const int64_t R = gi(p, n_p, "rank", 0);
|
||||
const int64_t nv = gi(p, n_p, "n_vocab", 0);
|
||||
const int64_t astr = gi(p, n_p, "anchor_stride", 1);
|
||||
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t rows = M * steps;
|
||||
const RadOpdDesc list[] = {
|
||||
opd_idx(rows, nv, -1, 0, K), /* cand: drawn over the vocab */
|
||||
opd((uint32_t)RAD_F32, rows, K), /* unary */
|
||||
opd((uint32_t)RAD_BF16, rows, R), /* hp, absent is a plane of ones */
|
||||
opd_idx(M * astr, nv), /* anchor */
|
||||
opd((uint32_t)RAD_BF16, nv, R), /* pred */
|
||||
opd((uint32_t)RAD_BF16, nv, R), /* succ */
|
||||
opd_idx(M, nv, -1, 0, steps), /* tokens */
|
||||
};
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
int r3d_shape_sample_mask(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
/* mask_rows is M: one bitmask row a sequence is the widest the plane gets, and an
|
||||
* unconstrained row shares it with mask_row -1. A set bit is an allowed token. */
|
||||
const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, M),
|
||||
opd((uint32_t)RAD_I32, M, (nv + 31) / 32) };
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
int r3d_shape_sample_logprobs(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t k = gi(p, n_p, "k", 0);
|
||||
if (k <= 0) return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0),
|
||||
opd((uint32_t)RAD_F32, M, 2 + 2 * k) };
|
||||
R3D_PICK(list); /* logits, params, stats [M, 2+2k] */
|
||||
}
|
||||
|
||||
int r3d_shape_sample_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t nc = nv < (int64_t)kCand ? nv : (int64_t)kCand;
|
||||
const RadOpdDesc list[] = {
|
||||
opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0),
|
||||
opd((uint32_t)RAD_I32, M, nc), opd((uint32_t)RAD_F32, M, nc),
|
||||
opd((uint32_t)RAD_I32, M, 2 * nc)
|
||||
}; /* logits, params, cand_idx, cand_val (logits, not probs), pairs */
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The four narrowing stages -- top-p, min-p, typical, XTC -- in place over the candidate set.
|
||||
* The set is drawn, not sorted: the ABI has no descending fill domain, and top-p is a prefix rule
|
||||
* in candidate order, which applies equally to a random order. An implementation that sorted
|
||||
* internally would genuinely disagree with the schema. */
|
||||
int r3d_shape_narrow(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t nc = gi(p, n_p, "n_cand", 0);
|
||||
if (M <= 0 || nc <= 0) return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc list[] = { opd_idx(M, nc, -1, 0, nc), opd((uint32_t)RAD_F32, M, nc),
|
||||
opd_params(M, 0, 0) };
|
||||
R3D_PICK(list); /* cand_idx INOUT, cand_val INOUT, params */
|
||||
}
|
||||
|
||||
int r3d_shape_sample_pick(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t nc = gi(p, n_p, "n_cand", 0);
|
||||
if (M <= 0 || nc <= 0) return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc list[] = { opd_idx(M, nc, -1, 0, nc), opd((uint32_t)RAD_F32, M, nc),
|
||||
opd_params(M, 0, 0), opd((uint32_t)RAD_I32, M) };
|
||||
R3D_PICK(list); /* cand_idx, cand_val, params (seed and pos), token */
|
||||
}
|
||||
|
||||
/* Penalties and DRY: logits, params with a history window inside it, and the history itself -- real
|
||||
* token ids that repeat as text repeats. DRY's breaker plane marks about half its positions, so the
|
||||
* exemption runs as well as the penalty. */
|
||||
int r3d_shape_sample_penalties(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc list[] = {
|
||||
opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0),
|
||||
opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist)
|
||||
};
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
int r3d_shape_sample_dry(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc brk = opd_idx(M, 2, -1, 0, kHist);
|
||||
const_cast<RadOpdDesc&>(brk).dtype = (uint32_t)RAD_U8;
|
||||
const RadOpdDesc list[] = {
|
||||
opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0),
|
||||
opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist), brk
|
||||
};
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The windowed n-gram ban adds a {n, window} pair a row and an optional exemption bitmask. */
|
||||
int r3d_shape_sample_ngram_ban(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc list[] = {
|
||||
opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0),
|
||||
opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist),
|
||||
opd_idx(M, 64, -1, 0, 2),
|
||||
opd((uint32_t)RAD_I32, M, (nv + 31) / 32)
|
||||
};
|
||||
R3D_PICK(list);
|
||||
}
|
||||
|
||||
/* The four narrowing stages share the description above; the op names which predicate the kernel
|
||||
* applies, and the schema they share says the operands are the same. */
|
||||
int r3d_shape_sample_topp(const RadParam* p, int n_p, int o, RadOpdDesc* out) {
|
||||
return r3d_shape_narrow(p, n_p, o, out);
|
||||
}
|
||||
int r3d_shape_sample_minp(const RadParam* p, int n_p, int o, RadOpdDesc* out) {
|
||||
return r3d_shape_narrow(p, n_p, o, out);
|
||||
}
|
||||
int r3d_shape_sample_typical(const RadParam* p, int n_p, int o, RadOpdDesc* out) {
|
||||
return r3d_shape_narrow(p, n_p, o, out);
|
||||
}
|
||||
int r3d_shape_sample_xtc(const RadParam* p, int n_p, int o, RadOpdDesc* out) {
|
||||
return r3d_shape_narrow(p, n_p, o, out);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/* r3d_tiling.h -- the tiled rows' LDS row law, in one place.
|
||||
*
|
||||
* Every tiled row in libr3d stages an [rows x pitch] f16 tile in LDS and then reads it back two
|
||||
* elements at a time for dot2_f16x2. Two functions spell that out and they must agree exactly, so
|
||||
* they live here and the rows include this file.
|
||||
*
|
||||
* srow(row, c8, pitch) the element offset of the c8-th run of EIGHT elements of `row`
|
||||
* srow_pair(row, kc, pitch) the element offset of the pair (kc, kc+1) of `row`, kc even
|
||||
*
|
||||
* The law, and why it is shaped like this:
|
||||
*
|
||||
* - Granularity is EIGHT elements (16 bytes at f16): staging writes a uint4 a step, so the XOR has
|
||||
* to move whole uint4s and never split one. A swizzle at pair granularity would make the store
|
||||
* unaligned and the compiler would say so in bytes of spill.
|
||||
* - The XOR is with (row & 7), so eight consecutive rows rotate the runs by one slot each. That is
|
||||
* what kills the dot loop's bank conflict: a wavefront reads 32 rows at the same kc, and with the
|
||||
* rotation the 32 reads land on 32 distinct 16-byte slots instead of the four a plain row-major
|
||||
* tile puts them on.
|
||||
* - The mask (pitch / 8 - 1) keeps the rotated index INSIDE the row. pitch is in elements, so a
|
||||
* row has pitch/8 runs, and pitch/8 is a power of two for every tile in the library (32, 128).
|
||||
* Without the mask a rotated index leaves the row and reads a neighbour's, which is the bug this
|
||||
* header exists to prevent: it is silent, it is data-dependent, and it measures 30x off.
|
||||
* - srow_pair takes the pair index kc>>3 -- the run the pair lives in -- and adds (kc & 7), the
|
||||
* element inside the run. Reading pairs through srow is what keeps the store, the load and the
|
||||
* swizzle one statement each.
|
||||
*
|
||||
* Measured law, in the family's numbers: a row that stages through srow and reads through
|
||||
* srow_pair, with dot2_f16x2 accumulating into f32, lands at rel_l2 1.7e-03 against
|
||||
* ref_gemm_nt_q's body at a bf16 output (the store's ulp binding, not the fold's) with 83% of
|
||||
* outputs bit-exact. A row that gets the swizzle wrong, in either direction, lands at rel_l2 3e+01.
|
||||
*
|
||||
* Header-only, like the rest of libr3d. Include it in a .hip at file scope, before the kernels; the
|
||||
* definitions are in an unnamed namespace, so each translation unit gets its own copy -- which is
|
||||
* what the rows had before this header existed, spelled the same way, so the host pass does not see
|
||||
* an unused static and the inliner sees the same function it always did.
|
||||
*/
|
||||
#ifndef R3D_TILING_H
|
||||
#define R3D_TILING_H
|
||||
|
||||
namespace {
|
||||
|
||||
/* The element offset of run `c8` of `row`. pitch is a row's element count, a power of two. */
|
||||
__device__ __forceinline__ int srow(int row, int c8, int pitch)
|
||||
{
|
||||
return row * pitch + (((c8 ^ (row & 7)) & (pitch / 8 - 1)) << 3);
|
||||
}
|
||||
|
||||
/* The element offset of the f16 pair (kc, kc+1), kc even: the run the pair lives in, plus the
|
||||
* element's place inside that run. */
|
||||
__device__ __forceinline__ int srow_pair(int row, int kc, int pitch)
|
||||
{
|
||||
return srow(row, kc >> 3, pitch) + (kc & 7);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
#endif /* R3D_TILING_H */
|
||||
@@ -0,0 +1,926 @@
|
||||
/* r3d_vocab_bf16.hip -- the lm_head projection: `logits_gemm`, and the same tiling under `gemm_nt`
|
||||
* at prefill sizes.
|
||||
*
|
||||
* y[M,N] = x[M,K] @ w[N,K]^T, f32 accumulate, k ascending.
|
||||
*
|
||||
* `logits_gemm` spells N and K as n_vocab and n_embd and its y is **f32**: the schema says so
|
||||
* (`ref_logits_gemm_shape` writes `o.t(RAD_F32, {M, nv})`, "f32 logits, as every sampler stage reads
|
||||
* them"), and none of those stages wants a bf16 logit. `gemm_nt` is the same arithmetic with a bf16
|
||||
* y, narrowed once by the store. Both entries are the same two kernels; `YF32` is the only
|
||||
* difference in the code and the only difference in what the board has to report.
|
||||
*
|
||||
* ---- why this row exists ------------------------------------------------------------------------
|
||||
*
|
||||
* The probe of the served checkpoint refuses exactly one op: `logits_gemm`. libref's
|
||||
* `ref_logits_gemm` is
|
||||
* `gemm_nt_impl(a, false, "n_vocab", "n_embd")` on 32 OpenMP threads: 1.1 TFLOP for the band's shape
|
||||
* (M=2048, n_vocab=130560, n_embd=2048), which this card does in about a second and the CPU in
|
||||
* tens. For decode it is the 535 MB vocabulary head read once a token -- one call per token, the
|
||||
* head the model cannot answer without. This row is not a speed decision. It is
|
||||
* a read of the container's own form, and the head is stored in two of them: bf16 plain, with
|
||||
* `layout`, `relayout` and `unrelayout` all null; and E4M3 codes with a bf16 scale per 128x128 block
|
||||
* as two planes of one `rad.planes` container, which is the form the served checkpoint ships and
|
||||
* which is answered by `r3d_layout_logits_head`, this file's transcription of `ref_layout_head`.
|
||||
* Nothing is repacked in either case, and no operand description is declined.
|
||||
*
|
||||
* ---- the prefill arm (M > 16) -------------------------------------------------------------------
|
||||
*
|
||||
* A block is TM x TN = 128 x 128 outputs, 256 threads, eight waves, eight outputs a side a lane: 64
|
||||
* f32 accumulators a lane, grid (N/TN) x (M/TM). Lane `tid` owns rows m0 + (tid/16)*8 .. +7 by
|
||||
* columns n0 + (tid%16)*8 .. +7, so its 64 outputs are one 8x8 square of the tile and its stores are
|
||||
* 32-byte runs of f32 (16-byte runs of bf16).
|
||||
*
|
||||
* k is walked in KC = 32 code chunks. Both tiles are stored row-major in f16 -- a row is the 32
|
||||
* k-values of one m, 64 bytes -- because the global load that fills them is 8 contiguous k of one
|
||||
* row: one `uint4` a thread, sixteen bytes, widened on the way in by four `bf16x2_to_f16x2`, which
|
||||
* is exact for everything f16 can hold (bf16 has eight mantissa bits, f16 ten) and arrives as an inf
|
||||
* for what it cannot, which the board counts rather than assumes away. The compute then reads those
|
||||
* 64-byte rows in f16x2 pairs: eight activation pairs and eight weight pairs per two codes,
|
||||
* sixty-four `fdot2` per two codes -- one pair-dot per output per two codes, 16 LDS reads against
|
||||
* 64 dots.
|
||||
*
|
||||
* The tile pitch is KC elements and the rows are XOR-swizzled in eight-element units, which is the
|
||||
* only arrangement that satisfies both ends at once. The staging store is a `uint4`, so a row's
|
||||
* chunk offset has to stay a multiple of eight elements; an unswizzled 64-byte row stride puts all
|
||||
* eight rows a lane reads on the same bank, 32-way. `srow` moves whole eight-element chunks by
|
||||
* `row & 7`, which preserves the 16-byte alignment and brings the compute reads to two-way. Two-way
|
||||
* and not conflict-free: the eight rows a lane owns sit at stride eight, so a period-8 swizzle
|
||||
* repeats inside a lane's own set. The cost is 512 LDS cycles a block-chunk against 2048 of
|
||||
* dots, a quarter, which is what the vectorised staging store buys.
|
||||
*
|
||||
* At the band, M=2048 n_vocab=130560 n_embd=2048, 16 x 1020 blocks of 256 threads:
|
||||
* 272.24 ms = 4023 GFLOP/s, which is 37% of the 10.8 TFLOP/s this card's 32 CUs do dense f16 with
|
||||
* f32 accumulate. At M=46 -- one tile row, 1020 blocks -- the same kernel does 16.64 ms =
|
||||
* 1478 GFLOP/s, and the shortfall is the shape, not the kernel: 46 rows against a 128-row tile
|
||||
* leaves 5/8 of every block's arithmetic idle. The host row for this op is `ref_logits_gemm`: 1.1
|
||||
* TFLOP per forward pass across the whole vocabulary, on OpenMP threads; this row is the card's
|
||||
* answer to that comparison.
|
||||
*
|
||||
* ---- the decode arm (M <= 16) -------------------------------------------------------------------
|
||||
*
|
||||
* The prefill tile reads the head M/TM times; at M=1 it would read 127/128 of it for nothing. At
|
||||
* M <= 16 the block is the decode shape `r3d_gemm_bf16_nt_m16.hip` uses: a wave is MT activation
|
||||
* rows by 32/MT weight rows, lane l owns (m = l % MT, n = n0 + l / MT), one accumulator a lane from
|
||||
* k=0 to K, and no wave reduction anywhere -- so each output's sum is the reference's ascending
|
||||
* chain, summand for summand, in the pair-dot's grouping. The activation arrives in 128-code chunks
|
||||
* and stays in LDS for the chunk (MT x 128 f16, 4 KiB at MT=16, the same eight-element swizzle at
|
||||
* the wider pitch); the weight goes straight from global to registers in 16-byte loads, eight codes
|
||||
* at a time, widened where it lands. A wave keeps 32/MT weight rows in flight -- 4 KiB at MT=1 --
|
||||
* which is what makes 16-byte strided reads across rows cost what they fetch. `nt=1` asks for
|
||||
* non-temporal head loads, the honest hint for bytes read once a token; on this card it is worth
|
||||
* nothing: 3.316 ms against 3.290 ms at M=1, 0.8% the other way. It is implemented
|
||||
* because the ABI names it, and left off by default because the number says to.
|
||||
*
|
||||
* At n_vocab = 130560, n_embd = 2048 the arm is M = 1 in 3.226 ms = 166 GB/s of head, and M = 16 in
|
||||
* 8.151 ms = 1050 GFLOP/s, 66 GB/s of bytes. The w2a8 row's 22 GB/s is not this arm's bound: it is
|
||||
* that kernel's own limit -- an ALU-bound pair-dot with one 16-byte weight load per 64 codes -- and
|
||||
* the card's DRAM is 256 GB/s. This arm is the streaming shape, 16 bytes a lane a step with the
|
||||
* activation in LDS, and it runs at two thirds of the card.
|
||||
*
|
||||
* So the bf16 head costs 3.23 ms per decode token, and M = 16 (a speculative verify) costs 0.51 ms
|
||||
* a token. The quantised head is the same op in half the bytes: the codes are 130560 x 2048 =
|
||||
* 267,386,880 bytes (255.0 MiB) and the scales 1020 x 16 bf16 = 32,640 bytes (31.9 KiB), so a decode
|
||||
* reads 255.03 MiB where the bf16 head reads 510.0 MiB. At the 163 GB/s this row's bf16 arm runs at
|
||||
* the floor that is 1.64 ms a token, and at the card's 256 GB/s, 1.04 ms. (The 66.8 MB figure is the
|
||||
* w2a8 row's 2-bit grid, a different head form.) Every number below says which of the three
|
||||
* placements the bytes were in, because the placement is worth more than anything in the kernel, and
|
||||
* all three are on this page so the choice between the head's forms is made on measurement.
|
||||
*
|
||||
* ---- the accumulation, and what it is exact against ---------------------------------------------
|
||||
*
|
||||
* libref's law per output is `acc += a*b` over ascending k from zero, and for this op with no bias.
|
||||
* One accumulator per output, k ascending, no reassociation across lanes, in both arms. The pair-dot
|
||||
* folds two products into the accumulator per step (`acc + a0*b0 + a1*b1` in one rounding) where the
|
||||
* reference rounds each product in, so the sums agree closely and are not bit-equal. f32 output,
|
||||
* K = 2048: rel_l2 1.77e-06 against the reference's law, identical -- 1.77e-06, to the
|
||||
* digits -- against the same law with the operands widened to f16 first, so the widening
|
||||
* contributes nothing and the fusion is the whole of it. 1.77e-06 is about 30
|
||||
* f32 ulps on a sum of 2048 terms, and a random walk of one rounding per 1024 steps predicts
|
||||
* sqrt(1024) * 6e-8 = 1e-6, which is where it lands. At K = 320 it is 2.0e-07, which scales the same
|
||||
* way. What it means for the sampler: the head's bf16 values carry 4.9e-4 of quantisation each, so
|
||||
* this is 300x finer than the input, and a top-k decision flips only on a tie tighter than 1e-6.
|
||||
*
|
||||
* Nothing here is integer arithmetic, so the v_fdot2_f32_f16 mantissa rule that bounds
|
||||
* r3d_gemm_nt_q_w2a8.hip does not bite: the products are not integers, so there is no 2^20 wall, and
|
||||
* the board's tail is ordinary rounding, counted with the plane pre-filled at 0x7fc0 -- no non-finite
|
||||
* output at any size, including the 268-million-output band.
|
||||
*
|
||||
* ---- the head's stored form, and who answers it ---------------------------------------------------
|
||||
*
|
||||
* The band's `dtype=bf16` is the ACTIVATION's dtype. The head is quantised: the graph reads
|
||||
* 'output.weight' as two planes of fp8_e4m3 * bf16[128x128], and the mapped tier reads the
|
||||
* container where it lies, and its stored form is not the container's (rad.planes). The placement
|
||||
* needs a reader for the head's stored form, and a layout hook is what a reader is. So:
|
||||
*
|
||||
* r3d_layout_logits_head (operand 1 -- `ref_layout_head` is `layout_scaled(operand, 1, -1, ...)`)
|
||||
* tag `rad.planes`; codes E4M3 (libref's `scaled_rows` also admits int8) with a float scale --
|
||||
* bf16, f16 or f32 -- on a block of {128, 128} (`R3D_FP8_BLOCK`); ends in `rad_planes_layout`.
|
||||
* It moves no byte and `relayout` stays null. `ref_layout_head` is libref-internal-static, so
|
||||
* its body, and `layout_scaled`'s, and `enc_scaled_rows`' and `float_scale_dt`' with it, are
|
||||
* transcribed here as the w2a8 hook transcribed `ref_layout_gemm_q`: checks and their order,
|
||||
* unchanged. Two fields are worth naming: `rad_enc_is`
|
||||
* compares `scheme`, and `transform` is the optional pre-transform. The
|
||||
* encoding is affine with an EMPTY transform; a fixture that writes "affine" into `transform`
|
||||
* makes the hook decline every head.
|
||||
*
|
||||
* The law. `ScaledRows::at(r, c) = codes.at(r, c) * scale.cover(r, c)`: the code widened exactly,
|
||||
* multiplied by the scale covering it, one f32 rounding, then the plain ascending-k GEMM in f32.
|
||||
* The widening is exact both ways -- E4M3 is 4 exponent and 3 mantissa bits, f16 is 5 and 10, and
|
||||
* int8 lands in f16 whole -- so the codes reach the dot as the numbers the checkpoint means, and
|
||||
* the only divergence stays the dot's fused rounding: rel_l2 2.77e-04 at M=1, K=2048,
|
||||
* which is one f16 ulp's worth (2^-12 = 2.44e-04) and is the fold, not the dot; against the fold
|
||||
* law, below, it is 4.5e-06, and `<=2 ulps` is 1.000 with `>6 ulps` 0 at every size,
|
||||
* 268-million-output band included. y stays f32: logits are f32 and the reference's store is f32.
|
||||
*
|
||||
* The fold, and the hardware rule it obeys. The reference dequantises each element into f32; the
|
||||
* tile is f16, so the scale enters as a f16 multiply at staging -- the tiled arm once per staged
|
||||
* 8-column group, the decode arm once per 128-code chunk, and a chunk of 32 sits inside one
|
||||
* 128-column block (128 % 32 == 0, 128 % 128 == 0), so one scale per staged row. That costs no
|
||||
* registers: the prefill arm is the register file's at 237 VGPRs, and per-k-block partials would
|
||||
* need 64 more accumulators and spill. The multiply must be a hardware f16 multiply
|
||||
* (`v_mul_f16`, round to nearest, subnormals kept), not `f16x2_pack`: that builtin is
|
||||
* `v_cvt_pkrtz_f16_f32`, ROUNDS TOWARD ZERO, and r3d_codecs.h says so and says to call it only
|
||||
* with values f16 already represents exactly. A folded weight is not one of those -- code 431 by
|
||||
* a scale of 4.5e-5 is eleven significant bits -- and a toward-zero packer biases every product
|
||||
* toward zero and flushes the subnormal end: rel_l2 2.8e-04 against the fold law with only 0.53 of
|
||||
* outputs within 2 ulps. The f16 multiply is one rounding in the right direction and one
|
||||
* instruction: 4.5e-06 and 1.000. The number and the verdict: 2.77e-04 against the reference's
|
||||
* exact law is the fold's cost, 250x finer than the E4M3 code's own quantum (2^-4 = 6.25e-2), so
|
||||
* the fold does not move the logits by anything the quantisation did not already move. An f32
|
||||
* scale plane costs one more rounding (the scale to f16, 1.75e-04 against a model that folds
|
||||
* after the multiply); the shipped form's bf16 scale is f16-exact and pays nothing.
|
||||
*
|
||||
* With the head's bytes where the engine would put them (VRAM, with the header page
|
||||
* read by the shim on the host): prefill M=2048 in 325.06 ms = 3369 GFLOP/s against the bf16 head's
|
||||
* 269.31 ms = 4067 -- 17% slower, all of it staging, and the case for the quantised head at prefill
|
||||
* is the 255 MiB of weight traffic, not the FLOPs. M=46: 22.43 ms = 0.488 ms a token against
|
||||
* 0.361. Decode M=1: 13.603 ms a token, 19.7 GB/s of codes, 8x above the 1.64 ms floor, and the
|
||||
* cause is the E4M3 decoder. `__builtin_amdgcn_cvt_pk_f16_fp8` exists in clang and expands
|
||||
* to software on gfx1102 -- zero `v_cvt_pk_f16_fp8` in the ISA -- so eight codes cost
|
||||
* ~100 instructions of `e4m3_to_f32` against the bf16 arm's four, and the arm is ALU-bound. The
|
||||
* fix has a size: a 256-entry f16 table in LDS is 512 bytes, 8 LDS reads a staged group against
|
||||
* ~100 ALU, which puts the arm back near its floor; that is a tiling pass, not this row's work.
|
||||
* The speculation block is where the form already pays: M=8 (7 drafts + 1) reads the head ONCE and
|
||||
* costs 21.67 ms = 2.708 ms a token, 5x cheaper per token than M=1 on the same kernel.
|
||||
*
|
||||
* Where the bytes live, on this box, at M=1: in VRAM 13.6 ms; on the mapped tier
|
||||
* (hipHostMalloc, read over PCIe by 8-byte strided loads) 643 ms a token; managed and left alone
|
||||
* 2071 ms a token, 122 MB/s, because managed pages do not migrate for a read-mostly device access
|
||||
* on this ROCm and the kernel faults page by page. The head is placed on
|
||||
* the mapped tier. A hook makes that placement legal; it does not make it fast, and these three
|
||||
* numbers are the argument for uploading the head. The board takes the timed number after
|
||||
* `hipMemPrefetchAsync` and says so on every line.
|
||||
*
|
||||
* Both forms are served, chosen by the header: `rad_planes_header(w)` at the shim's head branch
|
||||
* dispatches on it, and a plain bf16 operand goes down the bf16 path untouched. The choice is
|
||||
* the container's, not the row's. The shim reads the container's header
|
||||
* (which is why the operand's bytes must be host-readable: `scaled_rows()` does the same host read,
|
||||
* so this is the engine's convention, not this row's invention); the kernel reads the same bytes on
|
||||
* the card, so the fixture is hipMallocManaged + prefetch, or hipHostMalloc, never plain malloc --
|
||||
* plain malloc faults 700 on the kernel's first read.
|
||||
*
|
||||
* ---- the decoder is a table, and what the table moved --------------------------------------------
|
||||
*
|
||||
* r3d_fp8_dequant.h replaces the E4M3 codec with a 256-entry f16 table in LDS (512 bytes, eight
|
||||
* reads an eight-code group) because clang lists __builtin_amdgcn_cvt_pk_f16_fp8 for gfx1102 and a
|
||||
* build that calls it contains ZERO v_cvt_pk_f16_fp8: the builtin is software here. The A/B is one
|
||||
* source built twice (-DR3D_NO_E4M3_TBL selects the codec), same fixture, same seed:
|
||||
*
|
||||
* M=8 speculation 2.500 -> 0.924 ms/token (20.002 -> 7.395 ms) 2.70x THE WIN
|
||||
* M=2048 prefill 323.978 -> 322.661 ms (3380 -> 3394 GFLOP/s) flat, -0.4%
|
||||
* M=1 decode 12.999 -> 13.293 ms/token (20.6 -> 20.2 GB/s) NOT moved, 2.3% worse
|
||||
* M=46 prefill 21.603 -> 21.792 ms (1139 -> 1129 GFLOP/s) flat
|
||||
*
|
||||
* The table is exact by construction -- the codec, evaluated once per bit pattern at block start --
|
||||
* and rel_l2 is bit-identical between the two binaries (2.770e-04 vs the fold law / 4.452e-06 vs the
|
||||
* fold model at prefill; 2.758e-04 / 4.559e-06 at M=1), which is the check that the swap moved work
|
||||
* and not arithmetic. It is a 2.70x win where the decoder was the binding resource (MT=8: four
|
||||
* decodes and four folds a lane per eight codes, no memory wall in reach) and a NAMED NON-RESULT at
|
||||
* M=1: 13 ms at 20 GB/s of codes is 8x off the 1.64 ms floor this row's own 163 GB/s implies, and
|
||||
* removing ~100 ALU instructions an eight-code group does not move it. The suspect at M=1 is the
|
||||
* load width -- eight codes a lane through an 8-byte load, where the bf16 arm takes sixteen bytes a
|
||||
* lane and streams at 163 GB/s -- so the shape to try there is a 16-byte code load (16 codes, eight
|
||||
* pairs, half the wavefronts), not more ALU. 44 kernels, all vgpr_spill_count: 0, both builds.
|
||||
*
|
||||
* ---- what is refused, and where ------------------------------------------------------------------
|
||||
*
|
||||
* sk > 1: the grid is vocab-wide at every M -- 1020 blocks in x at the band for the prefill arm,
|
||||
* 8160 for the decode arm at MT=16 -- so no shape this row serves is short of parallelism, and a
|
||||
* split would buy a second kernel and a documented order change for nothing. kb: KC = 32 only; a
|
||||
* tile pitched at anything else is a different swizzle, not a knob, and the launcher enumerates the
|
||||
* values it accepts and refuses the rest. K not a multiple of KC, an x pitch not a multiple of 8, a
|
||||
* y pitch not a multiple of 4 (f32) or 8 (bf16), a weight that is not contiguous, and quantised
|
||||
* heads that are not this form. The head branch, in its order:
|
||||
* a quantised head on the bf16-y row -- logits are f32; the tiled row keeps a bf16 head
|
||||
* a `zero` plane on the head -- codes+scale+zero is gemm_nt_q's asymmetric grid, and the row
|
||||
* that reads it is r3d_gemm_nt_q_w2a8.hip; that is w2a8's grid, not this op
|
||||
* a joined operand that is not two planes
|
||||
* a joined head whose planes are not codes + scale (a `table`, a `bias`: names it)
|
||||
* codes tiled by anything but one code a cell
|
||||
* sub-byte codes (4-bit: w4a16's ground, and the row that reads it is w2a8's neighbour)
|
||||
* e5m2 and every other code dtype: no decoder here
|
||||
* a scale plane that is a table, not a tiling
|
||||
* an integer scale: not float_scale_dt's set
|
||||
* a scale block that is not 128x128 -- per-(row, group) scales are gemm_nt_q's grid, and a
|
||||
* per-row scale is a different indexing of the plane than ScaledRows::cover is
|
||||
* a plane that does not cover the band (codes must be N x K, scales ceil(N/128) x
|
||||
* ceil(K/128)); a plane whose row_bytes is shorter than its row
|
||||
* and the bf16 branch's: a plain head that is not bf16, x and y dtypes,
|
||||
* no axes, pitches, the head's numel and contiguity, absurd shapes,
|
||||
* alignment, sk > 1. The launcher's own: a head with a null plane, a dtype
|
||||
* outside the served set, a row pitch a vector load cannot walk (a 16-bit scale row is 2
|
||||
* bytes a column, so K = 320 -- 3 scale columns, 6 bytes -- is legal), addresses.
|
||||
* 24 refusals, 24 as stated, and the hook's two served encodings answer RAD_OK with
|
||||
* tag `rad.planes` and the codes' dtype.
|
||||
*/
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_codecs.h"
|
||||
#include "r3d_fp8_dequant.h" /* the E4M3 -> f16 table: 512 bytes of LDS for ~100 ALU a group */
|
||||
#include "r3d_tiling.h" /* the LDS row law: srow, srow_pair */
|
||||
#include "r3d_args.h"
|
||||
#include "r3d_launch.h"
|
||||
|
||||
#include "rad_planes.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kBlockThreads = 256;
|
||||
constexpr int kWaves = kBlockThreads / kWave; /* 8 */
|
||||
constexpr int kTM = 128; /* activation rows a block */
|
||||
constexpr int kTN = 128; /* weight rows a block */
|
||||
constexpr int kKC = 32; /* codes a tile step */
|
||||
constexpr int kSkinnyMax = 16; /* the MT ceiling of the decode arm */
|
||||
constexpr int kChunkK = 128; /* the decode arm's activation chunk */
|
||||
|
||||
#if defined(__has_builtin)
|
||||
# if __has_builtin(__builtin_nontemporal_load)
|
||||
# define R3D_HAS_NT 1
|
||||
# endif
|
||||
#endif
|
||||
#ifndef R3D_HAS_NT
|
||||
# define R3D_HAS_NT 0
|
||||
#endif
|
||||
|
||||
/* The tile address, in f16 elements: `pitch`-wide rows whose eight-element chunks are XORed by the
|
||||
* row's low bits. Multiples of eight in, so a uint4 store and an f16x2 read are both aligned by
|
||||
* construction, at both pitches this file uses (32 and 128). */
|
||||
/* srow / srow_pair: r3d_tiling.h, the family's law in one place. */
|
||||
|
||||
/* Eight bf16 -> eight f16, exact for every value f16 can hold. */
|
||||
__device__ __forceinline__ uint4 widen8(uint4 w)
|
||||
{
|
||||
return make_uint4(bf16x2_to_f16x2(w.x), bf16x2_to_f16x2(w.y), bf16x2_to_f16x2(w.z),
|
||||
bf16x2_to_f16x2(w.w));
|
||||
}
|
||||
|
||||
constexpr int kFp8Block = 128; /* the head's scale block: R3D_FP8_BLOCK, llama_dense_fp8 */
|
||||
|
||||
/* The head as the container stores it: E4M3 codes with one float scale per (128 x 128) block.
|
||||
* Passed by value; every pointer in it is a device address, resolved by the shim out of the joined
|
||||
* bytes (rad_planes_find), which is what a layout hook's absence asks of a kernel -- the container's
|
||||
* own form, read where it lies, no byte moved. */
|
||||
struct HeadQ {
|
||||
const uint8_t* codes; /* [N][K] */
|
||||
const uint8_t* scale; /* [ceil(N/128)][ceil(K/128)] */
|
||||
long long code_row; /* bytes a codes row: the plane's row_bytes, not K's element count */
|
||||
long long scale_row; /* bytes a scale row */
|
||||
int sdt; /* the scale's dtype: 0 bf16, 1 f16, 2 f32 (float_scale_dt's set) */
|
||||
int cdt; /* the codes' dtype: 0 E4M3, 1 int8 */
|
||||
};
|
||||
|
||||
/* The scale covering logical (n, k): `scale.cover` from the reference's ScaledRows, one scalar load a
|
||||
* row a chunk. The plane is 32 KiB at the band, so it is in cache from the first block that touches
|
||||
* a row and the load is not the traffic; the codes are. */
|
||||
__device__ __forceinline__ float scale_at(const HeadQ h, int n, int k)
|
||||
{
|
||||
const uint8_t* p = h.scale + (long long)(n >> 7) * h.scale_row
|
||||
+ (long long)(k >> 7) * (h.sdt == 2 ? 4 : 2);
|
||||
if (h.sdt == 2) { float f; __builtin_memcpy(&f, p, 4); return f; }
|
||||
const uint16_t u = *(const uint16_t*)p;
|
||||
return h.sdt == 1 ? f16_to_f32(u) : bf16_to_f32(u);
|
||||
}
|
||||
|
||||
/* Eight codes -> eight f16, exact. E4M3 is four exponent and three mantissa bits and f16 is five and
|
||||
* ten, and int8 lands in f16 whole, so the decoder is a widening, not a rounding: the numbers the
|
||||
* checkpoint means are the numbers multiplied (r3d_gemm_fp8a16_nt_m1.hip says the same about the
|
||||
* same codec). e4m3x2_to_f16x2 decodes the two codes in a dword's LOW half, so the pairs straddle
|
||||
* dwords: two dwords in, four pairs out. Feeding it whole dwords decodes eight codes and leaves the
|
||||
* rest of the step multiplying registers that were never written -- the shape the sibling unit
|
||||
* documents, and the reason this helper takes the pair the way it does. */
|
||||
#if defined(__has_builtin)
|
||||
# if __has_builtin(__builtin_amdgcn_cvt_pk_f16_fp8)
|
||||
# define R3D_HAS_FP8CVT 1 /* gfx11+: v_cvt_pk_f16_fp8, two codes to two f16, one instruction */
|
||||
# endif
|
||||
#endif
|
||||
#ifndef R3D_HAS_FP8CVT
|
||||
# define R3D_HAS_FP8CVT 0
|
||||
#endif
|
||||
|
||||
__device__ __forceinline__ uint32_t cvt_pk_f16_fp8(uint32_t b)
|
||||
{
|
||||
#if R3D_HAS_FP8CVT
|
||||
return __builtin_bit_cast(uint32_t, __builtin_amdgcn_cvt_pk_f16_fp8(b));
|
||||
#else
|
||||
return f16x2_pack(e4m3_to_f32((uint8_t)(b & 0xffu)), e4m3_to_f32((uint8_t)((b >> 8) & 0xffu)));
|
||||
#endif
|
||||
}
|
||||
|
||||
__device__ __forceinline__ void codes8_to_f16x4(const uint2 c, int cdt, const uint16_t* tbl,
|
||||
uint32_t* w)
|
||||
{
|
||||
const uint32_t d[2] = { c.x, c.y };
|
||||
if (tbl && !cdt) {
|
||||
/* The table: eight LDS reads for eight codes. Exact by construction -- the table is built
|
||||
* from the codec below, one entry per bit pattern -- so a row's numbers do not move; what
|
||||
* moves is where the work happens. r3d_fp8_dequant.h carries the reason and the measurement.
|
||||
* Passing null tbl asks for the codec, which is how the board A/Bs the two in one binary. */
|
||||
r3d_e4m3x8_ld(tbl, c, w);
|
||||
return;
|
||||
}
|
||||
if (!cdt) {
|
||||
/* The instruction this wants: two codes to two f16, one op. clang has the builtin on this
|
||||
* target's list and gfx1102 does not have the instruction: the ISA of this build contains
|
||||
* zero v_cvt_pk_f16_fp8, so the builtin expands to the software decode below and
|
||||
* eight codes cost ~100 instructions of exponent work. At M=1: 19.7 GB/s of codes,
|
||||
* 8x above the 1.64 ms floor, ALU-bound. The builtin stays because it says what the operation
|
||||
* is and a card with the instruction gets it for free; the fix for THIS card is a 256-entry
|
||||
* f16 table in LDS, 512 bytes, 8 LDS reads where the ~100 ALU are, which is a tiling pass. */
|
||||
w[0] = cvt_pk_f16_fp8(d[0]);
|
||||
w[1] = cvt_pk_f16_fp8(d[0] >> 16);
|
||||
w[2] = cvt_pk_f16_fp8(d[1]);
|
||||
w[3] = cvt_pk_f16_fp8(d[1] >> 16);
|
||||
return;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
const uint32_t pair = (d[j >> 1] >> (16 * (j & 1))) & 0xffffu;
|
||||
w[j] = i8x2_to_f16x2(pair);
|
||||
}
|
||||
}
|
||||
|
||||
/* The fold: the decoded code times the scale covering it, in f16 pairs.
|
||||
*
|
||||
* The reference dequantises per element into f32 (`ScaledRows::at` = code * scale, one rounding) and
|
||||
* then multiplies. Folding into the staged f16 costs one f16 rounding per weight -- half an ulp,
|
||||
* 2.4e-4 relative, on a code whose own quantum is 2^-4 = 6.3e-2, a factor of 250. It buys the whole
|
||||
* structure: the tile stays f16, the dot loop is untouched, the accumulators do not double, and the
|
||||
* register file, which is the tightest thing in the prefill arm at 237 VGPRs, does not move. The
|
||||
* alternative -- a per-block partial summed separately and scaled -- needs 64 more accumulators and
|
||||
* spills. The number the board prints is this fold's. */
|
||||
__device__ __forceinline__ uint32_t scale_pair(uint32_t w, float sc)
|
||||
{
|
||||
#if defined(__HIP_DEVICE_COMPILE__)
|
||||
/* One f16 multiply, hardware, round-to-nearest.
|
||||
*
|
||||
* It is NOT f16x2_pack of an f32 product: that builtin is v_cvt_pkrtz_f16_f32, rounds toward
|
||||
* zero, and r3d_codecs.h says out loud to call it only with values f16 already represents
|
||||
* exactly. A folded weight is not one of those -- code 431 times a scale of 4.5e-5 is a product
|
||||
* with eleven significant bits -- so the packer truncates, and truncation is a bias: every
|
||||
* product moves toward zero, and it shows as rel_l2 2.8e-04 (half an f16 ulp, the
|
||||
* whole of it) with the subnormal end flushed to zero on top. F16 arithmetic is one v_mul_f16
|
||||
* an element and rounds the way the reference's f32 multiply rounds.
|
||||
*/
|
||||
const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16);
|
||||
const _Float16 a = __builtin_bit_cast(_Float16, lo16);
|
||||
const _Float16 b = __builtin_bit_cast(_Float16, hi16);
|
||||
const _Float16 s = (_Float16)sc; /* f32 -> f16, round to nearest even */
|
||||
const _Float16 rl = a * s, rh = b * s; /* v_mul_f16: one rounding, subnormals kept */
|
||||
return (uint32_t)__builtin_bit_cast(uint16_t, rl) |
|
||||
((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16);
|
||||
#else
|
||||
return (uint32_t)f32_to_f16(f16_to_f32((uint16_t)(w & 0xffffu)) * sc) |
|
||||
((uint32_t)f32_to_f16(f16_to_f32((uint16_t)(w >> 16)) * sc) << 16);
|
||||
#endif
|
||||
}
|
||||
|
||||
/* The head's 16-byte load, ordinary or streamed-once. */
|
||||
template <int NT>
|
||||
__device__ __forceinline__ uint4 loadw8(const uint16_t* p)
|
||||
{
|
||||
#if R3D_HAS_NT
|
||||
if (NT) {
|
||||
/* The builtin wants a native vector, not HIP's class: four unsigned ints, bit-cast. */
|
||||
typedef unsigned int v4u __attribute__((ext_vector_type(4)));
|
||||
const v4u t = __builtin_nontemporal_load((const v4u*)p);
|
||||
uint4 r;
|
||||
__builtin_memcpy(&r, &t, 16);
|
||||
return r;
|
||||
}
|
||||
#else
|
||||
(void)NT;
|
||||
#endif
|
||||
return *(const uint4*)p;
|
||||
}
|
||||
|
||||
/* Eight codes, the quantised head's 8-byte load, ordinary or streamed-once: the same builtin
|
||||
* requirement as the 16-byte one, a native vector. Half the bytes of the bf16 head is the whole
|
||||
* point of the form, and it is the load that changes. */
|
||||
template <int NT>
|
||||
__device__ __forceinline__ uint2 loadc8(const uint8_t* p)
|
||||
{
|
||||
#if R3D_HAS_NT
|
||||
if (NT) {
|
||||
typedef unsigned int v2u __attribute__((ext_vector_type(2)));
|
||||
const v2u t = __builtin_nontemporal_load((const v2u*)p);
|
||||
uint2 r;
|
||||
__builtin_memcpy(&r, &t, 8);
|
||||
return r;
|
||||
}
|
||||
#else
|
||||
(void)NT;
|
||||
#endif
|
||||
return *(const uint2*)p;
|
||||
}
|
||||
|
||||
/* ============================================================ the prefill arm, M > 16
|
||||
*
|
||||
* y is f32 for logits_gemm and bf16 for gemm_nt; `YF32` is that choice, and it is the only one.
|
||||
*/
|
||||
template <bool YF32, bool WQ>
|
||||
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
|
||||
gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, HeadQ h,
|
||||
void* __restrict__ y, int M, int N, int K, int a_ld, int y_ld)
|
||||
{
|
||||
(void)b; /* the plain head; WQ reads the container through h */
|
||||
__shared__ __align__(16) uint16_t sA[kTM * kKC]; /* f16, TM rows x KC, swizzled */
|
||||
__shared__ __align__(16) uint16_t sB[kTN * kKC]; /* f16, TN rows x KC, swizzled */
|
||||
|
||||
const int tid = (int)threadIdx.x;
|
||||
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; /* the E4M3 decoder, 512 bytes */
|
||||
#ifndef R3D_NO_E4M3_TBL
|
||||
if (WQ) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* fills, then the barrier it holds */
|
||||
const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr;
|
||||
#else
|
||||
(void)sTbl; /* the board's A/B: the codec, unbuilt */
|
||||
const uint16_t* const r3d_tbl = (const uint16_t*)nullptr;
|
||||
#endif
|
||||
const int m0 = (int)blockIdx.y * kTM;
|
||||
const int n0 = (int)blockIdx.x * kTN;
|
||||
const int rg = tid >> 4, cg = tid & 15; /* this lane's 8x8 square */
|
||||
|
||||
float acc[8][8];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) acc[i][j] = 0.0f;
|
||||
|
||||
const int m_r = m0 + rg * 8, n_c = n0 + cg * 8;
|
||||
|
||||
for (int k0 = 0; k0 < K; k0 += kKC) {
|
||||
/* Stage 128 rows x 4 chunks of eight a side: one uint4 a thread a side, two a side. Rows
|
||||
* past M and codes past K stage as zeros, which is the clamping a ragged tail needs, keeps
|
||||
* the loads straight-line and contributes nothing to a sum. */
|
||||
#pragma unroll
|
||||
for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) {
|
||||
const int mm = j / (kKC / 8), c8 = j % (kKC / 8);
|
||||
const int m = m0 + mm, k = k0 + c8 * 8;
|
||||
uint4 w = make_uint4(0, 0, 0, 0);
|
||||
if (m < M && k < K) w = *(const uint4*)(a + (long long)m * a_ld + k);
|
||||
*(uint4*)&sA[srow(mm, c8, kKC)] = widen8(w);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = tid; j < kTN * (kKC / 8); j += kBlockThreads) {
|
||||
const int nn = j / (kKC / 8), c8 = j % (kKC / 8);
|
||||
const int n = n0 + nn, k = k0 + c8 * 8;
|
||||
uint4 staged = make_uint4(0, 0, 0, 0);
|
||||
if (n < N && k < K) {
|
||||
if (WQ) {
|
||||
/* Eight codes, one scale: a group of 8 sits inside one 128-column block, so
|
||||
* the whole staged run shares the scale, and the tile's 32-code chunk sits
|
||||
* inside one block too (128 % 32 == 0). The scale indexes the tile's row, not
|
||||
* the lane's: the plane is (n-block, k-block), and this row is n. */
|
||||
const uint2 c = *(const uint2*)(h.codes + (long long)n * h.code_row + k);
|
||||
uint32_t w[4];
|
||||
codes8_to_f16x4(c, h.cdt, r3d_tbl, w);
|
||||
const float sc = scale_at(h, n, k);
|
||||
staged = make_uint4(scale_pair(w[0], sc), scale_pair(w[1], sc),
|
||||
scale_pair(w[2], sc), scale_pair(w[3], sc));
|
||||
} else {
|
||||
staged = widen8(*(const uint4*)(b + (long long)n * K + k));
|
||||
}
|
||||
}
|
||||
*(uint4*)&sB[srow(nn, c8, kKC)] = staged;
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
#pragma unroll
|
||||
for (int kc = 0; kc < kKC; kc += 2) {
|
||||
uint32_t af[8], bf[8];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i)
|
||||
af[i] = *(const uint32_t*)&sA[srow_pair(rg * 8 + i, kc, kKC)];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j)
|
||||
bf[j] = *(const uint32_t*)&sB[srow_pair(cg * 8 + j, kc, kKC)];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
/* The store, eight columns at a time: 32 bytes of f32, 16 of bf16. Guarded row by row, so a
|
||||
* ragged M writes nothing and a ragged N writes whole runs of columns it owns. */
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const int m = m_r + i;
|
||||
if (m >= M) break;
|
||||
if (n_c + 8 <= N) {
|
||||
if (YF32) {
|
||||
float* row = (float*)y + (long long)m * y_ld;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; j += 4)
|
||||
*(uint4*)(row + n_c + j) =
|
||||
make_uint4(__float_as_uint(acc[i][j]), __float_as_uint(acc[i][j + 1]),
|
||||
__float_as_uint(acc[i][j + 2]), __float_as_uint(acc[i][j + 3]));
|
||||
} else {
|
||||
uint16_t* row = (uint16_t*)y + (long long)m * y_ld;
|
||||
uint32_t p[4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j)
|
||||
p[j] = (uint32_t)f32_to_bf16(acc[i][2 * j]) |
|
||||
((uint32_t)f32_to_bf16(acc[i][2 * j + 1]) << 16);
|
||||
*(uint4*)(row + n_c) = make_uint4(p[0], p[1], p[2], p[3]);
|
||||
}
|
||||
} else {
|
||||
/* The ragged N tail, unrolled: a dynamic index into acc would put the 64 accumulators
|
||||
* in local memory, and the compiler says so -- 80 KiB of spill against a 64 KiB limit. */
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
if (n_c + j < N) {
|
||||
if (YF32) ((float*)y)[(long long)m * y_ld + n_c + j] = acc[i][j];
|
||||
else ((uint16_t*)y)[(long long)m * y_ld + n_c + j] = f32_to_bf16(acc[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================ the decode arm, M <= 16
|
||||
*
|
||||
* A wave is MT activation rows by KLW = 32/MT weight rows, one accumulator a lane, the whole of k in
|
||||
* ascending order. The activation tile is block-wide, so every wave stages it -- a wave whose row is
|
||||
* past the vocabulary stages too and simply does not read, which is the rule that keeps a tile from
|
||||
* coming up with holes.
|
||||
*/
|
||||
template <int MT, bool YF32, int NT, bool WQ>
|
||||
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(4)
|
||||
logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, HeadQ h,
|
||||
void* __restrict__ y, int M, int N, int K, int x_ld, int y_ld)
|
||||
{
|
||||
constexpr int KLW = kWave / MT;
|
||||
constexpr int STEPS = MT * (kChunkK / 8); /* uint4 staging steps a chunk */
|
||||
|
||||
__shared__ __align__(16) uint16_t sX[MT * kChunkK]; /* f16, MT rows x chunk, swizzled */
|
||||
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
|
||||
#ifndef R3D_NO_E4M3_TBL
|
||||
if (WQ) r3d_e4m3_f16_init(sTbl, (int)threadIdx.x, kBlockThreads);
|
||||
const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr;
|
||||
#else
|
||||
(void)sTbl;
|
||||
const uint16_t* const r3d_tbl = (const uint16_t*)nullptr;
|
||||
#endif
|
||||
|
||||
const int lane = (int)threadIdx.x & (kWave - 1);
|
||||
const int warp = (int)threadIdx.x / kWave;
|
||||
const int m = lane & (MT - 1);
|
||||
const int n = (int)blockIdx.x * (kWaves * KLW) + warp * KLW + lane / MT;
|
||||
const bool live = n < N;
|
||||
|
||||
/* A dead lane reads row N-1, a row that exists: the loads stay uniform and nothing is read out
|
||||
* of bounds; its result is dropped at the store. */
|
||||
const uint16_t* wrow = w + (long long)(live ? n : N - 1) * K;
|
||||
const int nsteps = M < MT ? M : MT;
|
||||
float acc = 0.0f;
|
||||
|
||||
for (int k0 = 0; k0 < K; k0 += kChunkK) {
|
||||
for (int j = (int)threadIdx.x; j < STEPS; j += kBlockThreads) {
|
||||
const int r = j / (kChunkK / 8), c8 = j % (kChunkK / 8);
|
||||
const int k = k0 + c8 * 8;
|
||||
uint4 v = make_uint4(0, 0, 0, 0);
|
||||
if (r < nsteps && k < K) v = *(const uint4*)(x + (long long)r * x_ld + k);
|
||||
*(uint4*)&sX[srow(r, c8, kChunkK)] = widen8(v);
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
if (live) {
|
||||
const uint16_t* wp = wrow + k0;
|
||||
const uint8_t* cp = h.codes + (long long)(live ? n : N - 1) * h.code_row + k0;
|
||||
/* One scale a chunk: kChunkK is the scale block, so the lane's 128 codes are inside a
|
||||
* single (n-block, k-block) and the load is one scalar per 128 codes. */
|
||||
const float sc = WQ ? scale_at(h, live ? n : N - 1, k0) : 0.0f;
|
||||
const int kend = K - k0 < kChunkK ? K - k0 : kChunkK; /* a multiple of 8: the
|
||||
* launcher takes K % 8 == 0 */
|
||||
for (int kc = 0; kc < kend; kc += 8) {
|
||||
uint32_t w0, w1, w2, w3;
|
||||
if (WQ) {
|
||||
uint32_t q[4];
|
||||
codes8_to_f16x4(loadc8<NT>(cp + kc), h.cdt, r3d_tbl, q);
|
||||
w0 = scale_pair(q[0], sc); w1 = scale_pair(q[1], sc);
|
||||
w2 = scale_pair(q[2], sc); w3 = scale_pair(q[3], sc);
|
||||
} else {
|
||||
const uint4 wv = loadw8<NT>(wp + kc);
|
||||
w0 = bf16x2_to_f16x2(wv.x); w1 = bf16x2_to_f16x2(wv.y);
|
||||
w2 = bf16x2_to_f16x2(wv.z); w3 = bf16x2_to_f16x2(wv.w);
|
||||
}
|
||||
const int s = srow_pair(m, kc, kChunkK);
|
||||
acc = dot2_f16x2(*(const uint32_t*)&sX[s], w0, acc);
|
||||
acc = dot2_f16x2(*(const uint32_t*)&sX[s + 2], w1, acc);
|
||||
acc = dot2_f16x2(*(const uint32_t*)&sX[s + 4], w2, acc);
|
||||
acc = dot2_f16x2(*(const uint32_t*)&sX[s + 6], w3, acc);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
if (live && m < M) {
|
||||
if (YF32) ((float*)y)[(long long)m * y_ld + n] = acc;
|
||||
else ((uint16_t*)y)[(long long)m * y_ld + n] = f32_to_bf16(acc);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the shared launcher
|
||||
*
|
||||
* Returns 0, -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 the HIP
|
||||
* launch failed, -5 an address it cannot read at 16 bytes.
|
||||
*/
|
||||
template <bool YF32>
|
||||
int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ld, int sk, int kb,
|
||||
int nt, long stream, const HeadQ* hq = nullptr)
|
||||
{
|
||||
if (!xv || !wv || !yv) return -1;
|
||||
if (M < 1 || N < 1 || K < 1) return -2;
|
||||
if (sk > 1) return -2; /* the grid is vocab-wide at every M, see header */
|
||||
if (kb == 0) kb = kKC;
|
||||
if (kb != kKC) return -2; /* 32 is the tile's k-chunk and the only one */
|
||||
if (nt < 0 || nt > 1) return -2;
|
||||
if (K % kKC) return -2; /* the tile's chunk; 2048 at the band */
|
||||
if (K % 8) return -3; /* 16-byte weight loads */
|
||||
if (!x_ld) x_ld = K;
|
||||
if (!y_ld) y_ld = N;
|
||||
if (x_ld % 8) return -3; /* 16-byte activation loads (bf16) */
|
||||
if (y_ld % (YF32 ? 4 : 8)) return -3; /* 16-byte store runs (f32: 4, bf16: 8) */
|
||||
if (x_ld < K || y_ld < N) return -3;
|
||||
if ((xv & 15) || (wv & 15) || (yv & 15)) return -5;
|
||||
|
||||
const uint16_t* x = (const uint16_t*)(uintptr_t)xv;
|
||||
const uint16_t* w = (const uint16_t*)(uintptr_t)wv;
|
||||
void* y = (void*)(uintptr_t)yv;
|
||||
hipStream_t s = (hipStream_t)(uintptr_t)stream;
|
||||
|
||||
/* The head's form is the shim's answer, resolved out of the container before the launch; this
|
||||
* is where its pointers are checked as pointers. The declared entries pass null and get the
|
||||
* plain bf16 head, which is what r3d.h's signature for them describes. */
|
||||
HeadQ h;
|
||||
std::memset(&h, 0, sizeof h);
|
||||
const int wq = hq != nullptr;
|
||||
if (hq) {
|
||||
h = *hq;
|
||||
if (!h.codes || !h.scale) return -1;
|
||||
if (h.sdt < 0 || h.sdt > 2 || h.cdt < 0 || h.cdt > 1) return -2;
|
||||
if (h.code_row & 7) return -3; /* 8-byte code loads, one row a stride */
|
||||
if (h.scale_row & (h.sdt == 2 ? 3 : 1))
|
||||
return -3; /* a scale row is 4 bytes a column for f32, 2 for
|
||||
* bf16/f16: a plane of 3 columns is 6 bytes and the
|
||||
* loads land on even addresses. K = 320 is legal. */
|
||||
if (((long long)(uintptr_t)h.codes & 7) || ((long long)(uintptr_t)h.scale & 3)) return -5;
|
||||
}
|
||||
|
||||
if (M <= kSkinnyMax) {
|
||||
#define R3D_SKINNY(MTV, NTV, WQV) \
|
||||
do { \
|
||||
const int klw = kWave / (MTV); \
|
||||
const int per = kWaves * klw; \
|
||||
const dim3 grid((unsigned)((N + per - 1) / per)), block(kBlockThreads); \
|
||||
R3D_KLAUNCH(R3D_KNAME((logits_skinny_kernel<MTV, YF32, NTV, WQV>)), grid, block, s, x, w, \
|
||||
h, y, M, N, K, x_ld, y_ld); \
|
||||
} while (0)
|
||||
#define R3D_SKINNY_MT(MTV) \
|
||||
do { \
|
||||
if (wq) { if (nt) R3D_SKINNY(MTV, 1, 1); else R3D_SKINNY(MTV, 0, 1); } \
|
||||
else { if (nt) R3D_SKINNY(MTV, 1, 0); else R3D_SKINNY(MTV, 0, 0); } \
|
||||
} while (0)
|
||||
if (M == 1) R3D_SKINNY_MT(1);
|
||||
else if (M <= 2) R3D_SKINNY_MT(2);
|
||||
else if (M <= 4) R3D_SKINNY_MT(4);
|
||||
else if (M <= 8) R3D_SKINNY_MT(8);
|
||||
else R3D_SKINNY_MT(16);
|
||||
#undef R3D_SKINNY_MT
|
||||
#undef R3D_SKINNY
|
||||
} else {
|
||||
const dim3 grid((unsigned)((N + kTN - 1) / kTN), (unsigned)((M + kTM - 1) / kTM));
|
||||
const dim3 block(kBlockThreads);
|
||||
if (wq)
|
||||
R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel<YF32, true>)), grid, block, s, x, w, h, y, M,
|
||||
N, K, x_ld, y_ld);
|
||||
else
|
||||
R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel<YF32, false>)), grid, block, s, x, w, h, y, M,
|
||||
N, K, x_ld, y_ld);
|
||||
}
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* The shim's shared body: the checks the two ops agree on, then the launch. `y_is_f32` is the op's
|
||||
* schema (logits are f32 because every sampler stage reads f32; gemm_nt's y is bf16), nkey/kkey the
|
||||
* axis names libref spells them with ("n_vocab"/"n_embd" and "N"/"K" -- ref_logits_gemm is
|
||||
* gemm_nt_impl with the axes renamed, so this body is shared by construction, not by imitation). */
|
||||
int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, const char* kkey)
|
||||
{
|
||||
if (a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data)
|
||||
return R3D_NO(RAD_E_INVAL);
|
||||
const RadTensor* x = &a->t[0];
|
||||
const RadTensor* w = &a->t[1];
|
||||
const RadTensor* y = &a->t[2];
|
||||
|
||||
const RadPlanesEntry* ce = nullptr;
|
||||
const RadPlanesEntry* se = nullptr;
|
||||
HeadQ h;
|
||||
std::memset(&h, 0, sizeof h);
|
||||
int joined = 0;
|
||||
|
||||
/* ---- the head's stored form ---------------------------------------------------------------
|
||||
* The band's `dtype` key is the ACTIVATION's dtype: on this graph `dtype=bf16` with the head
|
||||
* stored as E4M3 codes and a bf16 scale per 128x128 block, in two planes of one container. The
|
||||
* stored form is answered by a layout hook -- `ref_layout_head`, transcribed below as
|
||||
* r3d_layout_logits_head, the way the w2a8 hook transcribed ref_layout_gemm_q -- and this is
|
||||
* its launch-side twin: read the header, read the two planes, dispatch on what they are. The
|
||||
* checks and their order are the reference's `scaled_rows`: the roles, then the dtypes and
|
||||
* blocks, then the coverage (which needs N and K, so it sits below, where the reference has
|
||||
* them already).
|
||||
*
|
||||
* The bf16 head is served as is: the container's header, not the row's preference, picks
|
||||
* the form. Two forms, one row, chosen by the bytes.
|
||||
*/
|
||||
const RadPlanesHeader* ph = rad_planes_header(r3d_p(w));
|
||||
if (ph) {
|
||||
if (!y_is_f32) return R3D_NO(RAD_E_DTYPE); /* logits are f32; the bf16-y row keeps a bf16 head */
|
||||
if (rad_planes_find(r3d_p(w), "zero", nullptr))
|
||||
return R3D_NO(RAD_E_DTYPE); /* codes+scale+zero is gemm_nt_q's asymmetric grid: w2a8 */
|
||||
if (ph->n_planes != 2) return R3D_NO(RAD_E_DTYPE);
|
||||
const uint8_t* cb = (const uint8_t*)rad_planes_find(r3d_p(w), "codes", &ce);
|
||||
const uint8_t* sb = (const uint8_t*)rad_planes_find(r3d_p(w), "scale", &se);
|
||||
if (!cb || !sb || !ce || !se)
|
||||
return R3D_NO(RAD_E_DTYPE); /* a joined head that is not codes + one scale */
|
||||
if (ce->kind != RAD_PLANE_TILED || ce->block[0] != 1 || ce->block[1] != 1)
|
||||
return R3D_NO(RAD_E_DTYPE); /* codes must be one code an element, tiled plain */
|
||||
if (ce->dtype != RAD_F8E4M3 && ce->dtype != RAD_I8) {
|
||||
if (rad_dtype_bytes(ce->dtype, 8) < 8)
|
||||
return R3D_NO(RAD_E_DTYPE); /* sub-byte codes: w4a16's ground, not this form */
|
||||
return R3D_NO(RAD_E_DTYPE); /* e5m2 and the rest: no decoder here */
|
||||
}
|
||||
if (se->kind != RAD_PLANE_TILED) return R3D_NO(RAD_E_DTYPE);
|
||||
if (se->dtype == RAD_BF16) h.sdt = 0;
|
||||
else if (se->dtype == RAD_F16) h.sdt = 1;
|
||||
else if (se->dtype == RAD_F32) h.sdt = 2;
|
||||
else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not a float_scale_dt */
|
||||
if (se->block[0] != kFp8Block || se->block[1] != kFp8Block)
|
||||
return R3D_NO(RAD_E_SHAPE); /* per-(row,group) scales are gemm_nt_q's grid; per-row
|
||||
* is not the indexing this kernel does */
|
||||
h.codes = cb; h.scale = sb; h.code_row = ce->row_bytes; h.scale_row = se->row_bytes;
|
||||
h.cdt = ce->dtype == RAD_I8 ? 1 : 0;
|
||||
joined = 1;
|
||||
} else if (w->dtype != RAD_BF16) {
|
||||
return R3D_NO(RAD_E_DTYPE);
|
||||
}
|
||||
if (x->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
|
||||
if (y->dtype != (y_is_f32 ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16)) return R3D_NO(RAD_E_DTYPE);
|
||||
|
||||
long long N = r3d_geti_or(a, nkey, 0);
|
||||
long long K = r3d_geti_or(a, kkey, 0);
|
||||
if (N <= 0) N = r3d_dim(w, 0);
|
||||
if (K <= 0) K = r3d_dim(w, 1);
|
||||
if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE);
|
||||
|
||||
long long M = 0, x_rows = 0;
|
||||
const long long y_pitch = r3d_rows_pitch(y, N, &M); /* M = numel(y)/N, the reference's fold */
|
||||
if (y_pitch < N || M <= 0) return R3D_NO(RAD_E_STRIDE);
|
||||
const long long x_pitch = r3d_rows_pitch(x, K, &x_rows);
|
||||
if (x_pitch < K || x_rows < M) return R3D_NO(RAD_E_STRIDE);
|
||||
if (r3d_numel(w) < N * K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_contig(w)) return R3D_NO(RAD_E_STRIDE); /* N rows of K contiguous codes */
|
||||
if (joined) {
|
||||
/* The coverage checks, `scaled_rows`' last block: the planes must cover the band, and the
|
||||
* scale plane covers it by blocks -- ceil, so a ragged vocabulary is fine (131 rows need 2
|
||||
* scale rows) and a plane one row short is not. */
|
||||
const long long sb_r = (N + kFp8Block - 1) / kFp8Block;
|
||||
const long long sb_c = (K + kFp8Block - 1) / kFp8Block;
|
||||
if (ce->rows != N || ce->cols != K) return R3D_NO(RAD_E_SHAPE);
|
||||
if (se->rows != sb_r || se->cols != sb_c) return R3D_NO(RAD_E_SHAPE);
|
||||
if (ce->row_bytes < ce->cols || se->row_bytes < se->cols * (h.sdt == 2 ? 4 : 2))
|
||||
return R3D_NO(RAD_E_STRIDE);
|
||||
}
|
||||
if (M > (long long)1 << 24 || N > (long long)1 << 28 || K > (long long)1 << 28)
|
||||
return R3D_NO(RAD_E_SHAPE);
|
||||
if (!r3d_aligned(r3d_p(x), 16) || !r3d_aligned(r3d_p(w), 16) || !r3d_aligned(r3d_p(y), 16))
|
||||
return R3D_NO(RAD_E_ALIGN);
|
||||
|
||||
const int sk = (int)r3d_geti_or(a, "sk", 1);
|
||||
if (sk > 1) return R3D_NO(RAD_E_SHAPE); /* the grid is vocab-wide at every M, see the header */
|
||||
const int kb = (int)r3d_geti_or(a, "kb", 0);
|
||||
const int nt = (int)r3d_geti_or(a, "nt", 0);
|
||||
|
||||
const HeadQ* hp = joined ? &h : nullptr;
|
||||
const int e = y_is_f32
|
||||
? gemm_launch<true>(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K,
|
||||
(int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp)
|
||||
: gemm_launch<false>(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K,
|
||||
(int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
|
||||
: e == -3 ? RAD_E_STRIDE : e == -5 ? RAD_E_ALIGN : RAD_E_DEVICE);
|
||||
}
|
||||
|
||||
/* The reference's `enc_scaled_rows` and `float_scale_dt`, inlined: libref keeps them static inline in
|
||||
* its own header, so a plugin that transcribes ref_layout_head transcribes them with it. Checks and
|
||||
* order are its, unchanged: affine, untransformed, two planes, the roles in order, codes tiled with
|
||||
* block {1,1} and a code dtype it admits, the scale tiled with a float dtype. */
|
||||
bool float_scale_dt(uint32_t dt)
|
||||
{
|
||||
return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32;
|
||||
}
|
||||
|
||||
bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n)
|
||||
{
|
||||
if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return false;
|
||||
if (n != 2 || !sel) return false; /* sel_roles(enc, sel, n, "codes", "scale") */
|
||||
const char* want[2] = { "codes", "scale" };
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
if (sel[i] < 0 || sel[i] >= enc->n_planes) return false;
|
||||
if (std::strncmp(enc->plane[sel[i]].role, want[i], RAD_ENC_STR) != 0) return false;
|
||||
}
|
||||
const RadEncPlane& c = enc->plane[sel[0]];
|
||||
const RadEncPlane& sc = enc->plane[sel[1]];
|
||||
return c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 &&
|
||||
(c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && sc.kind == RAD_PLANE_TILED &&
|
||||
float_scale_dt(sc.dtype);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T, the declared entry (r3d.h's
|
||||
* r3d_vocab_bf16.hip section). M <= 16 takes the decode arm, above it the prefill tile. */
|
||||
extern "C" int r3d_logits_gemm_bf16(long x, long lm, long y, int M, int n_vocab, int n_embd,
|
||||
int x_ld, int y_ld, int sk, int nt, long scratch, long stream)
|
||||
{
|
||||
(void)scratch; /* no split, so no partials: see the header */
|
||||
return gemm_launch<true>(x, lm, y, M, n_vocab, n_embd, x_ld, y_ld, sk, kKC, nt, stream);
|
||||
}
|
||||
|
||||
/* The same tiling with a bf16 y, for gemm_nt at prefill sizes (M >= 17; M <= 16 is the m16 row). */
|
||||
extern "C" int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int K, int a_ld,
|
||||
int y_ld, int sk, int kb, int nt, long scratch, long stream)
|
||||
{
|
||||
(void)scratch;
|
||||
return gemm_launch<false>(a, b, y, M, N, K, a_ld, y_ld, sk, kb, nt, stream);
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_logits_gemm_bf16(const RadArgs* a, RadStream s)
|
||||
{
|
||||
return rad_gemm_run(a, s, 1, "n_vocab", "n_embd");
|
||||
}
|
||||
|
||||
extern "C" int r3d_rad_gemm_nt_bf16_tiled(const RadArgs* a, RadStream s)
|
||||
{
|
||||
return rad_gemm_run(a, s, 0, "N", "K");
|
||||
}
|
||||
|
||||
/* The head's layout hook, `ref::ref_layout_head` transcribed: operand 1 of
|
||||
* logits_gemm, two planes, codes and one scale, untransformed -- and the answer is the container's
|
||||
* own form. It moves no byte, and its `relayout` writer (below) exists for the round-trip: this is
|
||||
* a reader, which is what
|
||||
* the mapped tier asks for when a weight's stored form is not the container's. Operand 0 (the
|
||||
* activations) and a one-plane selection are declined as `layout_scaled` declines them, and so is
|
||||
* every other encoding: a silent no-op on a head is the worst failure a row can have. */
|
||||
/* The head's WRITER. A layout query that answers RAD_OK is a promise the ABI makes to the loader --
|
||||
* "out describes the stored form, and relayout will produce it" (rad_abi.h) -- and the load step
|
||||
* holds the row to it. The container stores the quantiser's pair; the plan wants one operand; the
|
||||
* row that owns the band assembles it, losslessly, with rad_planes_relayout: the header, the
|
||||
* entries and each plane's rows, copied.
|
||||
* No code is transformed and no number is derived -- a kernel doing arithmetic
|
||||
* here would make the served numbers depend on which library loaded the container (rad_abi.h).
|
||||
* The query and the writer share the plan through rad_planes_plan, so they cannot disagree. The
|
||||
* operand guard is the hook's own rule repeated: a call routed to the wrong slot writes nothing. */
|
||||
extern "C" int r3d_relayout_logits_head(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n_planes, void* dst,
|
||||
int64_t dst_bytes)
|
||||
{
|
||||
(void)p; (void)n_p;
|
||||
if (operand != 1) return R3D_NO(RAD_E_UNSUPPORTED);
|
||||
return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes);
|
||||
}
|
||||
|
||||
extern "C" int r3d_layout_logits_head(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n, RadLayout* out)
|
||||
{
|
||||
(void)p; (void)n_p; /* layout_scaled ignores both */
|
||||
if (n < 2 || operand != 1) return RAD_E_UNSUPPORTED; /* layout_scaled(operand, 1, -1, ...) */
|
||||
if (!enc_scaled_rows(enc, sel, n)) return RAD_E_DTYPE;
|
||||
return rad_planes_layout(enc, sel, planes, n, out);
|
||||
}
|
||||
@@ -55,9 +55,11 @@ for d in "$S"/arch/*/ "$S"/plugin/*/; do
|
||||
[ -f "$d/CMakeLists.txt" ] && dirs="$dirs $(basename "$(dirname "$d")")/$(basename "$d")"
|
||||
done
|
||||
# The device libraries: built out of tree only with the tree's HIP compiler, and left out of every
|
||||
# comparison below without it.
|
||||
# comparison below without it. Each declares the family it serves, so a tree built for one family
|
||||
# produces one of them: libr3d returns without a target when RAD_GPU_TARGETS holds no gfx11, and the
|
||||
# checks below compare the two builds of the same list, not a fixed list.
|
||||
devlibs=""
|
||||
for d in libr4d; do
|
||||
for d in libr4d libr3d; do
|
||||
[ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && devlibs="$devlibs $d"
|
||||
done
|
||||
[ -n "$HIPC" ] && dirs="$dirs $devlibs"
|
||||
|
||||
Reference in new issue
Block a user