Merge main into laya-arch-plugin

This commit is contained in:
Brandon Bertelsen committed 2026-10-29 13:45:18 -04:00
commit ec243c2a7d
189 files changed
+11212 -7060

No files matched your search

+38 -1
View File
@@ -75,12 +75,19 @@ struct KvDyn {
} /* namespace */
/* ------------------------------------------------------------------ attn_paged */
/* attn_paged_tree's ninth operand, `spec_parent` (RadBatch::spec_parent, rad_drafter_tree), is
* read here too: a row whose entry is -2 is an ordinary causal row; any other row is a node of its
* sequence's verify block, whose entry is its parent's row within the sequence's rows (-1 for the
* root, the block's first row). Inside the block such a row sees itself and its ancestors only,
* and its window is measured from the block's first position plus its depth -- the position its
* token has if its path is committed -- rather than from its row. */
int ref_attn_paged(const RadArgs* a, RadStream) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
const RadTensor* kdes = t_in(a, 4);
const RadTensor* vdes = t_in(a, 5);
const RadTensor* cus = t_in(a, 6);
const RadTensor* tpar = a->n_t > 8 ? t_in(a, 8) : nullptr;
if (!q->data || !kv->data || !bt->data || !su->data || !o->data) return RAD_E_INVAL;
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
@@ -162,6 +169,27 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
const int64_t qb = tok * q_rs + h * q_hs;
const int64_t ob = tok * o_rs + h * o_hs;
/* A tree row: its ancestors inside the block (a bit per row) and its depth. */
const int64_t base = ctx - qlen;
bool tree = false;
uint64_t tmask = 0;
int64_t tdep = 0;
if (tpar) {
const int64_t first = tok - i;
int64_t pj = ld_int(tpar->dtype, tpar->data, offlin(tpar, tok));
if (pj != -2 && i < 64) {
tree = true;
tmask = 1ull << i;
for (int64_t at = i; pj >= 0 && pj < at; ) {
tmask |= 1ull << pj;
++tdep;
at = pj;
pj = ld_int(tpar->dtype, tpar->data, offlin(tpar, first + pj));
}
}
}
const int64_t wpos = tree ? base + tdep : pos;
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
@@ -171,8 +199,9 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
* unmapped. */
auto key_at = [&](int64_t j) -> int64_t {
if (causal && j > pos) return -1;
if (tree && j >= base && !((tmask >> (j - base)) & 1)) return -1;
if (window > 0) {
const int64_t d = pos - j;
const int64_t d = wpos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) return -1;
}
const int64_t blk =
@@ -247,6 +276,14 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* attn_paged with its tree operand present: ref_attn_paged reads it (see there). Refused without
* one, and for a non-causal layer, whose two-sided window has no tree reading here. */
int ref_attn_paged_tree(const RadArgs* a, RadStream s) {
if (a->n_t < 9 || !t_in(a, 8)) return RAD_E_INVAL;
if (p_int(a, "causal", 1) != 1) return RAD_E_UNSUPPORTED;
return ref_attn_paged(a, s);
}
/* ------------------------------------------------------------------ attn_dense */
/* For the vision tower: unpaged, unquantised, `cu_seqlens` bounding one image (or attention window)
* per entry so a whole batch is one launch. Causal is a parameter so a dense decoder-only prefill
+3 -3
View File
@@ -286,7 +286,7 @@ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, c
* acc += (sub * a_scale[m]) * scale
* ZP_I8_GROUP sub = sum(a * (code - zero)) exact
* acc += (sub * a_scale[m][g]) * scale
* ZP_F16 BF16 inputs are first narrowed to F16 (as by the graph's former cast); sub is
* ZP_F16 BF16 inputs are first narrowed to F16 (the cast kernel's rounding); sub is
* the sum over ascending k of a * (code - zero), then acc += sub * scale
*
* `a` is already in column order (the caller undoes the step order). `a_sum` is quant_act_i8's,
@@ -321,8 +321,8 @@ static int gemm_zp(const ZpGrid& zg, const RadTensor* A, const RadTensor* as_,
if (A->rank >= 2 && A->shape[A->rank - 1] != acols) return RAD_E_SHAPE;
int64_t ars = row_stride(A, acols), acs = laststride(A);
/* The W4 decode graph supplies BF16 directly so HIP can narrow on load. Preserve the former
* explicit BF16->F16 cast semantics on host backends before evaluating the F16 activation grid. */
/* A BF16 activation (the W4 decode graph's, which the card narrows on load) is narrowed to F16
* first, with the cast kernel's rounding, so the F16 grid sees what the card's GEMM sees. */
std::vector<uint16_t> narrowed;
RadTensor a_f16{};
if (zg.act == ZP_F16 && A->dtype == RAD_BF16) {
+4
View File
@@ -127,6 +127,7 @@ int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream);
int ref_gated_quant_fp8 (const RadArgs*, RadStream);
int ref_gemm_nt_q_gated (const RadArgs*, RadStream);
int ref_dflash_select (const RadArgs*, RadStream);
int ref_dflash_tree (const RadArgs*, RadStream);
int ref_gram_accum (const RadArgs*, RadStream);
int ref_rmsnorm_had_quant_i8(const RadArgs*, RadStream);
int ref_gated_had_quant_i8 (const RadArgs*, RadStream);
@@ -147,6 +148,7 @@ int ref_logits_gemm (const RadArgs*, RadStream);
/* ---- attention */
int ref_attn_paged (const RadArgs*, RadStream);
int ref_attn_paged_tree (const RadArgs*, RadStream);
int ref_attn_dense (const RadArgs*, RadStream);
int ref_attn_cross (const RadArgs*, RadStream);
int ref_table_add (const RadArgs*, RadStream);
@@ -395,6 +397,7 @@ REF_SHAPE_FN(ref_rmsnorm_quant_fp8);
REF_SHAPE_FN(ref_gated_quant_fp8);
REF_SHAPE_FN(ref_gemm_nt_q_gated);
REF_SHAPE_FN(ref_dflash_select);
REF_SHAPE_FN(ref_dflash_tree);
REF_SHAPE_FN(ref_gram_accum);
REF_SHAPE_FN(ref_rmsnorm_had_quant_i8);
REF_SHAPE_FN(ref_gated_had_quant_i8);
@@ -412,6 +415,7 @@ REF_SHAPE_FN(ref_embed_lookup_q);
REF_SHAPE_FN(ref_logits_gemm);
REF_SHAPE_FN(ref_attn_paged);
REF_SHAPE_FN(ref_attn_paged_tree);
REF_SHAPE_FN(ref_attn_dense);
REF_SHAPE_FN(ref_attn_cross);
REF_SHAPE_FN(ref_table_add);
+114
View File
@@ -820,3 +820,117 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
}
return RAD_OK;
}
/* ------------------------------------------------------------- dflash_tree */
/* `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w -> `tokens`, `parents`
*
* dflash_select's lattice and edge scores, grown into a tree of `nodes` nodes instead of walked
* into one path (rad_drafter_tree). Node 0 is the anchor, at lattice position -1 with log
* probability 0. A node at position l with token t has a child for every valid candidate c at
* position l + 1, scored as dflash_select scores it after t, with log probability its parent's
* plus log_softmax(score / temp)[c] over the valid candidates there. Best-first: each round
* selects the not-yet-selected child of any selected node with the largest log probability (ties
* to the one pushed first: lower parent, then lower c), until `nodes` are selected. Selected node
* j (1-based, in selection order, so a parent always precedes its child) is written as
* tokens[j-1] and parents[j-1], the parent's node index (0 the anchor). A frontier that runs dry
* (every candidate invalid) pads with token 0 under the last node, which the verify rejects.
*
* In f32: score as dflash_select; x = score / temp; m = max x; lse = m + log(sum exp(x - m)) over
* the valid candidates, summed in c order; child = parent + (x - lse). */
int ref_dflash_tree(const RadArgs* a, RadStream) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *cand = &a->t[0], *un = &a->t[1], *anc = &a->t[3];
const RadTensor *pred = &a->t[4], *succ = &a->t[5], *out = &a->t[6], *par = &a->t[7];
const RadTensor* hp = t_in(a, 2);
if (!cand->data || !un->data || !anc->data || !pred->data || !succ->data || !out->data ||
!par->data)
return RAD_E_INVAL;
const int64_t steps = p_int(a, "steps", 0);
const int64_t K = p_int(a, "top_k", 0);
const int64_t M = steps > 0 && K > 0
? band_rows(numel(cand) / (steps * K), p_int(a, "M", 0)) : 0;
const int64_t R = p_int(a, "rank", pred->rank >= 2 ? pred->shape[pred->rank - 1] : 0);
const int64_t nv = p_int(a, "n_vocab", pred->rank >= 2 ? pred->shape[pred->rank - 2] : 0);
const int64_t astr = p_int(a, "anchor_stride", 1);
const int64_t N = p_int(a, "nodes", steps);
const float temp = p_f32(a, "temp", 1.0f);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0 || N <= 0 ||
!(temp > 0.0f))
return RAD_E_SHAPE;
if (numel(un) < M * steps * K) return RAD_E_SHAPE;
if (numel(anc) < (M - 1) * astr + 1 || numel(out) < M * N || numel(par) < M * N)
return RAD_E_SHAPE;
if (numel(pred) < nv * R || numel(succ) < nv * R) return RAD_E_SHAPE;
if (hp && numel(hp) < M * steps * R) return RAD_E_SHAPE;
const int64_t cs = laststride(cand), us = laststride(un), os = laststride(out);
const int64_t pps = laststride(par);
const int64_t ps = laststride(pred), sxs = laststride(succ);
const int64_t hs = hp ? laststride(hp) : 1;
REF_PAR_FOR(M * N * K * R)
for (int64_t m = 0; m < M; ++m) {
struct Node { int64_t l, tok, parent; float lp; };
struct Kid { float lp; int64_t parent, l, tok; bool taken; };
std::vector<Node> sel; /* selected, node 0 the anchor */
std::vector<Kid> front; /* every child pushed so far, in push order */
std::vector<float> ax((size_t)R), x((size_t)K);
sel.push_back({ -1, ld_int(anc->dtype, anc->data, offlin(anc, m * astr)), -1, 0.0f });
auto expand = [&](int64_t n) {
const Node nd = sel[(size_t)n];
const int64_t l = nd.l + 1;
if (l >= steps) return;
const int64_t r = m * steps + l;
const int64_t cb = rowoff(cand, r, K), ub = rowoff(un, r, K);
const int64_t hb = hp ? rowoff(hp, r, R) : 0;
const bool ok = nd.tok >= 0 && nd.tok < nv;
for (int64_t i = 0; i < R; ++i)
ax[(size_t)i] = (ok ? ldt(pred, rowoff(pred, nd.tok, R) + i * ps) : 0.0f) *
(hp ? ldt(hp, hb + i * hs) : 1.0f);
float mx = -INFINITY;
for (int64_t c = 0; c < K; ++c) {
const int64_t tok = ld_int(cand->dtype, cand->data, cb + c * cs);
float sc = ldt(un, ub + c * us);
const bool valid = tok >= 0 && tok < nv;
if (valid) {
const int64_t sb = rowoff(succ, tok, R);
for (int64_t i = 0; i < R; ++i) sc += ax[(size_t)i] * ldt(succ, sb + i * sxs);
}
x[(size_t)c] = valid ? sc / temp : -INFINITY;
if (x[(size_t)c] > mx) mx = x[(size_t)c];
}
if (mx == -INFINITY) return;
float sum = 0.0f;
for (int64_t c = 0; c < K; ++c)
if (x[(size_t)c] > -INFINITY) sum += std::exp(x[(size_t)c] - mx);
const float lse = mx + std::log(sum);
for (int64_t c = 0; c < K; ++c) {
if (!(x[(size_t)c] > -INFINITY)) continue;
front.push_back({ nd.lp + (x[(size_t)c] - lse), n, l,
ld_int(cand->dtype, cand->data, cb + c * cs), false });
}
};
expand(0);
for (int64_t j = 1; j <= N; ++j) {
int64_t best = -1;
for (size_t f = 0; f < front.size(); ++f)
if (!front[f].taken && (best < 0 || front[f].lp > front[(size_t)best].lp))
best = (int64_t)f;
if (best < 0) {
sel.push_back({ steps, 0, (int64_t)sel.size() - 1, -INFINITY });
} else {
Kid& k = front[(size_t)best];
k.taken = true;
sel.push_back({ k.l, k.tok, k.parent, k.lp });
expand((int64_t)sel.size() - 1);
}
const Node& nd = sel.back();
st_int(out->dtype, out->data, rowoff(out, m, N) + (j - 1) * os, nd.tok);
st_int(par->dtype, par->data, rowoff(par, m, N) + (j - 1) * pps, nd.parent);
}
}
return RAD_OK;
}
+31
View File
@@ -289,6 +289,13 @@ static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT(
static const RadOperandSpec oDflashSelect[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
OUT("tokens") };
static const RadParamSpec pDflashTree[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"),
P_INT("rank"), P_INT("n_vocab"),
P_INTO("anchor_stride"), P_INT("nodes"),
P_F64O("temp"), P_STR("dtype") };
static const RadOperandSpec oDflashTree[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
OUT("tokens"), OUT("parents") };
static const RadParamSpec pRmsHadQuant[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
P_STR("dtype"), P_F64O("wadd") };
@@ -368,6 +375,11 @@ static const RadOperandSpec oAttnPaged[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), OUT("out")
};
/* attn_paged with the verify block's tree (RadBatch::spec_parent, rad_drafter_tree). */
static const RadOperandSpec oAttnPagedTree[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), OUT("out"), OPD("spec_parent")
};
/* Effective on kv_store, where `block_size` is RAD_REQUIRED: admits every value and refuses only a
* query that omits it. On attn_paged the key is RAD_DERIVED and the constraint is skipped
* (core/plugin/select.cpp). See the file header for the spec §7.2 consequence. */
@@ -1322,6 +1334,12 @@ static const RadOpSchema kSchemas[] = {
"previous pick. `hp` absent is a plane of ones, which drops the form to a plain low-rank "
"bigram. Serial in l by construction -- the predecessor is not known until the previous step "
"has been decided." },
{ "dflash_tree", ARR(pDflashTree), ARR(oDflashTree),
"dflash_select's lattice and edge scores grown best-first into a tree of `nodes` nodes: node 0 "
"is the anchor, each selected node's children are the valid candidates at the next position "
"with log probability parent + log_softmax(score / temp) over them, and each round selects the "
"unselected child with the largest (ties to the first pushed). tokens[j-1] and parents[j-1] are "
"the j-th selected node and its parent's index (0 the anchor)." },
{ "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense),
"ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / "
"rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column "
@@ -1407,6 +1425,11 @@ static const RadOpSchema kSchemas[] = {
"one kernel serves decode, speculative verify and prefill. seqused is the TOTAL key count "
"including this step's query rows. k_descale / v_descale are optional and apply to an fp8 "
"cache. `scale` is not in docs/OPS.md and defaults to 1/sqrt(head_dim)." },
{ "attn_paged_tree", ARR(pAttnPaged), ARR(oAttnPagedTree),
"attn_paged over a tree verify (rad_drafter_tree): spec_parent[row] is -2 for an ordinary "
"causal row, else the row's parent's index within its sequence's rows (-1 for the block's "
"first row). Inside the block such a row sees itself and its ancestors only, and its window is "
"measured from the block's first position plus its depth." },
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense),
"Dense varlen attention over cu_seqlens segments (rows cu/cu_div). Nothing paged. `window` is "
"attn_paged's rule over a segment's positions: causal, i - j < window; non-causal, |i - j| < "
@@ -2284,6 +2307,9 @@ SIMPLE("ref_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm",
SIMPLE("ref_dflash_select", "dflash_select", "draft",
"DFlash2's greedy walk over the candidate lattice",
"i32 candidates, bf16 codebooks, i32 tokens out", ref_dflash_select),
SIMPLE("ref_dflash_tree", "dflash_tree", "draft",
"DFlash2's candidate lattice grown best-first into a tree",
"i32 candidates, bf16 codebooks, i32 tokens and parents out", ref_dflash_tree),
SIMPLE("ref_givens_rotate", "givens_rotate", "quant",
"channel scale and Givens rotations per part, in the output's dtype",
"float in, float out; int32 pairs, f32 angles and channel scales", ref_givens_rotate),
@@ -2341,6 +2367,11 @@ ROW("ref_attn_paged", "attn_paged", "attn",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
nullptr, nullptr, ref_attn_paged, nullptr),
ROW("ref_attn_paged_tree", "attn_paged_tree", "attn",
"paged causal / sliding-window attention with a tree verify block (spec_parent)",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales; i32 parents",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
nullptr, nullptr, ref_attn_paged_tree, nullptr),
SIMPLE("ref_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT,
ref_attn_dense),
SIMPLE("ref_attn_cross", "attn_cross", "attn",
+36
View File
@@ -1344,6 +1344,18 @@ int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("attn_paged", operand, out);
}
/* attn_paged's operands and its tree's parents, each row an ordinary causal one (-2): a drawn
* plane would name parents that are not a tree. */
int ref_attn_paged_tree_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
if (operand < 8) return ref_attn_paged_shape(p, n_p, operand, out);
const int64_t M = gi(p, n_p, "q_len", 0);
if (M <= 0) return RAD_E_UNSUPPORTED;
Opd o;
for (int i = 0; i < 8; ++i) o.skip();
o.t_idx({ M }, 0, -2, 0); /* spec_parent */
return o.finish("attn_paged_tree", operand, out);
}
int ref_attn_dense_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
@@ -2116,6 +2128,30 @@ int ref_dflash_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
return o.finish("dflash_select", operand, out);
}
/* dflash_select's operands, then `nodes` tokens and parents a sequence. */
int ref_dflash_tree_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t steps = gi(p, n_p, "steps", 0);
const int64_t K = gi(p, n_p, "top_k", 0);
const int64_t R = gi(p, n_p, "rank", 0);
const int64_t nv = gi(p, n_p, "n_vocab", 0);
const int64_t astr = gi(p, n_p, "anchor_stride", 1);
const int64_t N = gi(p, n_p, "nodes", steps);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0 || N <= 0)
return RAD_E_UNSUPPORTED;
const int64_t rows = M * steps;
Opd o;
o.t_idx_dt((uint32_t)RAD_I32, { rows, K }, nv, -1, 0); /* cand */
o.t((uint32_t)RAD_F32, { rows, K }); /* unary */
o.t((uint32_t)RAD_BF16, { rows, R }); /* hp */
o.t_idx_dt((uint32_t)RAD_I32, { M * astr }, nv, -1, 0); /* anchor */
o.t((uint32_t)RAD_BF16, { nv, R }); /* pred */
o.t((uint32_t)RAD_BF16, { nv, R }); /* succ */
o.t_idx_dt((uint32_t)RAD_I32, { M, N }, nv, -1, 0); /* tokens */
o.t_idx_dt((uint32_t)RAD_I32, { M, N }, N + 1, -1, 0); /* parents */
return o.finish("dflash_tree", operand, out);
}
/* ================================================================== gated delta net
*
* The layouts are libref/ref_gdn.cpp's: