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

+16
View File
@@ -935,6 +935,7 @@ as the weight's GEMM stored them and claims no form. It changes no value.
| op | params | operands |
|---|---|---|
| `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` |
| `attn_paged_anchor_window` | same parameters as `attn_paged` | same operands as `attn_paged` → `out` |
| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt `cu_div`/opt `block`/opt `window_right`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
| `attn_cross` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `cu_seqlens`, `cu_k` → `out` |
| `attn_na3d` | `M`(range) `head_dim` `kt` `kh` `kw` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `geom` → `out` |
@@ -955,6 +956,10 @@ as the weight's GEMM stored them and claims no form. It changes no value.
**`attn_paged`**'s band is `q_len`, not `M`: one query row at decode, `1 + n_spec` at a speculative
verify, thousands in a prefill chunk, and libr4d has a different kernel for each band.
`attn_paged_anchor_window` has the same layout but different visibility: the first query position
in each sequence is the shared anchor for every query row, with the lower-bound predicate
`anchor - key < window`; causal mode additionally masks keys after the anchor. It is a distinct op
name so an older plugin cannot silently interpret this as per-query `attn_paged`.
`block_size` is read off the resolved kernel, not chosen: declare the group, declare the op, then
ask `rad_kv_block_size()` (`spec.md` §7.2).
@@ -3355,6 +3360,17 @@ bytes do not depend on the batch.
A drafter is an ordinary graph over ordinary ops except at its two ends: what proposes the
candidates, and what enters the head from the trunk.
### DSpark
| op | params | operands |
|---|---|---|
| `dflash_markov_greedy` | `M` `steps` `rank` `n_vocab` `anchor_stride`/opt `dtype` | `logits`, `anchor`, `pred`w, `succ`w → `tile_scores`, `tile_tokens`, `tokens` |
`dflash_markov_greedy` is the exact DSpark reference walk, not DFlash2's candidate-lattice selector.
For every position it adds `sum_r pred[previous,r] * succ[token,r]` to every vocabulary logit,
chooses the greatest biased score (ties to the lower token id), and uses that id as the next
predecessor. The explicit tile outputs are scratch for the device's vocabulary-wide reduction.
### DFlash2
| op | params | operands |
+1
View File
@@ -201,6 +201,7 @@ set(R4D_UNITS
"r4d_lora_bf16|"
"r4d_dflash_conv_t2_g16_bf16|"
"r4d_dflash_select_bf16|"
"r4d_dflash_markov_bf16|"
"r4d_dflash_tree_bf16|"
# Routed MoE: router, scatter, the grouped block-scaled fp8 GEMM and gather, in one unit because
# the other three only feed the GEMM.
+32 -10
View File
@@ -194,6 +194,7 @@ struct AttnArgs {
int* tinfo; /* [tile] = (first row, positions) */
float qscale; /* softmax scale * log2(e) */
int max_blocks, n_seq, q_len, tps, kv_heads, causal, window, n_split;
int shared_window; /* all query rows use sequence anchor */
/* A tree verify (attn_paged_qrow_tree): RadBatch::spec_parent, one a query row; read only by
* the TREE instances. */
const int* tpar;
@@ -302,15 +303,16 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
const int qbase = ctx - qlen + pfirst; /* absolute position of the tile's first query */
const int plast = qbase + npos - 1;
const int causal = A.causal, window = A.window;
const int tbase = ctx - qlen; /* first query position, the block anchor */
const int window_base = A.shared_window ? tbase : ((TREE && A.tpar) ? tbase : qbase);
/* ---- the tile's key range, and this split's share of it */
int hi = causal ? plast + 1 : ctx;
if (!causal && window > 0) hi = imin(hi, plast + window);
int hi = causal ? (A.shared_window ? tbase + 1 : plast + 1) : ctx;
if (!causal && window > 0 && !A.shared_window) hi = imin(hi, plast + window);
hi = imin(imin(hi, ctx), A.max_blocks * 16);
/* A tree row's window is measured from the block's first position plus its depth, which can
* be below its own position, so a tree launch starts every tile at the block's first. */
const int tbase = ctx - qlen;
const int lo = window > 0 ? imax(0, ((TREE && A.tpar) ? tbase : qbase) - window + 1) : 0;
* be below its own position; an anchor-window launch also uses the first row for every query. */
const int lo = window > 0 ? imax(0, window_base - window + 1) : 0;
const int lo_a = lo & ~(BK - 1);
const int nkt = hi > lo_a ? (hi - lo_a + BK - 1) / BK : 0;
const int per = (nkt + A.n_split - 1) / A.n_split;
@@ -434,11 +436,14 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
reduce_scatter<8, BK>(sc, lane);
}
const int pq = pos[i];
bool vis = kok && (causal ? kk <= pq : true);
bool vis = kok && (causal ? kk <= (A.shared_window ? tbase : pq) : true);
if constexpr (TREE)
if (tr[i] && vis && kk >= tbase) vis = ((tm[i] >> (kk - tbase)) & 1ull) != 0;
const int wpq = TREE ? wq[i] : pq;
if (window > 0) vis = vis && (wpq - kk < window) && (causal || kk - wpq < window);
const int wpq = A.shared_window ? tbase : (TREE ? wq[i] : pq);
if (A.shared_window)
vis = vis && (wpq - kk < window);
else if (window > 0)
vis = vis && (wpq - kk < window) && (causal || kk - wpq < window);
const float sv = vis ? sc[0] : -__builtin_inff();
const float mn = __builtin_fmaxf(m[i], wave_max(sv));
if (mn == -__builtin_inff()) return; /* nothing visible yet: uniform */
@@ -1040,7 +1045,7 @@ __global__ __launch_bounds__(kThreads) void r4dchain_merge_window(AttnArgs A) {
r4d_chain_done();
}
template <int HD, int GQA, bool KV8, bool TREE = false>
template <int HD, int GQA, bool KV8, bool TREE = false, bool SHARED = false>
static int launch_attn(const RadArgs* a, RadStream stream) {
constexpr int R = Geo<HD>::R, BK = Geo<HD>::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2;
if (!a || a->n_t < (TREE ? 9 : 8)) return RAD_E_INVAL;
@@ -1137,7 +1142,8 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
if (qmax_w <= 0 || qmax_w > rows) qmax_w = rows;
}
/* Never a tree: its verify blocks are decode-sized, and only the scalar kernel reads one. */
const bool shaped = !TREE && qmax_w >= kWmmaMinQ && rows >= n_seq * (kWmmaMinQ / 2);
const bool shaped = !TREE && !SHARED && qmax_w >= kWmmaMinQ &&
rows >= n_seq * (kWmmaMinQ / 2);
const bool aligned = rad_ptr_aligned(q->data, 16) && rad_ptr_aligned(o->data, 16) &&
(q_rs | q_hs | o_rs | o_hs) % 8 == 0;
if (shaped && aligned) {
@@ -1171,6 +1177,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
W.kv_heads = (int)kvh;
W.causal = (int)causal;
W.window = (int)window;
W.shared_window = SHARED;
W.n_split = 1;
R4D_KLAUNCH(R4D_KNAME(attn_wmma_kernel<HD, GQA, KV8>), dim3((unsigned)ntw, (unsigned)kvh, 1u),
dim3(kWThreads), (hipStream_t)stream, W);
@@ -1214,6 +1221,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
A.kv_heads = (int)kvh;
A.causal = (int)causal;
A.window = (int)window;
A.shared_window = SHARED;
A.n_split = (int)ns;
A.tpar = TREE ? (const int*)tp->data : nullptr;
@@ -1267,6 +1275,20 @@ R4D_WIN_TREE_DEF(256, 1) R4D_WIN_TREE_DEF(256, 2) R4D_WIN_TREE_DEF(256, 4) R4D_W
R4D_WIN_TREE_DEF(512, 1) R4D_WIN_TREE_DEF(512, 2) R4D_WIN_TREE_DEF(512, 4) R4D_WIN_TREE_DEF(512, 8)
#undef R4D_WIN_TREE_DEF
/* Exact DSpark mask: every query row uses the first query position as the sliding-window anchor.
* This is a distinct op name so a library without this semantic cannot silently resolve it. */
#define R4D_WIN_ANCHOR_DEF(HD, G) \
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_bf16kv(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, false, false, true>(a, s); \
} \
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_fp8kv(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, true, false, true>(a, s); \
}
R4D_WIN_ANCHOR_DEF(128, 1)
R4D_WIN_ANCHOR_DEF(256, 1) R4D_WIN_ANCHOR_DEF(256, 2) R4D_WIN_ANCHOR_DEF(256, 4) R4D_WIN_ANCHOR_DEF(256, 8)
R4D_WIN_ANCHOR_DEF(512, 1) R4D_WIN_ANCHOR_DEF(512, 2) R4D_WIN_ANCHOR_DEF(512, 4) R4D_WIN_ANCHOR_DEF(512, 8)
#undef R4D_WIN_ANCHOR_DEF
/* Called at declare with no tensors. Partials are capped at kPartBudget (tile, head, split)
* triples for any batch, so the size is a constant. */
int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*) { return r4d_win::scratch_need<128>(); }
+191
View File
@@ -0,0 +1,191 @@
// Full-vocabulary DSpark Markov greedy walk. Unlike dflash_select's candidate-lattice walk, this
// operation applies the learned bigram bias to every draft-head logit and greedily selects the
// largest biased score at each position, matching the pinned llama.cpp reference.
#include <hip/hip_runtime.h>
#include <climits>
#include "r4d_gdn_args.h"
#include "r4d_dflash_conv_body.h" // r4d_bf2f, r4d_u16
#include "r4d_common.h" // r4d_wave_sum
namespace {
constexpr int kThreads = 256;
constexpr int kWave = 32;
constexpr int kWarps = kThreads / kWave;
constexpr int kCandidatesPerTile = 64;
constexpr int kCandidatesPerWarp = kCandidatesPerTile / kWarps;
constexpr int kMaxRank = 512;
// One CTA scans 64 vocabulary rows, eight at a time (one warp per row). The rank reduction is
// parallel across the warp and codebook loads remain contiguous. Each CTA writes its exact local
// argmax; a second kernel reduces those tile winners before the next dependent position starts.
__global__ __launch_bounds__(kThreads) void markov_score_tiles(
const r4d_u16* __restrict__ logits, long logits_pitch,
const int* __restrict__ anchor, long anchor_stride,
const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ,
float* __restrict__ tile_scores, int* __restrict__ tile_tokens,
const int* __restrict__ out, long out_pitch,
int step, int steps, int rank, int vocab, int n_tiles) {
const int seq = blockIdx.y;
const int tile = blockIdx.x;
const int tid = threadIdx.x;
const int lane = tid & (kWave - 1);
const int warp = tid / kWave;
const int prev = step == 0 ? anchor[(long)seq * anchor_stride]
: out[(long)seq * out_pitch + step - 1];
const bool prev_ok = prev >= 0 && prev < vocab;
__shared__ float s_pred[kMaxRank];
__shared__ float s_best[kWarps];
__shared__ int s_token[kWarps];
for (int r = tid; r < rank; r += kThreads)
s_pred[r] = prev_ok ? r4d_bf2f(pred[(long)prev * rank + r]) : 0.0f;
__syncthreads();
float warp_best = -INFINITY;
int warp_token = tile * kCandidatesPerTile + warp;
#pragma unroll
for (int j = 0; j < kCandidatesPerWarp; ++j) {
const int token = tile * kCandidatesPerTile + warp + j * kWarps;
if (token < vocab) {
float dot = 0.0f;
#pragma unroll 8
for (int r = lane; r < rank; r += kWave)
dot += s_pred[r] * r4d_bf2f(succ[(long)token * rank + r]);
dot = r4d_wave_sum(dot);
if (lane == 0) {
const float score = r4d_bf2f(logits[(long)seq * steps * logits_pitch +
(long)step * logits_pitch + token]) + dot;
if (score > warp_best || (score == warp_best && token < warp_token)) {
warp_best = score;
warp_token = token;
}
}
}
}
if (lane == 0) {
s_best[warp] = warp_best;
s_token[warp] = warp_token;
}
__syncthreads();
if (tid == 0) {
float best = -INFINITY;
int best_token = tile * kCandidatesPerTile;
#pragma unroll
for (int w = 0; w < kWarps; ++w) {
const float score = s_best[w];
const int token = s_token[w];
if (score > best || (score == best && token < best_token)) {
best = score;
best_token = token;
}
}
tile_scores[(long)seq * n_tiles + tile] = best;
tile_tokens[(long)seq * n_tiles + tile] = best_token;
}
}
__global__ __launch_bounds__(kThreads) void markov_reduce_tiles(
const float* __restrict__ tile_scores, const int* __restrict__ tile_tokens,
int* __restrict__ out, long out_pitch, int step, int n_tiles) {
const int seq = blockIdx.x;
const int tid = threadIdx.x;
__shared__ float s_best[kThreads];
__shared__ int s_token[kThreads];
float best = -INFINITY;
int best_token = INT_MAX;
for (int tile = tid; tile < n_tiles; tile += kThreads) {
const float score = tile_scores[(long)seq * n_tiles + tile];
const int token = tile_tokens[(long)seq * n_tiles + tile];
if (score > best || (score == best && token < best_token)) {
best = score;
best_token = token;
}
}
s_best[tid] = best;
s_token[tid] = best_token;
__syncthreads();
for (int stride = kThreads / 2; stride > 0; stride >>= 1) {
if (tid < stride) {
const float score = s_best[tid + stride];
const int token = s_token[tid + stride];
if (score > s_best[tid] || (score == s_best[tid] && token < s_token[tid])) {
s_best[tid] = score;
s_token[tid] = token;
}
}
__syncthreads();
}
if (tid == 0) out[(long)seq * out_pitch + step] = s_token[0];
}
int markov_emit(const r4d_u16* logits, long logits_pitch, const int* anchor, long anchor_stride,
const r4d_u16* pred, const r4d_u16* succ, float* tile_scores, int* tile_tokens,
int* out, long out_pitch, int sequences, int steps, int rank, int vocab,
int n_tiles, RadStream stream) {
for (int step = 0; step < steps; ++step) {
hipLaunchKernelGGL(markov_score_tiles, dim3(n_tiles, sequences), dim3(kThreads), 0,
(hipStream_t)stream, logits, logits_pitch, anchor, anchor_stride, pred,
succ, tile_scores, tile_tokens, out, out_pitch, step, steps, rank, vocab,
n_tiles);
hipLaunchKernelGGL(markov_reduce_tiles, dim3(sequences), dim3(kThreads), 0,
(hipStream_t)stream, tile_scores, tile_tokens, out, out_pitch, step,
n_tiles);
}
return (int)hipGetLastError();
}
} // namespace
extern "C" int r4d_rad_dflash_markov_greedy(const RadArgs* a, RadStream stream) {
constexpr int LOGITS = 0, ANCHOR = 1, PRED = 2, SUCC = 3;
constexpr int TILE_SCORE = 4, TILE_TOKEN = 5, OUT = 6;
const RadTensor* logits = r4d_opt(a, LOGITS);
const RadTensor* anchor = r4d_opt(a, ANCHOR);
const RadTensor* pred = r4d_opt(a, PRED);
const RadTensor* succ = r4d_opt(a, SUCC);
const RadTensor* scores = r4d_opt(a, TILE_SCORE);
const RadTensor* tokens = r4d_opt(a, TILE_TOKEN);
const RadTensor* out = r4d_opt(a, OUT);
if (!logits || !anchor || !pred || !succ || !scores || !tokens || !out)
return R4D_NO(RAD_E_INVAL);
const long long steps = r4d_geti_or(a, "steps", 0);
const long long rank = r4d_geti_or(a, "rank", 0);
const long long vocab = r4d_geti_or(a, "n_vocab", 0);
const long long anchor_stride = r4d_geti_or(a, "anchor_stride", 1);
if (steps <= 0 || rank < kWave || rank > kMaxRank || rank % kWave || vocab <= 0 ||
anchor_stride <= 0)
return R4D_NO(RAD_E_INVAL);
if (out->dtype != RAD_I32 || out->rank != 2 || out->shape[1] < steps)
return R4D_NO(RAD_E_SHAPE);
const long long sequences = out->shape[0];
const long long out_pitch = r4d_row_pitch(out);
const long long logits_pitch = r4d_row_pitch(logits);
if (sequences <= 0 || out_pitch < steps || logits->dtype != RAD_BF16 || logits->rank != 2 ||
logits->shape[0] < sequences * steps || logits->shape[1] < vocab || logits_pitch < vocab)
return R4D_NO(RAD_E_SHAPE);
if (anchor->dtype != RAD_I32 || !r4d_contig(anchor) ||
r4d_numel(anchor) < (sequences - 1) * anchor_stride + 1)
return R4D_NO(RAD_E_SHAPE);
if (pred->dtype != RAD_BF16 || succ->dtype != RAD_BF16 || !r4d_contig(pred) ||
!r4d_contig(succ) || r4d_numel(pred) < vocab * rank || r4d_numel(succ) < vocab * rank)
return R4D_NO(RAD_E_SHAPE);
const long long n_tiles = (vocab + kCandidatesPerTile - 1) / kCandidatesPerTile;
if (scores->dtype != RAD_F32 || tokens->dtype != RAD_I32 || scores->rank != 2 ||
tokens->rank != 2 || scores->shape[0] < sequences || tokens->shape[0] < sequences ||
scores->shape[1] < n_tiles || tokens->shape[1] < n_tiles ||
r4d_row_pitch(scores) < n_tiles || r4d_row_pitch(tokens) < n_tiles)
return R4D_NO(RAD_E_SHAPE);
return R4D_RAW(markov_emit((const r4d_u16*)logits->data, (long)logits_pitch,
(const int*)anchor->data, (long)anchor_stride,
(const r4d_u16*)pred->data, (const r4d_u16*)succ->data,
(float*)scores->data, (int*)tokens->data, (int*)out->data,
(long)out_pitch, (int)sequences, (int)steps, (int)rank,
(int)vocab, (int)n_tiles, stream));
}
+11
View File
@@ -188,6 +188,16 @@ int r4d_rad_attn_window_h512_gqa8_fp8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*);
#define R4D_ATTN_ANCHOR_DECL(HD, G) \
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_bf16kv(const RadArgs*, RadStream); \
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_fp8kv(const RadArgs*, RadStream);
R4D_ATTN_ANCHOR_DECL(128, 1)
R4D_ATTN_ANCHOR_DECL(256, 1) R4D_ATTN_ANCHOR_DECL(256, 2) R4D_ATTN_ANCHOR_DECL(256, 4)
R4D_ATTN_ANCHOR_DECL(256, 8)
R4D_ATTN_ANCHOR_DECL(512, 1) R4D_ATTN_ANCHOR_DECL(512, 2) R4D_ATTN_ANCHOR_DECL(512, 4)
R4D_ATTN_ANCHOR_DECL(512, 8)
#undef R4D_ATTN_ANCHOR_DECL
int r4d_rad_dflash_markov_greedy(const RadArgs*, RadStream);
/* attn_paged_qrow_tree (docs/OPS.md): the h256/gqa2 split-KV decode and the windowed kernels with a
* tree verify's mask from operand 8, `spec_parent`. */
int r4d_rad_attn_qrow_tree_decode_h256_gqa2_fp8 (const RadArgs*, RadStream);
@@ -1001,6 +1011,7 @@ int r4d_shape_qsa_work (const RadParam*, int, int operand, RadOpdDesc*
int r4d_shape_dflash_conv (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_dflash_select (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_dflash_markov (const RadParam*, int, int operand, RadOpdDesc*);
/* -- declared fusions (r4d_fuse.cpp, pure host) --
*
+65
View File
@@ -713,6 +713,20 @@ static const RadOperandSpec oDflashSelect[] = {
{ "succ", RAD_OPD_WEIGHT, 0 },
{ "tokens", RAD_OPD_OUT, 0 },
};
/* DSpark's exact, vocabulary-wide greedy Markov walk. Per-tile score/id planes are explicit
* outputs so the device implementation can parallelize each full-vocabulary step and reduce it
* before the next autoregressive step. */
static const RadParamSpec pDflashMarkov[] = {
{ "M", RAD_P_INT, RAD_REQUIRED }, { "steps", RAD_P_INT, RAD_REQUIRED },
{ "rank", RAD_P_INT, RAD_REQUIRED }, { "n_vocab", RAD_P_INT, RAD_REQUIRED },
{ "anchor_stride", RAD_P_INT, RAD_OPTIONAL }, { "dtype", RAD_P_STR, RAD_REQUIRED },
};
static const RadOperandSpec oDflashMarkov[] = {
{ "logits", RAD_OPD_IN, 0 }, { "anchor", RAD_OPD_IN, 0 },
{ "pred", RAD_OPD_WEIGHT, 0 }, { "succ", RAD_OPD_WEIGHT, 0 },
{ "tile_scores", RAD_OPD_OUT, 0 }, { "tile_tokens", RAD_OPD_OUT, 0 },
{ "tokens", RAD_OPD_OUT, 0 },
};
/* dflash_tree: dflash_select's, plus the node count, the softmax temperature and the parents. */
static const RadParamSpec pDflashTree[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
@@ -3259,6 +3273,8 @@ static const RadOpSchema kSchemas[] = {
"paged causal attention, varlen. The ranged parameter is q_len, not M: one query row "
"at decode, up to 64/gqa at a speculative verify, thousands in a prefill chunk, and "
"libr4d has a different kernel for each band."),
SCHEMA("attn_paged_anchor_window", pAttnPaged, oAttnPaged,
"paged attention whose query rows all use the sequence's first query as the sliding-window anchor."),
/* attn_paged under its own name, for q read at its own row pitch. The windowed kernels
* (r4d_attn_paged_window.hip) read q in place in a fused [q|k|v] projection; the other
* attn_paged kernels read q dense and refuse a slice (RAD_E_STRIDE). Under this name the op
@@ -3379,6 +3395,10 @@ static const RadOpSchema kSchemas[] = {
"positions, and the greedy walk that turns a block of independent top-k sets into one "
"path. Only the K edges leaving the previous pick are scored, because the walk is "
"serial and the other K-1 rows of the score matrix are never read."),
SCHEMA("dflash_markov_greedy", pDflashMarkov, oDflashMarkov,
"DSpark's exact greedy Markov walk: add the full-vocabulary bilinear bias to each "
"draft-head logit, choose the greatest token (ties to the lower id), then use it as the "
"next position's predecessor."),
SCHEMA("dflash_tree", pDflashTree, oDflashTree,
"dflash_select's lattice and edge scores grown best-first into a tree of `nodes` nodes: "
"a taken node's children are the valid candidates at the next position, each with log "
@@ -4209,6 +4229,16 @@ R4D_WIN_C(cWinH512G1Bf16, 512, 1, "bf16", 0) R4D_WIN_C(cWinH512G1Fp8, 512, 1, "f
R4D_WIN_C(cWinH512G2Bf16, 512, 2, "bf16", 0) R4D_WIN_C(cWinH512G2Fp8, 512, 2, "fp8_e4m3", 0)
R4D_WIN_C(cWinH512G4Bf16, 512, 4, "bf16", 0) R4D_WIN_C(cWinH512G4Fp8, 512, 4, "fp8_e4m3", 0)
R4D_WIN_C(cWinH512G8Bf16, 512, 8, "bf16", 0) R4D_WIN_C(cWinH512G8Fp8, 512, 8, "fp8_e4m3", 0)
/* DSpark uses the same geometry constraints, but requires a positive window. */
R4D_WIN_C(cAnchorH128G1Bf16, 128, 1, "bf16", 1) R4D_WIN_C(cAnchorH128G1Fp8, 128, 1, "fp8_e4m3", 1)
R4D_WIN_C(cAnchorH256G1Bf16, 256, 1, "bf16", 1) R4D_WIN_C(cAnchorH256G1Fp8, 256, 1, "fp8_e4m3", 1)
R4D_WIN_C(cAnchorH256G2Bf16, 256, 2, "bf16", 1) R4D_WIN_C(cAnchorH256G2Fp8, 256, 2, "fp8_e4m3", 1)
R4D_WIN_C(cAnchorH256G4Bf16, 256, 4, "bf16", 1) R4D_WIN_C(cAnchorH256G4Fp8, 256, 4, "fp8_e4m3", 1)
R4D_WIN_C(cAnchorH256G8Bf16, 256, 8, "bf16", 1) R4D_WIN_C(cAnchorH256G8Fp8, 256, 8, "fp8_e4m3", 1)
R4D_WIN_C(cAnchorH512G1Bf16, 512, 1, "bf16", 1) R4D_WIN_C(cAnchorH512G1Fp8, 512, 1, "fp8_e4m3", 1)
R4D_WIN_C(cAnchorH512G2Bf16, 512, 2, "bf16", 1) R4D_WIN_C(cAnchorH512G2Fp8, 512, 2, "fp8_e4m3", 1)
R4D_WIN_C(cAnchorH512G4Bf16, 512, 4, "bf16", 1) R4D_WIN_C(cAnchorH512G4Fp8, 512, 4, "fp8_e4m3", 1)
R4D_WIN_C(cAnchorH512G8Bf16, 512, 8, "bf16", 1) R4D_WIN_C(cAnchorH512G8Fp8, 512, 8, "fp8_e4m3", 1)
#undef R4D_WIN_C
/* Twelve queries per KV head, head_dim 256 (r4d_attn_paged_h256_gqa12.hip): Qwen3.8-Flash-Next's
* QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound, tighter
@@ -4622,6 +4652,10 @@ static const RadConstraint cDflashSelect[] = {
C_GE("steps", 1), C_GE("top_k", 1), C_LE("top_k", 32),
C_DIV("rank", 32), C_LE("rank", 512), C_IN("dtype", "bf16"),
};
static const RadConstraint cDflashMarkov[] = {
C_GE("steps", 1), C_DIV("rank", 32), C_LE("rank", 512),
C_GE("n_vocab", 1), C_IN("dtype", "bf16"),
};
/* dflash_tree's frontier (nodes x top_k children) and its node table live in LDS. */
static const RadConstraint cDflashTree[] = {
C_GE("steps", 1), C_LE("steps", 63), C_GE("top_k", 1), C_LE("top_k", 32),
@@ -7199,6 +7233,27 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
#undef R4D_WIN_PAIR
#undef R4D_WIN_ROW
/* DSpark's shared-anchor mask is intentionally a distinct op/kernel family, not an accepted
* `window` variation of attn_paged's per-query visibility. Its base/upper key bounds are tied to
* the sequence's first query row. */
#define R4D_ANCHOR_ROW(HD, G, KVN, KVS, C, KVDOC) \
{ "attn_anchor_window_h" #HD "_gqa" #G "_" #KVN, "attn_paged_anchor_window", "attn", \
"paged attention with the first query row as the shared sliding-window anchor", \
"head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \
"bf16 query, " KVDOC " kv cache, bf16 out, f32 partials", \
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_WINDOW, \
ROW(C), NOTUNE, \
nullptr, nullptr, r4d_rad_attn_anchor_window_h##HD##_gqa##G##_##KVS, \
r4d_rad_attn_window_h##HD##_scratch, nullptr, nullptr, r4d_shape_attn_paged },
#define R4D_ANCHOR_PAIR(HD, GQ) \
R4D_ANCHOR_ROW(HD, GQ, bf16kv, bf16kv, cAnchorH##HD##G##GQ##Bf16, "bf16") \
R4D_ANCHOR_ROW(HD, GQ, fp8kv, fp8kv, cAnchorH##HD##G##GQ##Fp8, "fp8-e4m3 (per-(seq,head) descales)")
R4D_ANCHOR_PAIR(128, 1)
R4D_ANCHOR_PAIR(256, 1) R4D_ANCHOR_PAIR(256, 2) R4D_ANCHOR_PAIR(256, 4) R4D_ANCHOR_PAIR(256, 8)
R4D_ANCHOR_PAIR(512, 1) R4D_ANCHOR_PAIR(512, 2) R4D_ANCHOR_PAIR(512, 4) R4D_ANCHOR_PAIR(512, 8)
#undef R4D_ANCHOR_PAIR
#undef R4D_ANCHOR_ROW
/* ...and under attn_paged_qrow_tree, the scalar kernel with a tree verify's mask (the launch
* refuses a non-causal one and never takes the WMMA kernel). */
#define R4D_WIN_TREE_ROW(HD, G, KVN, KVS, C, KVDOC) \
@@ -9541,6 +9596,16 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
nullptr, nullptr, r4d_rad_dflash_conv, nullptr, nullptr, nullptr,
r4d_shape_dflash_conv },
{ "dflash_markov_greedy_bf16", "dflash_markov_greedy", "dflash",
"Full-vocabulary DSpark Markov bias and serial greedy argmax; dependent positions each follow "
"a complete scan of the draft-head vocabulary",
"steps >= 1, rank a multiple of 32 and <= 512, 64 vocabulary ids per scratch tile",
"bf16 logits and codebooks, i32 anchor, f32/i32 tile winners, i32 tokens out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cDflashMarkov), NOTUNE,
nullptr, nullptr, r4d_rad_dflash_markov_greedy, nullptr, nullptr, nullptr,
r4d_shape_dflash_markov },
{ "dflash_select_bf16", "dflash_select", "dflash",
"DFlash2 candidate selector: the low-rank edge scores and the greedy walk over them, one "
"workgroup a sequence and no launch between steps",
+24
View File
@@ -2201,3 +2201,27 @@ extern "C" int r4d_shape_dflash_select(const RadParam* p, int n_p, int operand,
};
R4D_PICK(l);
}
extern "C" int r4d_shape_dflash_markov(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t steps = pi(p, n_p, "steps");
const int64_t R = pi(p, n_p, "rank");
const int64_t V = pi(p, n_p, "n_vocab");
const int64_t astr = pi(p, n_p, "anchor_stride", 1);
const uint32_t D = dt_act(p, n_p, "dtype");
if (M <= 0 || steps <= 0 || R <= 0 || V <= 0 || astr < 1)
return RAD_E_UNSUPPORTED;
const int64_t tiles = (V + 63) / 64;
const int64_t rows = M * steps;
const RadOpdDesc l[] = {
opd(D, rows, V),
opd_idx((M - 1) * astr + 1, 0, V),
opd(D, V, R),
opd(D, V, R),
opd((uint32_t)RAD_F32, M, tiles),
opd_idx(M, tiles, V),
opd_idx(M, steps, V),
};
R4D_PICK(l);
}
+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);
+222 -2
View File
@@ -1068,8 +1068,9 @@ TEST(op_vocabulary) {
/* The fused fp8 forms. A host run needs every op covered, so these keep a host-backend run
* from failing with "site 'host' is unavailable for this band". */
"rmsnorm_quant_fp8", "gated_quant_fp8", "gemm_nt_q_gated", "dflash_select",
"dflash_markov_greedy",
/* Tree verification (rad_drafter_tree): the drafter's tree and the attention over it. */
"dflash_tree", "attn_paged_tree",
"dflash_tree", "attn_paged_tree", "attn_paged_anchor_window",
"rmsnorm_had_quant_i8",
"gated_had_quant_i8",
"dequant",
@@ -1165,7 +1166,7 @@ TEST(op_vocabulary) {
CHECK_EQ(kern("gdn_chunk_scan")->n_constraints, 0);
int constrained = 0;
for (int i = 0; i < api().kernel_count(); ++i) constrained += api().kernel_at(i)->n_constraints > 0;
CHECK_EQ(constrained, 3);
CHECK_EQ(constrained, 4);
}
/* ================================================================== the numerics
@@ -3237,6 +3238,43 @@ TEST(op_attn_paged_ragged) {
* right after a one-token prompt is (core/sched/advance_impl.h ADV_HIST ends the context at the
* last committed position). Rows sit at seqused - q_len + j = -2, -1, 0, 1: the first two see no
* key and are zero, not NaN, and the last two are as if the run were two rows. */
TEST(op_attn_paged_anchor_window_is_exact_at_512_history_and_shared_across_rows) {
constexpr int qlen = 7, ctx = 520, bs = 16, seqs = 2, window = 513;
const int blocks = (ctx + bs - 1) / bs;
T q(RAD_F32, {seqs * qlen, 1, 1});
T kv(RAD_F32, {seqs * blocks, 1, bs, 2});
for (int s = 0; s < seqs; ++s) {
const int slot_base = s * blocks * bs;
const float before = s == 0 ? 500.0f : 700.0f; /* anchor - 513: masked */
const float edge = s == 0 ? 10.0f : 20.0f; /* anchor - 512: visible */
const float future = s == 0 ? 1000.0f : 2000.0f;
st_dt(RAD_F32, kv.t.data, (int64_t)(slot_base + 0) * 2 + 1, before);
st_dt(RAD_F32, kv.t.data, (int64_t)(slot_base + 1) * 2 + 1, edge);
st_dt(RAD_F32, kv.t.data, (int64_t)(slot_base + ctx - 1) * 2 + 1, future);
}
T bt(RAD_I32, {seqs, blocks});
std::vector<int64_t> block_ids(seqs * blocks);
for (int s = 0; s < seqs; ++s)
for (int b = 0; b < blocks; ++b) block_ids[s * blocks + b] = s * blocks + b;
bt.n(block_ids);
T su(RAD_I32, {seqs}); su.n({ctx, ctx});
T cu(RAD_I32, {seqs + 1}); cu.n({0, qlen, 2 * qlen});
T out(RAD_F32, {seqs * qlen, 1, 1});
for (int causal : {0, 1}) {
A a; a.t(q).t(kv).t(bt).t(su).tnull().tnull().t(cu).t(out)
.i("q_len", qlen).i("head_dim", 1).i("gqa", 1).i("block_size", bs)
.i("causal", causal).i("window", window).s("q_dtype", "f32").s("kv_dtype", "f32");
CHECK_OK(run("attn_paged_anchor_window", a));
const float denom = causal ? 513.0f : 519.0f;
const float expected0 = causal ? 10.0f / denom : 1010.0f / denom;
const float expected1 = causal ? 20.0f / denom : 2020.0f / denom;
for (int i = 0; i < qlen; ++i) {
CHECK_NEAR(out.at(i), expected0, 1e-6);
CHECK_NEAR(out.at(qlen + i), expected1, 1e-6);
}
}
}
TEST(op_attn_paged_rows_before_the_context) {
const float sc = 1.0f / 1.41421356f;
T q(RAD_F32, {4, 1, 2});
@@ -9401,6 +9439,182 @@ TEST(dflash_select_walks_from_its_own_previous_pick) {
CHECK_EQ(tok.iat(1), 0LL);
}
/* The DSpark reference scores all vocabulary entries after applying the Markov bias. Both
* sequences choose tokens outside their base-logit top 16; step 1 conditions on the prior greedy
* choice, and the step-0 tie across tile boundaries resolves to the lower token id. */
TEST(dflash_markov_greedy_scans_full_vocab_and_keeps_sequences_independent) {
constexpr int V = 130, R = 32, M = 2, steps = 2, tiles = 3;
std::vector<float> logits_values(M * steps * V, 0.0f);
for (int r = 0; r < M * steps; r += 2)
for (int v = 0; v < 16; ++v) logits_values[r * V + v] = 100 - v;
T logits(RAD_BF16, {M * steps, V}); logits.f(logits_values);
T anchor(RAD_I32, {M, 2}); anchor.n({1, -1, 2, -1});
std::vector<float> pred_values(V * R, 0.0f), succ_values(V * R, 0.0f);
pred_values[1 * R + 0] = 1; /* sequence 0, step 0 predecessor */
succ_values[127 * R + 0] = 200; /* outside the base top 16 */
succ_values[129 * R + 0] = 200; /* equal biased score in a later tile */
pred_values[127 * R + 1] = 1; /* sequence 0 step 1 depends on token 127 */
succ_values[100 * R + 1] = 100;
pred_values[2 * R + 2] = 1; /* sequence 1 has a separate anchor/codebook walk */
succ_values[80 * R + 2] = 200;
pred_values[80 * R + 3] = 1;
succ_values[101 * R + 3] = 90;
T pred(RAD_BF16, {V, R}); pred.f(pred_values);
T succ(RAD_BF16, {V, R}); succ.f(succ_values);
T tile_scores(RAD_F32, {M, tiles});
T tile_tokens(RAD_I32, {M, tiles});
T out(RAD_I32, {M, steps});
A a; a.t(logits).t(anchor).t(pred).t(succ).t(tile_scores).t(tile_tokens).t(out)
.i("M", M).i("steps", steps).i("rank", R).i("n_vocab", V)
.i("anchor_stride", 2).s("dtype", "bf16");
CHECK_OK(run("dflash_markov_greedy", a));
CHECK_EQ(out.iat(0), 127LL);
CHECK_EQ(out.iat(1), 100LL);
CHECK_EQ(out.iat(2), 80LL);
CHECK_EQ(out.iat(3), 101LL);
CHECK_EQ(tile_tokens.iat(0), 0LL);
CHECK_EQ(tile_tokens.iat(1), 100LL);
CHECK_EQ(tile_tokens.iat(2), 128LL);
CHECK_EQ(tile_scores.at(0), 0.0f);
CHECK_EQ(tile_scores.at(1), 100.0f);
CHECK_EQ(tile_scores.at(2), 0.0f);
}
/* A one-row, one-layer DSpark oracle assembled from libref's ordinary ops. The literals check the
* architecture-specific chain rather than only each primitive: each tap has its own RMS gain,
* the normalized taps feed fc/h_norm then context K/V projections, context and draft K/V land in
* the paged cache, and a gated attention residual plus the exact-GELU MLP gives the layer output. */
TEST(dspark_taps_context_kv_and_layer_output_match_hand_oracle) {
T tap0_src(RAD_F32, {1, 2}); tap0_src.f({1, 1});
T tap0_gain(RAD_BF16, {2}); tap0_gain.f({1, 2});
T tap0(RAD_BF16, {1, 2});
A tap0a; tap0a.t(tap0_src).t(tap0_gain).t(tap0)
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
CHECK_OK(run("rmsnorm", tap0a));
CHECK_EQ(tap0.at(0), 1.0f); CHECK_EQ(tap0.at(1), 2.0f);
T tap1_src(RAD_F32, {1, 2}); tap1_src.f({2, 2});
T tap1_gain(RAD_BF16, {2}); tap1_gain.f({2, 1});
T tap1(RAD_BF16, {1, 2});
A tap1a; tap1a.t(tap1_src).t(tap1_gain).t(tap1)
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
CHECK_OK(run("rmsnorm", tap1a));
CHECK_EQ(tap1.at(0), 2.0f); CHECK_EQ(tap1.at(1), 1.0f);
T taps(RAD_BF16, {1, 4}); taps.f({tap0.at(0), tap0.at(1), tap1.at(0), tap1.at(1)});
T fc_w(RAD_BF16, {2, 4}); fc_w.f({1, 0, 0, 0, 0, 0, 0, 1});
T context(RAD_BF16, {1, 2});
A fca; fca.t(taps).t(fc_w).t(context).i("M", 1).i("N", 2).i("K", 4).s("dtype", "bf16");
CHECK_OK(run("gemm_nt", fca));
CHECK_EQ(context.at(0), 1.0f); CHECK_EQ(context.at(1), 1.0f);
T context_gain(RAD_BF16, {2}); context_gain.f({1, 1});
T context_norm(RAD_BF16, {1, 2});
A cna; cna.t(context).t(context_gain).t(context_norm)
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
CHECK_OK(run("rmsnorm", cna));
CHECK_EQ(context_norm.at(0), 1.0f); CHECK_EQ(context_norm.at(1), 1.0f);
T wq(RAD_BF16, {2, 2}); wq.f({0, 0, 0, 0});
T wk(RAD_BF16, {2, 2}); wk.f({0, 0, 0, 0});
T wv(RAD_BF16, {2, 2}); wv.f({0, 0, 1, 1});
T q_proj(RAD_BF16, {1, 2}), k_ctx(RAD_BF16, {1, 2}), v_ctx(RAD_BF16, {1, 2});
A qa; qa.t(context_norm).t(wq).t(q_proj).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
A ka; ka.t(context_norm).t(wk).t(k_ctx).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
A va; va.t(context_norm).t(wv).t(v_ctx).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
CHECK_OK(run("gemm_nt", qa)); CHECK_OK(run("gemm_nt", ka)); CHECK_OK(run("gemm_nt", va));
CHECK_EQ(k_ctx.at(0), 0.0f); CHECK_EQ(k_ctx.at(1), 0.0f);
CHECK_EQ(v_ctx.at(0), 0.0f); CHECK_EQ(v_ctx.at(1), 2.0f);
/* The query projection is from the draft row, but has the same simple normalized input. */
T query_src(RAD_F32, {1, 2}); query_src.f({1, 1});
T query_norm(RAD_BF16, {1, 2});
A qna; qna.t(query_src).t(context_gain).t(query_norm)
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
CHECK_OK(run("rmsnorm", qna));
T k_query(RAD_BF16, {1, 2}), v_query(RAD_BF16, {1, 2});
A kqa; kqa.t(query_norm).t(wk).t(k_query).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
A vqa; vqa.t(query_norm).t(wv).t(v_query).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
CHECK_OK(run("gemm_nt", kqa)); CHECK_OK(run("gemm_nt", vqa));
T keys(RAD_BF16, {2, 1, 2}); keys.f({k_ctx.at(0), k_ctx.at(1), k_query.at(0), k_query.at(1)});
T values(RAD_BF16, {2, 1, 2}); values.f({v_ctx.at(0), v_ctx.at(1), v_query.at(0), v_query.at(1)});
T slots(RAD_I32, {2}); slots.n({0, 1});
T cache(RAD_BF16, {1, 1, 2, 4});
A store; store.t(keys).t(values).t(slots).t(cache)
.i("M", 2).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2).s("kv_dtype", "bf16");
CHECK_OK(run("kv_store", store));
for (int slot = 0; slot < 2; ++slot) {
CHECK_EQ(cache.at(slot * 4 + 0), 0.0f); CHECK_EQ(cache.at(slot * 4 + 1), 0.0f);
CHECK_EQ(cache.at(slot * 4 + 2), 0.0f); CHECK_EQ(cache.at(slot * 4 + 3), 2.0f);
}
T q(RAD_BF16, {1, 1, 2}); q.f({q_proj.at(0), q_proj.at(1)});
T bt(RAD_I32, {1, 1}); bt.n({0});
T used(RAD_I32, {1}); used.n({2});
T attended(RAD_BF16, {1, 1, 2});
A attn; attn.t(q).t(cache).t(bt).t(used).tnull().tnull().tnull().t(attended)
.i("q_len", 1).i("head_dim", 2).i("gqa", 1).i("block_size", 2)
.i("causal", 0).i("window", 513).i("n_head", 1)
.s("q_dtype", "bf16").s("kv_dtype", "bf16");
CHECK_OK(run("attn_paged_anchor_window", attn));
CHECK_EQ(attended.at(0), 0.0f); CHECK_EQ(attended.at(1), 2.0f);
T gate_w(RAD_BF16, {1, 2}); gate_w.f({0, 0});
T gate_logit(RAD_BF16, {1, 1}), gate(RAD_BF16, {1, 1});
A ga; ga.t(query_norm).t(gate_w).t(gate_logit)
.i("M", 1).i("N", 1).i("K", 2).s("dtype", "bf16");
CHECK_OK(run("gemm_nt", ga));
A sig; sig.t(gate_logit).t(gate).i("M", 1).i("n", 1).s("dtype", "bf16");
CHECK_OK(run("sigmoid", sig));
CHECK_EQ(gate.at(0), 0.5f);
T gated(RAD_BF16, {1, 2});
A scale; scale.t(attended).t(gate).tnull().t(gated)
.i("M", 1).i("n", 2).s("act", "none").s("dtype", "bf16");
CHECK_OK(run("scale_rows", scale));
CHECK_EQ(gated.at(0), 0.0f); CHECK_EQ(gated.at(1), 1.0f);
T wo(RAD_BF16, {2, 2}); wo.f({1, 0, 0, 1});
T delta(RAD_BF16, {1, 2});
A oa; oa.t(gated).t(wo).t(delta).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
CHECK_OK(run("gemm_nt", oa));
CHECK_EQ(delta.at(0), 0.0f); CHECK_EQ(delta.at(1), 1.0f);
T residual(RAD_F32, {1, 2}); residual.f({1, 1});
T after_attn(RAD_F32, {1, 2});
A adda; adda.t(residual).t(delta).t(after_attn).i("M", 1).i("n", 2).s("dtype", "f32");
CHECK_OK(run("add", adda));
CHECK_EQ(after_attn.at(0), 1.0f); CHECK_EQ(after_attn.at(1), 2.0f);
T ff_norm(RAD_BF16, {1, 2});
A fna; fna.t(after_attn).t(context_gain).t(ff_norm)
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
CHECK_OK(run("rmsnorm", fna));
T ff_w(RAD_BF16, {2, 2}); ff_w.f({1, 0, 1, 0});
T gate_up(RAD_BF16, {1, 2});
A fua; fua.t(ff_norm).t(ff_w).t(gate_up)
.i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
CHECK_OK(run("gemm_nt", fua));
T ff(RAD_BF16, {1, 1});
A act; act.t(gate_up).t(gate_up).t(ff)
.i("M", 1).i("n", 1).s("act", "gelu").s("dtype", "bf16");
CHECK_OK(run("act_mul", act));
T down_w(RAD_BF16, {2, 1}); down_w.f({1, 0});
T down(RAD_BF16, {1, 2});
A da; da.t(ff).t(down_w).t(down).i("M", 1).i("N", 2).i("K", 1).s("dtype", "bf16");
CHECK_OK(run("gemm_nt", da));
const float normalized = bf16_to_f32((uint16_t)f32_to_bf16(1.0f / std::sqrt(2.5f)));
const float gelu = 0.5f * normalized * (1.0f + std::erf(normalized / std::sqrt(2.0f)));
const float rounded_gelu = bf16_to_f32((uint16_t)f32_to_bf16(gelu));
const float expected_ff = bf16_to_f32((uint16_t)f32_to_bf16(rounded_gelu * normalized));
CHECK_NEAR(ff.at(0), expected_ff, 1e-6);
CHECK_EQ(down.at(0), expected_ff); CHECK_EQ(down.at(1), 0.0f);
T layer_out(RAD_F32, {1, 2});
A outa; outa.t(after_attn).t(down).t(layer_out).i("M", 1).i("n", 2).s("dtype", "f32");
CHECK_OK(run("add", outa));
CHECK_NEAR(layer_out.at(0), 1.0f + expected_ff, 1e-6);
CHECK_EQ(layer_out.at(1), 2.0f);
}
TEST(gemm_nt_q_bias_adds_a_bias_per_column) {
T a_(RAD_I8, {1, 2}); a_.n({1, 2});
T as(RAD_F32, {1}); as.f({0.5f});
@@ -9817,6 +10031,9 @@ std::vector<Geo> geometries() {
.s("dtype", "fp8a8").s("act", "silu")),
G("dflash_select", "M", 2, a.i("M", R).i("steps", 3).i("top_k", 4).i("rank", 8)
.i("n_vocab", 30).s("dtype", "bf16")),
G("dflash_markov_greedy", "M", 2, a.i("M", R).i("steps", 3).i("rank", 32)
.i("n_vocab", 130).i("anchor_stride", 1)
.s("dtype", "bf16")),
G("dflash_tree", "M", 2, a.i("M", R).i("steps", 3).i("top_k", 4).i("rank", 8)
.i("n_vocab", 30).i("nodes", 3).s("dtype", "bf16")),
G("gemm_nt", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "f32")),
@@ -9831,6 +10048,9 @@ std::vector<Geo> geometries() {
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)),
G("attn_paged_anchor_window", "q_len", 3,
a.i("q_len", R).i("head_dim", 8).i("gqa", 2).i("block_size", 4).i("causal", 1)
.i("window", 4).s("q_dtype", "f32").s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)),
G("attn_paged_tree", "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)