radiance 1.14.0

New models and formats:
- libr3d: a kernel library for RDNA3 (gfx11) cards
- nomic-embed-text-v2-moe (the nomicbert plugin)
- Gemma 4 E2B with its per-layer MLP width, and Google's unmodified E2B/E4B directories in bf16
- DeepSeek-V4.1-Flash converted straight from its release: the Engram tables, the fused imatrix and
  rad-convert --chat-template for a release that ships no template
- GGUF Q8_0, Q4_K and Q6_K tensors import as their planes; rad-convert writes them without a recipe
- Qwen3.8-Flash-Next-FP8 converts and serves through qwen4exp_fp8

Speed:
- hc_read's decode kernels as one grid (34.7 -> 25.2 us at 4 rows) and its tiled up-mix pipelined
- gemm_fp8a8: the narrow form's scales staged through LDS (Flash-Next int8 at 32 rows 83.6 -> 68.3
  us), the gated three-tile form at 8 waves (gate_up at 48 rows 272.9 -> 180.6 us)
- Qwen3.8-27B: the delta net's out-projection read beside its decode recurrent update (x1 19.40 ->
  19.10 ms a step), and the verify's split-KV attention sized by context depth (x3 at 180K 42.4 ->
  40.3 ms a step)
- Hy-Memory (HYV3) decode: fused QK norm, RoPE and KV store, residual adds folded into the norms,
  coalesced one-token expert GEMMs
- spechub: the coupled verify walks the live candidates only (151 -> 31 us a launch)

Speculation:
- DFlash2: lossless coupled acceptance at T > 0 (--draft-coupling on)
- A block drafter's proposals verified as a tree, on by default for the Gemma 4 31B's DFlash2, with
  a block-16 tree that runs its short block under load

Features:
- Decode-hot residency: --draft-expert-placement host, --expert-profile, --expert-pin-top, and
  --expert-stats FILE for the routed experts each layer selects
- --ngram-placement ram=DIR: one n-gram table shared by engines on separate cards
- Prefix cache: --prefix-resume exact (default) resumes a hit on the cold run's own chunk grid, so it
  answers bit-identically; snapshots at a head other prompts share, from 528-token prompts, and for
  tip-only one drafter window below the tip; hits on models whose KV groups have different block
  sizes; the snapshot store keeps a floor of 8 ahead of --host-headroom-mib
- Typed tool-call argument tags; rad-chatparse --request renders and reads back one request as the
  server does
- MiniMax-H3: keyframes ride a latent upscale
- Gemma 3's fused all-reduce junction on the lossy wire

