From 9ca20a1fba62ad653bc1ca54ca61d000bfd609c6 Mon Sep 17 00:00:00 2001 From: Constantin Date: Sun, 1 Nov 2026 16:51:49 -0500 Subject: [PATCH] Use F32 draft logits for the DSpark Markov walk Score the walk on F32 head logits, reject non-I32 anchors in libref, and assert the real proposal path. Near-tie policy vs the reference is still open. --- arch/common/rad_block_dspark_bf16.h | 16 ++--- docs/OPS.md | 15 +++-- libr4d/r4d_dflash_markov_bf16.hip | 38 ++++++++---- libr4d/r4d_plugin.h | 2 + libr4d/r4d_rows.cpp | 11 ++++ libr4d/r4d_shapes.cpp | 7 +++ libref/ref_ops.h | 2 + libref/ref_quant.cpp | 18 +++++- libref/ref_registry.cpp | 6 ++ libref/ref_shapes.cpp | 14 ++++- tests/dspark_device_test.cpp | 93 ++++++++++++++++++++++++++--- tests/dspark_head_slice.py | 39 ++++++++++++ tests/ref_test.cpp | 26 +++++++- tests/spark25_arch_test.cpp | 53 +++++++++++----- 14 files changed, 284 insertions(+), 56 deletions(-) create mode 100644 tests/dspark_head_slice.py diff --git a/arch/common/rad_block_dspark_bf16.h b/arch/common/rad_block_dspark_bf16.h index 2826dfeb..6cca24f3 100644 --- a/arch/common/rad_block_dspark_bf16.h +++ b/arch/common/rad_block_dspark_bf16.h @@ -73,8 +73,8 @@ * * `dflash_markov_greedy` scans the full vocabulary at every position and greedily chooses the * largest biased score, following the structure of the pinned reference's serial Markov walk. - * BF16 base logits, reduction order and tie behavior can differ from that reference. It does not - * prune to the base head's top K, use a joint-path heap, or apply confidence to logits. + * Base logits are F32; reduction order and tie behavior can still differ from the reference. It + * does not prune to the base head's top K, use a joint-path heap, or apply confidence to logits. * * The confidence head (`conf_proj`, one sigmoid a position predicting acceptance) is imported and * ignored: it exists to let a serving loop cut the block short, this engine's depth is fixed at @@ -156,7 +156,7 @@ struct DsparkBF16 { rad_buf gate_up = 0; rad_buf ff = 0; /* ---- the head and the walk, one row per draft position */ - rad_buf dlog = 0; /* [srows, n_vocab] bf16 full-vocabulary draft logits */ + rad_buf dlog = 0; /* [srows, n_vocab] f32 full-vocabulary draft logits */ rad_buf best_score = 0; /* [max_seqs, ceil(n_vocab/64)] f32 partial argmax scores */ rad_buf best_token = 0; /* [max_seqs, ceil(n_vocab/64)] i32 partial argmax ids */ rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */ @@ -567,12 +567,12 @@ inline int DsparkBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const * greedy Markov op scans all vocabulary entries at every position and feeds each winning id * into the next position's bigram bias. */ - op_dlogits = rw(b, RAD_OP(b, "gemm_nt", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), - RAD_INT("K", E), RAD_STR("dtype", "bf16")), + op_dlogits = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab), + RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w_head)), {w.h}, {w.dlog}); - op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy", + op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy_f32", RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()), RAD_INT("rank", cfg.rank), RAD_INT("n_vocab", g.n_vocab_all), @@ -884,7 +884,7 @@ inline int declare_dspark(DsparkBF16* ds, DsparkBF16::Wire* w, rad_kvgroup* kv, dw.attn = decl_b(b, nm.f("ds_attn"), RAD_BF16, {qr, qd}); dw.gate_up = decl_b(b, nm.f("ds_gate_up"), RAD_BF16, {qr, 2 * dg.n_ff}); dw.ff = decl_b(b, nm.f("ds_ff"), RAD_BF16, {qr, dg.n_ff}); - dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_BF16, {sr, dg.n_vocab}); + dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab}); const int64_t n_markov_tiles = (dg.n_vocab_all + 63) / 64; dw.best_score = decl_b(b, nm.f("ds_markov_score"), RAD_F32, {dg.max_seqs, n_markov_tiles}); diff --git a/docs/OPS.md b/docs/OPS.md index 830f0a8f..2084d90c 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -3364,17 +3364,20 @@ candidates, and what enters the head from the trunk. | 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` | `M` `steps` `rank` `n_vocab` `anchor_stride`/opt `dtype` | BF16 `logits`, `anchor`, `pred`w, `succ`w → `tile_scores`, `tile_tokens`, `tokens` | +| `dflash_markov_greedy_f32` | `M` `steps` `rank` `n_vocab` `anchor_stride`/opt `dtype` | F32 `logits`, `anchor`, `pred`w, `succ`w → `tile_scores`, `tile_tokens`, `tokens` | `dflash_markov_greedy` implements the DSpark full-vocabulary greedy 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; their row pitches may differ. The current graph passes BF16 base logits, -whereas the pinned llama.cpp reference uses F32 logits, and the reduction orders also differ. -Its CPU argmax chooses the last equal maximum; its GPU reduction uses a backend-specific order. -This op's lower-id tie rule is not a claim of reference tie equivalence. Near-tie proposal -equivalence is therefore not established. +vocabulary-wide reduction; their row pitches may differ. The F32 variant uses the same BF16 +codebooks (`dtype=bf16`) but takes F32 base logits; it is a separate operation so an older BF16-only +kernel cannot silently resolve it. The DSpark graph uses `logits_gemm` and the F32 variant. The +pinned llama.cpp reference also uses F32 base logits, but reduction orders may differ. Its CPU +argmax chooses the last equal maximum; its GPU reduction uses a backend-specific order. This op's +lower-id tie rule is not a claim of reference tie equivalence. Near-tie proposal equivalence is +therefore not established. ### DFlash2 diff --git a/libr4d/r4d_dflash_markov_bf16.hip b/libr4d/r4d_dflash_markov_bf16.hip index 3605487a..e6b5af6b 100644 --- a/libr4d/r4d_dflash_markov_bf16.hip +++ b/libr4d/r4d_dflash_markov_bf16.hip @@ -1,6 +1,6 @@ // Full-vocabulary DSpark Markov greedy walk. Unlike dflash_select's candidate-lattice walk, this -// operation applies the learned bigram bias to every BF16 draft-head logit and greedily selects -// the largest biased score. The pinned llama.cpp graph uses F32 base logits and may differ. +// operation applies the learned bigram bias to every draft-head logit and greedily selects +// the largest biased score. Separate entry points accept BF16 or F32 base logits. #include #include #include "r4d_gdn_args.h" @@ -26,8 +26,14 @@ bool rows_fit(long long rows, long long pitch, long long width, int element_byte // 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. +template +__device__ float load_logit(Logit x); +template<> __device__ float load_logit(r4d_u16 x) { return r4d_bf2f(x); } +template<> __device__ float load_logit(float x) { return x; } + +template __global__ __launch_bounds__(kThreads) void markov_score_tiles( - const r4d_u16* __restrict__ logits, long logits_pitch, + const Logit* __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, long scores_pitch, @@ -62,8 +68,8 @@ __global__ __launch_bounds__(kThreads) void markov_score_tiles( 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; + const float score = load_logit(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; @@ -129,13 +135,14 @@ __global__ __launch_bounds__(kThreads) void markov_reduce_tiles( 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, +template +int markov_emit(const Logit* logits, long logits_pitch, const int* anchor, long anchor_stride, const r4d_u16* pred, const r4d_u16* succ, float* tile_scores, long scores_pitch, int* tile_tokens, long tokens_pitch, 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, + hipLaunchKernelGGL((markov_score_tiles), dim3(n_tiles, sequences), dim3(kThreads), 0, (hipStream_t)stream, logits, logits_pitch, anchor, anchor_stride, pred, succ, tile_scores, scores_pitch, tile_tokens, tokens_pitch, out, out_pitch, step, steps, rank, vocab, n_tiles); @@ -148,7 +155,8 @@ int markov_emit(const r4d_u16* logits, long logits_pitch, const int* anchor, lon } // namespace -extern "C" int r4d_rad_dflash_markov_greedy(const RadArgs* a, RadStream stream) { +template +static int markov_launch(const RadArgs* a, RadStream stream, uint32_t logits_dtype) { 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); @@ -177,9 +185,9 @@ extern "C" int r4d_rad_dflash_markov_greedy(const RadArgs* a, RadStream stream) // blockIdx.y is limited to 65535, and all kernel loop indices are int. if (sequences <= 0 || sequences > 65535 || sequences > LLONG_MAX / steps || (sequences - 1) > (LLONG_MAX - 1) / anchor_stride || - !rows_fit(sequences, out_pitch, steps, sizeof(int)) || logits->dtype != RAD_BF16 || + !rows_fit(sequences, out_pitch, steps, sizeof(int)) || logits->dtype != logits_dtype || logits->rank != 2 || logits->shape[0] < sequences * steps || logits->shape[1] < vocab || - !rows_fit(sequences * steps, logits_pitch, vocab, sizeof(r4d_u16))) + !rows_fit(sequences * steps, logits_pitch, vocab, sizeof(Logit))) return R4D_NO(RAD_E_SHAPE); if (anchor->dtype != RAD_I32 || !r4d_contig(anchor) || @@ -197,7 +205,7 @@ extern "C" int r4d_rad_dflash_markov_greedy(const RadArgs* a, RadStream stream) !rows_fit(sequences, r4d_row_pitch(tokens), n_tiles, sizeof(int))) return R4D_NO(RAD_E_SHAPE); - return R4D_RAW(markov_emit((const r4d_u16*)logits->data, (long)logits_pitch, + return R4D_RAW(markov_emit((const Logit*)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, (long)r4d_row_pitch(scores), @@ -205,3 +213,11 @@ extern "C" int r4d_rad_dflash_markov_greedy(const RadArgs* a, RadStream stream) (long)out_pitch, (int)sequences, (int)steps, (int)rank, (int)vocab, (int)n_tiles, stream)); } + +extern "C" int r4d_rad_dflash_markov_greedy(const RadArgs* a, RadStream stream) { + return markov_launch(a, stream, RAD_BF16); +} + +extern "C" int r4d_rad_dflash_markov_greedy_f32(const RadArgs* a, RadStream stream) { + return markov_launch(a, stream, RAD_F32); +} diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index f84e8002..f103d5ec 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -198,6 +198,7 @@ R4D_ATTN_ANCHOR_DECL(512, 1) R4D_ATTN_ANCHOR_DECL(512, 2) R4D_ATTN_ANCHOR_DECL(5 R4D_ATTN_ANCHOR_DECL(512, 8) #undef R4D_ATTN_ANCHOR_DECL int r4d_rad_dflash_markov_greedy(const RadArgs*, RadStream); +int r4d_rad_dflash_markov_greedy_f32(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); @@ -1012,6 +1013,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*); +int r4d_shape_dflash_markov_f32(const RadParam*, int, int operand, RadOpdDesc*); /* -- declared fusions (r4d_fuse.cpp, pure host) -- * diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 31a21374..c83bbd8e 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -3399,6 +3399,8 @@ static const RadOpSchema kSchemas[] = { "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_markov_greedy_f32", pDflashMarkov, oDflashMarkov, + "DSpark full-vocabulary greedy walk with F32 base logits and BF16 codebooks."), 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 " @@ -9606,6 +9608,15 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) nullptr, nullptr, r4d_rad_dflash_markov_greedy, nullptr, nullptr, nullptr, r4d_shape_dflash_markov }, +{ "dflash_markov_greedy_f32", "dflash_markov_greedy_f32", "dflash", + "Full-vocabulary DSpark greedy walk with F32 base logits", + "steps >= 1, rank a multiple of 32 and <= 512, 64 vocabulary ids per scratch tile", + "f32 logits, bf16 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_f32, nullptr, nullptr, nullptr, + r4d_shape_dflash_markov_f32 }, + { "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", diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index a9456265..1b9579ed 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -2225,3 +2225,10 @@ extern "C" int r4d_shape_dflash_markov(const RadParam* p, int n_p, int operand, }; R4D_PICK(l); } + +extern "C" int r4d_shape_dflash_markov_f32(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int rc = r4d_shape_dflash_markov(p, n_p, operand, out); + if (rc == RAD_OK && operand == 0) out->dtype = RAD_F32; + return rc; +} diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 3659f4cd..0c98eac3 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -133,6 +133,7 @@ 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_markov_greedy_f32(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); @@ -415,6 +416,7 @@ 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_markov_greedy_f32); REF_SHAPE_FN(ref_dflash_tree); REF_SHAPE_FN(ref_gram_accum); REF_SHAPE_FN(ref_rmsnorm_had_quant_i8); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index e6f03289..240e47e6 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -832,16 +832,18 @@ int ref_dflash_select(const RadArgs* a, RadStream) { * `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) { +static int ref_markov_greedy(const RadArgs* a, uint32_t logits_dtype) { 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 || + if (logits->dtype != logits_dtype || 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; + /* The device requires I32 anchors and reports invalid anchor tensors as shape errors. */ + if (anchor->dtype != RAD_I32) return RAD_E_SHAPE; const int64_t steps = p_int(a, "steps", 0); const int64_t R = p_int(a, "rank", 0); @@ -879,10 +881,12 @@ int ref_dflash_markov_greedy(const RadArgs* a, RadStream) { 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 float base = ldt(logits, lb + token * ls); + float score = logits_dtype == RAD_F32 ? 0.0f : base; 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 (logits_dtype == RAD_F32) score += base; if (score > best || (score == best && token < best_token)) { best = score; best_token = token; @@ -903,6 +907,14 @@ int ref_dflash_markov_greedy(const RadArgs* a, RadStream) { return RAD_OK; } +int ref_dflash_markov_greedy(const RadArgs* a, RadStream) { + return ref_markov_greedy(a, RAD_BF16); +} + +int ref_dflash_markov_greedy_f32(const RadArgs* a, RadStream) { + return ref_markov_greedy(a, RAD_F32); +} + /* ------------------------------------------------------------- dflash_tree */ /* `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w -> `tokens`, `parents` * diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 71f47074..860a6c06 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -1386,6 +1386,8 @@ static const RadOpSchema kSchemas[] = { "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_markov_greedy_f32", ARR(pDflashMarkov), ARR(oDflashMarkov), + "Full-vocabulary greedy Markov walk with F32 base logits and BF16 codebooks." }, { "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 " @@ -2400,6 +2402,10 @@ 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_markov_greedy_f32", "dflash_markov_greedy_f32", "draft", + "Full-vocabulary greedy Markov walk with F32 base logits", + "f32 logits, bf16 codebooks, f32/i32 tile winners, i32 tokens out", + ref_dflash_markov_greedy_f32), 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), diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 57917653..e7260f89 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -2240,7 +2240,8 @@ int ref_dflash_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* } /* 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) { +static int ref_markov_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out, + uint32_t logits_dtype, const char* op) { 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); @@ -2251,14 +2252,21 @@ int ref_dflash_markov_greedy_shape(const RadParam* p, int n_p, int operand, RadO 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(logits_dtype, { 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); + return o.finish(op, operand, out); +} + +int ref_dflash_markov_greedy_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return ref_markov_shape(p, n_p, operand, out, RAD_BF16, "dflash_markov_greedy"); +} +int ref_dflash_markov_greedy_f32_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return ref_markov_shape(p, n_p, operand, out, RAD_F32, "dflash_markov_greedy_f32"); } /* dflash_select's operands, then `nodes` tokens and parents a sequence. */ diff --git a/tests/dspark_device_test.cpp b/tests/dspark_device_test.cpp index 80d22105..9b13316f 100644 --- a/tests/dspark_device_test.cpp +++ b/tests/dspark_device_test.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include using Fn = int (*)(const RadArgs*, RadStream); @@ -31,7 +32,7 @@ static RadParam pi(const char* k, long long v) { RadParam p{}; p.key=k; p.kind=R static RadParam ps(const char* k, const char* v) { RadParam p{}; p.key=k; p.kind=RAD_P_STR; p.sval=v; return p; } static Fn symbol(void* h, const char* name) { auto f = reinterpret_cast(dlsym(h,name)); check(f != nullptr, name); return f; } -static void markov(Fn fn, int R) { +static void markov(Fn fn, int R, bool f32) { constexpr int M=2, S=2, V=130, T=3, LP=137, SP=5, TP=7, OP=4; std::vector l(M*S*LP,bf(0)), p(V*R,bf(0)), u(V*R,bf(0)); for (int m=0;m anchor{1,-1,2,-1}, ti(M*TP,-777), out(M*OP,-777); std::vector ts(M*SP,-777.f); - Device dl(l), dp(p), du(u); Device da(anchor), di(ti), dout(out); Device ds(ts); - RadTensor a[]={t(dl.p,RAD_BF16,{M*S,V}),t(da.p,RAD_I32,{M,2}),t(dp.p,RAD_BF16,{V,R}),t(du.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{M,T}),t(di.p,RAD_I32,{M,T}),t(dout.p,RAD_I32,{M,S})}; + std::vector lf(l.size()); for(size_t i=0;i dl(l), dp(p), du(u); Device da(anchor), di(ti), dout(out); + Device ds(ts), dlf(lf); + RadTensor a[]={t(f32 ? (void*)dlf.p : (void*)dl.p,f32 ? RAD_F32 : RAD_BF16,{M*S,V}),t(da.p,RAD_I32,{M,2}),t(dp.p,RAD_BF16,{V,R}),t(du.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{M,T}),t(di.p,RAD_I32,{M,T}),t(dout.p,RAD_I32,{M,S})}; a[0].stride[0]=LP; a[4].stride[0]=SP; a[5].stride[0]=TP; a[6].stride[0]=OP; RadParam par[]={pi("M",M),pi("steps",S),pi("rank",R),pi("n_vocab",V),pi("anchor_stride",2),ps("dtype","bf16")}; RadArgs args{}; args.t=a; args.n_t=7; args.p=par; args.n_p=6; @@ -73,11 +76,11 @@ static void markov(Fn fn, int R) { a[4].stride[1]=2; check(fn(&args,nullptr)!=RAD_OK,"reject non-unit scratch inner stride"); a[4].stride[1]=1; a[5].stride[0]=T-1; check(fn(&args,nullptr)!=RAD_OK,"reject overlapping scratch rows"); a[5].stride[0]=LLONG_MAX; check(fn(&args,nullptr)!=RAD_OK,"reject overflowing scratch span"); - std::printf("markov rank=%d padded scores=%d tokens=%d: PASS\n",R,SP,TP); + std::printf("markov logits=%s rank=%d padded scores=%d tokens=%d: PASS\n",f32?"f32":"bf16",R,SP,TP); } // A controlled precision counterexample, not a measurement of real checkpoint logits. -static void near_tie(Fn fn) { +static void near_tie(Fn fn, Fn fn_f32) { constexpr int R=32, V=2; std::vector l{bf(1.001f),bf(1.002f)}, w(V*R,bf(0)); std::vector anchor{0}, token{-1}, tile{-1}; std::vector score{-1}; @@ -88,9 +91,39 @@ static void near_tie(Fn fn) { RadArgs args{}; args.t=a; args.n_t=7; args.p=par; args.n_p=4; check(fn(&args,nullptr)==RAD_OK,"near tie launch"); hipcheck(hipDeviceSynchronize()); check(dout.get()[0]==0 && 1.002f>1.001f,"BF16/F32 near tie divergence"); + std::vector full{1.001f,1.002f}; Device df(full); + a[0]=t(df.p,RAD_F32,{1,V}); + check(fn(&args,nullptr)!=RAD_OK,"BF16 op refuses F32 logits"); + check(fn_f32(&args,nullptr)==RAD_OK,"F32 near tie launch"); hipcheck(hipDeviceSynchronize()); + check(dout.get()[0]==1,"F32 near tie retains winner"); + a[0]=t(dl.p,RAD_BF16,{1,V}); + check(fn_f32(&args,nullptr)!=RAD_OK,"F32 op refuses BF16 logits"); std::puts("near tie: F32 argmax=1, BF16 input argmax=0: PASS (synthetic)"); } +// Real device head -> F32 Markov chain, with an exactly representable BF16-input near tie. +static void head_chain(Fn head, Fn walk) { + constexpr int K=8, V=2, R=32; + std::vector x(K,bf(0)), w(V*K,bf(0)), cb(V*R,bf(0)); + x[0]=bf(1); x[1]=bf(0.001953125f); w[0]=bf(1); w[K]=bf(1); w[K+1]=bf(1); + std::vector logits(V,-1), scores(1,-1); + std::vector anchor{0}, tile{-1}, out{-1}; + Device dx(x), dw(w), dc(cb); Device dl(logits), ds(scores); + Device da(anchor), dt(tile), dout(out); + RadTensor h[]={t(dx.p,RAD_BF16,{1,K}),t(dw.p,RAD_BF16,{V,K}),t(dl.p,RAD_F32,{1,V})}; + RadParam hp[]={pi("M",1),pi("n_vocab",V),pi("n_embd",K),ps("dtype","bf16")}; + RadArgs ha{}; ha.t=h; ha.n_t=3; ha.p=hp; ha.n_p=4; + check(head(&ha,nullptr)==RAD_OK,"F32 logits head launch"); hipcheck(hipDeviceSynchronize()); + auto got=dl.get(); check(got[0]==1.f && got[1]==1.001953125f,"F32 logits head CPU dot oracle"); + check(bf(got[0])==bf(got[1]),"head-chain BF16 negative control"); + RadTensor a[]={t(dl.p,RAD_F32,{1,V}),t(da.p,RAD_I32,{1}),t(dc.p,RAD_BF16,{V,R}),t(dc.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{1,1}),t(dt.p,RAD_I32,{1,1}),t(dout.p,RAD_I32,{1,1})}; + RadParam par[]={pi("M",1),pi("steps",1),pi("rank",R),pi("n_vocab",V),ps("dtype","bf16")}; + RadArgs args{}; args.t=a; args.n_t=7; args.p=par; args.n_p=5; + check(walk(&args,nullptr)==RAD_OK,"head-chain walk launch"); hipcheck(hipDeviceSynchronize()); + check(dout.get()[0]==1,"F32 head-chain winner"); + std::puts("F32 head -> Markov near tie and BF16 negative control: PASS"); +} + static void attention(Fn shared, Fn ordinary, int G, int ctx0, int ctx1, int causal) { constexpr int M=2, Q=7, H=256, BS=16, W=513; const int ctx[M]={ctx0,ctx1}, blocks=(std::max(ctx0,ctx1)+15)/16, nblocks=M*blocks; @@ -141,12 +174,56 @@ static void attention(Fn shared, Fn ordinary, int G, int ctx0, int ctx1, int cau std::printf("attention gqa=%d ctx=%d,%d causal=%d shared oracle and negative control: PASS\n",G,ctx0,ctx1,causal); } +// Real checkpoint head slice, but synthetic BF16 activations and zero Markov weights. This tests +// head arithmetic, not full-graph/reference equivalence or real hidden-state acceptance. +static void checkpoint_head(Fn head, Fn walk, const char* weights_path) { + constexpr int M=16, V=1025, K=2560, R=32, T=(V+63)/64; + std::vector w((size_t)V*K), x((size_t)M*K), cb((size_t)V*R,bf(0)); + std::ifstream f(weights_path,std::ios::binary); check((bool)f,"open checkpoint head slice"); + f.read(reinterpret_cast(w.data()),w.size()*sizeof(uint16_t)); + check((size_t)f.gcount()==w.size()*sizeof(uint16_t) && f.peek()==EOF,"exact head slice size"); + uint32_t rng=123456789; for(auto& v:x) { rng=rng*1664525u+1013904223u; v=bf(((int)(rng>>24)-128)/128.f); } + std::vector logits((size_t)M*V,0), scores((size_t)M*T,0); + std::vector anchor(M,0), tile((size_t)M*T,-1), out(M,-1); + Device dx(x), dw(w), dc(cb); Device dl(logits), ds(scores); + Device da(anchor), dt(tile), dout(out); + RadTensor h[]={t(dx.p,RAD_BF16,{M,K}),t(dw.p,RAD_BF16,{V,K}),t(dl.p,RAD_F32,{M,V})}; + RadParam hp[]={pi("M",M),pi("n_vocab",V),pi("n_embd",K),ps("dtype","bf16")}; + RadArgs ha{}; ha.t=h; ha.n_t=3; ha.p=hp; ha.n_p=4; + check(head(&ha,nullptr)==RAD_OK,"checkpoint head launch"); hipcheck(hipDeviceSynchronize()); + auto got=dl.get(); double maxerr=0, se=0, sr=0, minmargin=INFINITY; int changed=0,ties=0; + std::vector refwin(M); + for(int m=0;mbest) {second=best;best=ref;winner=v;} else if(ref>second) second=ref; + } + refwin[m]=winner; minmargin=std::min(minmargin,best-second); + int gw=0,bw=0,nmax=0; float gmax=-INFINITY, bmax=-INFINITY; + for(int v=0;vgmax) {gmax=y;gw=v;} if(by>bmax) {bmax=by;bw=v;nmax=1;} else if(by==bmax) ++nmax; + } + if(gw!=bw) ++changed; if(nmax>1) ++ties; + check(gw==winner,"checkpoint head F32 top1 versus FP64 oracle"); + } + RadTensor a[]={t(dl.p,RAD_F32,{M,V}),t(da.p,RAD_I32,{M}),t(dc.p,RAD_BF16,{V,R}),t(dc.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{M,T}),t(dt.p,RAD_I32,{M,T}),t(dout.p,RAD_I32,{M,1})}; + RadParam p[]={pi("M",M),pi("steps",1),pi("rank",R),pi("n_vocab",V),ps("dtype","bf16")}; + RadArgs args{};args.t=a;args.n_t=7;args.p=p;args.n_p=5; + check(walk(&args,nullptr)==RAD_OK,"checkpoint head walk"); hipcheck(hipDeviceSynchronize()); + auto picks=dout.get(); for(int m=0;m 100_000_000: + raise ValueError("unreasonably large safetensors header") + header = json.loads(f.read(n)) + t = header["model.embedding.weight"] + if t["dtype"] != "BF16" or t["shape"] != [131072, 2560]: + raise ValueError("expected Spark BF16 embedding [131072, 2560]") + start, end = t["data_offsets"] + size = 1025 * 2560 * 2 + if end - start < size: + raise ValueError("short tensor") + f.seek(8 + n + start) + data = f.read(size) + if len(data) != size: + raise ValueError("short read") +with args.output.open("xb") as f: + f.write(data) +print(f"{args.safetensors}: model.embedding.weight rows 0..1024; " + f"bytes={len(data)} sha256={hashlib.sha256(data).hexdigest()} -> {args.output}") diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 62ed1ac3..5d9688b6 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -1068,7 +1068,7 @@ 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", + "dflash_markov_greedy", "dflash_markov_greedy_f32", /* Tree verification (rad_drafter_tree): the drafter's tree and the attention over it. */ "dflash_tree", "attn_paged_tree", "attn_paged_anchor_window", "rmsnorm_had_quant_i8", @@ -9480,6 +9480,27 @@ TEST(dflash_markov_greedy_scans_full_vocab_and_keeps_sequences_independent) { CHECK_EQ(tile_scores.at(2), 0.0f); } +TEST(dflash_markov_f32_preserves_a_near_tie_and_refuses_bf16) { + T logits(RAD_F32, {1, 2}); logits.f({1.001f, 1.002f}); + T anchor(RAD_I32, {1}); anchor.n({0}); + T pred(RAD_BF16, {2, 32}), succ(RAD_BF16, {2, 32}); + T score(RAD_F32, {1, 1}), token(RAD_I32, {1, 1}), out(RAD_I32, {1, 1}); + A a; a.t(logits).t(anchor).t(pred).t(succ).t(score).t(token).t(out) + .i("M", 1).i("steps", 1).i("rank", 32).i("n_vocab", 2).s("dtype", "bf16"); + CHECK_OK(run("dflash_markov_greedy_f32", a)); + CHECK_EQ(out.iat(0), 1); + T bad_anchor(RAD_F32, {1}); bad_anchor.f({0}); + a.ts[1] = bad_anchor.t; + CHECK_EQ(run("dflash_markov_greedy_f32", a), RAD_E_SHAPE); + a.ts[1] = anchor.t; + CHECK(run("dflash_markov_greedy", a) != RAD_OK); + T bf_logits(RAD_BF16, {1, 2}); bf_logits.f({1.001f, 1.002f}); + a.ts[0] = bf_logits.t; + CHECK(run("dflash_markov_greedy_f32", a) != RAD_OK); + CHECK_OK(run("dflash_markov_greedy", a)); + CHECK_EQ(out.iat(0), 0); +} + /* Independent pitches in the two scratch arrays are part of the tensor contract. Guard cells * distinguish correct row addressing from treating both outputs as tightly packed. */ TEST(dflash_markov_greedy_padded_scratch_rows) { @@ -10056,6 +10077,9 @@ std::vector geometries() { 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_markov_greedy_f32", "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")), diff --git a/tests/spark25_arch_test.cpp b/tests/spark25_arch_test.cpp index 2f702391..9804c926 100644 --- a/tests/spark25_arch_test.cpp +++ b/tests/spark25_arch_test.cpp @@ -564,7 +564,7 @@ TEST(a_dspark_drafter_is_declared_over_the_trunk) { CHECK_EQ(pstr(&o, "act"), std::string("gelu")); /* exact erf, as the trunk's */ } CHECK_EQ(count_op(b, "rope") >= 4 * 2 + 1, true); - const RecOp* markov = find_op(b, "dflash_markov_greedy", 0); + const RecOp* markov = find_op(b, "dflash_markov_greedy_f32", 0); REQUIRE(markov); CHECK_EQ(pint(markov, "steps"), 7); CHECK_EQ(pint(markov, "rank"), 256); @@ -585,8 +585,8 @@ TEST(a_dspark_drafter_is_declared_over_the_trunk) { const RecBuf* dlog = nullptr; for (const auto& bf : b.bufs) if (bf.name == "ds_dlog") dlog = &bf; REQUIRE(dlog != nullptr); - CHECK_EQ(dlog->d.dtype, (uint32_t)RAD_BF16); - CHECK_EQ(count_op(b, "logits_gemm"), 1); /* the trunk's head; the draft's is a GEMM */ + CHECK_EQ(dlog->d.dtype, (uint32_t)RAD_F32); + CHECK_EQ(count_op(b, "logits_gemm"), 2); /* trunk and draft F32 heads */ CHECK(count_op(b, "gemm_nt") > 0); /* The drafter is declared after the trunk, and the graph resolves: no op the plugin declared is @@ -621,18 +621,31 @@ TEST(the_drafter_passes_run_and_the_draft_is_proposed_from_the_block) { * writes the proposal buffer -- and no trunk layer at all. */ RadCtx& q = *v[2]; int attn = 0, gemm = 0; - bool selected = false, proposed = false; + bool selected = false, proposed = false, draft_head = false; + rad_buf head_logits = 0; for (const auto& i : q.issues) { const RecOp* o = b.op_of(i.op); REQUIRE(o != nullptr); if (o->op == "attn_paged_anchor_window") ++attn; if (o->op == "gemm_nt") ++gemm; - if (o->op == "dflash_markov_greedy") { + if (o->op == "logits_gemm") { + REQUIRE_EQ(i.opd.size(), (size_t)3); + REQUIRE_EQ(i.opd[2].kind, (uint8_t)RAD_OPK_BUF); + head_logits = i.opd[2].handle; + REQUIRE(head_logits > 0 && head_logits <= b.bufs.size()); + CHECK_EQ(b.bufs[head_logits - 1].d.dtype, (uint32_t)RAD_F32); + draft_head = true; + } + if (o->op == "dflash_markov_greedy_f32") { selected = true; REQUIRE_EQ(i.opd.size(), (size_t)7); /* logits, anchor, pred, succ, tiles, tokens */ - proposed = true; + CHECK_EQ(i.opd[0].handle, head_logits); + CHECK_EQ(i.opd[6].kind, (uint8_t)RAD_OPK_BUF); + CHECK_EQ(i.opd[6].handle, b.drafter.proposal); + proposed = i.opd[6].handle == b.drafter.proposal; } } + CHECK(draft_head); CHECK_EQ(attn, 5); CHECK(gemm > 0); CHECK(selected); @@ -640,25 +653,33 @@ TEST(the_drafter_passes_run_and_the_draft_is_proposed_from_the_block) { /* The context pass stores K and V for every committed token and proposes nothing. */ RadCtx& h = *v[1]; - int stores = 0, selects = 0; + int stores = 0; for (const auto& i : h.issues) { const RecOp* o = b.op_of(i.op); REQUIRE(o != nullptr); if (o->op == "kv_store") ++stores; - if (o->op == "dflash_select") ++selects; } CHECK_EQ(stores, 5); - CHECK_EQ(selects, 0); + auto drafter_silent = [&](const RadCtx& pass) { + for (const auto& i : pass.issues) { + const RecOp* o = b.op_of(i.op); + if (!o || o->op == "dflash_markov_greedy_f32" || o->op == "dflash_select") + return false; + for (const auto& operand : i.opd) + if (operand.kind == RAD_OPK_BUF && + (operand.handle == b.drafter.proposal || operand.handle == head_logits)) + return false; + } + return true; + }; + CHECK(drafter_silent(h)); + CHECK(!drafter_silent(q)); /* negative control: a real draft pass must fail the silence test */ /* And the trunk's own step, with the drafter silent. */ const auto dec = kit(b, { 1, 1, 1, 1 }, {}); const auto d = run_passes(b, spark25_bf16::step, { dec.get() }); CHECK_PASSES(b, d); - for (const auto& i : d[0]->issues) { - const RecOp* o = b.op_of(i.op); - REQUIRE(o != nullptr); - CHECK(o->op != "dflash_select"); - } + CHECK(drafter_silent(*d[0])); } TEST(a_drafter_is_refused_when_the_pair_or_the_depth_is_wrong) { @@ -696,7 +717,7 @@ TEST(a_drafter_is_refused_when_the_pair_or_the_depth_is_wrong) { } /* A library that only has the older per-query window or candidate-pruned selector must refuse * DSpark declaration, not silently substitute an operation with different semantics. */ - for (const char* op : {"attn_paged_anchor_window", "dflash_markov_greedy"}) { + for (const char* op : {"attn_paged_anchor_window", "dflash_markov_greedy_f32"}) { MetaKV k = with_dspark(spark_meta()); RadBuilder b; b.refuse.insert(op); @@ -751,7 +772,7 @@ TEST(the_int8_trunk_carries_the_same_drafter) { CHECK_EQ(b.drafter.window, 513); CHECK(find_w(b, "dspark.fc.weight") != nullptr); CHECK_EQ(count_op(b, "attn_paged_anchor_window"), 1); - CHECK_EQ(count_op(b, "dflash_markov_greedy"), 1); + CHECK_EQ(count_op(b, "dflash_markov_greedy_f32"), 1); CHECK_EQ(count_op(b, "dflash_select"), 0); const auto ver = kit(b, std::vector(4, 8), {}); const auto ctx_pass = context_pass(b, *ver);