From 979b54e09132455ab4b59a4aa740c23299073e1b Mon Sep 17 00:00:00 2001 From: baKon Date: Fri, 16 Oct 2026 03:06:38 -0500 Subject: [PATCH] libr4d: lora_shrink and lora_expand, scalar f32 v1 r4d_lora_bf16.hip: shrink is one block a row (a base row's block leaves at once), one wave a column of R, each lane's k in order and a fixed xor butterfly, so a row's bytes depend on nothing but the row. Expand is one thread an output over M strips of 256 columns, j ascending, sum then scale then one rounding to y's dtype: libref's order, so the emulator holds it to libref bit for bit. A base row of y is neither read nor written. Strides of a, a_scale, t, y and the pools come from the tensors; the grid is M (and N) only. Rows lora_shrink_scalar / lora_expand_scalar with libref's schemas field for field, constrained with C_IN on the tensor dtype names, so an activation the decode does not read never resolves. Not concurrent: the core orders them behind their GEMM. r4d_selftest gets a device case (not run here: this host's GPU is off limits for this work). --- libr4d/CMakeLists.txt | 2 + libr4d/README.md | 1 + libr4d/r4d_lora_bf16.hip | 430 +++++++++++++++++++++++++++++++++++++++ libr4d/r4d_plugin.h | 3 + libr4d/r4d_rows.cpp | 87 +++++++- libr4d/r4d_selftest.cpp | 148 ++++++++++++++ 6 files changed, 669 insertions(+), 2 deletions(-) create mode 100644 libr4d/r4d_lora_bf16.hip diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 17879e15..10537213 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -149,6 +149,8 @@ set(R4D_UNITS # expert_scale, each one kernel for a chain of small ones. "r4d_norm_join_bf16|" "r4d_expert_scale_bf16|" + # Runtime LoRA's two halves (lora_shrink, lora_expand), per-row adapter slot; scalar f32 v1. + "r4d_lora_bf16|" "r4d_dflash_conv_t2_g16_bf16|" "r4d_dflash_select_bf16|" # Routed MoE: router, scatter, the grouped block-scaled fp8 GEMM and gather, in one unit because diff --git a/libr4d/README.md b/libr4d/README.md index 99a5a294..a922c365 100644 --- a/libr4d/README.md +++ b/libr4d/README.md @@ -59,6 +59,7 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set. | `dflash_conv_t2_g16_bf16` | the drafter's causal conv, two taps, 16 groups | | `dflash_select_bf16` | the drafter's candidate selector: edge scores and the greedy path walk | | `dequant_w4_bf16` | unpacks a 4-bit fragment-ordered weight back to bf16 | +| `lora_shrink` / `lora_expand` | runtime LoRA's two halves beside a trunk GEMM, each row's adapter read from a per-row slot on the device (base rows untouched): `t = x A[slot]^T` one block a row, `y += scale ⊙ (t B[slot]^T)` one thread an output; scalar f32, a row's bytes independent of M | | `quant_act_i8` / `quant_act_i8_asum` | per-row int8 activation quantiser, in the r4d GEMMs' fragment byte order; the `_asum` form also emits the per-group row sums the asymmetric GEMMs need | | `had_quant_act_i8` | the same with a block Walsh-Hadamard rotation first, which is what makes one scale per row viable | | `rmsnorm_had_quant_i8` | residual add, RMS norm, rotate and quantise in one kernel | diff --git a/libr4d/r4d_lora_bf16.hip b/libr4d/r4d_lora_bf16.hip new file mode 100644 index 00000000..f5984e01 --- /dev/null +++ b/libr4d/r4d_lora_bf16.hip @@ -0,0 +1,430 @@ +/* r4d_lora_bf16.hip -- runtime LoRA's two halves, lora_shrink and lora_expand, per-row slot. + * + * lora_shrink t[m, j] = sum_k x(m, k) * A[s, j, k] s = slot[m] + * lora_expand y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * B[s, n, j] + * + * The core issues the pair right after a targeted trunk GEMM, in the GEMM's own row slice, with + * `a`/`a_scale` the GEMM's activation operands and `y` its output (docs/OPS.md). A row whose slot + * is outside [0, S) is a BASE row and both kernels leave it before touching anything: shrink + * writes no `t`, expand neither reads nor writes `y` -- `y + 0` would already turn a -0 into +0, + * and the engine's promise is that a base row is bit for bit what the GEMM wrote. + * + * V1, SCALAR f32 AND CORRECT FIRST. The adapter term is a rank-R correction (R <= 64 a module) + * next to an N x K GEMM, so it is small whatever it costs per FLOP; the WMMA form -- a 16-row tile + * per distinct slot, other slots' rows masked out of the fragment -- is a later speed pass. What + * this form already guarantees, and the later one must keep: + * + * * NO SPLIT THAT MOVES WITH M. A row's shrink is one wave per column j, lane l summing the k + * that are l mod 32 in ascending order, then a fixed xor butterfly; expand is one thread per + * (m, n) summing j ascending. Neither depends on the batch a row arrives in, which is what + * lets the engine claim "a request alone == the same request in a mixed batch" for the LoRA + * term. + * * THE GRID IS M AND THE DECLARED PARAMETERS. Which adapters are active is read on the device, + * from `slot` and the pools, so a recorded pass replays the same packets whatever the slots + * hold. + * * NO HOST READS, NO SCRATCH, NO LDS: the reduction is cross-lane only, so a block never waits + * on another wave and a base row leaves before any cross-lane op. + * + * x(m, k) IS gemm_nt_q's ACTIVATION VALUE: a code times its group's scale (one f32 product), or a + * bf16/f16/f32 element as it stands, with the scale stream's grid read the way libref's + * make_scales reads it. The decodes below are the ABI's conversions (rad_plugin.h) restated for + * the device, bit for bit, so a code decodes here exactly as it does in the oracle. gfx1201 has no + * bf16 convert; the narrowing is the ABI's RTNE with its quiet-NaN rule. Every multiply-add rounds + * twice (-ffp-contract=off, RadAddPlugin.cmake), so expand computes libref's bytes and shrink + * differs from them only by its summation order. + * + * Kernels are written against r4d_launch.h so tests/r4d_emu runs this source on the host. + */ +#include + +#include + +#include "r4d_plugin.h" +#include "r4d_launch.h" +#include "rad_plugin.h" + +namespace r4d_lora { + +/* What `a` holds; a template argument so the decode is chosen once per launch, not per element. */ +enum { kBF16 = 0, kF16 = 1, kF32 = 2, kE4M3 = 3, kE5M2 = 4, kI8 = 5 }; + +struct ShrinkArgs { + const void* a; long long a_rs, a_cs; /* element strides of `a` */ + const float* as; long long s_rs, s_cs; /* null: no scale stream */ + const int32_t* slot; long long slot_st; + const uint16_t* la; long long la_s0, la_s1, la_s2; + float* t; long long t_rs, t_cs; + int K, group, R, S; /* K < 2^31: 32-bit k and k / group */ +}; + +struct ExpandArgs { + const float* t; long long t_rs, t_cs; + const int32_t* slot; long long slot_st; + const uint16_t* lb; long long lb_s0, lb_s1, lb_s2; + const float* sc; long long sc_rs, sc_cs; + void* y; long long y_rs, y_cs; + long long N, ntiles; + int R, S; +}; + +/* ------------------------------------------------------- the ABI's conversions, on the device */ +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((unsigned)h << 16); } + +__device__ __forceinline__ uint16_t f2bf(float f) { /* rad_f32_to_bf16 */ + const unsigned u = __float_as_uint(f); + if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t)((u >> 16) | 0x0040u); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +__device__ inline float f16_to_f32(uint16_t h) { /* rad_f16_to_f32 */ + const unsigned s = (unsigned)(h >> 15) << 31; + const unsigned e = ((unsigned)h >> 10) & 0x1fu; + unsigned m = (unsigned)h & 0x3ffu, u; + if (e == 0u) { + if (m == 0u) { + u = s; + } else { + int sh = 0; + while (!(m & 0x400u)) { m <<= 1; ++sh; } + m &= 0x3ffu; + u = s | ((unsigned)(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 __uint_as_float(u); +} + +__device__ inline uint16_t f32_to_f16(float f) { /* rad_f32_to_f16 */ + const unsigned u = __float_as_uint(f); + const unsigned s = (u >> 16) & 0x8000u, a = u & 0x7fffffffu; + if (a >= 0x7f800000u) + return (uint16_t)(s | 0x7c00u | (a > 0x7f800000u ? ((a >> 13) & 0x3ffu) | 0x200u : 0u)); + if (a >= 0x47800000u) return (uint16_t)(s | 0x7c00u); + if (a < 0x33000000u) return (uint16_t)s; + const int e = (int)(a >> 23) - 127; + unsigned m = a & 0x7fffffu; + if (e < -14) { + const int sh = -14 - e + 13; + m |= 0x800000u; + const unsigned lo = m & ((1u << sh) - 1u), half = 1u << (sh - 1); + unsigned q = m >> sh; + if (lo > half || (lo == half && (q & 1u))) ++q; + return (uint16_t)(s | q); + } + unsigned q = m >> 13, he = (unsigned)(e + 15); + const unsigned lo = m & 0x1fffu; + if (lo > 0x1000u || (lo == 0x1000u && (q & 1u))) ++q; + if (q == 0x400u) { q = 0; ++he; } + if (he >= 0x1fu) return (uint16_t)(s | 0x7c00u); + return (uint16_t)(s | (he << 10) | q); +} + +__device__ inline float e4m3_to_f32(uint8_t b) { /* rad_fp8e4m3_to_f32 */ + const unsigned s = (unsigned)(b >> 7) << 31; + const unsigned e = ((unsigned)b >> 3) & 0xfu; + unsigned m = (unsigned)b & 0x7u, u; + if (e == 0u) { + if (m == 0u) { + u = s; + } else { + int sh = 0; + while (!(m & 0x8u)) { m <<= 1; ++sh; } + m &= 0x7u; + u = s | ((unsigned)(127 - 6 - sh) << 23) | (m << 20); + } + } else if (e == 0xfu && m == 0x7u) { + u = s | 0x7fc00000u; + } else { + u = s | ((e - 7u + 127u) << 23) | (m << 20); + } + return __uint_as_float(u); +} + +template +__device__ __forceinline__ float ld_act(const void* p, long long i) { + if (ADT == kBF16) return bf2f(((const uint16_t*)p)[i]); + if (ADT == kF16) return f16_to_f32(((const uint16_t*)p)[i]); + if (ADT == kF32) return ((const float*)p)[i]; + if (ADT == kE4M3) return e4m3_to_f32(((const uint8_t*)p)[i]); + if (ADT == kE5M2) return f16_to_f32((uint16_t)((unsigned)((const uint8_t*)p)[i] << 8)); + return (float)((const int8_t*)p)[i]; +} + +/* The sum of a wave's 32 values, the same on every lane and in a fixed order: an xor butterfly over + * ds_bpermute. Each step adds the same two values on both partners (a + b == b + a), so the lanes + * never drift apart and no lane's answer depends on the schedule. */ +__device__ __forceinline__ float wave_sum(float v, int lane) { + for (int off = 16; off >= 1; off >>= 1) { + const int o = __builtin_amdgcn_ds_bpermute((lane ^ off) << 2, __float_as_int(v)); + v = v + __int_as_float(o); + } + return v; +} + +/* ---------------------------------------------------------------- the kernels */ + +/* One block a row, eight waves; wave w owns columns j = w, w + 8, ... The x row is re-read per + * column from cache rather than staged: K reaches 17408, past what LDS holds as f32. */ +template +__global__ __launch_bounds__(256) void lora_shrink_kernel(ShrinkArgs A) { + const long long m = blockIdx.x; + const int s = A.slot[m * A.slot_st]; + if (s < 0 || s >= A.S) return; /* a base row: no t written */ + const int lane = (int)(threadIdx.x & 31u), wave = (int)(threadIdx.x >> 5); + const long long x0 = m * A.a_rs, s0 = m * A.s_rs; + for (int j = wave; j < A.R; j += 8) { + const uint16_t* arow = A.la + (long long)s * A.la_s0 + (long long)j * A.la_s1; + float acc = 0.0f; + for (int k = lane; k < A.K; k += 32) { + float x = ld_act(A.a, x0 + (long long)k * A.a_cs); + if (A.as) x = x * A.as[s0 + (long long)(k / A.group) * A.s_cs]; + acc += x * bf2f(arow[(long long)k * A.la_s2]); + } + acc = wave_sum(acc, lane); + if (lane == 0) A.t[m * A.t_rs + (long long)j * A.t_cs] = acc; + } +} + +/* One thread an output element over a flat grid of M row-strips of 256 columns. */ +template +__global__ __launch_bounds__(256) void lora_expand_kernel(ExpandArgs A) { + const long long b = blockIdx.x; + const long long m = b / A.ntiles; + const long long n = (b - m * A.ntiles) * 256 + threadIdx.x; + if (n >= A.N) return; + const int s = A.slot[m * A.slot_st]; + if (s < 0 || s >= A.S) return; /* a base row: y not read, not written */ + const float* trow = A.t + m * A.t_rs; + const uint16_t* brow = A.lb + (long long)s * A.lb_s0 + n * A.lb_s1; + float acc = 0.0f; + for (int j = 0; j < A.R; ++j) + acc += trow[(long long)j * A.t_cs] * bf2f(brow[(long long)j * A.lb_s2]); + const float d = A.sc[(long long)s * A.sc_rs + n * A.sc_cs] * acc; + const long long o = m * A.y_rs + n * A.y_cs; + if (YDT == kBF16) { + uint16_t* y = (uint16_t*)A.y + o; + *y = f2bf(bf2f(*y) + d); + } else if (YDT == kF16) { + uint16_t* y = (uint16_t*)A.y + o; + *y = f32_to_f16(f16_to_f32(*y) + d); + } else { + float* y = (float*)A.y + o; + *y = *y + d; + } +} + +/* ---------------------------------------------------------------- operand reading (host) */ + +/* `t` read as [rows, cols]: the trailing axes that span `cols` must be one dense run, the leading + * ones fold to rows, and the row stride is the axis just outside the run -- libref/ref_gemm.h's + * row_stride, so a rank-3 [tokens, heads, width] activation and a column slice of a fused plane are + * read the way the oracle reads them. False when no single (rows, row stride, column stride) + * describes the tensor. */ +static bool as_rows(const RadTensor* t, int64_t cols, int64_t* rows, int64_t* rs, int64_t* cs) { + if (!t || t->rank < 1 || cols <= 0) return false; + const int r = (int)t->rank; + int i = r - 1; + int64_t span = t->shape[i]; + while (span < cols && i > 0) { + if (t->stride[i - 1] != t->stride[i] * t->shape[i]) return false; + --i; + span *= t->shape[i]; + } + if (span != cols) return false; + int64_t n = 1; + for (int d = 0; d < i; ++d) n *= t->shape[d]; + for (int d = 0; d + 1 < i; ++d) + if (t->shape[d + 1] > 1 && t->stride[d] != t->stride[d + 1] * t->shape[d + 1]) return false; + *rows = n; + *rs = i > 0 ? t->stride[i - 1] : cols; + *cs = t->stride[r - 1]; + return true; +} + +/* The per-row slot array: [M], or [M, 1] -- its length and element stride. */ +static bool as_vec(const RadTensor* t, int64_t* n, int64_t* st) { + if (!t) return false; + if (t->rank == 1) { *n = t->shape[0]; *st = t->stride[0]; return true; } + int64_t cs = 0; + return as_rows(t, 1, n, st, &cs); +} + +/* A pool [S, rows, cols]: its three strides; anything but rank 3 is read dense. */ +static void pool3(const RadTensor* t, int64_t rows, int64_t cols, long long* s0, long long* s1, + long long* s2) { + if (t->rank == 3) { *s0 = t->stride[0]; *s1 = t->stride[1]; *s2 = t->stride[2]; return; } + *s0 = rows * cols; *s1 = cols; *s2 = 1; +} + +/* libref/ref_gemm.h's grid_block: the power of two whose ceiling division gives `blocks`. */ +static int64_t grid_block(int64_t ext, int64_t blocks) { + if (ext <= 0) return 1; + if (blocks <= 1) return ext; + const int64_t lo = (ext + blocks - 1) / blocks; + int64_t b = 1; + while (b < lo) b <<= 1; + return (ext + b - 1) / b == blocks ? b : lo; +} + +/* The dtype parameter is the tensor's own name (rad_dtype_name); a row resolved for one dtype and + * handed another would compute the wrong decode, so a disagreement is refused, not followed. */ +static bool dtype_agrees(const RadArgs* a, uint32_t dt) { + const char* d = rad_args_gets(a, "dtype"); + return !d || rad_dtype_parse(d) == dt; +} + +/* The launches, one per dtype instantiation: the grid is M blocks for shrink and M strips of 256 + * columns for expand, 256 threads each, whatever the slots hold. */ +template +static void launch_shrink(const ShrinkArgs& P, int64_t blocks, RadStream stream) { + (void)stream; /* the host emulator's launch takes none */ + R4D_KLAUNCH(R4D_KNAME(lora_shrink_kernel), dim3((unsigned)blocks), dim3(256), + (hipStream_t)stream, P); +} +template +static void launch_expand(const ExpandArgs& P, int64_t blocks, RadStream stream) { + (void)stream; + R4D_KLAUNCH(R4D_KNAME(lora_expand_kernel), dim3((unsigned)blocks), dim3(256), + (hipStream_t)stream, P); +} + +} /* namespace r4d_lora */ + +extern "C" { + +/* operands: a, a_scale?, slot, lora_a, t */ +int r4d_rad_lora_shrink(const RadArgs* a, RadStream stream) { + using namespace r4d_lora; + if (!a || a->n_t < 5) return RAD_E_INVAL; + const RadTensor *X = rad_arg_in(a, 0), *XS = rad_arg_in(a, 1), *SL = rad_arg_in(a, 2); + const RadTensor *LA = rad_arg_in(a, 3), *T = rad_arg_in(a, 4); + if (!X || !SL || !LA || !T) return RAD_E_INVAL; + if (XS && XS->dtype == RAD_DT_INVALID) XS = nullptr; /* absent, as libref */ + const int64_t K = rad_args_geti_or(a, "K", 0), R = rad_args_geti_or(a, "R", 0); + const int64_t S = rad_args_geti_or(a, "S", 0); + if (K <= 0 || K > 0x7fffffff || R <= 0 || S <= 0 || R > (1 << 16) || S > (1 << 20)) + return RAD_E_SHAPE; + int adt; + switch (X->dtype) { + case RAD_BF16: adt = kBF16; break; + case RAD_F16: adt = kF16; break; + case RAD_F32: adt = kF32; break; + case RAD_F8E4M3: adt = kE4M3; break; + case RAD_F8E5M2: adt = kE5M2; break; + case RAD_I8: adt = kI8; break; + default: return RAD_E_DTYPE; + } + if (!dtype_agrees(a, X->dtype)) return RAD_E_DTYPE; + if (adt >= kE4M3 && !XS) return RAD_E_INVAL; /* a code without its scale has no value */ + if (LA->dtype != RAD_BF16 || T->dtype != RAD_F32 || SL->dtype != RAD_I32) return RAD_E_DTYPE; + + int64_t M = 0, t_rs = 0, t_cs = 0, xr = 0, x_rs = 0, x_cs = 0, sr = 0, sl_st = 0; + if (!as_rows(T, R, &M, &t_rs, &t_cs)) return RAD_E_SHAPE; /* the step's rows: t's view */ + if (M <= 0) return RAD_E_SHAPE; /* zero rows is not a call */ + const int64_t band = rad_args_geti_or(a, "M", 0); /* libref's band_rows rule */ + if (band > 0 && M > band) return RAD_E_SHAPE; + if (!as_rows(X, K, &xr, &x_rs, &x_cs) || xr < M) return RAD_E_SHAPE; + if (!as_vec(SL, &sr, &sl_st) || sr < M) return RAD_E_SHAPE; + if (rad_tensor_numel(LA) < S * R * K) return RAD_E_SHAPE; + if (M > 0x7fffffff) return RAD_E_SHAPE; + + ShrinkArgs P{}; + P.a = X->data; P.a_rs = x_rs; P.a_cs = x_cs; + if (XS) { + /* gemm_nt_q's reading of the stream: [rows, groups] with its own strides, or a flat + * [rows * groups]; the group is what the stream's extent implies. A grid with fewer rows + * than the activation is a weight's block grid, never an activation's. */ + if (XS->dtype != RAD_F32) return RAD_E_DTYPE; + int64_t groups = 0; + if (XS->rank >= 2) { + if (XS->shape[XS->rank - 2] < M) return RAD_E_SHAPE; + groups = XS->shape[XS->rank - 1]; + P.s_rs = XS->stride[XS->rank - 2]; + P.s_cs = XS->stride[XS->rank - 1]; + } else { + const int64_t nel = rad_tensor_numel(XS); + if (nel < M) return RAD_E_SHAPE; + groups = nel / M; + P.s_rs = groups; + P.s_cs = 1; + } + if (groups <= 0) return RAD_E_SHAPE; + const int64_t group = grid_block(K, groups); + const int64_t gp = rad_args_geti_or(a, "group", 0); /* the grid, as libref */ + if (gp > 0 && (K + gp - 1) / gp != (K + group - 1) / group) return RAD_E_SHAPE; + P.group = (int)group; + P.as = (const float*)XS->data; + } + P.slot = (const int32_t*)SL->data; P.slot_st = sl_st; + P.la = (const uint16_t*)LA->data; + pool3(LA, R, K, &P.la_s0, &P.la_s1, &P.la_s2); + P.t = (float*)T->data; P.t_rs = t_rs; P.t_cs = t_cs; + P.K = (int)K; P.R = (int)R; P.S = (int)S; + if (!P.as) P.group = (int)K; + + switch (adt) { + case kBF16: launch_shrink(P, M, stream); break; + case kF16: launch_shrink(P, M, stream); break; + case kF32: launch_shrink(P, M, stream); break; + case kE4M3: launch_shrink(P, M, stream); break; + case kE5M2: launch_shrink(P, M, stream); break; + default: launch_shrink(P, M, stream); break; + } + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +/* operands: t, slot, lora_b, scale, y (inout) */ +int r4d_rad_lora_expand(const RadArgs* a, RadStream stream) { + using namespace r4d_lora; + if (!a || a->n_t < 5 || !rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *T = rad_arg_in(a, 0), *SL = rad_arg_in(a, 1), *LB = rad_arg_in(a, 2); + const RadTensor *SC = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4); + const int64_t N = rad_args_geti_or(a, "N", 0), R = rad_args_geti_or(a, "R", 0); + const int64_t S = rad_args_geti_or(a, "S", 0); + if (N <= 0 || R <= 0 || S <= 0 || R > (1 << 16) || S > (1 << 20)) return RAD_E_SHAPE; + int ydt; + switch (Y->dtype) { + case RAD_BF16: ydt = kBF16; break; + case RAD_F16: ydt = kF16; break; + case RAD_F32: ydt = kF32; break; + default: return RAD_E_DTYPE; + } + if (!dtype_agrees(a, Y->dtype)) return RAD_E_DTYPE; + if (T->dtype != RAD_F32 || SC->dtype != RAD_F32 || LB->dtype != RAD_BF16 || + SL->dtype != RAD_I32) + return RAD_E_DTYPE; + + int64_t M = 0, y_rs = 0, y_cs = 0, tr = 0, t_rs = 0, t_cs = 0, sr = 0, sl_st = 0; + if (!as_rows(Y, N, &M, &y_rs, &y_cs)) return RAD_E_SHAPE; /* the step's rows: y's view */ + if (M <= 0) return RAD_E_SHAPE; /* zero rows is not a call */ + const int64_t band = rad_args_geti_or(a, "M", 0); /* libref's band_rows rule */ + if (band > 0 && M > band) return RAD_E_SHAPE; + if (!as_rows(T, R, &tr, &t_rs, &t_cs) || tr < M) return RAD_E_SHAPE; + if (!as_vec(SL, &sr, &sl_st) || sr < M) return RAD_E_SHAPE; + if (rad_tensor_numel(LB) < S * N * R || rad_tensor_numel(SC) < S * N) return RAD_E_SHAPE; + const int64_t ntiles = (N + 255) / 256; + if (M * ntiles > 0x7fffffff) return RAD_E_SHAPE; + + ExpandArgs P{}; + P.t = (const float*)T->data; P.t_rs = t_rs; P.t_cs = t_cs; + P.slot = (const int32_t*)SL->data; P.slot_st = sl_st; + P.lb = (const uint16_t*)LB->data; + pool3(LB, N, R, &P.lb_s0, &P.lb_s1, &P.lb_s2); + P.sc = (const float*)SC->data; + P.sc_rs = SC->rank >= 2 ? SC->stride[SC->rank - 2] : N; + P.sc_cs = SC->rank >= 2 ? SC->stride[SC->rank - 1] : 1; + P.y = Y->data; P.y_rs = y_rs; P.y_cs = y_cs; + P.N = N; P.ntiles = ntiles; P.R = (int)R; P.S = (int)S; + + switch (ydt) { + case kBF16: launch_expand(P, M * ntiles, stream); break; + case kF16: launch_expand(P, M * ntiles, stream); break; + default: launch_expand(P, M * ntiles, stream); break; + } + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* extern "C" */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 7031530f..bc49dafa 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -128,6 +128,9 @@ int r4d_rad_norm_add_norm_bf16 (const RadArgs*, RadStream); int r4d_rad_norm_add_norm_route_bf16(const RadArgs*, RadStream); int r4d_rad_join_add_scale_bf16 (const RadArgs*, RadStream); int r4d_rad_expert_scale_bf16 (const RadArgs*, RadStream); +/* Runtime LoRA's two halves, each row's adapter named by its slot (r4d_lora_bf16.hip). */ +int r4d_rad_lora_shrink (const RadArgs*, RadStream); +int r4d_rad_lora_expand (const RadArgs*, RadStream); int r4d_rad_attn_vit (const RadArgs*, RadStream); int r4d_rad_attn_dense (const RadArgs*, RadStream); int r4d_rad_seg_sinusoid (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index f5b21fff..f7d1d8e1 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2042,6 +2042,41 @@ static const RadOperandSpec oExpertScale[] = { { "ew", RAD_OPD_INOUT, 0 }, }; +/* ------------------------------------------------------------------------------- runtime LoRA + * libref's schemas field for field (libref/ref_registry.cpp says what they mean): the loader + * refuses a library whose schema differs from the first declarer's. The pools are plain inputs -- + * the engine owns them as program buffers and fills a slot between steps -- and `dtype` is the + * tensor dtype name of `a` (shrink) or `y` (expand), which is what the rows below match on. */ +static const RadParamSpec pLoraShrink[] = { + P_INT("M"), + P_INT("K"), + P_INT("R"), + P_INT("S"), + P_INTO("group"), + P_STR("dtype"), +}; +static const RadOperandSpec oLoraShrink[] = { + { "a", RAD_OPD_IN, 0 }, + { "a_scale", RAD_OPD_IN, 1 }, + { "slot", RAD_OPD_IN, 0 }, + { "lora_a", RAD_OPD_IN, 0 }, + { "t", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pLoraExpand[] = { + P_INT("M"), + P_INT("N"), + P_INT("R"), + P_INT("S"), + P_STR("dtype"), +}; +static const RadOperandSpec oLoraExpand[] = { + { "t", RAD_OPD_IN, 0 }, + { "slot", RAD_OPD_IN, 0 }, + { "lora_b", RAD_OPD_IN, 0 }, + { "scale", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_INOUT, 0 }, +}; + #define SCHEMA(op, p, o, doc) { (op), ROW(p), ROW(o), (doc) } /* ---- image generation (r4d_gen.hip, r4d_attn_gen.hip) ------------------------------------- @@ -2660,6 +2695,14 @@ static const RadOpSchema kSchemas[] = { "ew[t, k] = ew[t, k] * w_e[ids[t, k]] over [M, top_k], w_e an [n_expert] table, an id " "outside it reading 0; one product rounded once, so the embed_lookup + mul pair's value " "bit for bit. Gemma 4's per_expert_scale on the renormalised routing weights."), + SCHEMA("lora_shrink", pLoraShrink, oLoraShrink, + "t[m, j] = sum_k x(m, k) * lora_a[s, j, k] for each row m whose s = slot[m] is in " + "[0, S), f32 accumulate; x(m, k) is the value gemm_nt_q uses for that element of `a`. " + "A base row's `t` is not written; a row's bytes do not depend on M."), + SCHEMA("lora_expand", pLoraExpand, oLoraExpand, + "y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * lora_b[s, n, j] for each row m " + "whose s = slot[m] is in [0, S), f32 accumulate, one rounding to y's dtype. A base " + "row's `y` is neither read nor written."), SCHEMA("ln_mod", pLnMod, oLnMod, "y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the " "row's sequence's modulation row of `s`."), @@ -3139,6 +3182,19 @@ static const RadConstraint cPairArgmax[] = { static const RadConstraint cExpertScale[] = { C_GE("top_k", 1), C_LE("top_k", 64), C_GE("n_expert", 1), C_IN("dtype", "bf16"), }; +/* Runtime LoRA. Any M, K and N: the scalar kernels loop over whatever extents arrive, and the grid + * is M blocks (shrink) or M strips of 256 columns (expand). R and S are bounded only by the shims' + * 32-bit index sanity. The dtype set is every activation the decode below reads -- an fp8 or i8 + * one with its scale stream -- and the three outputs a GEMM writes; anything else does not + * resolve here. */ +static const RadConstraint cLoraShrink[] = { + C_GE("R", 1), C_LE("R", 65536), C_GE("S", 1), C_LE("S", 1048576), + C_IN("dtype", "bf16 f16 f32 fp8_e4m3 fp8_e5m2 i8"), +}; +static const RadConstraint cLoraExpand[] = { + C_GE("R", 1), C_LE("R", 65536), C_GE("S", 1), C_LE("S", 1048576), + C_IN("dtype", "bf16 f16 f32"), +}; /* ---- the routed mixture of experts ---------------------------------------------------------- * @@ -6251,6 +6307,28 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cExpertScale), NOTUNE, nullptr, nullptr, r4d_rad_expert_scale_bf16 }, + +/* Runtime LoRA, v1: scalar f32, correct first (r4d_lora_bf16.hip). NO opd_shape: libref describes + * both ops, so rad-kbench draws the same operands for this row as for the oracle -- `slot` in + * [0, S], S itself a base row. NOT CONCURRENT: see rad_kernel_concurrent below. */ +{ "lora_shrink_scalar", "lora_shrink", "gemm", + "t = x A[slot]^T per row, base rows untouched: one block a row, one wave a column, the k of a " + "lane in order and a fixed xor butterfly across the wave", + "any M and K, 1 <= R <= 65536, 1 <= S <= 2^20; row and column strides of a, a_scale and t " + "honoured", + "bf16 / f16 / f32 a, or fp8_e4m3 / fp8_e5m2 / i8 a with its f32 scale stream; bf16 lora_a; " + "i32 slot; f32 t", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cLoraShrink), NOTUNE, + nullptr, nullptr, r4d_rad_lora_shrink }, +{ "lora_expand_scalar", "lora_expand", "gemm", + "y += scale * (t B[slot]^T) per row, base rows neither read nor written: one thread an " + "output, j in order", + "any M and N, 1 <= R <= 65536, 1 <= S <= 2^20; row and column strides of t and y honoured", + "f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cLoraExpand), NOTUNE, + nullptr, nullptr, r4d_rad_lora_expand }, { "attn_prefix_self_h128_bf16", "attn_prefix_self", "attn", "attention over a paged prefix and the pass's own rows, causal over the own rows or not", "head_dim 128, 1/2/4/8 query heads a KV head, a flat grid over the sequences' query blocks; " @@ -6553,13 +6631,18 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { * gemm_mxfp4a8_decode's split partial is the op's scratch and its arrival counters are keyed on the * output alone; router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken * at init, one per declared op and band). Concurrent launches never share these, so those three - * rows are concurrent. A new row with stream-ordered state belongs in the list above. */ + * rows are concurrent. A new row with stream-ordered state belongs in the list above. + * + * lora_* no state of their own, and ordered ON PURPOSE: the core appends them + * behind the GEMM whose `y` they update and refills the pools they read + * between steps with its own copies, so they are kept out of the replay's + * overlap analysis rather than leaning on it. */ extern "C" int rad_kernel_concurrent(int i) { const RadKernelInfo* k = rad_kernel_at(i); if (!k) return 0; if (k->family && std::strcmp(k->family, "ar") == 0) return 0; static const char* const kStateful[] = { - "hc_", "mtp_enter", "ar_", "gemm_w4a8_tiled", "gemm_w8a8_tiled", + "hc_", "mtp_enter", "ar_", "gemm_w4a8_tiled", "gemm_w8a8_tiled", "lora_", }; for (const char* p : kStateful) if (std::strncmp(k->name, p, std::strlen(p)) == 0) return 0; diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 7afab208..ca03e060 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -12464,6 +12464,153 @@ static void ngram_ahead_case(const Plugin& pl) { ok("ngram_ids_i32 ahead: the ids ahead are the ones the next step computes", ahd1 == ids2); } +/* ---- RUNTIME LoRA: lora_shrink then lora_expand, against an f64 host sum and libref's bytes. + * + * Both rows in one case, because expand reads the `t` shrink wrote -- the order the engine issues + * them in. Slots mix -1, 0..3 and 4 (= S): a base row keeps the 0xFF fill of `t` and every byte of + * `y` (a -0 included), and the column slices' neighbours are untouched. Adapter rows: shrink + * within (K + 2) 2^-24 sum|terms| of the f64 sum (an f32 dot's worst case in any order); expand + * exactly the bytes of libref's f32 order (j ascending, sum then scale then add, one RTNE) over + * the `t` the device wrote. `a` bf16 or E4M3 with a scale every 128 columns; `y` bf16 and f32; + * M = 1 (decode), 17 and 130 (prefill-like), K = 1000 (a partial scale group). */ +static void lora_case(const Plugin& pl) { + if (!(sel("lora_shrink_scalar") || sel("lora_expand_scalar"))) return; + const RadKernelInfo* rs = find(pl, "lora_shrink_scalar"); + const RadKernelInfo* re = find(pl, "lora_expand_scalar"); + if (!rs || !re) { ok("lora rows", false, "row absent"); return; } + static const int32_t kSlot[] = { -1, 0, 1, 2, 3, 4, 2, -5, 1 }; + const int S = 4; + struct Shape { int M, R, K, N; bool fp8, f32y; }; + const Shape shapes[] = { { 1, 16, 1000, 640, false, false }, { 17, 48, 1000, 300, true, false }, + { 130, 32, 256, 1000, true, true }, { 130, 16, 64, 64, false, true } }; + for (const Shape& sh : shapes) { + const int M = sh.M, R = sh.R, K = sh.K, N = sh.N, group = 128; + const int groups = (K + group - 1) / group, lda = K + 8, lds = groups + 4, ldy = N + 6; + const size_t ea = sh.fp8 ? 1 : 2, ey = sh.f32y ? 4 : 2; + uint32_t st = 0x2545f491u; + auto rnd = [&]() { /* uniform in [-1, 1) */ + st = st * 1664525u + 1013904223u; + return (float)((int32_t)(st >> 8) - (1 << 23)) / (float)(1 << 23); + }; + std::vector a((size_t)M * lda * ea); + for (size_t i = 0; i < (size_t)M * lda; ++i) { + if (sh.fp8) a[i] = rad_f32_to_fp8e4m3(8.0f * rnd()); + else { const uint16_t b = rad_f32_to_bf16(2.0f * rnd()); std::memcpy(&a[2 * i], &b, 2); } + } + std::vector as((size_t)M * lds); + for (float& v : as) v = 0.01f + 0.02f * (rnd() + 1.0f); + std::vector slot((size_t)M); + for (int m = 0; m < M; ++m) slot[(size_t)m] = kSlot[(m * 7 + 2) % 9]; + std::vector la((size_t)S * R * K), lb((size_t)S * N * R); + for (uint16_t& v : la) v = rad_f32_to_bf16(0.1f * rnd()); + for (uint16_t& v : lb) v = rad_f32_to_bf16(0.1f * rnd()); + std::vector sc((size_t)S * N); + for (float& v : sc) v = 1.0f + 0.5f * rnd(); + std::vector y0((size_t)M * ldy * ey); + for (size_t i = 0; i < (size_t)M * ldy; ++i) { + const float v = i % 3 == 0 ? -0.0f : rnd(); + if (sh.f32y) std::memcpy(&y0[4 * i], &v, 4); + else { const uint16_t b = rad_f32_to_bf16(v); std::memcpy(&y0[2 * i], &b, 2); } + } + + void* d_a = dalloc(a.size()); st_memcpy(d_a, a.data(), a.size(), hipMemcpyHostToDevice); + void* d_as = dalloc(as.size() * 4); + st_memcpy(d_as, as.data(), as.size() * 4, hipMemcpyHostToDevice); + void* d_sl = dalloc(slot.size() * 4); + st_memcpy(d_sl, slot.data(), slot.size() * 4, hipMemcpyHostToDevice); + void* d_la = dalloc(la.size() * 2); + st_memcpy(d_la, la.data(), la.size() * 2, hipMemcpyHostToDevice); + void* d_lb = dalloc(lb.size() * 2); + st_memcpy(d_lb, lb.data(), lb.size() * 2, hipMemcpyHostToDevice); + void* d_sc = dalloc(sc.size() * 4); + st_memcpy(d_sc, sc.data(), sc.size() * 4, hipMemcpyHostToDevice); + void* d_t = dalloc((size_t)M * R * 4); + st_memset(d_t, 0xFF, (size_t)M * R * 4); /* a base row keeps this */ + void* d_y = dalloc(y0.size()); st_memcpy(d_y, y0.data(), y0.size(), hipMemcpyHostToDevice); + + /* `a` columns [0, K) of [M, lda]; its scale [M, groups] of [M, lds]; `y` columns [3, 3+N). */ + RadTensor ta = T(d_a, sh.fp8 ? RAD_F8E4M3 : RAD_BF16, { M, K }); + ta.stride[0] = lda; + RadTensor ts = T(sh.fp8 ? d_as : nullptr, RAD_F32, { M, groups }); + ts.stride[0] = lds; + RadTensor ty = T((uint8_t*)d_y + 3 * ey, sh.f32y ? RAD_F32 : RAD_BF16, { M, N }); + ty.stride[0] = ldy; + std::vector t1 = { ta, ts, T(d_sl, RAD_I32, { M }), T(d_la, RAD_BF16, { S, R, K }), + T(d_t, RAD_F32, { M, R }) }; + std::vector p1 = { PI("M", M), PI("K", K), PI("R", R), PI("S", S), + PI("group", sh.fp8 ? group : 0), + PS("dtype", sh.fp8 ? "fp8_e4m3" : "bf16") }; + std::vector t2 = { T(d_t, RAD_F32, { M, R }), T(d_sl, RAD_I32, { M }), + T(d_lb, RAD_BF16, { S, N, R }), T(d_sc, RAD_F32, { S, N }), ty }; + std::vector p2 = { PI("M", M), PI("N", N), PI("R", R), PI("S", S), + PS("dtype", sh.f32y ? "f32" : "bf16") }; + RadArgs a1, a2; + std::memset(&a1, 0, sizeof(a1)); std::memset(&a2, 0, sizeof(a2)); + a1.t = t1.data(); a1.n_t = (int)t1.size(); a1.p = p1.data(); a1.n_p = (int)p1.size(); + a2.t = t2.data(); a2.n_t = (int)t2.size(); a2.p = p2.data(); a2.n_p = (int)p2.size(); + const int rc1 = rs->launch(&a1, nullptr); + const int rc2 = re->launch(&a2, nullptr); + st_stream_sync(nullptr); + std::vector t((size_t)M * R); + st_memcpy(t.data(), d_t, t.size() * 4, hipMemcpyDeviceToHost); + std::vector y(y0.size()); + st_memcpy(y.data(), d_y, y.size(), hipMemcpyDeviceToHost); + + int64_t bad_base = 0, bad_t = 0, bad_y = 0; + double worst = 0; + for (int m = 0; m < M; ++m) { + const int32_t s = slot[(size_t)m]; + const bool base = s < 0 || s >= S; + for (int j = 0; j < R; ++j) { + const float v = t[(size_t)m * R + j]; + uint32_t bits; std::memcpy(&bits, &v, 4); + if (base) { bad_base += bits != 0xFFFFFFFFu; continue; } + double sum = 0, mag = 0; + for (int k = 0; k < K; ++k) { + const size_t ai = (size_t)m * lda + k; + float x; + if (sh.fp8) x = rad_fp8e4m3_to_f32(a[ai]) * as[(size_t)m * lds + k / group]; + else { uint16_t b; std::memcpy(&b, &a[2 * ai], 2); x = rad_bf16_to_f32(b); } + const double term = (double)x * rad_bf16_to_f32(la[((size_t)s * R + j) * K + k]); + sum += term; mag += std::fabs(term); + } + const double tol = (K + 2) * std::ldexp(1.0, -24) * mag + 1e-30; + worst = std::max(worst, std::fabs(v - sum) / tol); + bad_t += !(std::fabs(v - sum) <= tol); + } + for (int c = 0; c < ldy; ++c) { + const size_t i = (size_t)m * ldy + c; + const int n = c - 3; + if (base || n < 0 || n >= N) { + bad_base += std::memcmp(&y[i * ey], &y0[i * ey], ey) != 0; + continue; + } + float acc = 0.0f; /* libref's order over the device's t */ + for (int j = 0; j < R; ++j) + acc += t[(size_t)m * R + j] * rad_bf16_to_f32(lb[((size_t)s * N + n) * R + j]); + const float d = sc[(size_t)s * N + n] * acc; + uint8_t want[4]; + if (sh.f32y) { + float yv; std::memcpy(&yv, &y0[4 * i], 4); + const float w = yv + d; std::memcpy(want, &w, 4); + } else { + uint16_t yb; std::memcpy(&yb, &y0[2 * i], 2); + const uint16_t w = rad_f32_to_bf16(rad_bf16_to_f32(yb) + d); + std::memcpy(want, &w, 2); + } + bad_y += std::memcmp(&y[i * ey], want, ey) != 0; + } + } + ok(fmt("lora M %d R %d K %d N %d %s / %s y", M, R, K, N, sh.fp8 ? "e4m3+scale" : "bf16", + sh.f32y ? "f32" : "bf16").c_str(), + rc1 == RAD_OK && rc2 == RAD_OK && !bad_base && !bad_t && !bad_y, + fmt("rc %d/%d, %lld base-row bytes touched, %lld t outside the bound (worst %.3f), " + "%lld y not libref's bytes", rc1, rc2, (long long)bad_base, (long long)bad_t, worst, + (long long)bad_y)); + dfree_all(); + } +} + static void device_phase(const Plugin& pl) { int n = 0; if (hipGetDeviceCount(&n) != hipSuccess || n < 1) { @@ -12487,6 +12634,7 @@ static void device_phase(const Plugin& pl) { ngram_ahead_case(pl); embed_lookup_q_case(pl); + lora_case(pl); /* --- the paged cache's write side --- */ kv_store_case(pl, "kv_store_bf16", "bf16");