Fixes:
- A speculative step shorter than its band (an MTP step of 4 rows at gqa 8) no longer stops the
  engine with a scratch refusal at issue (#293)
- --p2p off: prefill back to 1.12.0's rate; 1.13.0's push check read a host-memory slot over the link
  twice (#323)
- A chat template that cannot render a conversation is refused at load, not mid-request
- imatrix entries found under llama.cpp's spelling; the W4A8 prefill's tail scale read; the GDN conv
  kernels on an f32 weight; dense integer rows at the group they compute (a Q8_0 weight at group 32)
- --expert-profile refuses a profile recorded on another model
- hc_read's one-grid wait traps past its deadline instead of reading a stale value

Changes: Plugin ABI 31, unchanged. RADIANCE_DRAFT_TREE, DFLASH2_TREE_NODES, DFLASH2_TREE_TEMP and
DFLASH_Q_TEMP are gone (trees run where the probe says they pay; temperatures 1.25 / 0.6).
This commit is contained in:
Deadcode committed 2026-10-29 12:04:24 +01:00
1 parent 481fcd5df0
commit 4a61d7296b
160 files changed
+8790 -6819

No files matched your search

+134 -194
View File
@@ -1,39 +1,31 @@
/* r3d_quant_fp8.hip -- the activation quantisers and the dequantise that reads a container's own
* codes.
*
* The arithmetic is libref's, transcribed. The group core is `q8_group`: an amax over
* the group's consecutive columns, `sc = amax * (1.0f / top)` -- a MULTIPLY by the reciprocal, not a
* divide -- codes `v * (1/sc)` clamped to +-top and encoded by the codec, and scale 1 for an
* all-zero group, whose reciprocal would be an infinity. The five bodies are libref's
* quant_act_fp8, quant_act_i8, quant_act_i8g, gated_quant_fp8 and dequant, loop order and rounding
* points as written. The clamp is required and not defensive: `amax * (1/scale)` is
* 448 exactly and can round an ulp above once the reciprocal is rounded, and a code out of range
* encodes as NaN, which then spreads through every row that reads it.
* The arithmetic is libref's, transcribed: quant_act_fp8, quant_act_i8, quant_act_i8g,
* gated_quant_fp8 and dequant, loop order and rounding points as written. The group core is
* `q8_group`: an amax over the group's columns, `sc = amax * (1.0f / top)` (a multiply by the
* reciprocal, not a divide), codes `v * (1/sc)` clamped to +-top, and scale 1 for an all-zero
* group. The clamp is required: `amax * (1/scale)` can round an ulp above 448, and an
* out-of-range code encodes as NaN.
*
* RDNA3 has no fp8 instruction (r3d_common.h), so both directions are the software codecs in
* r3d_codecs.h, which are bit-exact mirrors of rad_plugin.h's; the absmax is a butterfly
* (r3d_xor_max), which reproduces a `__shfl_xor` loop bit for bit, and a max is exact and
* order-free, so the bracketing is q8_group's ascending one whatever the lane mapping.
* RDNA3 has no fp8 instruction (r3d_common.h), so both directions use the software codecs in
* r3d_codecs.h, bit-exact mirrors of rad_plugin.h's. The absmax is a butterfly (r3d_xor_max); a
* max is exact and order-free, so it matches q8_group whatever the lane mapping.
*
* No kernel here carries a layout hook, and the codes are the bytes their consumer reads, which is
* the reason a container converted on this card is readable anywhere. Four of the five planes are
* plain row-major with one f32 scale per (row, group), because a dot2 GEMM reads codes in the order
* they are stored. The fifth is the op whose NAME carries the order: libref stores quant_act_i8's
* codes in the int8 WMMA's step order (`i8_step_pos`, the middle two dwords of every 16-byte step
* exchanged) because that is what the w4a8, w8a8 and w2a8 GEMMs read, so this kernel stores them
* that way too and its n is a multiple of 16; quant_act_i8g is the row-major int8 plane, and it is
* the one this library's i8a8 GEMM consumes. The two are not interchangeable.
* The codes are the bytes their consumer reads, with no layout hook. Four of the five planes are
* row-major with one f32 scale per (row, group), the order a dot2 GEMM reads. quant_act_i8 stores
* its codes in the int8 WMMA's step order (`i8_step_pos`) because the w4a8, w8a8 and w2a8 GEMMs
* read that, so its n is a multiple of 16. quant_act_i8g is the row-major int8 plane this
* library's i8a8 GEMM consumes. The two are not interchangeable.
*
* The store address costs nothing either way: a lane owns FOUR CONSECUTIVE COLUMNS, so its codes are
* one dword, a wave's are 128 contiguous bytes, and a wave covers exactly one 128-column group;
* `i8_step_pos` preserves c % 4, so it permutes a wave's 128 bytes without splitting a lane. The
* launchers therefore refuse `n % 4` -- and quant_act_i8 `n % 16` -- and a ragged last group
* (n % group != 0) is written zero-padded: padding is a zero code and takes no part in the amax.
* A lane owns four consecutive columns, so its codes are one dword and a wave's are 128
* contiguous bytes; `i8_step_pos` preserves c % 4, so it never splits a lane. The launchers
* refuse `n % 4` (quant_act_i8: `n % 16`), and a ragged last group is zero-padded: padding is a
* zero code and takes no part in the amax.
*
* Group widths: the rows ask for 128, the checkpoint's weight-scale block width, and the kernels
* also serve any other power of two from 4 to 512, so a selftest can drive a narrow group and a
* future row on a 64-wide grid needs no new kernel. A group is a power of two because the amax
* butterfly is over the lanes covering it, GROUP/4 of them.
* Group widths: the rows ask for 128, the checkpoint's weight-scale block width; the kernels serve
* any power of two from 4 to 512. A group is a power of two because the amax butterfly is over
* the GROUP/4 lanes covering it.
*/
#include "r3d.h"
@@ -51,15 +43,13 @@ enum : uint32_t {
kWaveCols = kWave * kColsPerLane /* 128: the columns a wave covers */
};
/* The largest code each quantiser saturates at. E4M3 has no infinity, so 448 is the largest finite
* value, and the scale is a dequant multiplier like the checkpoint's weight_scale_inv: the GEMM
* multiplies the activation's scale by the weight's block scale and never divides. */
/* The largest code each quantiser saturates at; 448 is E4M3's largest finite value. The scale is a
* dequant multiplier like the checkpoint's weight_scale_inv: the GEMM multiplies, never divides. */
constexpr float kTopE4M3 = 448.0f;
constexpr float kTopI8 = 127.0f;
/* The floor quant_act_i8's amax is raised to before its DIVIDE by 127, where quant_act_fp8
* multiplies by a reciprocal, so the two quantisers round one ulp apart here; that is libref's
* spelling and the GEMMs read the scale as it is. */
/* The floor quant_act_i8's amax is raised to before it divides by 127. quant_act_fp8 multiplies by
* a reciprocal instead, so the two can round one ulp apart; both follow libref. */
constexpr float kI8Floor = 1e-8f;
/* The LDS code-sum accumulator's width, in groups, as in libr4d's r4d_quant_act_i8. */
@@ -70,10 +60,9 @@ __device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
/* q8_group's clamp, in q8_group's order and with q8_group's comparisons, at the codec's top -- 448
* for E4M3, 127 for int8. fminf/fmaxf are NOT the same function here: they replace a NaN with the
* bound, and a NaN in an activation is a value the reference encodes as the format's NaN, not as
* +-top. */
/* q8_group's clamp, in its order and with its comparisons, at the codec's top (448 for E4M3, 127
* for int8). Not fminf/fmaxf: they replace a NaN with the bound, and the reference encodes a NaN
* activation as the format's NaN. */
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
@@ -87,9 +76,7 @@ __device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) {
return lo | (hi << 16);
}
/* The same four codes as int8, at the same rounding points: clamp to +-127, then the codec's
* round-to-nearest-even. quant_act_i8g's store; quant_act_i8's is the same bytes at a permuted
* address. */
/* The same four codes as int8: clamp to +-127, then the codec's round-to-nearest-even. */
__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8));
const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8));
@@ -98,24 +85,22 @@ __device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
}
/* q8_group's scale from the group's amax: the reciprocal of `top` MULTIPLIED, not a divide -- the
* one place the two int8 quantisers and the fp8 one agree, and the reason the per-row
* quant_act_i8 spells its scale as a divide and is a separate body. */
/* q8_group's scale from the group's amax: multiplied by the reciprocal of `top`, not divided. The
* per-row quant_act_i8 divides, which is why it is a separate body. */
__device__ __forceinline__ float group_scale(float am, float top) {
return am > 0.0f ? am * (1.0f / top) : 1.0f;
}
/* The map libref uses, verbatim: where a row's column c is stored in the step-ordered int8 plane.
* Bits 2 and 3 of c exchanged = the middle two dwords of every 16-byte step swapped, which is the
* order the int8 WMMA reads an A fragment. The map is its own inverse, and it preserves c % 4, so a
* lane's four columns stay contiguous and its store stays one dword. */
/* libref's map from column c to its position in the step-ordered int8 plane: bits 2 and 3 of c
* exchanged, i.e. the middle two dwords of every 16-byte step swapped, the order the int8 WMMA
* reads an A fragment. It is its own inverse and preserves c % 4, so a lane's store stays one
* dword. */
__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) {
return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1);
}
/* block_sum's twin for a maximum -- r3d_common.h has the sum. A max needs no order argument at all:
* it is exact, so the wave partials combine in any order -- but it is spelled the same way, so a
* reader sees one reduction shape in this library and not two. `lds` holds kWaves floats. */
/* block_sum's (r3d_common.h) twin for a maximum. A max is exact, so the wave partials combine in
* any order. `lds` holds kWaves floats. */
__device__ __forceinline__ float block_max(float v, float* lds) {
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
v = wave_max(v);
@@ -129,18 +114,16 @@ __device__ __forceinline__ float block_max(float v, float* lds) {
/* ================================================================== quant_act_fp8
*
* Per-(row, group) symmetric E4M3 of an activation, over q8_group. One workgroup
* a row, a wave a group, a lane four columns -- libr4d's layout, because the reason for
* it (one dword a lane, 128 contiguous bytes a wave) is the store and not the instruction set.
* Per-(row, group) symmetric E4M3 of an activation, over q8_group. One workgroup a row, a wave a
* group, a lane four columns: libr4d's layout, chosen for the store (one dword a lane, 128
* contiguous bytes a wave), not the instruction set.
*
* GROUP is the group's width. At 128 a wave covers one group and the amax is r3d_xor_max<32>. A
* narrower group is covered by GROUP/4 lanes of the wave and the butterfly is over those lanes, so
* one wave quantises 128/GROUP groups in a pass; a wider one is covered by one wave in sub-blocks
* of 128 whose maxima are fmaxf'd. All three are q8_group's bracketing.
* At GROUP = 128 a wave covers one group and the amax is r3d_xor_max<32>. A narrower group is
* covered by GROUP/4 lanes, so one wave quantises 128/GROUP groups a pass; a wider one is walked
* by one wave in 128-column sub-blocks whose maxima are fmaxf'd.
*
* Rows are dim 0, so a rank-3 activation ([tokens, heads, width], a GDN block's out-projection
* input) is one row per token, as libref reads it: its consuming GEMM's K is heads*width, and one
* row per head would put scales on a grid that GEMM does not read.
* input) is one row per token, as libref reads it: the consuming GEMM's K is heads*width.
*/
template <int GROUP>
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
@@ -168,8 +151,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
for (int j = 0; j < kColsPerLane; ++j) {
const uint32_t c = c0 + (uint32_t)j;
/* Past the row's end a lane contributes 0.0f, so padding is a zero code and takes
* no part in the amax. n is a multiple of 4, so a lane's four columns are all in
* the row or all outside it: the ragged edge never splits a lane. */
* no part in the amax. n is a multiple of 4, so the edge never splits a lane. */
v[sb][j] = c < n ? ld_bf(xr, c) : 0.0f;
}
float m = 0.0f;
@@ -178,10 +160,9 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
am = fmaxf(am, r3d_xor_max<kLanes>(m));
}
const float sc = group_scale(am, kTopE4M3);
/* The scale store is guarded by the group count, not just by the lane: a wave covers
* kPer = 128/GROUP groups and a row's group count is ceil(n/group), which is not a multiple
* of kPer when the last group is ragged. Unguarded, those lanes wrote one row past the
* scale row -- and on a ragged n, past the plane's end. */
/* Guarded by the group count as well as the lane: a wave covers kPer = 128/GROUP groups
* and ceil(n/group) need not be a multiple of kPer, so the surplus lanes would write past
* the scale row (and on the last row, past the plane). */
if ((lane & (kLanes - 1)) == 0) {
const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes;
if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc;
@@ -197,17 +178,14 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
/* ================================================================== quant_act_i8g
*
* The same group core at int8, q8_group called with top 127. One scale
* per (row, group), `sc = amax * (1.0f / 127)` -- the reciprocal MULTIPLIED, as in the fp8 path, so
* this is quant_act_fp8 with a different codec and not quant_act_i8 at a finer granularity -- codes
* clamp(v * (1/sc), +-127) to nearest even, stored ROW-MAJOR, and scale 1 for an all-zero group.
* q8_group at top 127: one scale per (row, group), `sc = amax * (1.0f / 127)` as in the fp8 path
* (so this is quant_act_fp8 with an int8 codec, not quant_act_i8 at a finer granularity), codes
* clamp(v * (1/sc), +-127) rounded to nearest even, scale 1 for an all-zero group.
*
* The row-major store is the point of the op: libr3d's only int8 GEMM is the i8a8 one, and a dot2
* GEMM reads a row in the order it is stored. The step-ordered plane belongs to quant_act_i8, whose
* consumers are libr4d's WMMA GEMMs, and the two are not interchangeable.
* The store is row-major because libr3d's int8 GEMM (i8a8) is a dot2 GEMM that reads a row in
* stored order. The step-ordered plane is quant_act_i8's, read by libr4d's WMMA GEMMs.
*
* Same lane mapping and same ragged rules as quant_act_fp8_kernel, so the two bodies read as one
* shape with the codec swapped.
* Lane mapping and ragged rules are quant_act_fp8_kernel's.
*/
template <int GROUP>
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8g_kernel(
@@ -258,13 +236,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8g_kernel(
} /* namespace */
/* x [M][n] bf16, `x_ld` elements a row (0 = n)
* q [M][n] E4M3, DENSE: the launcher takes no code pitch, so the plane is
* row-major with no hole in it, rounded up to 4 bytes for the padding
* q [M][n] E4M3, dense (the launcher takes no code pitch)
* s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group))
*
* A launcher checks what a `__global__` cannot and issues one kernel: 0, -1 a null pointer, -2 a bad
* extent (including a group with no instantiation), -3 a pitch that does not describe the operand,
* -4 the HIP launch failed. It allocates nothing and synchronises on nothing. */
* Each launcher validates and issues one kernel: 0, -1 a null pointer, -2 a bad extent (including
* a group with no instantiation), -3 a pitch that does not describe the operand, -4 the HIP launch
* failed. It allocates nothing and does not synchronise. */
extern "C" int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld,
int s_ld, long stream) {
if (!x || !q || !s) return -1;
@@ -301,27 +278,20 @@ namespace {
/* ================================================================== quant_act_i8
*
* The activation of the w4a8, w8a8 and w2a8 GEMMs, ONE SCALE PER ROW,
* max(amax, 1e-8) / 127, codes x * (1/scale) rounded to nearest even by the int8 codec.
* The activation of the w4a8, w8a8 and w2a8 GEMMs: one scale per row, max(amax, 1e-8) / 127,
* codes x * (1/scale) rounded to nearest even by the int8 codec.
*
* The codes go out in libref's STEP ORDER, `i8_step_pos`: the middle two
* dwords of every 16-byte step exchanged, which is why this op's n is a multiple of 16 and not of
* 4. That order is what the op MEANS -- the w4a8, w8a8 and w2a8 GEMMs read the plane that way, and
* kbench compares the plane element by element -- so it is kept on a card that has no WMMA, and the
* row-major int8 plane is a separate op, quant_act_i8g below, which is the one this library's i8a8
* GEMM consumes. The permutation is per-lane and preserves c % 4, so a lane's four codes stay
* contiguous and the store stays one dword; a wave's 128 bytes are a permutation of the same 128.
* The codes are stored in libref's step order (`i8_step_pos`), hence n % 16 == 0. That order is
* the op's contract (those GEMMs read it and kbench compares the plane element-wise), so it is
* kept on a card without WMMA; the row-major plane is quant_act_i8g.
*
* One divergence from the reference's arithmetic, and it is inert: libref reduces a row with
* std::max and this with fmaxf. They agree on every input the op can see -- std::max(a, NaN) is a, so
* the reference's amax is never a NaN, and fmaxf drops the NaN the same way; an all-NaN row has amax
* 0 in both and scale 1e-8/127.
* libref reduces with std::max and this with fmaxf. Both drop a NaN operand, so they agree on
* every input; an all-NaN row has amax 0 and scale 1e-8/127 in both.
*
* ASUM, when present, also takes each row's code sums per `group` columns, group-major
* [n/group][Mpad] with Mpad = ceil(M/16)*16: an asymmetric weight grid needs sum_k a_k to subtract
* z_g * sum_k a_k from a group's dot product once instead of N times, and it reads whole 16-row
* tiles. The sums are integers, so the LDS accumulator's atomic adds are exact and their order is
* free. Rows M..Mpad-1 are not written; the caller zeroes them, as libref does.
* ASUM also writes each row's code sums per `group` columns, group-major [n/group][Mpad] with
* Mpad = ceil(M/16)*16: an asymmetric weight grid subtracts z_g * sum_k a_k once per group instead
* of N times, and reads whole 16-row tiles. The sums are integers, so the LDS atomics are exact in
* any order. Rows M..Mpad-1 are not written; the caller zeroes them, as libref does.
*/
template <bool ASUM>
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel(
@@ -359,10 +329,9 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel(
const uint32_t cc = c + (uint32_t)j;
const int8_t code = (cc < n) ? f32_to_i8_rtne(ld_bf(xr, cc) * inv) : (int8_t)0;
w |= (uint32_t)(uint8_t)code << (8 * j);
/* n % group == 0 and group % 4 == 0, so a lane's four columns are in one group. The
* sum is over column order, and the map is its own inverse, so summing the codes of
* columns [gi*group, (gi+1)*group) here is libref reading qr[i8_step_pos(i)] --
* same bytes, same groups. */
/* n % group == 0 and group % 4 == 0, so a lane's four columns are in one group. Sums
* are over logical columns, which equals libref reading qr[i8_step_pos(i)] since the
* map is its own inverse. */
if (ASUM && cc < n) atomicAdd(&gs[cc / group], (int)code);
}
*(uint32_t*)(qr + i8_step_pos(c)) = w; /* the step order, one dword a lane */
@@ -377,17 +346,14 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel(
} /* namespace */
/* x [M][n] bf16, `x_ld` elements a row (0 = n)
* q [M][n] i8, DENSE, in libref's STEP ORDER (i8_step_pos: bits 2 and 3 of the
* column exchanged), so n is a multiple of 16, not of 4
* s [M] f32, ONE scale a row, written at element pitch `s_ld` (0 = 1). A
* plane with more room than rows is legal and filled in libref's flat
* order -- the row's scale at s[r], the tail the caller's -- because
* that is what libref does with whatever capacity it is handed, and a
* byte comparison of the tail then agrees.
* q [M][n] i8, dense, in libref's step order (i8_step_pos), n % 16 == 0
* s [M] f32, one scale a row at element pitch `s_ld` (0 = 1). A larger
* plane is legal and filled as libref fills it: the row's scale at
* s[r], the tail left to the caller.
* asum [n/group][Mpad] f32, optional, group-major, Mpad = ceil(M/16)*16
*
* `group` sizes asum and is ignored without it, as libref ignores it: it is the width of the code
* sums, not the granularity of the scale, which is the whole row. */
* `group` is the width of the code sums, not of the scale, and is ignored without asum (as in
* libref). */
extern "C" int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n, int group,
int x_ld, int s_ld, long stream) {
if (!x || !q || !s) return -1;
@@ -419,13 +385,11 @@ extern "C" int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n,
}
/* x [M][n] bf16, `x_ld` elements a row (0 = n)
* q [M][n] i8, DENSE and ROW-MAJOR: the plane this library's i8a8 GEMM reads
* q [M][n] i8, dense and row-major: the plane this library's i8a8 GEMM reads
* s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group))
*
* `group` is the scale's width and is clamped to n when absent, as libref clamps it: `group >= n`
* and `group` absent are both one scale a row. Codes clamp to +-127 before
* the codec, in q8_group's order. 0, -1, -2 a bad extent or an uninstantiated group, -3 a pitch
* that does not describe the operand, -4 the HIP launch failed. */
* `group` is the scale's width; `group >= n` is one scale a row (the shim clamps an absent group
* to n, as libref does). Return codes as r3d_quant_act_fp8. */
extern "C" int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group,
long long x_ld, long long s_ld, long stream) {
if (!x || !q || !s) return -1;
@@ -462,20 +426,17 @@ namespace {
/* ================================================================== gated_quant_fp8
*
* act(gate) * up, then quant_act_fp8's quantiser, in one pass. `gate_up` is
* [M, 2n], gate in the first n and up in the second, which is what a fused gate_up projection
* writes; the product is what gets quantised, and `out_bf16`, when bound, receives it.
* act(gate) * up, then quant_act_fp8's quantiser, in one pass. `gate_up` is [M, 2n], gate first,
* as a fused gate_up projection writes it; `out_bf16`, when bound, receives the product.
*
* The product is narrowed to bf16 and read back before the absmax. That is the op and not an
* optimisation: the unfused pair writes a bf16 [M, n] tensor and quantises those bytes, so the
* codes are taken over the narrowed value and out_bf16 holds exactly the value they came from.
* Within the product the rounding points are libref's: sg = 1/(1+exp(-gate)) in f32, then
* (gate*sg) for silu -- MULTIPLIED, not divided, which is a different f32 -- then * up, then one
* bf16 narrowing. `expf` is the accurate form and not __expf (r3d_common.h); it is the one value in
* this unit the reference evaluates in double, so a code can move by one where the bf16 narrowing
* lands on a tie. Every other number here is bit-for-bit.
* The product is narrowed to bf16 and read back before the absmax, matching the unfused pair
* (which quantises a bf16 tensor), so out_bf16 holds exactly the value the codes came from.
* Rounding points are libref's: sg = 1/(1+exp(-gate)) in f32, then gate*sg for silu (multiplied,
* not divided), then * up, then one bf16 narrowing. `expf` is the accurate form, not __expf
* (r3d_common.h). The reference evaluates exp in double, so a code can differ by one where the
* bf16 narrowing lands on a tie; everything else is bit-exact.
*
* No row reduction, so no first pass and no barrier: a wave a group, a lane four columns.
* No row reduction, so no barrier: a wave a group, a lane four columns.
*/
template <int GROUP, int ACT>
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void gated_quant_fp8_kernel(
@@ -567,8 +528,7 @@ extern "C" int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16,
case 512: R3D_GQ(512, A); break; \
default: return -2; \
}
/* The gate is a template argument, so the multiply below is one instruction and not a branch in
* the inner loop; the switch is over the group widths, each with its own lane mapping. */
/* The activation is a template argument, so the inner loop has no branch on it. */
if (act == R3D_ACT_SILU) { R3D_GQ_ACT(R3D_ACT_SILU); }
else { R3D_GQ_ACT(R3D_ACT_SIGMOID); }
#undef R3D_GQ_ACT
@@ -580,16 +540,13 @@ namespace {
/* ================================================================== dequant
*
* y = code * scale, the read of a container's own quantised weight. Elementwise,
* so there is no reduction and no order to match; the code decodes exactly (E4M3's four exponent
* bits and three mantissa bits are a subset of f16's, and of f32's; E5M2 is f16's top byte,
* rad_plugin.h; int8 is exact in f32), the product is one f32 multiply per element, and the
* store narrows it to bf16 -- the width every consumer of a dequantised weight on this card reads,
* which is why the launcher names the codes' dtype and not the output's.
* y = code * scale, the read of a container's own quantised weight. Elementwise; each code
* decodes exactly to f32 (E4M3 is a subset of f16 and f32, E5M2 is f16's top byte per
* rad_plugin.h, int8 is exact), one f32 multiply follows, and the store narrows to bf16, the width
* every consumer of a dequantised weight here reads.
*
* The scale stream is [M, ceil(n/group)] and the shim requires it to carry every group, so the
* clamp below never fires on a well-formed call; libref clamps a short stream's index to its last
* scale instead of reading off the end, and a kernel row refuses that geometry instead.
* The shim requires the scale stream [M, ceil(n/group)] to carry every group, so the index clamp
* below (libref's behaviour for a short stream) never fires on a well-formed call.
*/
template <int QDT>
__device__ __forceinline__ float code_value(uint8_t b) {
@@ -612,8 +569,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void dequant_kernel(
const float sc = ldg_f32(sr + gi);
/* n is a multiple of 4 and the plane is dense, so a lane's four codes are one dword. */
const uint32_t w = ldg_u32((const uint32_t*)(qr + c));
/* One 8-byte store a lane: bf16x2_rne is software RTNE, because gfx11 has no
* v_cvt_pk_bf16_f32 (r3d_common.h), and the narrowing is the store's single round. */
/* One 8-byte store a lane. bf16x2_rne is software RTNE since gfx11 has no
* v_cvt_pk_bf16_f32 (r3d_common.h). */
uint32_t* yp = (uint32_t*)(yr + c);
yp[0] = bf16x2_rne(code_value<QDT>((uint8_t)(w & 0xffu)) * sc,
code_value<QDT>((uint8_t)(w >> 8)) * sc);
@@ -624,13 +581,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void dequant_kernel(
} /* namespace */
/* q [M][n] codes, DENSE: E4M3, E5M2 or i8, one byte apiece
/* q [M][n] codes, dense: E4M3, E5M2 or i8, one byte apiece
* s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group))
* y [M][n] bf16, `y_ld` elements a row (0 = n)
*
* `y` is bf16: the launcher describes the codes' dtype and not the output's, because a dequantised
* weight here is read by a bf16 dot2 GEMM, which is the same reason r3d.h gives this launcher one
* dtype argument. An f32 plane is r3d_cast's, which carries two. */
* `q_dt` names the codes; the output is always bf16, since a dequantised weight here feeds a bf16
* dot2 GEMM. An f32 output is r3d_cast's job. */
extern "C" int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s_ld,
int y_ld, long stream) {
if (!q || !s || !y) return -1;
@@ -660,22 +616,17 @@ extern "C" int r3d_dequant(long q, long s, long y, int M, int n, int group, int
/* ================================================================== the plugin ABI entry points
*
* Three things every shim here reads off the operands and not off the parameters:
* Every shim reads three things off the operands, not the parameters:
*
* * the dtype. A row's `dtype` constraint is a necessary condition on the geometry, not a promise
* about the tensors, and an f32 activation read as bf16 is a value that passes every other
* check.
* * the row count. `M` is the band's upper bound, so the args carry a bound and the operand
* carries the call.
* * the pitch. r3d_rows_pitch() answers in elements, or -1 for an inner axis that is strided.
* * the dtype. A row's `dtype` constraint is a condition on the geometry, not a promise about the
* tensors, and an f32 activation read as bf16 would pass every other check.
* * the row count. `M` is the band's upper bound; the operand carries the call's rows.
* * the pitch. r3d_rows_pitch() answers in elements, or -1 for a strided inner axis.
*
* The code planes are dense: none of the four launchers takes a code pitch, because a dot2 GEMM
* reads codes row-major and the engine hands them over in the order it stores them. A plane with a
* hole in it is a stride refusal and not a slow path. */
* Code planes are dense: no launcher takes a code pitch, and a plane with a hole is a stride
* refusal, not a slow path. */
/* bf16 is the only activation width these kernels read. An f32 activation is r3d_cast's problem,
* which takes the dtypes as arguments; a quantiser with a dtype switch in its inner loop is the
* wrong shape for an op whose whole point is the store. */
/* bf16 is the only activation dtype these kernels read; an f32 activation goes through r3d_cast. */
static inline int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
static inline int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; }
/* The codes' dtype picks the codec, so it is checked exactly and never as "some byte". */
@@ -695,11 +646,10 @@ static inline int r3d_launch_status(int e) {
}
}
/* The group must be a power of two from 4 to 512: the amax butterfly is over the lanes covering a
* group, GROUP/4 of them, and the kernels are instantiated for those widths. libref clamps
* `group <= 0 || group > n` to n, so "one scale a row" arrives as 0 and leaves as n;
* a width with no instantiation is refused and not rounded, because a rounded group would quantise
* on a grid the weight's scales are not on. */
/* The group must be a power of two from 4 to 512, the instantiated widths. As in libref,
* `group <= 0 || group > n` means one scale a row (n). Any other width is refused, not rounded,
* since a rounded group would quantise on a grid the weight's scales are not on. Returns 0 on
* refusal. */
static inline int r3d_group_of(long long g, long long n) {
if (g <= 0 || g > n) g = n;
return (g >= 4 && g <= 512 && (g & (g - 1)) == 0) ? (int)g : 0;
@@ -752,20 +702,15 @@ extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) {
R3D_NEED(dt_bf16(x));
R3D_NEED(dt_i8(q));
R3D_NEED(dt_f32(sc));
if (r3d_has(as)) R3D_NEED(dt_f32(as)); /* a slot with no bytes is the operand being absent */
if (r3d_has(as)) R3D_NEED(dt_f32(as)); /* a slot with no bytes is an absent operand */
const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1));
if (n <= 0 || n % 16) return R3D_NO(RAD_E_SHAPE); /* a whole 16-byte step: see i8_step_pos */
/* One scale a row: this op's scale granularity IS the row (the amax runs over the whole row,
* and the store is `stt(s, rowoff(s, r, 1), scale)`, a FLAT stream at element pitch 1), and
* libref lists `group` as the width of the row SUMS, not of the scale. A plane with more
* elements than rows is therefore accepted and filled in libref's order: the row's scale
* lands at s[r], the plane's first M elements, and the rest of it stays the caller's. That
* is exactly the plane the row's operand description gives --
* [M, ceil(n/group)], quant_act_i8g's width, of which this op writes the first column -- and
* refusing it would be the shim tightening its own row past the reference: libref requires
* numel(s) >= rows and nothing more, and the bytes it never touches compare equal. */
/* One scale a row, a flat stream at element pitch 1 as libref writes it (`group` is the
* width of the row sums, not the scale). A larger plane, such as the [M, ceil(n/group)] one
* the row's operand description may give, is accepted: libref requires only
* numel(s) >= rows, writes s[r] and leaves the rest untouched. */
long long rows = 0, qrows = 0, srows = 0;
const long long x_ld = r3d_rows_pitch(x, n, &rows);
@@ -777,8 +722,7 @@ extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) {
if (srows < rows || r3d_numel(sc) < rows) return R3D_NO(RAD_E_SHAPE);
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN);
/* `group` sizes asum only, and is not read without it. n % group == 0, because a sum is over
* whole columns of a row, and the LDS accumulator is 256 groups wide. */
/* `group` sizes asum only. n % group == 0, and the LDS accumulator is kI8MaxGroups wide. */
int group = 0;
if (as) {
group = (int)r3d_geti_or(a, "group", R3D_W8_GROUP);
@@ -797,8 +741,8 @@ extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) {
/* ------------------------------------------------------------------ quant_act_i8g */
/* The int8 plane at group granularity, and the one this library's i8a8 GEMM reads. Operands are
* libref's oQuantFp8 shape -- {x, q, scale} -- with the int8 codes' dtype. */
/* The int8 plane at group granularity, read by this library's i8a8 GEMM. Operands are libref's
* oQuantFp8 shape {x, q, scale} with int8 codes. */
enum { QAG_X = 0, QAG_Q, QAG_S };
extern "C" int r3d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) {
@@ -812,9 +756,7 @@ extern "C" int r3d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) {
const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1));
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
/* libref's clamp of `group`: absent, zero or wider than the row is one
* scale a row, so the default here is 0 and the clamp turns it into n. A width the kernels have
* no instantiation for is refused, not rounded to one. */
/* Absent `group` defaults to 0, which r3d_group_of turns into one scale a row. */
const int group = r3d_group_of(r3d_geti_or(a, "group", 0), n);
if (!group) return R3D_NO(RAD_E_SHAPE);
const long long ngrp = (n + group - 1) / group;
@@ -846,12 +788,11 @@ extern "C" int r3d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) {
R3D_NEED(dt_bf16(gu));
R3D_NEED(dt_e4m3(q));
R3D_NEED(dt_f32(sc));
if (r3d_has(y)) R3D_NEED(dt_bf16(y)); /* the same: an empty slot is no operand at all */
if (r3d_has(y)) R3D_NEED(dt_bf16(y)); /* an empty slot is an absent operand */
/* "silu" (down_proj's input) or "sigmoid" (a gated attention o_proj's), `mode` the integer
* spelling of the same choice, `act` winning where both are given. libref's `act` enumerates
* those two, so a gelu-gated feed-forward is not this row's: it asks for a gate the oracle has
* no definition for here. */
/* "silu" (down_proj's input) or "sigmoid" (a gated attention o_proj's); `mode` is the integer
* spelling and `act` wins when both are given. libref defines only these two, so a gelu gate
* is unsupported. */
const int act = r3d_act_code(a, "act", "mode", R3D_ACT_SILU);
if (act < 0) return R3D_NO(RAD_E_UNSUPPORTED);
@@ -861,8 +802,8 @@ extern "C" int r3d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) {
if (!group) return R3D_NO(RAD_E_SHAPE);
const long long ngrp = (n + group - 1) / group;
/* The fused gate_up projection writes the plane dense, gate half first, [M, 2n] with no hole: a
* sliced gate is r3d_act_mul_bf16's, which takes the two pitches. */
/* gate_up must be dense [M, 2n], as the fused projection writes it; a sliced gate goes through
* r3d_act_mul_bf16, which takes two pitches. */
long long rows = 0, qrows = 0, srows = 0, yrows = 0;
const long long gu_ld = r3d_rows_pitch(gu, 2 * n, &rows);
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
@@ -890,15 +831,14 @@ extern "C" int r3d_rad_dequant(const RadArgs* a, RadStream stream) {
const RadTensor* sc = r3d_opt(a, DQT_S);
const RadTensor* y = r3d_opt(a, DQT_Y);
if (!q || !sc || !y) return R3D_NO(RAD_E_INVAL);
/* The codes' dtype IS the encoding, so it is read off the tensor: E4M3 and E5M2 are one byte
* apiece and nothing in the bytes tells them apart. A plain u8 plane carries no encoding, so it
* is not accepted under the E4M3 code. */
/* The codes' dtype is the encoding, read off the tensor since E4M3 and E5M2 bytes look alike.
* A plain u8 plane carries no encoding and is refused (R3D_DT_U8 is the E4M3 code here). */
if (q->dtype == RAD_U8) return R3D_NO(RAD_E_DTYPE);
const int q_dt = r3d_dt_code(q->dtype);
if (q_dt != R3D_DT_U8 && q_dt != R3D_DT_E5M2 && q_dt != R3D_DT_I8)
return R3D_NO(RAD_E_DTYPE);
R3D_NEED(dt_f32(sc));
R3D_NEED(dt_bf16(y)); /* the launcher has no output dtype; see above */
R3D_NEED(dt_bf16(y)); /* the launcher writes bf16 only */
const long long n = r3d_geti_or(a, "n", r3d_dim(y, (int)y->rank - 1));
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
@@ -911,8 +851,8 @@ extern "C" int r3d_rad_dequant(const RadArgs* a, RadStream stream) {
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
/* The scale stream's extent gives the group count and `group` each group's width, as libref
* reads them; with no `group`, the stream is taken as one scale per group of ceil(n/ngrp). */
/* As in libref, `group` gives each group's width; without it the width is ceil(n/ngrp), with
* ngrp taken from the scale stream's extent. */
const long long ngrp_param = r3d_numel(sc) / rows > 0 ? r3d_numel(sc) / rows : 1;
long long group = r3d_geti_or(a, "group", 0);
if (group <= 0) group = (n + ngrp_param - 1) / ngrp_param;