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

+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);