libref, libavx: lora_shrink and lora_expand, the per-row runtime LoRA ops

The two halves of y += scale * (B . (A . x)) at a trunk GEMM, with each row's adapter named by an
i32 `slot`:

    lora_shrink  t[m, j] = sum_k x(m, k) * lora_a[s, j, k]
    lora_expand  y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * lora_b[s, n, j]

A row whose slot is outside [0, S) is a base row and neither op touches it: shrink writes no `t`,
expand neither reads nor writes `y`, so a base row stays bit for bit what the GEMM wrote (y + 0
would already turn a -0 into +0). x(m, k) is gemm_nt_q's activation value, read through the same
make_scales; an fp8/i8 activation without its scale stream is refused. The dtype parameters carry
the tensor dtype names (rad_dtype_name). Sums are per row in a fixed order, so a row's bytes do
not depend on M or on its neighbours.

libref is the oracle (straight f32 loops, OpenMP over whole output elements); libavx covers both
at every ISA level with vectorised dots. ref_test gains hand-computed cases (column slices, -1 and
S as base slots, a -0 that must survive, the fp8 scale fold, the missing-scale and wrong-group
refusals); avx_check gains a case table; docs/OPS.md the two rows; rad-kbench and avx_check a
tolerance row for the shrink's f32 reduction.
This commit is contained in:
baKon committed 2026-10-16 20:52:09 -05:00
1 parent 48f7b8eb6d
commit 7864acf50a
13 files changed
+569

No files matched your search

+1
View File
@@ -41,6 +41,7 @@ set(AVX_KERNEL_SRC
avx_gemm.cpp
avx_gemm_tile.cpp
avx_planes.cpp
avx_lora.cpp
avx_attn.cpp
avx_qsa.cpp
avx_moe.cpp
+16
View File
@@ -254,6 +254,22 @@ std::vector<Case> build_cases() {
2.0 * M * 192 * 256);
add("gemm_nt_q_gated", { HI("M", 7), HI("N", 512), HI("K", 256), HI("group", 128),
HS("dtype", "fp8a8"), HS("act", "silu") }, 0, 2.0 * 7 * 512 * 256);
/* Runtime LoRA. libref's description draws `slot` in [0, S], so S itself -- a base row --
* comes up in every case of more than one row and the comparison covers rows neither op may
* touch (a single row draws an adapter, or the case would compare nothing). M = 1 takes the
* shrink's team-over-columns arm and 9 and 65 its team-over-rows one; K = 1000
* leaves a partial scale group and a vector tail at every level; R = 48 is not a power of two.
* The dtype is `a`'s for shrink -- the coded ones with their scale stream -- and `y`'s for
* expand. */
for (int M : { 1, 9, 65 }) {
for (const char* dt : { "f32", "bf16", "f16", "fp8_e4m3", "i8" })
for (int K : { 256, 1000 })
add("lora_shrink", { HI("M", M), HI("K", K), HI("R", 48), HI("S", 4),
HI("group", 128), HS("dtype", dt) }, 0, 2.0 * M * 48 * K);
for (const char* dt : { "f32", "bf16", "f16" })
add("lora_expand", { HI("M", M), HI("N", 645), HI("R", 48), HI("S", 4),
HS("dtype", dt) }, 0, 2.0 * M * 645 * 48);
}
for (const char* dt : { "f32", "bf16" }) {
add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
HI("vocab_offset", 0), HF("mult", 1) });
+1
View File
@@ -133,6 +133,7 @@ static const Tol kTol[] = {
{ "moe_gemm", "f32", 2e-5 },
{ "moe_gemm", "bf16", 8e-3 },
{ "moe_gemm", "*", 3e-2 },
{ "lora_shrink", "*", 2e-5 },
{ "attn_", "bf16", 2e-2 },
{ "attn_", "f32", 1e-4 },
{ "attn_", "*", 3e-2 },
+1
View File
@@ -88,6 +88,7 @@ int avx_par_force(int threads);
/* ---- gemm and the vocabulary edges */ \
X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
X(lora_shrink) X(lora_expand) \
/* ---- attention */ \
X(attn_paged) X(attn_dense) X(kv_store) X(rope) \
X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \
+186
View File
@@ -0,0 +1,186 @@
/* avx_lora.cpp -- runtime LoRA's two halves on the host: lora_shrink and lora_expand.
*
* libref/ref_lora.cpp is the DEFINITION and says what the ops are; this is the same arithmetic over
* the same bytes with the dot products vectorised, which is the only difference and a tolerance
* question (avx_check). What is EXACT, and has to be, is which rows are touched: a row whose slot
* is outside [0, S) is a base row, its `t` row is never written and its `y` row is neither read nor
* written -- not a store of what was read, no store -- because the engine promises that a base row
* is bit for bit what the GEMM wrote.
*
* x(m, k) is gemm_nt_q's activation value: the code times its group's scale, read through the same
* scale-stream rule as avx_gemm.cpp (copied below for the reason avx_moe.cpp gives for its copy).
*
* THREADING. A row's dots never split, so its bytes do not depend on the team or on M. A prefill
* has rows to spare and goes wide over them; a decode step has one row and R columns, so there the
* row's activation is decoded once on the calling thread and the team goes wide over the columns.
* Either way each output element is one dotf() over the same two f32 rows.
*/
#include "avx_common.h"
#include "avx_vec.h"
using namespace avx;
namespace {
struct Mat { const RadTensor* t; int64_t rs, cs; };
static inline Mat as_mat(const RadTensor* t, int64_t cols) {
Mat m{ t, cols, 1 };
if (t->rank < 2) return m;
m.cs = t->stride[t->rank - 1];
m.rs = row_stride(t, cols);
return m;
}
/* gemm_nt_q's activation scale stream, read as libref/ref_gemm.h's make_scales reads it. */
struct Scales {
const void* p;
uint32_t dt;
int64_t rs, cs, group, rblk;
inline float at(int64_t row, int64_t k) const {
const int64_t g = group > 0 ? k / group : 0;
return rad_load_f32(p, dt, (rblk > 1 ? row / rblk : row) * rs + g * cs);
}
};
static Scales make_scales(const RadTensor* s, int64_t rows, int64_t K) {
Scales q{};
q.rblk = 1;
if (!s || !s->data || rows <= 0 || numel(s) <= 0) {
q.p = nullptr; q.group = K; q.dt = RAD_F32; return q;
}
q.p = s->data;
q.dt = s->dtype;
int64_t groups = 0;
if (s->rank >= 2) {
const int64_t srows = s->shape[s->rank - 2];
q.rblk = srows >= rows ? 1 : grid_block(rows, srows);
groups = s->shape[s->rank - 1];
q.rs = s->stride[s->rank - 2];
q.cs = s->stride[s->rank - 1];
} else {
const int64_t nel = numel(s);
if (nel >= rows) { groups = nel / rows; q.rs = groups; }
else { groups = 1; q.rblk = grid_block(rows, nel); q.rs = 1; }
q.cs = 1;
}
q.group = grid_block(K, groups);
return q;
}
/* A pool operand [S, rows, cols]; see libref/ref_lora.cpp. */
struct Pool3 { int64_t s0, s1, s2; };
static inline Pool3 pool3(const RadTensor* t, int64_t rows, int64_t cols) {
if (t->rank == 3) return Pool3{ t->stride[0], t->stride[1], t->stride[2] };
return Pool3{ rows * cols, cols, 1 };
}
static inline int64_t row_slot(const RadTensor* slot, int64_t m, int64_t S) {
const int64_t s = ldi(slot, offlin(slot, m));
return (s >= 0 && s < S) ? s : -1;
}
static inline bool float_act(uint32_t dt) {
return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32;
}
static inline bool coded_act(uint32_t dt) {
return dt == RAD_F8E4M3 || dt == RAD_F8E5M2 || dt == RAD_I8;
}
/* Row m of `a` as x(m, k) in f32: the codes widened, then each times its group's scale. */
static inline const float* x_row(const RadTensor* X, const Mat& mx, const Scales& SA, int64_t m,
int64_t K, float* xb) {
const float* xv = in_row(X, m * mx.rs, K, xb);
if (!SA.p) return xv;
for (int64_t k = 0; k < K; ++k) xb[k] = xv[k] * SA.at(m, k);
return xb;
}
} /* namespace */
/* operands: a, a_scale?, slot, lora_a, t */
AVX_KERNEL(lora_shrink) {
if (a->n_t < 5 || !rad_arg_in(a, 0) || !rad_arg_in(a, 2) || !rad_arg_in(a, 3) ||
!rad_arg_in(a, 4))
return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *SL = &a->t[2], *LA = &a->t[3], *T = &a->t[4];
const RadTensor* XS = rad_arg_in(a, 1);
const int64_t K = p_int(a, "K", 0), R = p_int(a, "R", 0), S = p_int(a, "S", 0);
if (K <= 0 || R <= 0 || S <= 0) return RAD_E_SHAPE;
const int64_t M = band_rows(numel(T) / R, p_int(a, "M", 0));
if (M <= 0) return RAD_E_SHAPE; /* zero rows is not a call */
if (numel(X) < M * K || numel(SL) < M || numel(LA) < S * R * K) return RAD_E_SHAPE;
if (!float_act(X->dtype) && !coded_act(X->dtype)) return RAD_E_DTYPE;
if (coded_act(X->dtype) && !XS) return RAD_E_INVAL;
if (T->dtype != RAD_F32) return RAD_E_DTYPE;
const Scales SA = make_scales(XS, M, K);
const int64_t gp = p_int(a, "group", 0);
if (gp > 0 && SA.p && SA.group != gp) return RAD_E_SHAPE;
const Mat mx = as_mat(X, K), mt = as_mat(T, R);
const Pool3 pa = pool3(LA, R, K);
float* const td = (float*)T->data;
if (M >= 8) {
AVX_PARALLEL_FOR_IF(M * R * K >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const int64_t s = row_slot(SL, m, S);
if (s < 0) continue; /* a base row: nothing written */
float* xb = scratch_f32((size_t)K);
float* ab = scratch_f32_b((size_t)K);
const float* xv = x_row(X, mx, SA, m, K, xb);
for (int64_t j = 0; j < R; ++j) {
const float* av = in_row(LA, s * pa.s0 + j * pa.s1, K, ab);
td[m * mt.rs + j * mt.cs] = dotf(xv, av, K);
}
}
return RAD_OK;
}
for (int64_t m = 0; m < M; ++m) {
const int64_t s = row_slot(SL, m, S);
if (s < 0) continue;
/* The calling thread's first buffer holds the row; every team member's second one holds
* its column of the pool, so nothing the team writes aliases the shared row. */
const float* xv = x_row(X, mx, SA, m, K, scratch_f32((size_t)K));
AVX_PARALLEL_FOR_IF(R * K >= AVX_PAR_MIN)
for (int64_t j = 0; j < R; ++j) {
const float* av = in_row(LA, s * pa.s0 + j * pa.s1, K, scratch_f32_b((size_t)K));
td[m * mt.rs + j * mt.cs] = dotf(xv, av, K);
}
}
return RAD_OK;
}
/* operands: t, slot, lora_b, scale, y (inout) */
AVX_KERNEL(lora_expand) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *T = &a->t[0], *SL = &a->t[1], *LB = &a->t[2], *SC = &a->t[3], *Y = &a->t[4];
const int64_t N = p_int(a, "N", 0), R = p_int(a, "R", 0), S = p_int(a, "S", 0);
if (N <= 0 || R <= 0 || S <= 0) return RAD_E_SHAPE;
const int64_t M = band_rows(numel(Y) / N, p_int(a, "M", 0));
if (M <= 0) return RAD_E_SHAPE; /* zero rows is not a call */
if (numel(T) < M * R || numel(SL) < M || numel(LB) < S * N * R || numel(SC) < S * N)
return RAD_E_SHAPE;
if (Y->dtype != RAD_BF16 && Y->dtype != RAD_F16 && Y->dtype != RAD_F32) return RAD_E_DTYPE;
if (T->dtype != RAD_F32 || SC->dtype != RAD_F32) return RAD_E_DTYPE;
const Mat mt = as_mat(T, R);
const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y);
const Pool3 pb = pool3(LB, N, R);
const int64_t sc_r = SC->rank >= 2 ? SC->stride[SC->rank - 2] : N;
const int64_t sc_c = SC->rank >= 2 ? laststride(SC) : 1;
const float* const scd = (const float*)SC->data;
AVX_PARALLEL_FOR_IF(M * N * R >= AVX_PAR_MIN)
for (int64_t e = 0; e < M * N; ++e) {
const int64_t m = e / N, n = e - m * N;
const int64_t s = row_slot(SL, m, S);
if (s < 0) continue; /* a base row: not read, not written */
const float* tv = in_row(T, m * mt.rs, R, scratch_f32((size_t)R));
const float* bv = in_row(LB, s * pb.s0 + n * pb.s1, R, scratch_f32_b((size_t)R));
const float d = scd[s * sc_r + n * sc_c] * dotf(tv, bv, R);
const int64_t o = m * ys_r + n * ys_c;
stt(Y, o, ldt(Y, o) + d);
}
return RAD_OK;
}
+21
View File
@@ -221,6 +221,15 @@ static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b
OUT("y"), OPD_O("a_sum"), WGT_O("b_ref") };
static const RadOperandSpec oGemmQBias[] = { OPD("a"), OPD("a_scale"), WGT("b"), WGT("b_scale"),
WGT("bias"), OUT("y") };
/* Runtime LoRA, libref's schemas slot for slot (libref/ref_registry.cpp says what they mean). */
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[] = { OPD("a"), OPD_O("a_scale"), OPD("slot"),
OPD("lora_a"), OUT("t") };
static const RadParamSpec pLoraExpand[] = { P_INT("M"), P_INT("N"), P_INT("R"), P_INT("S"),
P_STR("dtype") };
static const RadOperandSpec oLoraExpand[] = { OPD("t"), OPD("slot"), OPD("lora_b"), OPD("scale"),
INOUT("y") };
/* `act` is required here (optional in the quantiser); `N` is the weight's rows, twice the output
* width. */
static const RadParamSpec pGemmQGated[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
@@ -661,6 +670,12 @@ static const RadOpSchema kSchemas[] = {
"C = A B^T with group-scaled quantised operands. `a_sum` and `b_ref` are libr4d's asymmetric and "
"mxfp4 forms and are ignored here, as they are in libref." },
{ "gemm_nt_q_bias", ARR(pGemmQBias), ARR(oGemmQBias), "quantised C = A B^T + bias." },
{ "lora_shrink", ARR(pLoraShrink), ARR(oLoraShrink),
"t[m, j] = sum_k x(m, k) * lora_a[slot[m], j, k]; a base row (slot outside [0, S)) is not "
"written." },
{ "lora_expand", ARR(pLoraExpand), ARR(oLoraExpand),
"y[m, n] += scale[slot[m], n] * sum_j t[m, j] * lora_b[slot[m], n, j]; a base row is neither "
"read nor written." },
{ "gemm_nt_q_gated", ARR(pGemmQGated), ARR(oGemmQGated),
"gemm_nt_q over a [N, K] gate_up plane with gated_quant_fp8's pass in the epilogue, byte for "
"byte the pair. `N` is the weight's rows, twice the fused width; the output is [M, N/2]." },
@@ -1037,6 +1052,12 @@ ROWL("avx_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantise
"and integer zero per group, joined; f32 accumulate", L(gemm_nt_q), avx_layout_gemm_q),
SIMPLE("avx_gemm_nt_q_bias", "gemm_nt_q_bias", "gemm", "quantised C = A B^T + bias",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", L(gemm_nt_q_bias)),
SIMPLE("avx_lora_shrink", "lora_shrink", "gemm", "t = x A[slot]^T per row, base rows untouched",
"bf16 / f16 / f32 a, or fp8_e4m3 / fp8_e5m2 / i8 a with its f32 scale stream; bf16 lora_a; "
"i32 slot; f32 t", L(lora_shrink)),
SIMPLE("avx_lora_expand", "lora_expand", "gemm",
"y += scale * (t B[slot]^T) per row, base rows untouched",
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", L(lora_expand)),
SIMPLE("avx_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm",
"gemm_nt_q over a gate_up plane with the gated E4M3 quantiser in the epilogue",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; fp8_e4m3 out, f32 scale",