dflash2: lossless coupled acceptance at T > 0 (--draft-coupling on)

DFlash2's drafts were the greedy walk over its candidate lattice, accepted
only when they equal the target's own sampled draw: P(y == x) instead of
rejection sampling's sum min(P, Q). --draft-coupling already did the latter
for a linear MTP head; this extends it to the block drafter.

- dflash_couple_propose (spechub plugin, device row + host oracle): after
  dflash_select, the same lattice walked again, sampled. Position l scores
  each candidate as dflash_select does (unary + low-rank edge from the
  previous token), Q_l = FP64 softmax of score / q_temp over the best eight
  in-vocabulary candidates, x_l ~ Q_l at (seed, base, KEY_DRAFT + l + 1),
  x_l is the next predecessor. Position l writes round l+1's state row, so
  the engine binds it and the sampler's mtp_couple_verify (maximal coupling,
  residual (P - Q)+) verifies it exactly as an MTP round. Q depends on the
  committed text and on x_0..x_{l-1}, never on the verify, and is stored
  exactly. Greedy requests keep dflash_select's tokens (status 0); a draw
  for another card or a Q that cannot be built takes the walk's argmax and
  the ordinary verify (status -1). The shared arithmetic is in
  abi/rad_spechub.h (rad_dflash_couple_step / _walk).
- The block driver stages one draw per drafting row before the query pass,
  reads the states back with the slots and binds them after the commit
  (Engine::bind_couple, shared with the serial driver).
- qwen35_fp8 declares the planes and the op under --draft-coupling;
  RADIANCE_DFLASH_Q_TEMP sets Q's temperature (default 1, exact at any).
- Default (flag off): no op, no plane, no change.

Gates:
- spechub_dflash_couple_test (CPU): emitted token vs P by chi-square over 3
  seeds each, Fisher-combined p 0.135..0.919, for Q = P, Q on fewer tokens
  than P, Q mostly outside P, top_k 20 + top_p 0.95, top_p 0.6, top_k 3 at
  T 0.7, peaked Q; acceptance = sum min(P, Q) within 5 sigma; the walk's
  stored Q equals the softmax of its scores (1e-5) and x follows it (p
  0.993); the whole draft/verify/bonus loop over 3 tokens matches the
  target's autoregressive law (combined p 0.62 at q_temp 1, 0.67 at 0.5,
  0.024 with every 2nd step on the ordinary verify).
- Device row vs host oracle, 40 random lattices at the production geometry
  (V 248320, K 16, R 256, steps 7/3, M 1..16): tokens, x, ids, status
  identical; q differs only by FP64 exp ulps (<= 4.3e-16 relative).
  91 us a launch at M 16, steps 7.
- Engine, Qwen3.8-27B MXFP4 TP2, our serving flags, 4-6 tokens of two chat
  prompts at T 1 / top_p 0.95 / top_k 20, 5000-11000 samples per arm:
  coupled vs ordinary speculation chi-square p 0.23..0.81 (tokens 1-4 and
  pair 1-2); both differ from no speculation on one prompt by the same
  amount (the verify-vs-decode logits, not the rule).
- Flag off, old build (up12 5dbb5dc) vs this: greedy top-5 logprob traces
  identical over 300 tokens (spec 7 and 0, two requests each), 6/6
  fixed-seed sampled texts identical.
- ctest (the environment-only tests excluded) 105/105.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
mici81andClaude Opus 5.5 authored and StillDeadcode committed 2026-10-27 18:37:28 +01:00
1 parent 72a58d0c0c
commit cb0abe9ac7
18 files changed
+1330 -115

No files matched your search

