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

+34
View File
@@ -621,6 +621,40 @@ what a separate tensor would hold, so the fused form equals the unfused chain bi
may be `y` itself, the residual stream updated in place (the encoder towers' layers do this), so an
implementation reads `res` before it stores the product over it.
### Runtime LoRA: `lora_shrink` and `lora_expand`
| op | params | operands |
|---|---|---|
| `lora_shrink` | `M`(range) `K` `R` `S` `group`/opt `dtype` | `a`, `a_scale`?, `slot`, `lora_a` → `t` |
| `lora_expand` | `M`(range) `N` `R` `S` `dtype` | `t`, `slot`, `lora_b`, `scale`, `y`:inout |
The two halves of `y += scale ⊙ (B · (A · x))` at a trunk GEMM, issued by the core right after the
GEMM in the GEMM's own row slice, with several adapters and no adapter mixed in one step. `slot` is
an i32 per row naming its adapter's pool slot; **a row with `slot < 0 || slot >= S` is a base row
and neither op touches it**: `lora_shrink` writes nothing into its `t` row, and `lora_expand` does
not read or write its `y` row at all — so a base row stays bit for bit what the GEMM wrote, where
`y + 0` would already have turned a -0 into +0.
- `lora_shrink`: `t[m, j] = Σ_k x(m, k) · lora_a[s, j, k]`, `s = slot[m]`, f32 accumulate.
`a`/`a_scale` are the GEMM's own first two operands, and `x(m, k)` is the value `gemm_nt_q` uses
for that element: the code times its group's scale, read through the same scale-stream rule
(`[rows, groups]` or `[rows]`, the group derived from the stream), or a `bf16`/`f16`/`f32`
element as it stands. An `fp8_e4m3`/`fp8_e5m2`/`i8` `a` without `a_scale` is refused. `group`
is a cross-check on the stream and 0 means none; `dtype` is `a`'s tensor dtype name
(`rad_dtype_name`: `bf16`, `f16`, `f32`, `fp8_e4m3`, `i8`, ...), not a combined quant string.
`lora_a` is `[S, R, K]` bf16, `t` is `[M, R]` f32.
- `lora_expand`: `y[m, n] = y[m, n] + scale[s, n] · Σ_j t[m, j] · lora_b[s, n, j]`, f32
accumulate, one rounding to `y`'s dtype (`bf16`/`f16`/`f32`, named by `dtype`). `lora_b` is
`[S, N, R]` bf16 and `scale` `[S, N]` f32 — per output column, so a fused projection whose parts
carry different `alpha / r` is one launch.
`a`, `a_scale` and `y` may be row and column slices of wider buffers; every row stride is the
tensor's. The pools are ordinary inputs and not weights: the engine owns them as program buffers
and copies an adapter into a slot between steps, so a recorded pass replays the same pointers and
reads whatever adapters the slots hold. A row's result does not depend on `M` or on any other row
(no split of a reduction that moves with the batch), which is what lets a request's bytes be the
same alone and in a mixed batch. Implementations: libref, libavx, libr4d (scalar f32 rows).
## Attention
| op | params | operands |
+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",
+145
View File
@@ -0,0 +1,145 @@
/* ref_lora.cpp -- runtime LoRA: the two halves of y += scale * (B . (A . x)), per row.
*
* 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]
*
* A step mixes rows of several adapters and rows of none, so the adapter is a PER-ROW operand: a
* row whose slot is outside [0, S) is a BASE row and neither op touches it. That is stronger than
* "adds zero": `y + 0` turns a -0 into +0, and the promise the engine makes is that a base row is
* bit-for-bit what the gemm wrote. So shrink writes nothing into a base row of `t` and expand does
* no read-modify-write of a base row of `y` at all -- not a store of the value it read, no store.
*
* x(m, k) IS THE VALUE gemm_nt_q USES FOR THAT ACTIVATION ELEMENT, read the same way: the row and
* column strides of `a` (a column slice of a fused projection arrives with the whole projection's
* row stride), and the scale stream through ref_gemm.h's make_scales, which is gemm_nt_q's own
* reading of `a_scale`. A code times its group's scale is one f32 product; a bf16, f16 or f32
* activation is its value as it stands. One more rounding than gemm_nt_q's group sub-sum makes on
* a quantised activation, and it is the contract (docs/OPS.md): the LoRA term is a low-rank
* correction, and folding the scale per element keeps the kernels free of a group loop.
*
* THE SUM IS PER ROW AND ITS ORDER IS FIXED: k ascending for shrink, j ascending for expand, one
* f32 accumulator, no FMA (libref/CMakeLists.txt). Nothing here depends on M or on another row --
* the batch a row arrives in cannot change its bytes, which is what lets the engine claim "mixed
* batch == the same request alone" for the LoRA term.
*
* EVERY EXTENT IS THE OPERAND'S, and the parameters are cross-checks (ref_ops.h): `M` is the band,
* so the rows are `t`'s for shrink and `y`'s for expand, and `K`, `N`, `R`, `S` say how to read the
* tensors and are refused where the tensors are too small for them.
*/
#include "ref_common.h"
#include "ref_gemm.h"
#include "ref_ops.h"
using namespace ref;
namespace {
/* The slot of row m, or -1 for a base row. The id is read as an integer, never through f32. */
static inline int64_t row_slot(const RadTensor* slot, int64_t m, int64_t S) {
const int64_t s = ld_int(slot->dtype, slot->data, offlin(slot, m));
return (s >= 0 && s < S) ? s : -1;
}
/* A pool operand [S, rows, cols]: its three strides. The pools are whole declared buffers and so
* dense in the engine; a rank-3 tensor is read through its own strides anyway, because "the
* engine's buffers are dense" is a fact about one caller and not about the op. */
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 };
}
/* The activation dtypes x(m, k) is defined for. The float ones carry no scale; the coded ones are
* meaningless without one, and a missing scale is refused rather than read as one. */
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;
}
} /* namespace */
/* operands: a, a_scale?, slot, lora_a, t */
int ref_lora_shrink(const RadArgs* a, RadStream) {
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 = t_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; /* a code without its scale */
if (T->dtype != RAD_F32) return RAD_E_DTYPE;
/* gemm_nt_q's reading of the scale stream, and its `group` cross-check: the stream states the
* group, and a parameter that disagrees with it is a caller describing other bytes. Absent
* the stream the parameter says nothing -- a bf16 activation has no scale whatever `group`
* holds. */
const Scales SA = make_scales(XS, M, K, false);
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);
const uint32_t dx = X->dtype;
/* One thread an output element: the order inside it is k ascending whoever runs it. */
#pragma omp parallel for schedule(static)
for (int64_t e = 0; e < M * R; ++e) {
const int64_t m = e / R, j = e - m * R;
const int64_t s = row_slot(SL, m, S);
if (s < 0) continue; /* a base row: nothing written */
const int64_t x0 = m * mx.rs, a0 = s * pa.s0 + j * pa.s1;
float acc = 0.0f;
for (int64_t k = 0; k < K; ++k) {
float x = ld_dt(dx, X->data, x0 + k * mx.cs);
if (SA.p) x = x * SA.at(m, k);
acc += x * ld_dt(LA->dtype, LA->data, a0 + k * pa.s2);
}
((float*)T->data)[m * mt.rs + j * mt.cs] = acc;
}
return RAD_OK;
}
/* operands: t, slot, lora_b, scale, y (inout) */
int ref_lora_expand(const RadArgs* a, RadStream) {
if (!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;
#pragma omp parallel for schedule(static)
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 int64_t t0 = m * mt.rs, b0 = s * pb.s0 + n * pb.s1;
float acc = 0.0f;
for (int64_t j = 0; j < R; ++j)
acc += ((const float*)T->data)[t0 + j * mt.cs] *
ld_dt(LB->dtype, LB->data, b0 + j * pb.s2);
const float sc = ((const float*)SC->data)[s * sc_r + n * sc_c];
const int64_t o = m * ys_r + n * ys_c;
/* `sc * acc` and then the add, each rounded: the order is the definition. */
const float d = sc * acc;
stt(Y, o, ldt(Y, o) + d);
}
return RAD_OK;
}
+5
View File
@@ -118,6 +118,9 @@ int ref_gemm_nt (const RadArgs*, RadStream);
int ref_gemm_nt_bias (const RadArgs*, RadStream);
int ref_gemm_nt_q (const RadArgs*, RadStream);
int ref_gemm_nt_q_bias (const RadArgs*, RadStream);
/* Runtime LoRA's two halves, per-row adapter slot (ref_lora.cpp). */
int ref_lora_shrink (const RadArgs*, RadStream);
int ref_lora_expand (const RadArgs*, RadStream);
int ref_embed_lookup (const RadArgs*, RadStream);
int ref_embed_lookup_q (const RadArgs*, RadStream);
int ref_logits_gemm (const RadArgs*, RadStream);
@@ -283,6 +286,8 @@ REF_SHAPE_FN(ref_gemm_nt);
REF_SHAPE_FN(ref_gemm_nt_bias);
REF_SHAPE_FN(ref_gemm_nt_q);
REF_SHAPE_FN(ref_gemm_nt_q_bias);
REF_SHAPE_FN(ref_lora_shrink);
REF_SHAPE_FN(ref_lora_expand);
REF_SHAPE_FN(ref_embed_lookup);
REF_SHAPE_FN(ref_embed_lookup_q);
REF_SHAPE_FN(ref_logits_gemm);
+32
View File
@@ -285,6 +285,22 @@ static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b"
static const RadOperandSpec oGemmQBias[] = { OPD("a"), OPD("a_scale"), WGT("b"), WGT("b_scale"),
WGT("bias"), OUT("y") };
/* RUNTIME LoRA, the two halves of y += scale * (B . (A . x)) at a trunk GEMM, per row: `slot` names
* each row's adapter and a row outside [0, S) is a base row neither op touches. `a`/`a_scale` are
* the GEMM's own first two operands, read as gemm_nt_q reads them, and `y` is its output. The pools
* (`lora_a` [S, R, K], `lora_b` [S, N, R], `scale` [S, N]) are ordinary inputs and not weights: the
* engine owns them as program buffers and copies an adapter into a slot between steps, so there is
* no declared weight for an issue to name. `group` is OPTIONAL and 0 means no scale stream; `dtype`
* is the tensor dtype name (rad_dtype_name) of `a` for shrink and of `y` for expand. */
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") };
/* ---- attention ---------------------------------------------------------------------------- */
static const RadParamSpec pAttnPaged[] = {
P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"),
@@ -928,6 +944,16 @@ static const RadOpSchema kSchemas[] = {
"scaled once per group, which is what an int8 or fp8 WMMA kernel does. Scale streams are "
"[rows, groups] or [rows]; an mxfp4 weight's u8 scale stream is read as OCP e8m0." },
{ "gemm_nt_q_bias", ARR(pGemmQBias), ARR(oGemmQBias), "gemm_nt_q with a per-column bias." },
{ "lora_shrink", ARR(pLoraShrink), ARR(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, k ascending; x(m, k) is the value gemm_nt_q uses for that element of `a` (a code "
"times its group's scale from `a_scale`, a float as it is). A row outside [0, S) is a base row "
"and its `t` row is NOT WRITTEN. A row's bytes do not depend on M or on any other row." },
{ "lora_expand", ARR(pLoraExpand), ARR(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, j ascending, one rounding to y's dtype. A base row's `y` "
"is neither read nor written, so it stays bit for bit what the GEMM wrote (not y + 0: that "
"turns -0 into +0)." },
{ "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged),
"Paged attention over kv_cache[num_blocks, kv_heads, block_size, 2*head_dim] (K then V per "
@@ -1487,6 +1513,12 @@ ROWL("ref_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantise
ref_check_gemm_q, ref_gemm_nt_q, ref::ref_layout_gemm_q),
SIMPLE("ref_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", ref_gemm_nt_q_bias),
SIMPLE("ref_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", ref_lora_shrink),
SIMPLE("ref_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", ref_lora_expand),
ROW("ref_attn_paged", "attn_paged", "attn",
"paged causal / sliding-window attention, any query length",
+39
View File
@@ -1009,6 +1009,45 @@ int ref_gemm_nt_q_bias_shape(const RadParam* p, int n_p, int operand, RadOpdDesc
return gemm_q_shape(p, n_p, operand, true, out);
}
/* RUNTIME LoRA. `slot` is drawn in [0, S] -- S ITSELF IS A BASE ROW, one past the pool -- so a cold
* draw exercises the rows neither op may touch as well as the adapter rows; a draw never yields
* -1, which is the other spelling of a base row, so that one is a hand case (tests/lora_test.cpp,
* ref_test). A single row is drawn in [0, S): a one-row call whose row drew S would write nothing,
* and a comparison of nothing proves nothing (rad-avx-check refuses it as vacuous). The scale stream exists only beside a coded activation: a bf16, f16 or f32 `a` is
* read as it stands, the way gemm_nt_q's fp8a16 form reads it, and an fp8 or i8 one without its
* scale is refused by the launch. `group` defaults to the 128 every block-scaled checkpoint and
* quantiser in this project uses when the geometry does not state one. */
int ref_lora_shrink_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), K = gi(p, n_p, "K", 0);
const int64_t R = gi(p, n_p, "R", 0), S = gi(p, n_p, "S", 0);
int64_t group = gi(p, n_p, "group", 0);
const bool coded = D == (uint32_t)RAD_F8E4M3 || D == (uint32_t)RAD_F8E5M2 ||
D == (uint32_t)RAD_I8;
if (coded && group <= 0) group = 128;
Opd o;
o.t(D, { M, K }); /* a */
if (coded) o.t((uint32_t)RAD_F32, { M, (K + group - 1) / group }); /* a_scale */
else o.skip(); /* a_scale */
o.t_idx({ M }, M > 1 ? S + 1 : S, -1, 0); /* slot, S = base */
o.t((uint32_t)RAD_BF16, { S, R, K }); /* lora_a */
o.t((uint32_t)RAD_F32, { M, R }); /* t */
return o.finish("lora_shrink", operand, out);
}
int ref_lora_expand_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 int64_t R = gi(p, n_p, "R", 0), S = gi(p, n_p, "S", 0);
Opd o;
o.t((uint32_t)RAD_F32, { M, R }); /* t */
o.t_idx({ M }, M > 1 ? S + 1 : S, -1, 0); /* slot, S = base */
o.t((uint32_t)RAD_BF16, { S, N, R }); /* lora_b */
o.t((uint32_t)RAD_F32, { S, N }); /* scale */
o.t(D, { M, N }); /* y */
return o.finish("lora_expand", operand, out);
}
/* ================================================================== attention
*
* The paged layout (ref_ops.h):
+84
View File
@@ -271,6 +271,8 @@ TEST(op_vocabulary) {
"gated_had_quant_i8",
"dequant",
"gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed",
/* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */
"lora_shrink", "lora_expand",
"grid_embed_aa",
"attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key",
/* The rest of the QSA indexer and DFlash2's convolution: not fusions, so a model that
@@ -1682,6 +1684,86 @@ TEST(op_gemm_nt) {
CHECK_EQ(yb.at(7), 15.0f);
}
/* RUNTIME LoRA, by hand. Every value is exact in its dtype, so the answers are equalities. The
* contract under test is as much WHICH ROWS are touched as what lands in them: a row whose slot is
* -1 or S is a base row, its `t` row keeps the sentinel shrink found there and its `y` row keeps
* its bits -- a -0 included, which `y + 0` would have turned into +0. */
TEST(op_lora_shrink) {
/* `a` is a COLUMN SLICE: columns 1..4 of a [3, 6] buffer, row stride 6. */
T aw(RAD_BF16, {3, 6});
aw.f({9, 1, 2, 3, 4, 9, 9, 5, 6, 7, 8, 9, 9, 1, 1, 1, 1, 9});
T a_ = aw; /* the slice shares aw's bytes */
a_.t.data = (uint16_t*)aw.mem.data() + 1;
a_.t.shape[1] = 4;
T sl(RAD_I32, {3}); sl.n({1, -1, 0});
T la(RAD_BF16, {2, 2, 4});
la.f({1, 0, 0, 0, 0, 1, 0, 0, /* slot 0: j0, j1 */
1, 1, 1, 1, 1, -1, 0, 0.5f}); /* slot 1 */
T t(RAD_F32, {3, 2}); t.f({99, 99, 99, 99, 99, 99});
A a; a.t(a_).tnull().t(sl).t(la).t(t)
.i("M", 3).i("K", 4).i("R", 2).i("S", 2).i("group", 0).s("dtype", "bf16");
CHECK_OK(run("lora_shrink", a));
CHECK_EQ(t.at(0), 10.0f); /* 1+2+3+4 */
CHECK_EQ(t.at(1), 1.0f); /* 1-2+0+4*0.5 */
CHECK_EQ(t.at(2), 99.0f); /* base row: not written */
CHECK_EQ(t.at(3), 99.0f);
CHECK_EQ(t.at(4), 1.0f); /* slot 0 picks a[2][0], a[2][1] */
CHECK_EQ(t.at(5), 1.0f);
/* An E4M3 activation with an f32 scale every two columns: x = code * its group's scale. */
T q(RAD_F8E4M3, {1, 4}); q.f({1, 2, 0.5f, -1});
T qs(RAD_F32, {1, 2}); qs.f({2.0f, 0.25f});
T sq(RAD_I32, {1}); sq.n({0});
T lq(RAD_BF16, {1, 1, 4}); lq.f({1, 1, 1, 1});
T tq(RAD_F32, {1, 1});
A b; b.t(q).t(qs).t(sq).t(lq).t(tq)
.i("M", 1).i("K", 4).i("R", 1).i("S", 1).i("group", 2).s("dtype", "fp8_e4m3");
CHECK_OK(run("lora_shrink", b));
CHECK_EQ(tq.at(0), 5.875f); /* 2 + 4 + 0.125 - 0.25 */
/* A code with no scale has no value: refused, never read as scale one. */
A c; c.t(q).tnull().t(sq).t(lq).t(tq)
.i("M", 1).i("K", 4).i("R", 1).i("S", 1).i("group", 0).s("dtype", "fp8_e4m3");
CHECK_EQ(run("lora_shrink", c), RAD_E_INVAL);
/* A `group` the stream does not state is a caller describing other bytes. */
A d; d.t(q).t(qs).t(sq).t(lq).t(tq)
.i("M", 1).i("K", 4).i("R", 1).i("S", 1).i("group", 4).s("dtype", "fp8_e4m3");
CHECK_EQ(run("lora_shrink", d), RAD_E_SHAPE);
}
TEST(op_lora_expand) {
T t(RAD_F32, {4, 2}); t.f({10, 1, 5, 5, 1, 1, 7, 7});
T sl(RAD_I32, {4}); sl.n({1, -1, 0, 2}); /* 2 == S: a base row like -1 */
T lb(RAD_BF16, {2, 3, 2});
lb.f({1, 0, 0, 1, 1, 1, /* slot 0: n0, n1, n2 */
2, 0, 0, 0.5f, 1, -1}); /* slot 1 */
T sc(RAD_F32, {2, 3}); sc.f({1, 1, 1, 0.5f, 2, 1});
/* `y` is a COLUMN SLICE too: columns 0..2 of a [4, 5] buffer. */
T yw(RAD_BF16, {4, 5});
yw.f({1, 1, 1, 9, 9, -0.0f, 3, 7, 9, 9, 0, 0, 0, 9, 9, -0.0f, -0.0f, 5, 9, 9});
T y = yw;
y.t.shape[1] = 3;
A a; a.t(t).t(sl).t(lb).t(sc).t(y).i("M", 4).i("N", 3).i("R", 2).i("S", 2).s("dtype", "bf16");
CHECK_OK(run("lora_expand", a));
const uint16_t* yr = (const uint16_t*)yw.mem.data();
CHECK_EQ(yw.at(0), 11.0f); /* 1 + 0.5 * (10*2 + 1*0) */
CHECK_EQ(yw.at(1), 2.0f); /* 1 + 2 * (1*0.5) */
CHECK_EQ(yw.at(2), 10.0f); /* 1 + 1 * (10 - 1) */
CHECK_EQ((long long)yr[5], 0x8000LL); /* base row: -0 keeps its sign bit */
CHECK_EQ(yw.at(6), 3.0f);
CHECK_EQ(yw.at(7), 7.0f);
CHECK_EQ(yw.at(10), 1.0f); /* slot 0 over t[2] = (1, 1) */
CHECK_EQ(yw.at(11), 1.0f);
CHECK_EQ(yw.at(12), 2.0f);
CHECK_EQ((long long)yr[15], 0x8000LL); /* slot S: a base row */
CHECK_EQ((long long)yr[16], 0x8000LL);
CHECK_EQ(yw.at(17), 5.0f);
for (int r = 0; r < 4; ++r) { /* the slice's neighbours are not touched */
CHECK_EQ(yw.at(r * 5 + 3), 9.0f);
CHECK_EQ(yw.at(r * 5 + 4), 9.0f);
}
}
TEST(op_gemm_nt_q) {
/* int8 x int8 with a per-row activation scale and a per-row weight scale. */
T a_(RAD_I8, {2, 2}); a_.n({1, 2, 3, 4});
@@ -5587,6 +5669,8 @@ std::vector<Geo> geometries() {
G("gemm_nt_q", "M", 3, a.i("M", R).i("N", 20).i("K", 256).i("group", 128).s("dtype", "fp8a8")),
G("gemm_nt_q_bias", "M", 3, a.i("M", R).i("N", 20).i("K", 256).i("group", 128)
.s("dtype", "fp8a8")),
G("lora_shrink", "M", 3, a.i("M", R).i("K", 40).i("R", 8).i("S", 2).s("dtype", "f32")),
G("lora_expand", "M", 3, a.i("M", R).i("N", 20).i("R", 8).i("S", 2).s("dtype", "f32")),
G("attn_paged", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2).i("block_size", 4)
.i("causal", 1).i("window", 0).s("q_dtype", "f32")
.s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)),
+4
View File
@@ -71,6 +71,10 @@ const std::vector<TolRow> g_tol = {
/* A dot product per candidate against the bf16 head: a GEMM's error. */
{ "logit_rerank", "*", 8e-3 },
{ "moe_gemm", "*", 3e-2 },
/* Runtime LoRA's shrink is a K-long reduction into an f32 `t` whatever `a` is -- the codes are
* decoded the same way on both sides, so only the summation order differs, and that is what
* gemm_nt's f32 row allows. Expand's R-long sum lands in `y` and takes the dtype rows below. */
{ "lora_shrink", "*", 2e-5 },
/* Attention: a softmax over a long context plus a second reduction. */
{ "attn_", "bf16", 2e-2 },
{ "attn_", "f32", 1e-4 },