Implement exact DSpark attention and Markov ops

Shared-anchor window attention and full-vocabulary greedy Markov as named
ops, with libref oracles. Register the anchor-window kernel constraints.
This commit is contained in:
Constantin committed 2026-11-03 13:56:45 -05:00
1 parent b43088a334
commit 340ff8781a
13 files changed
+723 -19

No files matched your search

+21 -5
View File
@@ -81,7 +81,7 @@ struct KvDyn {
* 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) {
static int ref_attn_paged_impl(const RadArgs* a, RadStream, bool shared_anchor_window) {
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);
@@ -97,7 +97,8 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
const int64_t block_size = p_int(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0);
const int causal = (int)p_int(a, "causal", 1);
const int64_t window = p_int(a, "window", 0);
if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
if (head_dim <= 0 || gqa <= 0 || block_size <= 0 ||
(shared_anchor_window && window <= 0)) return RAD_E_SHAPE;
if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0;
@@ -198,11 +199,16 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
/* Key j's slot in the cache, or -1 when the mask hides it or its block is
* unmapped. */
auto key_at = [&](int64_t j) -> int64_t {
if (causal && j > pos) return -1;
const int64_t mask_pos = shared_anchor_window ? base : pos;
if (causal && j > mask_pos) return -1;
if (tree && j >= base && !((tmask >> (j - base)) & 1)) return -1;
if (window > 0) {
const int64_t d = wpos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) return -1;
const int64_t d = (shared_anchor_window ? base : wpos) - j;
if (shared_anchor_window) {
if (d >= window) return -1;
} else if (causal ? (d >= window) : (d >= window || d <= -window)) {
return -1;
}
}
const int64_t blk =
ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs);
@@ -276,6 +282,16 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
return RAD_OK;
}
int ref_attn_paged(const RadArgs* a, RadStream s) {
return ref_attn_paged_impl(a, s, false);
}
int ref_attn_paged_anchor_window(const RadArgs* a, RadStream s) {
if (!a || a->n_t < 8) return RAD_E_INVAL;
if (a->n_t > 8 && t_in(a, 8)) return RAD_E_UNSUPPORTED;
return ref_attn_paged_impl(a, s, true);
}
/* 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) {
+4
View File
@@ -132,6 +132,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_markov_greedy(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);
@@ -153,6 +154,7 @@ int ref_logits_gemm (const RadArgs*, RadStream);
/* ---- attention */
int ref_attn_paged (const RadArgs*, RadStream);
int ref_attn_paged_anchor_window(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);
@@ -412,6 +414,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_markov_greedy);
REF_SHAPE_FN(ref_dflash_tree);
REF_SHAPE_FN(ref_gram_accum);
REF_SHAPE_FN(ref_rmsnorm_had_quant_i8);
@@ -430,6 +433,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_anchor_window);
REF_SHAPE_FN(ref_attn_paged_tree);
REF_SHAPE_FN(ref_attn_dense);
REF_SHAPE_FN(ref_attn_cross);
+79
View File
@@ -824,6 +824,85 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------ dflash_markov_greedy */
/* `logits`, `anchor`, `pred`w, `succ`w -> tile-local winners and `tokens`.
*
* The pinned DSpark reference adds the full-vocabulary bilinear bigram bias to each draft-head
* score, then takes a vocabulary-wide greedy argmax at every position. This is deliberately not
* `dflash_select`: no top-K candidate restriction is applied, and the result at one position is
* the predecessor for the next. Scratch is a 64-token tile decomposition used by the device row;
* the reference writes the same tile winners before selecting the global winner. */
int ref_dflash_markov_greedy(const RadArgs* a, RadStream) {
if (a->n_t < 7) return RAD_E_INVAL;
const RadTensor *logits = &a->t[0], *anchor = &a->t[1], *pred = &a->t[2];
const RadTensor *succ = &a->t[3], *tile_scores = &a->t[4], *tile_tokens = &a->t[5];
const RadTensor *out = &a->t[6];
if (!logits->data || !anchor->data || !pred->data || !succ->data ||
!tile_scores->data || !tile_tokens->data || !out->data) return RAD_E_INVAL;
if (logits->dtype != RAD_BF16 || pred->dtype != RAD_BF16 || succ->dtype != RAD_BF16 ||
tile_scores->dtype != RAD_F32 || tile_tokens->dtype != RAD_I32 || out->dtype != RAD_I32)
return RAD_E_DTYPE;
const int64_t steps = p_int(a, "steps", 0);
const int64_t R = p_int(a, "rank", 0);
const int64_t V = p_int(a, "n_vocab", 0);
const int64_t astr = p_int(a, "anchor_stride", 1);
const int64_t M = steps > 0 && V > 0
? band_rows(numel(logits) / (steps * V), p_int(a, "M", 0)) : 0;
if (M <= 0 || steps <= 0 || R <= 0 || V <= 0 || astr <= 0) return RAD_E_SHAPE;
if (numel(logits) < M * steps * V || numel(anchor) < (M - 1) * astr + 1 ||
numel(pred) < V * R || numel(succ) < V * R || numel(out) < M * steps)
return RAD_E_SHAPE;
const int64_t n_tiles = (V + 63) / 64;
if (numel(tile_scores) < M * n_tiles || numel(tile_tokens) < M * n_tiles)
return RAD_E_SHAPE;
const int64_t ls = laststride(logits), ps = laststride(pred), ss = laststride(succ);
const int64_t os = laststride(out), tss = laststride(tile_scores), tis = laststride(tile_tokens);
REF_PAR_FOR(M * steps * V * R)
for (int64_t m = 0; m < M; ++m) {
std::vector<float> previous((size_t)R);
int64_t pid = ld_int(anchor->dtype, anchor->data, offlin(anchor, m * astr));
for (int64_t l = 0; l < steps; ++l) {
const int64_t row = m * steps + l;
const bool pid_ok = pid >= 0 && pid < V;
const int64_t pb = pid_ok ? rowoff(pred, pid, R) : 0;
for (int64_t r = 0; r < R; ++r)
previous[(size_t)r] = pid_ok ? ldt(pred, pb + r * ps) : 0.0f;
float global_best = -INFINITY;
int64_t global_token = 0;
for (int64_t tile = 0; tile < n_tiles; ++tile) {
const int64_t first = tile * 64;
const int64_t end = std::min<int64_t>(first + 64, V);
float best = -INFINITY;
int64_t best_token = first;
const int64_t lb = rowoff(logits, row, V);
for (int64_t token = first; token < end; ++token) {
float score = ldt(logits, lb + token * ls);
const int64_t sb = rowoff(succ, token, R);
for (int64_t r = 0; r < R; ++r)
score += previous[(size_t)r] * ldt(succ, sb + r * ss);
if (score > best || (score == best && token < best_token)) {
best = score;
best_token = token;
}
}
stt(tile_scores, rowoff(tile_scores, m, n_tiles) + tile * tss, best);
st_int(tile_tokens->dtype, tile_tokens->data,
rowoff(tile_tokens, m, n_tiles) + tile * tis, best_token);
if (best > global_best || (best == global_best && best_token < global_token)) {
global_best = best;
global_token = best_token;
}
}
st_int(out->dtype, out->data, rowoff(out, m, steps) + l * os, global_token);
pid = global_token;
}
}
return RAD_OK;
}
/* ------------------------------------------------------------- dflash_tree */
/* `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w -> `tokens`, `parents`
*
+24
View File
@@ -298,9 +298,15 @@ static const RadOperandSpec oGemmQGated[] = { OPD("a"), OPD("a_scale"), WGT("b")
static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"),
P_INT("rank"), P_INT("n_vocab"),
P_INTO("anchor_stride"), P_STR("dtype") };
static const RadParamSpec pDflashMarkov[] = { P_INT("M"), P_INT("steps"), P_INT("rank"),
P_INT("n_vocab"), P_INTO("anchor_stride"),
P_STR("dtype") };
static const RadOperandSpec oDflashSelect[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
OUT("tokens") };
static const RadOperandSpec oDflashMarkov[] = { OPD("logits"), OPD("anchor"), WGT("pred"),
WGT("succ"), OUT("tile_scores"),
OUT("tile_tokens"), 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"),
@@ -1376,6 +1382,10 @@ 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_markov_greedy", ARR(pDflashMarkov), ARR(oDflashMarkov),
"The DSpark reference walk: score all vocabulary ids at each position as draft_logit[token] + "
"sum_r pred[previous_token][r] * succ[token][r], select the greatest score (lower id breaks "
"ties), then use that token as the next predecessor." },
{ "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 "
@@ -1467,6 +1477,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_anchor_window", ARR(pAttnPaged), ARR(oAttnPaged),
"Paged attention with one shared window anchor at the first query position in each sequence. "
"Every row uses anchor - key < window as its lower-bound predicate; causal attention also masks "
"keys after the anchor. This operation has a distinct name because ordinary attn_paged measures "
"visibility from each query row." },
{ "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 "
@@ -2381,6 +2396,10 @@ 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_markov_greedy", "dflash_markov_greedy", "draft",
"DSpark's full-vocabulary greedy Markov walk",
"bf16 logits and codebooks, f32/i32 tile winners, i32 tokens out",
ref_dflash_markov_greedy),
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),
@@ -2441,6 +2460,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_anchor_window", "attn_paged_anchor_window", "attn",
"paged attention with an exact shared anchor-aligned sliding window",
"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_anchor_window, 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",
+33 -2
View File
@@ -1404,7 +1404,8 @@ int ref_lora_expand_mm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc
* The block count and context length are this description's choice; any cache large enough for
* the indices will do. */
int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
static int ref_attn_paged_shape_impl(const RadParam* p, int n_p, int operand, RadOpdDesc* out,
const char* op_name) {
/* `q_len` is the ranged parameter, a query length (one row at decode, thousands in a prefill
* chunk; different kernels, docs/OPS.md). */
const int64_t M = gi(p, n_p, "q_len", 0);
@@ -1443,7 +1444,15 @@ int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
* would have to agree with a tool's `M` rather than this description's. */
o.skip(); /* cu_seqlens */
o.t(Q, { S * M, nh, hd }); /* out */
return o.finish("attn_paged", operand, out);
return o.finish(op_name, operand, out);
}
int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return ref_attn_paged_shape_impl(p, n_p, operand, out, "attn_paged");
}
int ref_attn_paged_anchor_window_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return ref_attn_paged_shape_impl(p, n_p, operand, out, "attn_paged_anchor_window");
}
/* attn_paged's operands and its tree's parents, each row an ordinary causal one (-2): a drawn
@@ -2230,6 +2239,28 @@ int ref_dflash_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
return o.finish("dflash_select", operand, out);
}
/* The full-vocabulary DSpark Markov walk. Its tile planes hold one exact local max per 64 ids. */
int ref_dflash_markov_greedy_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 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);
if (M <= 0 || steps <= 0 || R <= 0 || nv <= 0 || astr <= 0)
return RAD_E_UNSUPPORTED;
const int64_t rows = M * steps;
const int64_t tiles = (nv + 63) / 64;
Opd o;
o.t((uint32_t)RAD_BF16, { rows, nv }); /* logits */
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((uint32_t)RAD_F32, { M, tiles }); /* tile_scores */
o.t_idx_dt((uint32_t)RAD_I32, { M, tiles }, nv, -1, 0); /* tile_tokens */
o.t_idx_dt((uint32_t)RAD_I32, { M, steps }, nv, -1, 0); /* tokens */
return o.finish("dflash_markov_greedy", 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);