Archived
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:
1 parent
48f7b8eb6d
commit
7864acf50a
13 files changed
+569
No files matched your search
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user