+3 -2
View File
@@ -242,8 +242,9 @@ typedef struct RadBuildCtx {
/* ---- appended in ABI 27 (draft coupling) */
/* Nonzero from --draft-coupling on: a linear serial drafter samples each round's proposal from
* its own shortlist law and declares the planes and ops the coupled verify reads
* (abi/rad_spechub.h, docs/OPS.md `mtp_couple_propose`). 0, the zero-initialised default,
* its own shortlist law, or a block drafter's walk each position's (DFlash2), and declares the
* planes and ops the coupled verify reads (abi/rad_spechub.h, docs/OPS.md `mtp_couple_propose`,
* `dflash_couple_propose`). 0, the zero-initialised default,
* declares the greedy drafter. A plugin that cannot couple returns RAD_E_UNSUPPORTED from
* declare when it is set; the engine refuses a model whose program carries no coupled planes.
*
+147 -1
View File
@@ -1,4 +1,5 @@
/* rad_spechub.h -- the linear-MTP coupling: wire rows and the shared arithmetic.
/* rad_spechub.h -- the speculative coupling (linear MTP and DFlash2's block walk): wire rows and
* the shared arithmetic.
*
* The core writes these rows and a kernel plugin reads them, so their layout is ABI. The helpers
* are header-only and stateless, so the host reference, the device kernel and the sampler share
@@ -262,6 +263,151 @@ static inline RAD_SPECHUB_HD bool rad_mtp_couple_decide(const RadMtpCoupleState&
return true;
}
/* ================================================================== DFlash2's coupled walk
*
* The block drafter's counterpart of mtp_couple_propose (`dflash_couple_propose`). DFlash2 proposes
* a block in one pass and `dflash_select` walks its candidate lattice greedily: at draft position l
* every candidate c of that position scores
*
* score[l, c] = unary[l, c] + sum_r pred[pid][r] * hp[l][r] * succ[cand[l, c]][r]
*
* with pid the anchor at l = 0 and the walk's own previous token after it. The coupled walk scores
* the same lattice but SAMPLES each position instead of taking its argmax:
*
* Q_l = the FP64 softmax of score[l, c] / q_temp over the eight best-scoring candidates whose
* ids are in the vocabulary (rad_mtp_couple_build_q), x_l ~ Q_l at the draw's
* (seed, base, KEY_DRAFT + l + 1), and pid = x_l for position l + 1.
*
* Q_l depends on the committed text (through the drafter's pass and the anchor) and on x_0..x_{l-1},
* never on the target's verification, and it is stored exactly in the state row the verify reads,
* which is all the maximal coupling needs to be exact (rad_mtp_couple_decide). The pairwise term is
* what makes Q_l follow the walk's own earlier samples rather than the drafter's marginal.
*
* Bit-identical on host and device: each candidate's edge is RAD_DFLASH_EDGE_PARTS partial sums,
* each a serial fmaf chain over a contiguous slice of the rank, added in order and then to the unary
* score. The plugin builds with -ffp-contract=off, so nothing else is fused. */
#define RAD_DFLASH_EDGE_PARTS 8
#define RAD_DFLASH_COUPLE_MAX_K 32
#define RAD_DFLASH_COUPLE_MAX_R 512
static inline RAD_SPECHUB_HD float rad_dflash_bf2f(uint16_t h) {
union { uint32_t u; float f; } c;
c.u = (uint32_t)h << 16;
return c.f;
}
/* Part `j` of one candidate's edge: a[r] * succ_row[r] over r in [j*R/P, (j+1)*R/P), fmaf in order.
* `a` is the candidate-independent half, pred[pid][r] * hp[r] (or pred[pid][r] with no hp, 0 for a
* predecessor outside the vocabulary). */
static inline RAD_SPECHUB_HD float rad_dflash_edge_part(const float* a, const uint16_t* succ_row,
int64_t R, int j) {
const int64_t w = R / RAD_DFLASH_EDGE_PARTS;
float acc = 0.0f;
for (int64_t r = (int64_t)j * w; r < (int64_t)(j + 1) * w; ++r)
acc = fmaf(a[r], rad_dflash_bf2f(succ_row[r]), acc);
return acc;
}
/* One position of the walk, given its K scores and ids (the ids as the candidate plane holds them).
* Fills `*s` as mtp_couple_propose fills a round's state and returns the proposed token:
*
* mode 0 (a greedy request): status 0, x = `greedy_x`, the token dflash_select already wrote;
* mode 1, its card's draw and a Q that builds: status 1, x ~ Q;
* mode 1 otherwise: status -1, x = the walk's argmax (ties to the lower index, dflash_select's
* rule over these scores), and the ordinary verify applies to it.
*
* The eight are taken in descending score, ties to the lower index, among candidates with an id
* in [0, vocab); a NaN score is never taken (build_q would refuse it). */
static inline RAD_SPECHUB_HD int32_t rad_dflash_couple_step(const float* sc, const int32_t* id,
int K, float q_temp,
const RadMtpCoupleDraw& d, bool card_ok,
int round, int64_t vocab,
int32_t greedy_x, RadMtpCoupleState* s) {
s->draw = d;
s->pos = 0;
s->round = round;
s->count = 0;
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
if (d.mode != 1) {
s->status = 0;
s->x = greedy_x;
return greedy_x;
}
s->status = -1;
if (card_ok) {
int32_t kid[8];
float kv[8];
unsigned taken = 0;
int n = 0;
for (; n < 8; ++n) {
int best = -1;
for (int c = 0; c < K; ++c) {
if ((taken >> c) & 1u) continue;
if (id[c] < 0 || id[c] >= vocab || sc[c] != sc[c]) continue;
if (best < 0 || sc[c] > sc[best]) best = c;
}
if (best < 0) break;
taken |= 1u << best;
kid[n] = id[best];
kv[n] = sc[best] / q_temp;
}
for (int i = n; i < 8; ++i) { kid[i] = -1; kv[i] = -INFINITY; }
if (n > 0 && rad_mtp_couple_build_q(kid, kv, vocab, s)) {
const double u = rad_spechub_uniform(d.seed, d.base,
RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)round);
s->x = s->ids[rad_mtp_couple_pick(*s, u)];
s->status = 1;
return s->x;
}
s->count = 0;
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
}
int best = 0;
float bv = -INFINITY;
for (int c = 0; c < K; ++c)
if (sc[c] > bv) { bv = sc[c]; best = c; }
s->x = id[best];
return s->x;
}
/* One sequence's whole walk on the host: the reference the device kernel is checked against, and
* what the tests drive. `cand`/`unary` are `steps` rows at pitches `ld_cand`/`ld_unary`, `hp`
* `steps` rows at `ld_hp` (null: ones), `tokens` the `steps` tokens dflash_select wrote (rewritten
* for a sampled row), `state` round 1's row with `st_round` u32 words between rounds. K <= 32, R a
* multiple of RAD_DFLASH_EDGE_PARTS and at most RAD_DFLASH_COUPLE_MAX_R (the plugin's validation).
* `pred`/`succ` are [vocab, R]. */
static inline void rad_dflash_couple_walk(const int32_t* cand, const float* unary, int64_t ld_cand,
int64_t ld_unary, const uint16_t* hp, int64_t ld_hp,
int32_t anchor, const uint16_t* pred,
const uint16_t* succ, int K,
int64_t R, int64_t vocab, int64_t steps, float q_temp,
const RadMtpCoupleDraw& d, bool card_ok, int32_t* tokens,
uint32_t* state, int64_t st_round) {
float a[RAD_DFLASH_COUPLE_MAX_R], sc[RAD_DFLASH_COUPLE_MAX_K] = {};
int32_t pid = anchor;
for (int64_t l = 0; l < steps; ++l) {
RadMtpCoupleState* s = reinterpret_cast<RadMtpCoupleState*>(state + l * st_round);
const int32_t* id = cand + l * ld_cand;
if (d.mode == 1) {
const float* un = unary + l * ld_unary;
const bool ok = pid >= 0 && pid < vocab;
for (int64_t r = 0; r < R; ++r)
a[r] = ok ? rad_dflash_bf2f(pred[(int64_t)pid * R + r]) *
(hp ? rad_dflash_bf2f(hp[l * ld_hp + r]) : 1.0f)
: 0.0f;
for (int c = 0; c < K; ++c) {
float acc = 0.0f;
if (id[c] >= 0 && id[c] < vocab)
for (int j = 0; j < RAD_DFLASH_EDGE_PARTS; ++j)
acc += rad_dflash_edge_part(a, succ + (int64_t)id[c] * R, R, j);
sc[c] = un[c] + acc;
}
}
pid = rad_dflash_couple_step(sc, id, K, q_temp, d, card_ok, (int)l + 1, vocab, tokens[l], s);
tokens[l] = pid;
}
}
#undef RAD_SPECHUB_HD
#endif /* __cplusplus */
#endif /* RAD_SPECHUB_H */
+47
View File
@@ -98,6 +98,7 @@
#include "rad_arch.h"
#include "rad_fp8.h"
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire (--draft-coupling) */
namespace rad {
namespace arch {
@@ -135,6 +136,10 @@ struct Dflash2 {
* architecture that does not call rad_drafter_short_block leaves it off and its graph as
* it was. */
int short_block = 0;
/* --draft-coupling: the temperature of the draft law Q the coupled walk samples from
* (dflash_couple_propose's `q_temp`). Any value keeps the output exact; it only moves
* acceptance, sum min(P, Q). */
double q_temp = 1.0;
int64_t steps() const { return block - 1; }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
@@ -190,6 +195,9 @@ struct Dflash2 {
rad_buf dpair = 0; /* [srows, sel_topk, 2] f32 */
rad_buf dgath = 0; /* [srows, world * sel_topk, 2] f32 */
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
/* --draft-coupling: [max_seqs, DRAW_WORDS] draws the engine stages, and [steps, max_seqs,
* STATE_WORDS] states it reads back (abi/rad_spechub.h). Both or neither. */
rad_buf couple_draws = 0, couple_state = 0;
};
/* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
@@ -296,6 +304,9 @@ struct Dflash2 {
static constexpr int64_t kRerankR = 32;
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
rad_op op_hp = 0, op_sel = 0;
/* --draft-coupling: the sampled walk after the greedy one (dflash_couple_propose), for the
* drafter's block and its short one. 0 when the coupling is off. */
rad_op op_couple = 0, op_couple_lo = 0;
/* The short block: kShortBlock rows (depth 3, the window that pays at many sequences), when
* the drafter's own block is longer (rad_drafter_short_block). */
static constexpr int64_t kShortBlock = 4;
@@ -949,6 +960,35 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_pred, w_succ)),
{w.cand, w.unary, w.hp}, {w.tokens});
/* --draft-coupling: the walk again, sampled (abi/rad_spechub.h, rad_dflash_couple_step), over
* the same lattice right after the greedy walk. A greedy request's row keeps the selector's
* tokens; a sampled one gets x ~ Q at every position and the Q it was drawn from, which the
* engine reads back and binds to the verify. The tokens stay global ids, so the engine's take
* (ADV_BTAKE) is unchanged. */
if (w.couple_draws || w.couple_state) {
if (!w.couple_draws || !w.couple_state || cfg.steps() > RAD_MTP_COUPLE_MAX_ROUNDS ||
cfg.sel_topk > RAD_DFLASH_COUPLE_MAX_K)
return RAD_E_UNSUPPORTED;
auto couple = [&](int64_t steps, int64_t stride) {
return rw(b, RAD_OP(b, "dflash_couple_propose",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", steps),
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", stride),
RAD_INT("max_rounds", cfg.steps()),
RAD_F64("q_temp", cfg.q_temp)),
RAD_WEIGHTS(w_pred, w_succ)),
{w.cand, w.unary, w.hp, w.couple_draws, w.tokens},
{w.tokens, w.couple_state});
};
op_couple = couple(cfg.steps(), cfg.block);
if (!op_couple) return RAD_E_INVAL;
if (block_lo) {
op_couple_lo = couple(block_lo - 1, block_lo);
if (!op_couple_lo) return RAD_E_INVAL;
}
}
/* The reads beside the all-reduces, after every weight they read is declared. */
if (op_ar && cfg.prefetch > 0)
for (int64_t l = 0; l < g.n_layer; ++l) {
@@ -1161,6 +1201,13 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
brows(w.tokens, batch->n_seq));
if (op_couple)
RAD_ISSUE_N(c, lo ? op_couple_lo : op_couple, batch->n_seq,
bcol(w.cand, 0, cfg.sel_topk, S), bcol(w.unary, 0, cfg.sel_topk, S),
brows(w.hp, S), praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred),
RAD_W(w_succ), praw(batch->seq_ids, RAD_I32, batch->n_seq),
brows(w.couple_draws, batch->n_seq), brows(w.tokens, batch->n_seq),
RAD_B(w.couple_state));
}
} /* namespace arch */
+35
View File
@@ -421,6 +421,41 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
* selector, never through the sampler's token buffer. */
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
/* --draft-coupling (RadBuildCtx::draft_coupling): the walk samples each draft from Q, its
* scores' softmax over the best eight candidates, and the sampler couples the target's own draw
* to it (abi/rad_spechub.h). The planes are named as the MTP head's, which is how the engine
* finds them. RADIANCE_DFLASH_Q_TEMP sets Q's temperature (default 1); any value keeps the
* output exact and moves only acceptance. */
if (ctx->draft_coupling) {
if (dc.steps() > RAD_MTP_COUPLE_MAX_ROUNDS || dc.sel_topk > RAD_DFLASH_COUPLE_MAX_K ||
dc.sel_rank % RAD_DFLASH_EDGE_PARTS || dc.sel_rank > RAD_DFLASH_COUPLE_MAX_R) {
rad_note(b, "--draft-coupling on: DFlash2's coupled walk takes at most %d drafts, %d "
"candidates and a selector rank that is a multiple of %d up to %d",
RAD_MTP_COUPLE_MAX_ROUNDS, RAD_DFLASH_COUPLE_MAX_K, RAD_DFLASH_EDGE_PARTS,
RAD_DFLASH_COUPLE_MAX_R);
return RAD_E_UNSUPPORTED;
}
if (const char* e = std::getenv("RADIANCE_DFLASH_Q_TEMP")) {
const double t = std::strtod(e, nullptr);
if (!(t > 0.0) || t > 100.0) {
fprintf(stderr, "radiance: RADIANCE_DFLASH_Q_TEMP=%s is not a temperature in "
"(0, 100]\n", e);
return RAD_E_INVAL;
}
dc.q_temp = t;
}
dw.couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
{dg.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, RAD_BUF_PERSIST);
dw.couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
{dc.steps(), dg.max_seqs, RAD_MTP_COUPLE_STATE_WORDS},
RAD_BUF_PERSIST);
if (!dw.couple_draws || !dw.couple_state) return RAD_E_INVAL;
rad_note(b, "DFlash2 coupled: the walk samples x~Q (FP64 softmax of its edge scores / %g "
"over the best eight candidates) at each of %lld positions, and the sampler "
"couples the target's own draw to it; fixed-seed tokens are NOT preserved",
dc.q_temp, (long long)dc.steps());
}
RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft",
nm.ckpt("lm_head.weight"), dw));
m.have_df = true;
+5 -4
View File
@@ -177,10 +177,11 @@ static const Flag g_flags[] = {
{ "--draft-short-from", "N", "a block drafter that also serves a shorter block runs it\n"
"from N decoding sequences on (0 never, the default): the\n"
"long block pays at one sequence, the short one at many" },
{ "--draft-coupling", "MODE", "off (default) | on -- a linear MTP drafter samples each proposal\n"
" from its own shortlist and the sampler couples the target's draw\n"
" to it: more accepted drafts on sampled requests, the same output\n"
" law, other tokens than off for a fixed seed" },
{ "--draft-coupling", "MODE", "off (default) | on -- a linear MTP drafter or DFlash2's walk\n"
" samples each proposal from its own shortlist and the sampler\n"
" couples the target's draw to it: more accepted drafts on sampled\n"
" requests, the same output law, other tokens than off for a fixed\n"
" seed" },
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
{ "--host", "ADDR", "listen address" },
+3 -1
View File
@@ -449,7 +449,9 @@ private:
bool couple_evidence_ = false; /* the completed-verify line was written (once a process) */
bool couple_host_note_ = false; /* the host-domain counterpart was written (once) */
bool couple_malformed_note_ = false; /* a status -1 round was reported (once) */
int stage_couple_draws(int n);
/* `rows` are serial_row_ or block_row_ (Scheduler::SerialRow / BlockRow). */
template <class Row> int stage_couple_draws(const Row* rows, int n);
int bind_couple(uint64_t seq, int i, int done, bool drafted, int32_t card);
/* One INFO line at the first coupled verify that completed: the step, the live requests whose
* rows carried a bound state, the kernel and its domain. Read from the sampler's build
* snapshot after collect_step's wait, so it reports a finished verify, not an enqueue. */
+78 -47
View File
@@ -60,12 +60,15 @@ int Engine::step_state_init() {
* uncoupled. */
mtp_couple_ = cfg_.draft_coupling;
if (mtp_couple_) {
/* Coupling is defined on a linear serial chain. A block drafter proposes a whole block
* from one pass, so it has no per-round draw to couple and no per-round state. */
if (drafter_.kind != RAD_DRAFT_SERIAL || drafter_.depth <= 0) {
RAD_ERR("--draft-coupling on requires the linear serial draft chain (RAD_DRAFT_SERIAL "
"with depth > 0); this model declares drafter '%s' kind %d depth %d, which has "
"no per-round draw to couple",
/* Coupling is defined on a linear chain of drafts: a serial head's rounds, or a block
* drafter whose walk samples each position in turn (DFlash2, dflash_couple_propose), its
* position l standing for round l + 1. Either way one draw a drafting row and one state a
* (round, row). */
if ((drafter_.kind != RAD_DRAFT_SERIAL && drafter_.kind != RAD_DRAFT_BLOCK) ||
drafter_.depth <= 0) {
RAD_ERR("--draft-coupling on requires a linear draft chain (a serial head or a block "
"drafter with a coupled walk, depth > 0); this model declares drafter '%s' "
"kind %d depth %d, which has no per-round draw to couple",
drafter_.name ? drafter_.name : "(none)", drafter_.kind, drafter_.depth);
return RAD_E_UNSUPPORTED;
}
@@ -85,7 +88,8 @@ int Engine::step_state_init() {
return RAD_E_STATE;
}
const RadBufDecl& sd = prog.buffers[couple_state_buf_].decl;
if (sd.rank != 3 || sd.shape[2] != (int64_t)RAD_MTP_COUPLE_STATE_WORDS) {
if (sd.rank != 3 || sd.shape[2] != (int64_t)RAD_MTP_COUPLE_STATE_WORDS ||
sd.shape[0] < (int64_t)drafter_.depth) {
RAD_ERR("--draft-coupling: 'mtp_couple_state' is not the [rounds, rows, %d]-word "
"plane the coupling reads", (int)RAD_MTP_COUPLE_STATE_WORDS);
return RAD_E_STATE;
@@ -99,8 +103,13 @@ int Engine::step_state_init() {
(int64_t)drafter_.depth * couple_rows_ * (int64_t)sizeof(RadMtpCoupleState),
RAD_MEM_HOST_PINNED));
if (!couple_draw_stage_ || !couple_readback_) return RAD_E_NOMEM;
RAD_INFO("MTP coupled LIVE: %d linear round(s), x~Q from the final reranked top8, maximal "
"coupling at the verify; fixed-seed tokens are NOT preserved", drafter_.depth);
if (drafter_.kind == RAD_DRAFT_BLOCK)
RAD_INFO("DFlash coupled LIVE: %d position(s), x~Q along the candidate walk, maximal "
"coupling at the verify; fixed-seed tokens are NOT preserved", drafter_.depth);
else
RAD_INFO("MTP coupled LIVE: %d linear round(s), x~Q from the final reranked top8, "
"maximal coupling at the verify; fixed-seed tokens are NOT preserved",
drafter_.depth);
}
RAD_TRY(rad_event_create_as(&step_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
@@ -206,7 +215,7 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
serial_rounds_ = rounds;
serial_rows_ = n;
/* Before any serial pass reads a draw; round 1 is the history pass below. */
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(n));
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(serial_row_.data(), n));
/* RADIANCE_DEBUG_STAGE: running means of a draft pass's host time: batch + advance, greedy
* sampler chain, barrier release and issue. They cost the step nothing until their sum exceeds
@@ -329,38 +338,45 @@ int Engine::finish_serial_drafter(const StepOut& so) {
if (!r0.sampler.allows_speculation(serial_row_[(size_t)i].seq)) continue;
const uint64_t seq = serial_row_[(size_t)i].seq;
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)rounds], done);
if (!mtp_couple_) continue;
/* Bound only for a request still running: one this commit finished, or whose draft the
* scheduler refused, binds nothing, and set_mtp_couple(..., 0) clears an earlier step's
* states (RAD_E_NOTFOUND for a request the sampler already dropped).
*
* The position is the committed output length after this commit, the n_out the next
* build_step reads. It comes from the scheduler's commit snapshot, not the plan's Request
* pointer, which reap() may already have freed (sched/mtp_couple_bind.h). */
MtpCoupleBindPoint bp;
bp.found = sched_.committed_seq(seq, &bp.n_out, &bp.live);
if (!bp.found)
RAD_WARN("MTP coupled: serial row for sequence %llu is not in the committed step; "
"clearing its coupling", (unsigned long long)seq);
int n_bound = 0, n_malformed = 0;
std::string why;
const int bs = mtp_couple_bind_rounds(
bp, couple_draw_stage_[(size_t)i], &couple_readback_[(size_t)i], (int)couple_rows_,
done, slots_host_[serial_row_[(size_t)i].card], meta_.n_vocab, couple_bound_,
&n_bound, &why, &n_malformed);
if (bs < 0) { RAD_ERR("%s", why.c_str()); return bs; }
if (n_malformed > 0 && !couple_malformed_note_) {
couple_malformed_note_ = true;
RAD_WARN("MTP coupled: sequence %llu: %d draft round(s) had a shortlist with no valid "
"Q (non-finite score, duplicate id or no live entry); those rounds keep the "
"greedy proposal and the ordinary verify (logged once)",
(unsigned long long)seq, n_malformed);
}
for (auto& rk : ranks_) {
const int st = rk->sampler.set_mtp_couple(seq, couple_bound_,
rc == RAD_OK ? n_bound : 0);
if (st < 0 && st != RAD_E_NOTFOUND) return st;
}
if (mtp_couple_)
RAD_TRY(bind_couple(seq, i, done, rc == RAD_OK, serial_row_[(size_t)i].card));
}
return RAD_OK;
}
/* --draft-coupling, after the commit: bind drafting row `i`'s `done` states (its readback column)
* to the positions the next build samples, and hand them to every rank's sampler.
*
* Bound only for a request still running: one this commit finished, or whose draft the scheduler
* refused (`drafted` false), binds nothing, and set_mtp_couple(..., 0) clears an earlier step's
* states (RAD_E_NOTFOUND for a request the sampler already dropped).
*
* The position is the committed output length after this commit, the n_out the next build_step
* reads. It comes from the scheduler's commit snapshot, not the plan's Request pointer, which
* reap() may already have freed (sched/mtp_couple_bind.h). */
int Engine::bind_couple(uint64_t seq, int i, int done, bool drafted, int32_t card) {
MtpCoupleBindPoint bp;
bp.found = sched_.committed_seq(seq, &bp.n_out, &bp.live);
if (!bp.found)
RAD_WARN("coupled draft: row for sequence %llu is not in the committed step; clearing its "
"coupling", (unsigned long long)seq);
int n_bound = 0, n_malformed = 0;
std::string why;
const int bs = mtp_couple_bind_rounds(bp, couple_draw_stage_[(size_t)i],
&couple_readback_[(size_t)i], (int)couple_rows_, done,
slots_host_[card], meta_.n_vocab, couple_bound_,
&n_bound, &why, &n_malformed);
if (bs < 0) { RAD_ERR("%s", why.c_str()); return bs; }
if (n_malformed > 0 && !couple_malformed_note_) {
couple_malformed_note_ = true;
RAD_WARN("coupled draft: sequence %llu: %d draft position(s) had a shortlist with no valid "
"Q (non-finite score, duplicate id or no live entry); those keep the greedy "
"proposal and the ordinary verify (logged once)",
(unsigned long long)seq, n_malformed);
}
for (auto& rk : ranks_) {
const int st = rk->sampler.set_mtp_couple(seq, couple_bound_, drafted ? n_bound : 0);
if (st < 0 && st != RAD_E_NOTFOUND) return st;
}
return RAD_OK;
}
@@ -391,18 +407,18 @@ void Engine::couple_verify_evidence(int step) {
}
}
/* --draft-coupling: the draw for every drafting row, before any serial pass reads it.
/* --draft-coupling: the draw for every drafting row, before any draft pass reads it.
*
* The coordinate is the pre-commit output size, which strictly grows between two steps that draft
* one request, so (base, round) never repeats a draft stream. The card is the slot the advance
* writes; the propose op keeps the greedy proposal for a row whose draw names another card. The
* rule is sched/mtp_couple_plan.h. */
int Engine::stage_couple_draws(int n) {
template <class Row>
int Engine::stage_couple_draws(const Row* rows, int n) {
std::string why;
const int stg = mtp_couple_plan_stage(sched_.plan(),
(int)(cfg_.max_seqs > 0 ? cfg_.max_seqs : 1),
serial_row_.data(), n, &couple_by_card_,
couple_draw_stage_, &why);
rows, n, &couple_by_card_, couple_draw_stage_, &why);
if (stg < 0) {
RAD_ERR("MTP coupled: %s", why.c_str());
return stg;
@@ -505,6 +521,9 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
block_row_.data(), (int)block_row_.size(), /*on_card=*/true);
/* --draft-coupling: the draws before the query pass reads them (stage_couple_draws). */
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(block_row_.data(), n));
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
* drafter will need, and skipping would leave a permanent hole in its cache. */
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
@@ -515,6 +534,15 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
RAD_TRY(block_pass(qb, "query", step));
RAD_TRY(advance_all(ADV_BTAKE, steps, true, n));
Rank& r0 = *ranks_[0];
if (mtp_couple_) {
/* Positions 1..steps of the drafting rows, on the stream of the slots below. */
const void* state = r0.ctx.buf_ptr(couple_state_buf_);
if (!state || steps > (int)drafter_.depth) return RAD_E_STATE;
const int64_t pitch = couple_rows_ * (int64_t)sizeof(RadMtpCoupleState);
RAD_TRY(rad_memcpy_2d_async(couple_readback_, pitch, state, pitch,
(int64_t)n * (int64_t)sizeof(RadMtpCoupleState), steps,
r0.ctx.stream()));
}
RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots,
(int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream()));
block_rows_ = n;
@@ -557,7 +585,10 @@ int Engine::finish_block_drafter(const StepOut& so) {
/* As in finish_serial_drafter: the step issued ahead only carries a request whose answer
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. */
if (!r0.sampler.allows_speculation(block_row_[(size_t)i].seq)) continue;
sched_.set_draft(block_row_[(size_t)i].seq, &draft_out_[(size_t)i * (size_t)steps], steps);
const uint64_t seq = block_row_[(size_t)i].seq;
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)steps], steps);
if (mtp_couple_)
RAD_TRY(bind_couple(seq, i, steps, rc == RAD_OK, block_row_[(size_t)i].card));
}
return RAD_OK;
}
+3 -2
View File
@@ -936,8 +936,9 @@ struct Config {
* the step just run; 0 never. Ignored without a drafter that declares one. */
int64_t draft_short_from = 0; /* --draft-short-from */
/* --draft-coupling off|on: a linear serial drafter samples its proposals and the sampler
* applies the maximal coupling at the verify (RadBuildCtx::draft_coupling, abi/rad_spechub.h).
/* --draft-coupling off|on: a linear serial drafter (or DFlash2's block walk) samples its
* proposals and the sampler applies the maximal coupling at the verify
* (RadBuildCtx::draft_coupling, abi/rad_spechub.h).
* Off by default; on changes which tokens a fixed seed yields, not their law. */
bool draft_coupling = false;
+4 -3
View File
@@ -1,4 +1,4 @@
/* mtp_couple_plan.h -- which draw the engine stages for each serial drafting row.
/* mtp_couple_plan.h -- which draw the engine stages for each drafting row (serial or block).
*
* Engine::stage_couple_draws (core/engine_draft.cpp) reads the draw of every sequence on its card
* from the step plan and, for each drafting row, the plan entry naming the row's sequence on the
@@ -24,7 +24,8 @@ namespace rad {
* RAD_OK, or RAD_E_STATE with `why` set: the plane is too small for the card slots, or a drafting
* row's card carries no plan entry naming its sequence (a stale row -- the plugin would refuse the
* staged draw, so it is refused here where the row can be named). */
inline int mtp_couple_plan_stage(const StepPlan& plan, int n_card, const Scheduler::SerialRow* rows,
template <class Row> /* Scheduler::SerialRow or Scheduler::BlockRow: a sequence and its card */
inline int mtp_couple_plan_stage(const StepPlan& plan, int n_card, const Row* rows,
int n, std::vector<RadMtpCoupleDraw>* by_card,
RadMtpCoupleDraw* stage, std::string* why) {
if (!by_card || !stage || !why) return RAD_E_INVAL;
@@ -39,7 +40,7 @@ inline int mtp_couple_plan_stage(const StepPlan& plan, int n_card, const Schedul
(*by_card)[(size_t)e.card] = { e.req->sp.seed, (uint64_t)e.req->output.size(), e.seq,
e.card, e.req->sp.greedy() ? 0u : 1u };
for (int i = 0; i < n; ++i) {
const Scheduler::SerialRow& row = rows[i];
const Row& row = rows[i];
if (row.card < 0 || row.card >= n_card || (*by_card)[(size_t)row.card].seq != row.seq) {
*why = "drafting row " + std::to_string(i) + " (sequence " + std::to_string(row.seq) +
", card " + std::to_string(row.card) + ") has no plan entry on its card";
+1 -1
View File
@@ -1943,7 +1943,7 @@ by 0.002-0.003 nats.
| `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
| `--draft-short-from N` | 0 | a block drafter that declares a shorter block runs it from N decoding sequences on, its own block again two below; 0 never (§4.6) |
| `--draft-coupling MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged; any other drafter is refused at startup |
| `--draft-coupling MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged. A DFlash2 drafter (Qwen3.5/3.8) couples its candidate walk instead: each position is sampled from the softmax of the walk's own scores over its best eight candidates, at temperature `RADIANCE_DFLASH_Q_TEMP` (default 1). Any other drafter is refused at startup |
| `--draft-model PATH` | | not implemented: merge the drafter at convert time |
**Server**
+22 -4
View File
@@ -2692,11 +2692,13 @@ resolutions of one op. The one exception is `sample_chain` (below).
| `sample_logprobs` | `M`(range) `n_vocab` `k` `vocab_off`/opt | `logits`, `params` → `stats` |
| `mtp_couple_propose` | `M`(range) `n_vocab` `round` `max_rounds` | `idx`:inout, `val`, `seq_ids`, `draw` → `state`:inout |
| `mtp_couple_verify` | `M`(range) `n_cand` `n_vocab` | `cand_idx`, `cand_val`, `params`, `state` → `token`:inout |
| `dflash_couple_propose` | `M`(range) `steps` `top_k` `rank` `n_vocab` `anchor_stride` `max_rounds` `q_temp`:f64/opt | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w, `seq_ids`, `draw`, `tokens`:inout → `state`:inout |
`mtp_couple_propose` and `mtp_couple_verify` are the linear-MTP coupling (`--draft-coupling on`),
and nothing else in the engine knows about coupling. Turning coupling on requires the
linear serial draft chain: a block drafter (`RAD_DRAFT_BLOCK`) or no drafter at all is refused at
bringup, because neither has a per-round draw to couple. The `spechub` plugin ships both rows and
`mtp_couple_propose`, `dflash_couple_propose` and `mtp_couple_verify` are the speculative coupling
(`--draft-coupling on`), and nothing else in the engine knows about coupling. Turning coupling on
requires a linear chain of drafts: a serial head's rounds, or a block drafter whose architecture
declares the coupled walk (DFlash2); no drafter, or a block drafter without the walk, is refused at
bringup, because neither has a per-round draw to couple. The `spechub` plugin ships every row and
their host oracle in one library and marks them per row, so the device rows count as production
kernels while the oracle stays reference; on a machine with no card only the oracle is left, and
the gate refuses the coupling there. A `RADIANCE_KERNELS` list is exclusive:
@@ -2714,6 +2716,22 @@ that seed and position keeps the ordinary token. `P` is FP64-normalised where `s
FP32/24-bit, so a coupled row realizes the ideal filtered target law and is **not** seed-identical
to the ordinary pick.
`dflash_couple_propose` is DFlash2's block walk sampled (abi/rad_spechub.h,
`rad_dflash_couple_step`). It runs right after `dflash_select` over the same lattice, one workgroup a
sequence. At position `l` every candidate scores `dflash_select`'s
`unary + Σ_r pred[pid][r]·hp[l][r]·succ[cand][r]`, with `pid` the anchor at `l = 0` and the walk's
own previous token after it; `Q_l` is the FP64 softmax of `score / q_temp` over the best eight
in-vocabulary candidates, `x_l ~ Q_l` at the draw's `(seed, base, KEY_DRAFT + l + 1)`, and `x_l` is
both the proposal (into `tokens`) and position `l + 1`'s predecessor. Position `l` writes the state
row of round `l + 1`, so the engine binds and the sampler verifies it exactly as an MTP round. A
greedy request's row (draw mode 0) keeps `dflash_select`'s tokens (`status = 0`); a draw staged for
another card, or a position whose eight cannot form a `Q`, takes the walk's argmax (`status = -1`)
and the ordinary verify. `Q_l` depends on the committed text and on `x_0 .. x_{l-1}`, never on the
verify, and is stored exactly, which is all the coupling needs to be lossless; `q_temp` (the
architecture's, `RADIANCE_DFLASH_Q_TEMP` on Qwen3.5/3.8) moves acceptance only. Each edge is eight
partial `fmaf` chains over contiguous slices of the rank, added in order, so the device kernel and
the host oracle agree bit for bit.
`sample_temp` divides a row's logits by its `temp` and leaves a row whose `temp` is 0 or less, or
exactly 1, as it is. The sampler relies on that: a step none of whose chain rows has another
temperature does not issue the stage.
+31 -38
View File
@@ -26,7 +26,7 @@ int r4d_dispatch_n = 0;
namespace {
const RadPluginInfo kInfo = {
RAD_PLUGIN_KERNEL, "spechub", "0.1.0",
"Linear-MTP maximal coupling: a Q draw per round and the coupled target verify", "gfx1201",
"Maximal coupling of speculative drafts: Q draws (MTP, DFlash2), coupled verify", "gfx1201",
};
} /* namespace */
@@ -35,12 +35,12 @@ extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
/* Mixed library: 0, and the per-row answer below does the classifying. */
extern "C" int rad_plugin_reference(void) { return 0; }
/* Row layout is [device 0, device 1, ref 0, ref 1] with a card, [ref 0, ref 1] without. The
* device rows are the production kernels; the host rows are the oracle rad-kbench checks them
* against and the only thing a card-less machine can run. */
/* Row layout is [device 0..2, ref 0..2] with a card, [ref 0..2] without; row/op index 2 is
* dflash_couple_propose. The device rows are the production kernels; the host rows are the oracle
* rad-kbench checks them against and the only thing a card-less machine can run. */
extern "C" int rad_kernel_reference(int i) {
#ifdef RAD_SPECHUB_WITH_DEVICE
return (i == 0 || i == 1) ? 0 : 1;
return (i >= 0 && i < RAD_SPECHUB_N_OPS) ? 0 : 1;
#else
(void)i;
return 1;
@@ -50,48 +50,41 @@ extern "C" int rad_kernel_reference(int i) {
extern "C" int rad_kernel_schema_count(void) { return rad_spechub_schema_count(); }
extern "C" const RadOpSchema* rad_kernel_schema_at(int i) { return rad_spechub_schema_at(i); }
/* Two device rows and the two host references beside them, in that order. A card-less machine loads
* the same library and resolves only the reference rows. */
/* The device rows and the host references beside them, in that order. A card-less machine loads the
* same library and resolves only the reference rows. */
extern "C" int rad_kernel_count(void) {
#ifdef RAD_SPECHUB_WITH_DEVICE
return 4;
return 2 * RAD_SPECHUB_N_OPS;
#else
return 2;
return RAD_SPECHUB_N_OPS;
#endif
}
namespace {
RadKernelInfo ref_row(int op, RadLaunchFn launch, const char* name) {
RadKernelInfo x = rad_spechub_row(op, launch);
x.name = name;
x.domain = RAD_DOMAIN_HOST;
x.priority = 0;
return x;
}
} /* namespace */
extern "C" const RadKernelInfo* rad_kernel_at(int i) {
const int op = i & 1;
#ifdef RAD_SPECHUB_WITH_DEVICE
if (i == 0 || i == 1) {
static const RadKernelInfo r[2] = {
rad_spechub_row(0, rad_mine_mtp_couple_propose_launch),
rad_spechub_row(1, rad_mine_mtp_couple_verify_launch),
};
return &r[i];
}
static const RadKernelInfo dev[RAD_SPECHUB_N_OPS] = {
rad_spechub_row(0, rad_mine_mtp_couple_propose_launch),
rad_spechub_row(1, rad_mine_mtp_couple_verify_launch),
rad_spechub_row(2, rad_mine_dflash_couple_launch),
};
if (i >= 0 && i < RAD_SPECHUB_N_OPS) return &dev[i];
i -= RAD_SPECHUB_N_OPS;
#endif
static const RadKernelInfo ref[2] = {
[] {
RadKernelInfo x = rad_spechub_row(0, rad_ref_mtp_couple_propose);
x.name = "ref_mtp_couple_propose";
x.domain = RAD_DOMAIN_HOST;
x.priority = 0;
return x;
}(),
[] {
RadKernelInfo x = rad_spechub_row(1, rad_ref_mtp_couple_verify);
x.name = "ref_mtp_couple_verify";
x.domain = RAD_DOMAIN_HOST;
x.priority = 0;
return x;
}(),
static const RadKernelInfo ref[RAD_SPECHUB_N_OPS] = {
ref_row(0, rad_ref_mtp_couple_propose, "ref_mtp_couple_propose"),
ref_row(1, rad_ref_mtp_couple_verify, "ref_mtp_couple_verify"),
ref_row(2, rad_ref_dflash_couple, "ref_dflash_couple_propose"),
};
#ifdef RAD_SPECHUB_WITH_DEVICE
if (i < 2 || i > 3) return nullptr;
return &ref[op];
#else
if (i < 0 || i > 1) return nullptr;
if (i < 0 || i >= RAD_SPECHUB_N_OPS) return nullptr;
return &ref[i];
#endif
}
+20 -1
View File
@@ -1,4 +1,4 @@
/* plugin/spechub/ref_spechub.cpp -- the two coupling ops on the host.
/* plugin/spechub/ref_spechub.cpp -- the coupling ops on the host.
*
* One row at a time through the abi/rad_spechub.h helpers. These are the rows the device kernels
* are checked against, and the only implementation a machine with no card can run.
@@ -20,3 +20,22 @@ int rad_ref_mtp_couple_verify(const RadArgs* a, RadStream) {
for (int64_t row = 0; row < c.M; ++row) rad_mtp_couple_verify_row(c, row);
return RAD_OK;
}
/* One sequence at a time through rad_dflash_couple_walk, the definition the device kernel matches
* bit for bit. */
int rad_ref_dflash_couple(const RadArgs* a, RadStream) {
RadDflashCoupleCall c{};
const int rc = rad_dflash_couple_args(a, &c);
if (rc != RAD_OK) return rc;
for (int64_t s = 0; s < c.M; ++s) {
const RadMtpCoupleDraw& d =
*reinterpret_cast<const RadMtpCoupleDraw*>(c.draw + s * c.ld_draw);
rad_dflash_couple_walk(c.cand + s * c.steps * c.ld_cand, c.unary + s * c.steps * c.ld_unary,
c.ld_cand, c.ld_unary,
c.hp ? c.hp + s * c.steps * c.ld_hp : nullptr, c.ld_hp,
c.anchor[s * c.anchor_stride], c.pred, c.succ, (int)c.K, c.R,
c.vocab, c.steps, c.q_temp, d, d.card == c.card[s],
c.tokens + s * c.ld_tok, c.state + s * c.st_row, c.st_round);
}
return RAD_OK;
}
+165 -3
View File
@@ -1,4 +1,4 @@
/* plugin/spechub/spechub.cpp -- the two coupling ops' schemas, shapes and argument validation.
/* plugin/spechub/spechub.cpp -- the coupling ops' schemas, shapes and argument validation.
*
* Shape hooks and geometry only: the arithmetic is in abi/rad_spechub.h (inline, host and device) and
* the launches are in spechub.hip and ref_spechub.cpp. This file is host C++ and compiles with no
@@ -16,6 +16,10 @@ const RadParamSpec kProposeParams[] = {
PI("M"), PI("n_vocab"), PI("round"), PI("max_rounds"),
};
const RadParamSpec kVerifyParams[] = { PI("M"), PI("n_cand"), PI("n_vocab") };
const RadParamSpec kDflashParams[] = {
PI("M"), PI("steps"), PI("top_k"), PI("rank"), PI("n_vocab"), PI("anchor_stride"),
PI("max_rounds"), { "q_temp", RAD_P_F64, RAD_OPTIONAL, 0 },
};
#undef PI
/* `idx` is INOUT: the round's proposal IS the head's column 0, and a sampled row overwrites it. */
@@ -38,6 +42,21 @@ const RadOperandSpec kVerifyOperands[] = {
{ "token", RAD_OPD_INOUT, 0 },
};
/* DFlash2's coupled walk: dflash_select's operands, then the coupling's. `tokens` is INOUT because a
* greedy request's row keeps the selector's walk; `state` holds one row per (round, sequence). */
const RadOperandSpec kDflashOperands[] = {
{ "cand", RAD_OPD_IN, 0 },
{ "unary", RAD_OPD_IN, 0 },
{ "hp", RAD_OPD_IN, 1 },
{ "anchor", RAD_OPD_IN, 0 },
{ "pred", RAD_OPD_WEIGHT, 0 },
{ "succ", RAD_OPD_WEIGHT, 0 },
{ "seq_ids", RAD_OPD_IN, 0 },
{ "draw", RAD_OPD_IN, 0 },
{ "tokens", RAD_OPD_INOUT, 0 },
{ "state", RAD_OPD_INOUT, 0 },
};
const RadOpSchema kSchemas[] = {
{ "mtp_couple_propose", kProposeParams, 4, kProposeOperands, 5,
"Linear MTP round `round`: x~Q, Q = FP64 T1 softmax of the final top8 scores; x into idx "
@@ -48,13 +67,19 @@ const RadOpSchema kSchemas[] = {
"candidates, FP64 P and 53-bit ACCEPT/RESID uniforms at params.pos; residual (P-Q)+ with "
"r(x)=0. Rows whose state is not status 1, not bound to params seed/pos, malformed, or whose "
"(P,Q) admit no coupling keep the ordinary token." },
{ "dflash_couple_propose", kDflashParams, 8, kDflashOperands, 10,
"DFlash2's candidate walk, sampled: at each step Q = FP64 softmax of (unary + low-rank edge "
"from the previous token) / q_temp over the best eight in-vocabulary candidates, x~Q at the "
"draw's (seed, base, KEY_DRAFT + step + 1), x the next step's predecessor; tokens and "
"state[step][row] written. mode0 rows keep tokens (status 0); a Q that cannot be built or "
"seq_ids != draw.card takes the walk's argmax (status -1)." },
};
} /* namespace */
int rad_spechub_schema_count() { return 2; }
int rad_spechub_schema_count() { return RAD_SPECHUB_N_OPS; }
const RadOpSchema* rad_spechub_schema_at(int i) {
return i >= 0 && i < 2 ? &kSchemas[i] : nullptr;
return i >= 0 && i < RAD_SPECHUB_N_OPS ? &kSchemas[i] : nullptr;
}
namespace {
@@ -238,8 +263,145 @@ int rad_mtp_couple_verify_args(const RadArgs* a, RadMtpCoupleVerifyCall* out) {
return RAD_OK;
}
/* ------------------------------------------------------------------ dflash_couple_propose */
namespace {
/* The walk's geometry, shared by the shape hook and the arg reader. `range` reads M as the band's
* high bound (a shape hook sizes the whole band). */
int dflash_geometry(const RadParam* p, int n, bool range, int64_t* M, int64_t* steps, int64_t* K,
int64_t* R, int64_t* vocab, int64_t* astr, int64_t* rounds) {
if (!p) return RAD_E_INVAL;
*M = range ? rad_param_getdim(p, n, "M", 0) : rad_param_geti(p, n, "M", 0);
*steps = rad_param_geti(p, n, "steps", 0);
*K = rad_param_geti(p, n, "top_k", 0);
*R = rad_param_geti(p, n, "rank", 0);
*vocab = rad_param_geti(p, n, "n_vocab", 0);
*astr = rad_param_geti(p, n, "anchor_stride", 1);
*rounds = rad_param_geti(p, n, "max_rounds", 0);
if (*M < 1 || *M > INT32_MAX || *vocab < 1 || *vocab > INT32_MAX || *astr < 1)
return RAD_E_UNSUPPORTED;
if (*rounds < 1 || *rounds > RAD_MTP_COUPLE_MAX_ROUNDS || *steps < 1 || *steps > *rounds)
return RAD_E_UNSUPPORTED;
if (*K < 1 || *K > RAD_DFLASH_COUPLE_MAX_K) return RAD_E_UNSUPPORTED;
if (*R < RAD_DFLASH_EDGE_PARTS || *R > RAD_DFLASH_COUPLE_MAX_R || *R % RAD_DFLASH_EDGE_PARTS)
return RAD_E_UNSUPPORTED;
return RAD_OK;
}
/* A rank-2 plane of at least `rows` x `width` with a unit inner stride; its row pitch, or -1. */
int64_t plane2(const RadTensor& t, uint32_t dtype, int64_t rows, int64_t width) {
if (!t.data || t.dtype != dtype || t.rank != 2) return -1;
if (t.shape[0] < rows || t.shape[1] < width || (t.shape[1] > 1 && t.stride[1] != 1)) return -1;
return t.stride[0] >= width ? t.stride[0] : -1;
}
bool dense_at_least(const RadTensor& t, uint32_t dtype, int64_t numel) {
if (!t.data || t.dtype != dtype || t.rank < 1) return false;
if (!rad_tensor_is_contiguous(&t)) return false;
return rad_tensor_numel(&t) >= numel;
}
} /* namespace */
int rad_dflash_couple_shape(const RadParam* p, int n, int i, RadOpdDesc* out) {
if (!out || i < 0 || i >= 10) return RAD_E_INVAL;
int64_t M, steps, K, R, v, astr, rounds;
const int rc = dflash_geometry(p, n, true, &M, &steps, &K, &R, &v, &astr, &rounds);
if (rc != RAD_OK) return rc;
RadOpdDesc d{};
d.idx_const = -1;
d.rank = 2;
switch (i) {
case 0: d.dtype = RAD_I32; d.shape[0] = M * steps; d.shape[1] = K;
d.fill = RAD_FILL_INDEX; d.idx_max = v; break;
case 1: d.dtype = RAD_F32; d.shape[0] = M * steps; d.shape[1] = K; break;
case 2: d.dtype = RAD_BF16; d.shape[0] = M * steps; d.shape[1] = R; break;
case 3: d.dtype = RAD_I32; d.rank = 1; d.shape[0] = M * astr;
d.fill = RAD_FILL_INDEX; d.idx_max = v; break;
case 4:
case 5: d.dtype = RAD_BF16; d.shape[0] = v; d.shape[1] = R; break;
case 6: d.dtype = RAD_I32; d.rank = 1; d.shape[0] = M;
d.fill = RAD_FILL_INDEX; d.idx_max = M; break;
case 7: d.dtype = RAD_U32; d.shape[0] = M; d.shape[1] = RAD_MTP_COUPLE_DRAW_WORDS; break;
case 8: d.dtype = RAD_I32; d.shape[0] = M; d.shape[1] = steps;
d.fill = RAD_FILL_INDEX; d.idx_max = v; break;
default:
d.dtype = RAD_U32;
d.rank = 3;
d.shape[0] = rounds;
d.shape[1] = M;
d.shape[2] = RAD_MTP_COUPLE_STATE_WORDS;
break;
}
*out = d;
return RAD_OK;
}
/* The live row count is the token plane's (one row a drafting sequence), as dflash_select takes it:
* RadArgs carries the band's bound for M, and the input planes are read at row s*steps+l. */
int rad_dflash_couple_args(const RadArgs* a, RadDflashCoupleCall* out) {
if (!a || !a->t || !out || a->n_t != 10) return RAD_E_INVAL;
int64_t M, steps, K, R, v, astr, rounds;
int rc = dflash_geometry(a->p, a->n_p, false, &M, &steps, &K, &R, &v, &astr, &rounds);
if (rc != RAD_OK) return rc;
const RadTensor* t = a->t;
const int64_t live = t[8].rank == 2 ? t[8].shape[0] : 0;
if (live < 1 || live > M) return RAD_E_SHAPE;
M = live;
RadDflashCoupleCall c{};
c.M = M; c.steps = steps; c.K = K; c.R = R; c.vocab = v; c.anchor_stride = astr;
c.q_temp = (float)rad_param_getf(a->p, a->n_p, "q_temp", 1.0);
if (!(c.q_temp > 0.0f) || c.q_temp != c.q_temp || c.q_temp > 1e6f) return RAD_E_INVAL;
if ((c.ld_cand = plane2(t[0], RAD_I32, M * steps, K)) < 0) return RAD_E_SHAPE;
if ((c.ld_unary = plane2(t[1], RAD_F32, M * steps, K)) < 0) return RAD_E_SHAPE;
if (t[2].data && (c.ld_hp = plane2(t[2], RAD_BF16, M * steps, R)) < 0) return RAD_E_SHAPE;
if (!dense_at_least(t[3], RAD_I32, (M - 1) * astr + 1)) return RAD_E_SHAPE;
if (!dense_at_least(t[4], RAD_BF16, v * R) || !dense_at_least(t[5], RAD_BF16, v * R))
return RAD_E_SHAPE;
if (!dense_at_least(t[6], RAD_I32, M)) return RAD_E_SHAPE;
if ((c.ld_draw = plane2(t[7], RAD_U32, M, RAD_MTP_COUPLE_DRAW_WORDS)) < 0) return RAD_E_SHAPE;
if ((c.ld_tok = plane2(t[8], RAD_I32, M, steps)) < 0) return RAD_E_SHAPE;
const RadTensor& st = t[9];
if (!st.data || st.dtype != RAD_U32 || st.rank != 3 || st.shape[0] < steps ||
st.shape[1] < M || st.shape[2] != (int64_t)RAD_MTP_COUPLE_STATE_WORDS || st.stride[2] != 1 ||
st.stride[1] < (int64_t)RAD_MTP_COUPLE_STATE_WORDS || st.stride[0] < st.stride[1] * M)
return RAD_E_SHAPE;
/* The wire rows are loaded whole as structs with doubles. */
if ((uintptr_t)t[7].data % 8 || c.ld_draw % 2 || (uintptr_t)st.data % 8 || st.stride[0] % 2 ||
st.stride[1] % 2)
return RAD_E_INVAL;
c.cand = (const int32_t*)t[0].data;
c.unary = (const float*)t[1].data;
c.hp = (const uint16_t*)t[2].data;
c.anchor = (const int32_t*)t[3].data;
c.pred = (const uint16_t*)t[4].data;
c.succ = (const uint16_t*)t[5].data;
c.card = (const int32_t*)t[6].data;
c.draw = (const uint32_t*)t[7].data;
c.tokens = (int32_t*)t[8].data;
c.state = (uint32_t*)st.data;
c.st_round = st.stride[0];
c.st_row = st.stride[1];
*out = c;
return RAD_OK;
}
RadKernelInfo rad_spechub_row(int i, RadLaunchFn launch) {
RadKernelInfo r{};
if (i == 2) {
r.name = "spechub_dflash_couple_propose";
r.op = "dflash_couple_propose";
r.family = "draft";
r.computes = "DFlash2's candidate walk with x~Q per step, FP64 softmax of the edge scores";
r.shape = "M,steps<=max_rounds<=8,top_k<=32,rank%8==0<=512,n_vocab,anchor_stride";
r.dtypes = "bf16,f32,i32,u32";
r.domain = RAD_DOMAIN_DEVICE;
r.priority = 100;
r.launch = launch;
r.opd_shape = rad_dflash_couple_shape;
return r;
}
r.name = i ? "spechub_mtp_couple_verify" : "spechub_mtp_couple_propose";
r.op = i ? "mtp_couple_verify" : "mtp_couple_propose";
r.family = "draft";
+26 -1
View File
@@ -44,15 +44,38 @@ struct RadMtpCoupleVerifyCall {
int64_t M, n_cand, vocab, ld[5];
};
/* DFlash2's coupled walk (`dflash_couple_propose`, abi/rad_spechub.h): one sequence a row. Its
* operands, in schema order: cand, unary, hp?, anchor, pred w, succ w, seq_ids, draw, tokens
* (INOUT: dflash_select's greedy walk, rewritten for a sampled row), state. */
struct RadDflashCoupleCall {
const int32_t* cand; /* [M*steps, >= K] */
const float* unary; /* [M*steps, >= K] */
const uint16_t* hp; /* [M*steps, >= R] bf16, or null for ones */
const int32_t* anchor; /* the step's token ids, the anchor of sequence s at s*anchor_stride */
const uint16_t* pred; /* [vocab, R] bf16 */
const uint16_t* succ; /* [vocab, R] bf16 */
const int32_t* card; /* [>= M] RadBatch::seq_ids */
const uint32_t* draw; /* [M, DRAW_WORDS] */
int32_t* tokens; /* [M, >= steps] */
uint32_t* state; /* [rounds, >= M, STATE_WORDS] */
int64_t M, steps, K, R, vocab, anchor_stride;
int64_t ld_cand, ld_unary, ld_hp, ld_draw, ld_tok, st_round, st_row;
float q_temp;
};
int rad_mtp_couple_propose_shape(const RadParam*, int, int, RadOpdDesc*);
int rad_mtp_couple_verify_shape(const RadParam*, int, int, RadOpdDesc*);
int rad_dflash_couple_shape(const RadParam*, int, int, RadOpdDesc*);
int rad_mtp_couple_propose_args(const RadArgs*, RadMtpCoupleProposeCall*);
int rad_mtp_couple_verify_args(const RadArgs*, RadMtpCoupleVerifyCall*);
int rad_dflash_couple_args(const RadArgs*, RadDflashCoupleCall*);
/* The geometry/validation the shape hooks and the arg readers share. `op` 0 proposes, 1 verifies. */
int rad_couple_validate(const RadArgs*, int op, int64_t* M, int64_t* vocab, int64_t* n_cand);
/* The op set. Two schemas, two device rows and two host-reference rows. */
/* The op set. Three schemas, three device rows and three host-reference rows; row/schema index 2 is
* dflash_couple_propose. */
#define RAD_SPECHUB_N_OPS 3
int rad_spechub_schema_count();
const RadOpSchema* rad_spechub_schema_at(int i);
RadKernelInfo rad_spechub_row(int i, RadLaunchFn launch);
@@ -62,6 +85,8 @@ int rad_mine_mtp_couple_propose_launch(const RadArgs*, RadStream);
int rad_mine_mtp_couple_verify_launch(const RadArgs*, RadStream);
int rad_ref_mtp_couple_propose(const RadArgs*, RadStream);
int rad_ref_mtp_couple_verify(const RadArgs*, RadStream);
int rad_mine_dflash_couple_launch(const RadArgs*, RadStream);
int rad_ref_dflash_couple(const RadArgs*, RadStream);
/* One propose row, host and device: x ~ Q over the final eight. Column 0 is what ADV_ROUND and
* ADV_TAKE read, and it becomes x only for a valid sampled row. */
+195 -1
View File
@@ -1,4 +1,4 @@
/* plugin/spechub/spechub.hip -- the device launches for the two coupling ops.
/* plugin/spechub/spechub.hip -- the device launches for the coupling ops.
*
* The propose kernel is one thread a row over abi/rad_spechub.h's helpers. The verify is one
* workgroup a row: the masses are computed in parallel, and the sums and walks run on one thread
@@ -152,8 +152,202 @@ __global__ void couple_verify(const int32_t* idx, const float* values, const uin
c.token[row * c.ld[4]] = out;
}
/* DFlash2's coupled walk: one workgroup a sequence. Per step the workgroup forms the
* candidate-independent half `sa` of the edge, then thread (c, j) computes part j of candidate c's
* edge (rad_dflash_edge_part, the host's serial fmaf chain over the same slice), and thread 0 adds
* the parts in order, takes the step (rad_dflash_couple_step) and publishes the token as the next
* predecessor. The arithmetic and its order are the host reference's, so tokens and states match
* rad_ref_dflash_couple bit for bit. */
constexpr int kDfThreads = RAD_DFLASH_COUPLE_MAX_K * RAD_DFLASH_EDGE_PARTS; /* 256 */
__global__ __launch_bounds__(kDfThreads) void dflash_couple(
const int32_t* cand, const float* unary, const uint16_t* hp, const int32_t* anchor,
const uint16_t* pred, const uint16_t* succ, const int32_t* card, const uint32_t* draw,
int32_t* tokens, uint32_t* state, int64_t steps, int64_t K, int64_t R, int64_t vocab,
int64_t astr, int64_t ld_cand, int64_t ld_unary, int64_t ld_hp, int64_t ld_draw,
int64_t ld_tok, int64_t st_round, int64_t st_row, float q_temp) {
__shared__ float sa[RAD_DFLASH_COUPLE_MAX_R];
__shared__ float part[kDfThreads];
__shared__ float sc[RAD_DFLASH_COUPLE_MAX_K];
__shared__ int32_t sid[RAD_DFLASH_COUPLE_MAX_K];
__shared__ int32_t spid;
/* The step's Q in the making: its live (id, score / q_temp) in selection order, their count
* (-1: no Q), the top score, the FP64 weights, their sum and the normalised q. */
__shared__ int32_t lid[8], slot_id[8];
__shared__ float lv[8], slot_v[8];
__shared__ int sn;
__shared__ float stop;
__shared__ double w[8], wq[8], ssum;
__shared__ RadMtpCoupleState sst;
const int64_t s = blockIdx.x;
const int tid = threadIdx.x;
const RadMtpCoupleDraw d = *reinterpret_cast<const RadMtpCoupleDraw*>(draw + s * ld_draw);
int32_t* tok = tokens + s * ld_tok;
uint32_t* st0 = state + s * st_row;
if (d.mode != 1) {
/* A greedy request: dflash_select's walk stands, and each round records it (status 0). */
if (tid == 0)
for (int64_t l = 0; l < steps; ++l)
(void)rad_dflash_couple_step(sc, sid, (int)K, q_temp, d, false, (int)l + 1, vocab,
tok[l],
reinterpret_cast<RadMtpCoupleState*>(st0 + l * st_round));
return;
}
const bool card_ok = d.card == card[s];
if (tid == 0) spid = anchor[s * astr];
__syncthreads();
const int c = tid / RAD_DFLASH_EDGE_PARTS, j = tid % RAD_DFLASH_EDGE_PARTS;
for (int64_t l = 0; l < steps; ++l) {
const int64_t row = s * steps + l;
const int32_t pid = spid;
const bool ok = pid >= 0 && pid < vocab;
for (int64_t r = tid; r < R; r += kDfThreads)
sa[r] = ok ? rad_dflash_bf2f(pred[(int64_t)pid * R + r]) *
(hp ? rad_dflash_bf2f(hp[row * ld_hp + r]) : 1.0f)
: 0.0f;
__syncthreads();
if (c < K) {
const int32_t id = cand[row * ld_cand + c];
float pv = 0.0f;
if (id >= 0 && id < vocab) {
const uint16_t* srow = succ + (int64_t)id * R;
if (R == 32 * RAD_DFLASH_EDGE_PARTS) {
/* DFlash2's rank 256: the slice's 32 values in four 16-byte loads issued
* together, then rad_dflash_edge_part's fmaf chain over them in its order. A
* load inside the chain would wait out one memory latency per element. */
const uint4* src = reinterpret_cast<const uint4*>(srow + j * 32);
uint4 v[4];
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] = src[i];
const uint16_t* h = reinterpret_cast<const uint16_t*>(v);
const float* a = sa + j * 32;
#pragma unroll
for (int r = 0; r < 32; ++r) pv = fmaf(a[r], rad_dflash_bf2f(h[r]), pv);
} else {
pv = rad_dflash_edge_part(sa, srow, R, j);
}
}
part[tid] = pv;
if (j == 0) sid[c] = id;
}
__syncthreads();
/* Each candidate's score from its parts, in the host's order. */
if (tid < K) {
float acc = 0.0f;
if (sid[tid] >= 0 && sid[tid] < vocab)
for (int q = 0; q < RAD_DFLASH_EDGE_PARTS; ++q)
acc += part[tid * RAD_DFLASH_EDGE_PARTS + q];
sc[tid] = unary[row * ld_unary + tid] + acc;
}
if (tid < 8) slot_id[tid] = -2;
__syncthreads();
RadMtpCoupleState* so = reinterpret_cast<RadMtpCoupleState*>(st0 + l * st_round);
/* rad_dflash_couple_step, spread over the workgroup: one lane walking the selection and
* build_q's FP64 work serially waits out an LDS or FP64 latency per element. Each operation
* and its order are the helper's, so the bits are too.
*
* The eight: candidate k's place is the number of eligible candidates ahead of it (a higher
* score, or an equal one at a lower index), which is exactly the order the helper's repeated
* first-maximum scan takes them in. */
if (tid < K) {
const int32_t id = sid[tid];
const float v = sc[tid];
if (id >= 0 && id < vocab && v == v) {
int rank = 0;
for (int k = 0; k < K; ++k) {
const int32_t ik = sid[k];
const float vk = sc[k];
rank += (ik >= 0 && ik < vocab && vk == vk && (vk > v || (vk == v && k < tid)));
}
if (rank < 8) { slot_id[rank] = id; slot_v[rank] = v / q_temp; }
}
}
__syncthreads();
if (tid == 0) {
sn = -1;
if (card_ok) {
int live = 0;
bool bad = false;
for (int n = 0; n < 8 && slot_id[n] != -2; ++n) {
const float v = slot_v[n];
/* build_q: +inf refuses the whole Q, -inf carries no mass, a repeat refuses. */
if (v == INFINITY) { bad = true; break; }
if (v == -INFINITY) continue;
for (int i = 0; i < live; ++i) bad = bad || lid[i] == slot_id[n];
if (bad) break;
lid[live] = slot_id[n];
lv[live++] = v;
}
if (!bad && live > 0) {
float top = lv[0];
for (int i = 1; i < live; ++i)
if (lv[i] > top) top = lv[i];
stop = top;
sn = live;
}
}
}
__syncthreads();
if (tid < 8 && tid < sn) w[tid] = ::exp((double)lv[tid] - stop);
__syncthreads();
if (tid == 0 && sn > 0) {
double sum = 0;
for (int i = 0; i < sn; ++i) sum += w[i];
ssum = sum;
}
__syncthreads();
if (tid < 8 && tid < sn) wq[tid] = w[tid] / ssum;
__syncthreads();
/* The state is built in LDS: a private struct indexed by a runtime count lives in scratch,
* and every access to it is a memory round trip. */
if (tid == 0) {
RadMtpCoupleState& s = sst;
s.draw = d;
s.pos = 0;
s.round = (int)l + 1;
s.status = -1;
s.count = 0;
for (int i = 0; i < 8; ++i) { s.ids[i] = -1; s.q[i] = 0; }
for (int i = 0; i < sn; ++i)
if (wq[i] > 0) { s.ids[s.count] = lid[i]; s.q[s.count++] = wq[i]; }
if (s.count > 0) {
const double u = rad_spechub_uniform(d.seed, d.base,
RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)(l + 1));
s.x = s.ids[rad_mtp_couple_pick(s, u)];
s.status = 1;
} else {
s.count = 0;
for (int i = 0; i < 8; ++i) { s.ids[i] = -1; s.q[i] = 0; }
int best = 0;
float bv = -INFINITY;
for (int k = 0; k < K; ++k)
if (sc[k] > bv) { bv = sc[k]; best = k; }
s.x = sid[best];
}
tok[l] = s.x;
spid = s.x;
}
__syncthreads();
/* One word a lane out to the state plane. */
if (tid < (int)RAD_MTP_COUPLE_STATE_WORDS)
reinterpret_cast<uint32_t*>(so)[tid] = reinterpret_cast<const uint32_t*>(&sst)[tid];
/* The next step reads spid and overwrites sa, part and the Q scratch (the copy above reads
* sst, which the next step writes only after its own barriers). */
}
}
} /* namespace */
int rad_mine_dflash_couple_launch(const RadArgs* a, RadStream stream) {
RadDflashCoupleCall c{};
const int rc = rad_dflash_couple_args(a, &c);
if (rc != RAD_OK) return rc;
return R4D_EMIT(stream, dflash_couple, dim3((unsigned)c.M), dim3(kDfThreads), 0,
c.cand, c.unary, c.hp, c.anchor, c.pred, c.succ, c.card, c.draw, c.tokens,
c.state, c.steps, c.K, c.R, c.vocab, c.anchor_stride, c.ld_cand, c.ld_unary,
c.ld_hp, c.ld_draw, c.ld_tok, c.st_round, c.st_row, c.q_temp);
}
int rad_mine_mtp_couple_propose_launch(const RadArgs* a, RadStream stream) {
RadMtpCoupleProposeCall c{};
const int rc = rad_mtp_couple_propose_args(a, &c);
+539
View File
@@ -0,0 +1,539 @@
/* tests/spechub_dflash_couple_test.cpp -- DFlash2's coupled walk and the verify it feeds, checked
* against the target's own law.
*
* The rule under test (abi/rad_spechub.h): the drafter samples x ~ Q from a law it states exactly,
* the verify keeps x with probability min(1, P(x)/Q(x)) on its own uniform and otherwise draws from
* norm((P - Q)+), and the bonus position is the ordinary pick. Then every emitted token is
* distributed as P, the distribution the non-speculative sampler draws from.
*
* 1. NAMED (P, Q) PAIRS. The emitted token against P by chi-square, and the acceptance
* rate against sum min(P, Q), for the shapes that break a wrong rule: Q = P, Q on fewer tokens
* than P, Q mostly outside P's support, and P cut by top-k, top-p and a temperature the way the
* sampler's candidate plane is cut (index -1, value -inf).
*
* Each chi-square runs over three independent seeds: every p-value above 0.001 and their Fisher
* combination above 0.01 (fisher_ok).
*
* 2. THE WALK'S Q. rad_dflash_couple_walk's state q[] is exactly the softmax of its edge scores
* over the best eight (recomputed here independently), and the drafted x follows it.
*
* 3. THE WHOLE LOOP. A synthetic block drafter (unary scores from the committed text only, the
* pairwise term from the walk's own previous token) drafts three positions a step through
* rad_dflash_couple_walk; the verify runs at n_out + k with the bound state, the first
* rejection ends the step, the bonus row is the ordinary pick. The joint law of the first
* three emitted tokens must be the target's autoregressive law, also when some positions fall
* back to the ordinary verify (status -1) and when Q is sharpened (q_temp < 1).
*
* 4. A greedy request's row keeps the selector's tokens (status 0).
*/
#include "rad_test.h"
#include "rad_sample.h"
#include "rad_spechub.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <map>
#include <numeric>
#include <random>
#include <vector>
namespace {
/* Upper tail of a chi-square with k degrees of freedom (Wilson-Hilferty). */
double chi2_tail(double x, int k) {
if (k <= 0) return 1.0;
const double z = (std::cbrt(x / k) - (1 - 2.0 / (9 * k))) / std::sqrt(2.0 / (9 * k));
return 0.5 * std::erfc(z / std::sqrt(2.0));
}
/* P as the verify computes it: the FP64 softmax over live ids at finite values, by token id. */
std::vector<double> target_law(const std::vector<int32_t>& ids, const std::vector<float>& v,
int vocab) {
std::vector<double> P((size_t)vocab, 0.0);
float top = -INFINITY;
for (size_t j = 0; j < ids.size(); ++j)
if (ids[j] >= 0 && v[j] > top) top = v[j];
double s = 0;
for (size_t j = 0; j < ids.size(); ++j)
if (ids[j] >= 0 && v[j] != -INFINITY) {
const double w = std::exp((double)v[j] - top);
P[(size_t)ids[j]] += w;
s += w;
}
for (double& p : P) p /= s;
return P;
}
/* The sampler's candidate plane over logits `l`: temperature, top-k, then top-p (f32 cumulative in
* descending order, keeping at least one), dropped entries as (-1, -inf), the plane sorted. */
void cut_plane(const std::vector<float>& l, float temp, int top_k, float top_p,
std::vector<int32_t>* ids, std::vector<float>* v) {
const int n = (int)l.size();
std::vector<int> ord((size_t)n);
std::iota(ord.begin(), ord.end(), 0);
std::sort(ord.begin(), ord.end(), [&](int a, int b) { return l[a] > l[b] || (l[a] == l[b] && a < b); });
const int k = top_k > 0 && top_k < n ? top_k : n;
ids->assign((size_t)n, -1);
v->assign((size_t)n, -INFINITY);
for (int i = 0; i < k; ++i) { (*ids)[(size_t)i] = ord[(size_t)i]; (*v)[(size_t)i] = l[ord[(size_t)i]] / temp; }
if (top_p < 1.0f) {
const float mx = (*v)[0];
float sum = 0;
for (int i = 0; i < k; ++i) sum += std::exp((*v)[(size_t)i] - mx);
float cum = 0;
int cut = k;
for (int i = 0; i < k; ++i) {
cum += std::exp((*v)[(size_t)i] - mx) / sum;
if (cum >= top_p) { cut = i + 1; break; }
}
for (int i = cut; i < k; ++i) { (*ids)[(size_t)i] = -1; (*v)[(size_t)i] = -INFINITY; }
}
}
/* sample_pick's rule (the bonus row and an uncoupled row): an f32 inverse CDF at the seed's own
* stream. */
int32_t f32_pick(const std::vector<int32_t>& ids, const std::vector<float>& v, uint64_t seed,
uint64_t pos) {
float mx = -INFINITY, sum = 0;
for (size_t i = 0; i < ids.size(); ++i) if (ids[i] >= 0) mx = std::max(mx, v[i]);
for (size_t i = 0; i < ids.size(); ++i) if (ids[i] >= 0) sum += std::exp(v[i] - mx);
const float u = rad_sample_uniform01(seed ^ RAD_SAMPLE_KEY_PICK, pos);
float cum = 0;
int32_t last = -1;
for (size_t i = 0; i < ids.size(); ++i) {
if (ids[i] < 0) continue;
if (v[i] > -INFINITY) last = ids[i];
cum += std::exp(v[i] - mx) / sum;
if (u < cum) return ids[i];
}
return last;
}
uint16_t f2bf(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
return (uint16_t)(u >> 16);
}
/* Chi-square of counts against a law; dof counts the cells with mass. A cell without mass must be
* empty. */
double chi_tail(const std::vector<int64_t>& cnt, const std::vector<double>& P, int64_t n) {
double chi = 0;
int dof = -1;
for (size_t i = 0; i < P.size(); ++i) {
if (P[i] == 0) { CHECK_EQ(cnt[i], (int64_t)0); continue; }
const double e = P[i] * (double)n;
chi += ((double)cnt[i] - e) * ((double)cnt[i] - e) / e;
++dof;
}
return chi2_tail(chi, dof);
}
/* Independent repeats of one check: every p-value above 0.001, and their Fisher combination,
* -2 sum ln p ~ chi2(2n), above 0.01. A single fixed seed would pass or fail one chi-square draw;
* several, combined, separate a biased rule from an unlucky seed. */
bool fisher_ok(const std::vector<double>& p, double* combined) {
double x = 0;
bool each = true;
for (double v : p) { x += -2.0 * std::log(std::max(v, 1e-300)); each = each && v > 0.001; }
*combined = chi2_tail(x, 2 * (int)p.size());
return each && *combined > 0.01;
}
/* One named case: the target plane (ids, v) and the draft's eight (id, score) slots. Every trial
* draws x ~ Q at its own coordinate, then couples. */
void run_case(const char* name, const std::vector<int32_t>& ids, const std::vector<float>& v,
int vocab, const int32_t* qid, const float* qv, int draws = 100000) {
std::vector<double> pv;
for (uint64_t rep = 0; rep < 3; ++rep) {
const std::vector<double> P = target_law(ids, v, vocab);
RadMtpCoupleState base{};
base.draw.seed = rad_sample_splitmix64(0xC0FFEEull + (uint64_t)vocab * 7919 + rep);
base.draw.mode = 1;
base.status = 1;
base.round = 1;
REQUIRE(rad_mtp_couple_build_q(qid, qv, vocab, &base));
double want_acc = 0;
{
std::vector<double> Q((size_t)vocab, 0.0);
for (int i = 0; i < base.count; ++i) Q[(size_t)base.ids[i]] = base.q[i];
for (int i = 0; i < vocab; ++i) want_acc += std::min(P[(size_t)i], Q[(size_t)i]);
}
std::vector<int64_t> cnt((size_t)vocab, 0);
int64_t acc = 0;
const uint64_t seed = base.draw.seed;
for (int t = 0; t < draws; ++t) {
RadMtpCoupleState s = base;
s.draw.base = (uint64_t)t;
s.x = s.ids[rad_mtp_couple_pick(s, rad_spechub_uniform(seed, s.draw.base,
RAD_MTP_COUPLE_KEY_DRAFT + 1))];
int32_t out = -1;
REQUIRE(rad_mtp_couple_decide(s, ids.data(), v.data(), (int64_t)ids.size(), vocab,
rad_spechub_uniform(seed, (uint64_t)t, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(seed, (uint64_t)t, RAD_SAMPLE_KEY_RESID),
&out));
REQUIRE(out >= 0 && out < vocab);
++cnt[(size_t)out];
acc += out == s.x;
}
const double tail = chi_tail(cnt, P, draws);
const double rate = (double)acc / draws;
std::fprintf(stderr, " %-34s chi2 p %.3f acceptance %.4f (sum min(P,Q) %.4f)\n", name, tail,
rate, want_acc);
pv.push_back(tail);
/* Q = P sums to one only to rounding, so the variance is clamped at zero. */
const double sd = std::sqrt(std::max(0.0, want_acc * (1 - want_acc)) / draws) + 1e-9;
CHECK_NEAR(rate, want_acc, 5.0 * sd);
}
double comb = 0;
const bool ok = fisher_ok(pv, &comb);
std::fprintf(stderr, " %-34s combined p %.3f over %zu seeds\n", name, comb, pv.size());
CHECK(ok);
}
/* Eight slots from up to eight (id, score) pairs. */
void slots(std::initializer_list<std::pair<int, float>> in, int32_t* id, float* v) {
int n = 0;
for (const auto& p : in) { id[n] = p.first; v[n] = p.second; ++n; }
for (; n < 8; ++n) { id[n] = -1; v[n] = -INFINITY; }
}
} /* namespace */
TEST(the_coupled_token_follows_the_target_for_named_pairs) {
const int V = 24;
std::vector<float> l((size_t)V);
for (int i = 0; i < V; ++i) l[(size_t)i] = 2.0f - 0.35f * (float)i + 0.2f * std::sin((float)i);
std::vector<int32_t> ids;
std::vector<float> v;
int32_t qid[8];
float qv[8];
/* Q = P: P on eight tokens (top-k 8) and Q the same scores. Acceptance must be 1. */
cut_plane(l, 1.0f, 8, 1.0f, &ids, &v);
slots({{0, l[0]}, {1, l[1]}, {2, l[2]}, {3, l[3]}, {4, l[4]}, {5, l[5]}, {6, l[6]}, {7, l[7]}},
qid, qv);
run_case("Q = P", ids, v, V, qid, qv);
/* Q on two tokens, P on all 24. */
cut_plane(l, 1.0f, 0, 1.0f, &ids, &v);
slots({{0, 1.0f}, {3, 0.2f}}, qid, qv);
run_case("Q support smaller than P", ids, v, V, qid, qv);
/* Q mostly outside P's support: P is the top 5, Q sits on 4..11. */
cut_plane(l, 1.0f, 5, 1.0f, &ids, &v);
slots({{4, 0.0f}, {5, 0.4f}, {6, 0.9f}, {7, 0.1f}, {8, 0.3f}, {9, 0.0f}, {10, 0.2f},
{11, 0.5f}}, qid, qv);
run_case("Q mostly outside P (disjoint-ish)", ids, v, V, qid, qv);
/* The service's settings over a flatter target: top-k 20, top-p 0.95, T 1. Q the first eight at
* a sharper temperature, as a draft head would be. */
std::vector<float> flat((size_t)V);
for (int i = 0; i < V; ++i) flat[(size_t)i] = -0.12f * (float)i;
cut_plane(flat, 1.0f, 20, 0.95f, &ids, &v);
slots({{0, 0.0f}, {1, -0.2f}, {2, -0.4f}, {3, -0.6f}, {4, -0.8f}, {5, -1.0f}, {6, -1.2f},
{7, -1.4f}}, qid, qv);
run_case("top_k 20 + top_p 0.95, sharp Q", ids, v, V, qid, qv);
/* top-p alone cutting deep into Q's support. */
cut_plane(l, 1.0f, 0, 0.6f, &ids, &v);
slots({{0, l[0]}, {1, l[1]}, {2, l[2]}, {3, l[3]}, {4, l[4]}, {5, l[5]}, {6, l[6]}, {7, l[7]}},
qid, qv);
run_case("top_p 0.6 inside Q's support", ids, v, V, qid, qv);
/* top-k 3 with a temperature, Q flatter than P. */
cut_plane(l, 0.7f, 3, 1.0f, &ids, &v);
slots({{0, 0.3f}, {1, 0.2f}, {2, 0.1f}, {3, 0.0f}, {12, 0.0f}}, qid, qv);
run_case("top_k 3 at T 0.7, flat Q", ids, v, V, qid, qv);
/* A peaked Q on P's second token. */
cut_plane(l, 1.0f, 0, 1.0f, &ids, &v);
slots({{1, 6.0f}, {0, 0.0f}}, qid, qv);
run_case("peaked Q on P's runner-up", ids, v, V, qid, qv);
}
namespace {
/* A synthetic block drafter over kV tokens. Its candidate lattice for a step depends only on the
* committed text (a block drafter sees nothing of its own picks); the pairwise codebooks make the
* walk's Q at position l depend on its own x_{l-1}. */
constexpr int kV = 6, kK = 4, kR = 16, kSteps = 3;
uint64_t ctx_hash(const std::vector<int32_t>& ctx, uint64_t salt) {
uint64_t h = salt;
for (int32_t t : ctx) h = rad_sample_splitmix64(h ^ (uint64_t)(t + 1) * 0x100000001b3ull);
return h;
}
float unit(uint64_t h) { return (float)((double)(h >> 40) / 16777216.0 * 2.0 - 1.0); }
/* The target: hash logits of the context, top 4 at T 0.8 (so the drafter's candidates often lie
* outside P's support). */
void target_plane(const std::vector<int32_t>& ctx, std::vector<int32_t>* ids,
std::vector<float>* v) {
const uint64_t h = ctx_hash(ctx, 0xabcdefull);
std::vector<float> l((size_t)kV);
for (int i = 0; i < kV; ++i) l[(size_t)i] = 2.0f * unit(rad_sample_splitmix64(h + (uint64_t)i));
cut_plane(l, 0.8f, 4, 1.0f, ids, v);
}
struct Lattice {
int32_t cand[kSteps * kK];
float unary[kSteps * kK];
uint16_t hp[kSteps * kR];
};
/* Position l's candidates: kK distinct ids from a hash of the committed text and l, with scores. */
void draft_lattice(const std::vector<int32_t>& committed, Lattice* L) {
for (int l = 0; l < kSteps; ++l) {
const uint64_t h = ctx_hash(committed, 0x5151ull + (uint64_t)l);
int ord[kV];
for (int i = 0; i < kV; ++i) ord[i] = i;
for (int i = kV - 1; i > 0; --i)
std::swap(ord[i], ord[rad_sample_splitmix64(h + 77 + (uint64_t)i) % (uint64_t)(i + 1)]);
for (int c = 0; c < kK; ++c) {
L->cand[l * kK + c] = ord[c];
L->unary[l * kK + c] = 1.5f * unit(rad_sample_splitmix64(h + 1000 + (uint64_t)c));
}
for (int r = 0; r < kR; ++r)
L->hp[l * kR + r] = f2bf(unit(rad_sample_splitmix64(h + 5000 + (uint64_t)r)));
}
}
struct Codebooks {
uint16_t pred[kV * kR], succ[kV * kR];
Codebooks() {
for (int i = 0; i < kV * kR; ++i) {
pred[i] = f2bf(unit(rad_sample_splitmix64(0x9000ull + (uint64_t)i)));
succ[i] = f2bf(unit(rad_sample_splitmix64(0xA000ull + (uint64_t)i)));
}
}
};
/* The target's own autoregressive law of the first `n` tokens, by sequence. */
double ar_prob(const std::vector<int32_t>& seq) {
double p = 1;
std::vector<int32_t> ctx;
for (int32_t t : seq) {
std::vector<int32_t> ids;
std::vector<float> v;
target_plane(ctx, &ids, &v);
p *= target_law(ids, v, kV)[(size_t)t];
ctx.push_back(t);
}
return p;
}
/* The engine's loop over whole steps. `fallback_every` > 0 refuses the draw's card every that many
* steps (status -1: the walk's argmax and the ordinary verify). Returns the acceptance rate. */
double run_loop(int trials, float q_temp, int fallback_every, uint64_t salt, double* p_value) {
const int L = 3;
static const Codebooks cb;
std::map<std::vector<int32_t>, int64_t> cnt;
int64_t drafted = 0, accepted = 0;
for (int t = 0; t < trials; ++t) {
const uint64_t seed = rad_sample_splitmix64(salt + (uint64_t)t);
std::vector<int32_t> out;
int step = 0;
while ((int)out.size() < L) {
const uint64_t n_out = out.size();
Lattice lat;
draft_lattice(out, &lat);
RadMtpCoupleDraw d{seed, n_out, 1, 0, 1u};
const bool card_ok = !(fallback_every > 0 && step % fallback_every == fallback_every - 1);
int32_t tok[kSteps] = {0, 0, 0};
RadMtpCoupleState st[kSteps];
const int32_t anchor = out.empty() ? 0 : out.back();
rad_dflash_couple_walk(lat.cand, lat.unary, kK, kK, lat.hp, kR, anchor, cb.pred,
cb.succ, kK, kR, kV, kSteps, q_temp, d, card_ok, tok,
reinterpret_cast<uint32_t*>(st), RAD_MTP_COUPLE_STATE_WORDS);
/* The engine's bind: the verify position after the commit. */
for (int k = 0; k < kSteps; ++k) st[k].pos = rad_mtp_couple_verify_pos(n_out, k + 1);
std::vector<int32_t> ctx = out;
for (int k = 0; k <= kSteps && (int)out.size() < L; ++k) {
std::vector<int32_t> ids;
std::vector<float> v;
target_plane(ctx, &ids, &v);
const uint64_t pos = n_out + (uint64_t)k;
int32_t y = -1;
bool more = false;
if (k < kSteps) {
++drafted;
if (rad_mtp_couple_binds(st[k], 1, seed, n_out, k, tok[k], kV)) {
const bool ok = rad_mtp_couple_decide(
st[k], ids.data(), v.data(), (int64_t)ids.size(), kV,
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID), &y);
CHECK(ok);
if (!ok) return 0.0;
} else {
CHECK(!card_ok);
CHECK_EQ(st[k].status, -1);
y = f32_pick(ids, v, seed, pos);
}
more = y == tok[k];
accepted += more;
} else {
y = f32_pick(ids, v, seed, pos);
}
out.push_back(y);
ctx.push_back(y);
if (!more) break;
}
++step;
}
out.resize((size_t)L);
++cnt[out];
}
std::vector<int64_t> c;
std::vector<double> P;
for (int code = 0; code < kV * kV * kV; ++code) {
std::vector<int32_t> seq((size_t)L);
for (int i = 0, x = code; i < L; ++i, x /= kV) seq[(size_t)i] = x % kV;
P.push_back(ar_prob(seq));
const auto it = cnt.find(seq);
c.push_back(it == cnt.end() ? 0 : it->second);
}
*p_value = chi_tail(c, P, trials);
return drafted ? (double)accepted / (double)drafted : 0.0;
}
} /* namespace */
/* THE WALK'S Q: the stored law is the softmax of the walk's own scores over its best eight, and x
* follows it. Scores are recomputed here from the lattice in FP64 (the product of two bf16 values
* is exact in f32 and in f64), so the comparison is to rounding. */
TEST(the_walk_stores_and_samples_the_softmax_of_its_edge_scores) {
static const Codebooks cb;
Lattice lat;
draft_lattice({2, 5, 1}, &lat);
const float q_temp = 0.8f;
const int32_t anchor = 1;
std::vector<int64_t> cnt((size_t)kV, 0);
RadMtpCoupleState first{};
const int draws = 100000;
for (int t = 0; t < draws; ++t) {
RadMtpCoupleDraw d{77, (uint64_t)t, 1, 0, 1u};
int32_t tok[kSteps] = {0, 0, 0};
RadMtpCoupleState st[kSteps];
rad_dflash_couple_walk(lat.cand, lat.unary, kK, kK, lat.hp, kR, anchor, cb.pred, cb.succ,
kK, kR, kV, kSteps, q_temp, d, true, tok,
reinterpret_cast<uint32_t*>(st), RAD_MTP_COUPLE_STATE_WORDS);
for (int k = 0; k < kSteps; ++k) {
CHECK_EQ(st[k].status, 1);
CHECK_EQ(st[k].round, k + 1);
CHECK_EQ(st[k].x, tok[k]);
CHECK(rad_mtp_couple_state_valid(st[k], kV));
}
if (t == 0) first = st[0];
++cnt[(size_t)tok[0]];
}
/* Position 0's predecessor is the anchor, so its Q is the same on every trial. */
double sc[kK], top = -1e300;
for (int c = 0; c < kK; ++c) {
double e = 0;
const int32_t id = lat.cand[c];
for (int r = 0; r < kR; ++r)
e += (double)rad_dflash_bf2f(cb.pred[anchor * kR + r]) * rad_dflash_bf2f(lat.hp[r]) *
rad_dflash_bf2f(cb.succ[id * kR + r]);
sc[c] = ((double)lat.unary[c] + e) / q_temp;
top = std::max(top, sc[c]);
}
double z = 0;
for (int c = 0; c < kK; ++c) z += std::exp(sc[c] - top);
std::vector<double> Q((size_t)kV, 0.0);
for (int c = 0; c < kK; ++c) Q[(size_t)lat.cand[c]] = std::exp(sc[c] - top) / z;
CHECK_EQ(first.count, kK);
for (int i = 0; i < first.count; ++i)
CHECK_NEAR(first.q[i], Q[(size_t)first.ids[i]], 1e-5);
const double tail = chi_tail(cnt, Q, draws);
std::fprintf(stderr, " position 0's drafts against the stated Q: chi2 p %.3f\n", tail);
CHECK(tail > 0.01);
}
namespace {
void loop_case(const char* name, float q_temp, int fallback_every) {
std::vector<double> pv;
for (uint64_t rep = 0; rep < 3; ++rep) {
double p = 0;
const double acc = run_loop(150000, q_temp, fallback_every,
0x5eed0000ull + rep * 0x100000000ull, &p);
std::fprintf(stderr, " joint law of 3 tokens, %s: chi2 p %.3f, acceptance %.3f\n", name,
p, acc);
pv.push_back(p);
}
double comb = 0;
const bool ok = fisher_ok(pv, &comb);
std::fprintf(stderr, " joint law of 3 tokens, %s: combined p %.3f over %zu seeds\n", name,
comb, pv.size());
CHECK(ok);
}
} /* namespace */
TEST(the_coupled_walk_emits_the_target_law_over_steps) {
loop_case("q_temp 1", 1.0f, 0);
}
TEST(the_coupled_walk_stays_exact_with_a_sharpened_q_and_ordinary_fallback_rows) {
loop_case("q_temp 0.5", 0.5f, 0);
loop_case("every 2nd step status -1", 1.0f, 2);
}
TEST(a_greedy_row_keeps_the_selectors_walk) {
static const Codebooks cb;
Lattice lat;
draft_lattice({3}, &lat);
RadMtpCoupleDraw d{5, 9, 1, 0, 0u};
int32_t tok[kSteps] = {4, 0, 2};
RadMtpCoupleState st[kSteps];
rad_dflash_couple_walk(lat.cand, lat.unary, kK, kK, lat.hp, kR, 3, cb.pred, cb.succ, kK, kR,
kV, kSteps, 1.0f, d, true, tok, reinterpret_cast<uint32_t*>(st),
RAD_MTP_COUPLE_STATE_WORDS);
const int32_t want[kSteps] = {4, 0, 2};
for (int k = 0; k < kSteps; ++k) {
CHECK_EQ(tok[k], want[k]);
CHECK_EQ(st[k].status, 0);
CHECK_EQ(st[k].x, want[k]);
CHECK_EQ(st[k].round, k + 1);
CHECK_EQ(st[k].count, 0);
CHECK(std::memcmp(&st[k].draw, &d, sizeof d) == 0);
}
}
/* A draw staged for another card (status -1) takes the walk's argmax over its own scores, which is
* what dflash_select picks over the same lattice up to rounding. */
TEST(a_refused_draw_takes_the_walks_argmax) {
static const Codebooks cb;
Lattice lat;
draft_lattice({0, 4}, &lat);
RadMtpCoupleDraw d{5, 9, 1, 3, 1u};
int32_t tok[kSteps] = {-7, -7, -7};
RadMtpCoupleState st[kSteps];
rad_dflash_couple_walk(lat.cand, lat.unary, kK, kK, lat.hp, kR, 4, cb.pred, cb.succ, kK, kR,
kV, kSteps, 1.0f, d, false, tok, reinterpret_cast<uint32_t*>(st),
RAD_MTP_COUPLE_STATE_WORDS);
int32_t pid = 4;
for (int k = 0; k < kSteps; ++k) {
CHECK_EQ(st[k].status, -1);
CHECK_EQ(st[k].count, 0);
double best = -1e300;
int32_t want = -1;
for (int c = 0; c < kK; ++c) {
double e = 0;
const int32_t id = lat.cand[k * kK + c];
for (int r = 0; r < kR; ++r)
e += (double)rad_dflash_bf2f(cb.pred[pid * kR + r]) *
rad_dflash_bf2f(lat.hp[k * kR + r]) * rad_dflash_bf2f(cb.succ[id * kR + r]);
const double s = (double)lat.unary[k * kK + c] + e;
if (s > best + 1e-5) { best = s; want = id; }
}
CHECK_EQ(tok[k], want);
CHECK_EQ(st[k].x, tok[k]);
pid = tok[k];
}
}
RAD_TEST_MAIN()
+6 -6
View File
@@ -94,21 +94,21 @@ TEST(spechub_wiring_the_device_rows_are_production_and_the_oracle_rows_are_refer
}
CHECK_EQ(dev + host, p.count());
#ifdef RAD_SPECHUB_WITH_DEVICE
CHECK_EQ(dev, 2);
CHECK_EQ(host, 2);
CHECK_EQ(dev, 3);
CHECK_EQ(host, 3);
#else
CHECK_EQ(dev, 0);
CHECK_EQ(host, 2);
CHECK_EQ(host, 3);
#endif
/* Both ops must have at least one production row on a device build. This is the property the
/* Every op must have at least one production row on a device build. This is the property the
* gate reads: with it, the coupling is servable without --debug-accept-reference-kernels. */
const std::vector<std::string> refonly = reference_only_ops(p, is_ref);
#ifdef RAD_SPECHUB_WITH_DEVICE
CHECK_EQ(refonly.size(), (size_t)0);
#else
/* No card: both ops are oracle-only, and the gate must still see them as such. */
CHECK_EQ(refonly.size(), (size_t)2);
/* No card: every op is oracle-only, and the gate must still see them as such. */
CHECK_EQ(refonly.size(), (size_t)3);
#endif
}