spec: --draft-verify token|block|traversal for the coupled MTP chain

--draft-coupling verifies each row of the chain on its own. Two lossless
sequence-level verifiers accept more drafts from the same chain: Block
Verification (arXiv 2403.10444) decides the whole chain at once, Traversal
Verification (arXiv 2505.12398) walks a path from its last draft back to its
first. --draft-verify token (default) is the engine as it was; block switches
the coupling on; traversal needs it and is refused otherwise.

Block: the sampler marks the consecutive bound rows of a request with the
block's length (RadMtpCoupleState::blk) and mtp_couple_verify decides the block
on the workgroup of its round-1 row, every FP64 sum a fixed lane tree so the
result is the host reference's bit for bit. The wide-plane serial helper is a
kernel of its own, which leaves couple_verify without scratch.

Traversal: a new op mtp_trav_verify takes the step's topology (parent row, draft
token per row) and decides a request on one workgroup, 0 bytes of scratch: the
target's law as integer masses of a fixed-point exponential, the walk in FP64.
Its header and kernel also handle nodes with several children (Gumbel-top-k and
RheoSampling siblings); the serial head here drafts one, so that part has no
producer yet and is covered by the tests only.

RadMtpCoupleState grows from 152 to 168 bytes (nkids, scheme, blk), so
RAD_ABI_VERSION is 41.

Exactness: mtp_block_test enumerates the draft tree of a toy model and runs
chi-square over the real verify code; mtp_rrs_test runs chi-square and an
exhaustive enumeration of the walk (worst |joint - P| 7e-14) with negative
controls that fail; spechub_device_test compares the device rows with the host
rows. Measured on Qwen3.8-Flash-Next IQR-V4 (TP2, MTP chain 3, coupling) on our
branch: about +1% tok/s with traversal, +4.6% at T 1.0 top_k 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Code000andClaude Opus 5.5 authored and StillDeadcode committed 2026-11-17 21:49:45 +01:00
1 parent 9b6eba80c6
commit d0fd4aa1bb
31 files changed
+5022 -30

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ extern "C" {
* version is refused at load with both versions printed. Each also exports the layout's fingerprint
* (rad_abi_layout.h), so two layouts given one number are refused as well. A new optional export
* (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default. */
#define RAD_ABI_VERSION 40u
#define RAD_ABI_VERSION 41u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
+4
View File
@@ -949,3 +949,7 @@ ABI_FIELD(RadMtpCoupleState, x)
ABI_FIELD(RadMtpCoupleState, count)
ABI_FIELD(RadMtpCoupleState, ids)
ABI_FIELD(RadMtpCoupleState, q)
ABI_FIELD(RadMtpCoupleState, nkids)
ABI_FIELD(RadMtpCoupleState, scheme)
ABI_FIELD(RadMtpCoupleState, blk)
ABI_FIELD(RadMtpCoupleState, pad_)
+323
View File
@@ -0,0 +1,323 @@
/* rad_mtp_block.h -- BLOCK VERIFICATION of a linear MTP draft chain (--draft-verify block).
*
* Sun, Mendlovic, Leviathan, Aharoni, Beirami, Ro, Suresh, "Block Verification Accelerates
* Speculative Decoding" (arXiv 2403.10444): the chain's draft tokens X_1 .. X_g are accepted or
* rejected JOINTLY. Token-wise speculative sampling (what --draft-coupling does at each row) is
* optimal per token; block verification is optimal for the whole block: the expected number of
* accepted tokens is never lower and the output law is the target's, exactly.
*
* With P_i = the target's law after X^i (the sampler's filtered candidate softmax at verify row i,
* i = 0 .. g-1) and Q_{i+1} = the head's law the draft X_{i+1} was sampled from (the coupled state
* of round i + 1, the FP64 softmax of the reranked top 8):
*
* p_0 = 1, p_i = min(1, p_{i-1} P_{i-1}(X_i) / Q_i(X_i)) i = 1 .. g
* S_i = sum_x max(p_i P_i(x) - Q_{i+1}(x), 0) i = 0 .. g-1
* h_i = S_i / (S_i + 1 - p_i) (i < g), h_g = p_g
*
* for i = g, g-1, ..., 0: accept the block's first i tokens with probability h_i; the first
* success is tau. (h_0 = 1: it always stops.)
* tau = g: X_1 .. X_g are emitted and the next token is the ordinary draw from P_g.
* tau < g: X_1 .. X_tau are emitted, then Y ~ max(p_tau P_tau - Q_{tau+1}, 0) normalised.
*
* Exactness is checked in tests/mtp_block_test.cpp by exact enumeration of the draft tree of a toy
* model (the law of the emitted tokens computed in closed form, to 1e-12) and by a chi-square of the
* real device-shared code, with a negative control (the same rule with a wrong residual).
*
* Y may equal X_{tau+1}; the core then takes that draft as accepted (ADV_ACCEPT: "the draft is the
* sampler's token at this row") and reads the next row, which keeps its ordinary pick: a draw from
* the target's law given exactly the tokens emitted so far, so the extra tokens continue the same
* autoregressive sample. The verify op therefore writes only rows 0 .. tau of the block and leaves
* every later row alone.
*
* Relation to --draft-coupling: the DRAFT half is shared (x ~ Q at temperature 1 from the head's
* top 8, coupled states with their FP64 Q); only the verify half differs. Maximal coupling decides
* row k from P_k and Q_{k+1} alone, so it is a per-row rule the core's token comparison walks
* unchanged. Block verification decides row k from the rows after it (h_i for i > k), so the two
* rules cannot be applied to the same row; `--draft-verify block` replaces the coupling's verify
* and requires the coupled drafting (it switches it on), and it is for a LINEAR chain; Traversal
* Verification (abi/rad_mtp_traversal.h, 2505.12398) is the walk that also covers a node with
* several children.
*/
#ifndef RAD_MTP_BLOCK_H
#define RAD_MTP_BLOCK_H
#include "rad_spechub.h"
#ifdef __cplusplus
#ifdef __HIPCC__
#define RAD_BLK_HD __host__ __device__
#else
#define RAD_BLK_HD
#endif
#define RAD_MTP_BLOCK_MAX RAD_MTP_COUPLE_MAX_ROUNDS /* g: the chain's longest block */
#define RAD_MTP_BLOCK_KEY_STOP 0x424c4b53544f5000ull /* the h_i uniforms, per block */
/* Summation structure. The device decides a block with one workgroup of RAD_MTP_BLOCK_LANES
* threads, so every FP64 sum over a row's candidate plane is DEFINED as this fixed tree, which the
* host reference mirrors operation for operation (FP64 addition is not associative: the tree is
* the definition, not an approximation):
* - plane slot j belongs to lane j % LANES; a lane adds its live slots in ascending j;
* - the lanes are reduced inside each group of RAD_MTP_BLOCK_WAVE by the butterfly
* a[l] = a[l] + a[l ^ d], d = 16, 8, 4, 2, 1 (every lane of a group ends with the same bits),
* and the LANES / WAVE group sums are added as ((g0 + g1) + (g2 + g3)).
* The exp() of a slot is the same libm / device function on both sides, as before. */
#define RAD_MTP_BLOCK_LANES 128
#define RAD_MTP_BLOCK_WAVE 32
/* One verify row's candidate plane, dense (n slots, holes id < 0 and -inf scores skipped), with
* `valid` and `top` the scan of the whole plane (rad_mtp_block_scan makes it on the host; the
* device reduces the same two values across its workgroup: a max and an OR are order free). */
struct RadBlockRow {
const int32_t* ids;
const float* val;
int64_t n;
int valid;
float top;
};
/* The dense row's validity and maximum, as rad_mtp_couple_decide scans them. */
static inline RAD_BLK_HD void rad_mtp_block_scan(RadBlockRow* r, int64_t vocab) {
float top = -INFINITY;
int valid = 1;
for (int64_t j = 0; j < r->n; ++j) {
if (r->ids[j] < 0) continue;
if (r->ids[j] >= vocab || r->val[j] != r->val[j] || r->val[j] == INFINITY) valid = 0;
else if (r->val[j] > top) top = r->val[j];
}
r->valid = valid;
r->top = top;
}
static inline RAD_BLK_HD bool rad_mtp_block_live(int32_t id, float v) { return id >= 0 && v != -INFINITY; }
/* A lane's partial sums of one row: v[0..7] the mass on Q's ids (by their place in the state),
* v[8] the mass off Q's support, v[9] the total. */
struct RadBlockAcc { double v[10]; };
static inline RAD_BLK_HD int rad_mtp_block_find(const RadMtpCoupleState& s, int32_t id) {
int k = 0;
while (k < s.count && id != s.ids[k]) ++k;
return k;
}
/* Adds the live slot (id, v) to a lane's partial. */
static inline RAD_BLK_HD void rad_mtp_block_acc_add(RadBlockAcc* a, const RadMtpCoupleState& s,
int32_t id, float v, float top) {
const double w = ::exp((double)v - top);
const int k = rad_mtp_block_find(s, id);
for (int kk = 0; kk < 8; ++kk) a->v[kk] += kk == k ? w : 0.0;
a->v[8] += k >= s.count ? w : 0.0;
a->v[9] += w;
}
/* The lanes' partials reduced by the tree above (the host form; the device does the butterfly with
* shuffles and adds the four group sums the same way). */
static inline RAD_BLK_HD RadBlockAcc rad_mtp_block_tree(const RadBlockAcc* lane) {
RadBlockAcc grp[RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE];
for (int w = 0; w < RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE; ++w) {
RadBlockAcc a[RAD_MTP_BLOCK_WAVE], t[RAD_MTP_BLOCK_WAVE];
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) a[l] = lane[w * RAD_MTP_BLOCK_WAVE + l];
for (int d = RAD_MTP_BLOCK_WAVE / 2; d > 0; d >>= 1) {
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) t[l] = a[l];
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l)
for (int c = 0; c < 10; ++c) a[l].v[c] = t[l].v[c] + t[l ^ d].v[c];
}
grp[w] = a[0];
}
RadBlockAcc o;
for (int c = 0; c < 10; ++c) o.v[c] = (grp[0].v[c] + grp[1].v[c]) + (grp[2].v[c] + grp[3].v[c]);
return o;
}
/* P_i over Q_{i+1}'s support (pq, normalised, duplicate candidates aggregated), the mass off that
* support (pout), the normaliser `sum` and the index `ix` of the draft token in the state's ids. */
struct RadBlockStat {
double pq[8];
double pout, sum;
int ix;
};
/* The stat from the reduced partials `t` (what the device builds from its workgroup's tree). */
static inline RAD_BLK_HD bool rad_mtp_block_stat_from(const RadBlockAcc& t, int valid, float top,
const RadMtpCoupleState& s, RadBlockStat* o) {
if (!valid || top == -INFINITY) return false;
const double sum = t.v[9];
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
o->ix = -1;
for (int k = 0; k < 8; ++k) o->pq[k] = k < s.count ? t.v[k] : 0.0;
for (int k = 0; k < s.count; ++k) {
o->pq[k] /= sum;
if (s.ids[k] == s.x) o->ix = k;
}
o->pout = t.v[8] / sum;
o->sum = sum;
return o->ix >= 0;
}
static inline RAD_BLK_HD bool rad_mtp_block_stat(const RadBlockRow& r, const RadMtpCoupleState& s,
RadBlockStat* o) {
if (!r.valid || r.top == -INFINITY) return false;
RadBlockAcc lane[RAD_MTP_BLOCK_LANES];
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l)
for (int c = 0; c < 10; ++c) lane[l].v[c] = 0;
for (int64_t j = 0; j < r.n; ++j)
if (rad_mtp_block_live(r.ids[j], r.val[j]))
rad_mtp_block_acc_add(&lane[j % RAD_MTP_BLOCK_LANES], s, r.ids[j], r.val[j], r.top);
return rad_mtp_block_stat_from(rad_mtp_block_tree(lane), r.valid, r.top, s, o);
}
/* The block's weights. p[i] (i = 0 .. g), h[i] (i = 0 .. g). */
struct RadBlockPlan {
int g;
double p[RAD_MTP_BLOCK_MAX + 1];
double h[RAD_MTP_BLOCK_MAX + 1];
double s[RAD_MTP_BLOCK_MAX + 1]; /* S_i, the residual's mass (s[g] unused) */
};
/* The residual mass of one token of row i at weight p: max(p P(x) - Q(x), 0) on Q's support,
* p P(x) off it. */
static inline RAD_BLK_HD double rad_mtp_block_resid_sum(const RadMtpCoupleState& s,
const RadBlockStat& t, double p) {
double r = p * t.pout;
for (int k = 0; k < s.count; ++k) r += rad_spechub_positive(p * t.pq[k] - s.q[k]);
return r;
}
/* st[i] / stat[i] for i = 0 .. g-1. */
static inline RAD_BLK_HD void rad_mtp_block_plan(const RadMtpCoupleState* st,
const RadBlockStat* stat, int g,
RadBlockPlan* o) {
o->g = g;
o->p[0] = 1.0;
for (int i = 0; i < g; ++i) {
const double ratio = stat[i].pq[stat[i].ix] / st[i].q[stat[i].ix];
const double v = o->p[i] * ratio;
o->p[i + 1] = v < 1.0 ? v : 1.0;
}
for (int i = 0; i < g; ++i) {
const double S = rad_mtp_block_resid_sum(st[i], stat[i], o->p[i]);
o->s[i] = S;
const double den = S + (1.0 - o->p[i]);
o->h[i] = (den > 0 && rad_spechub_finite(den)) ? S / den : 1.0;
}
o->s[g] = 0;
o->h[g] = o->p[g];
}
/* tau: the first i, counting down from g, whose uniform falls below h_i. The uniforms are keyed by
* the block's first output position, so no row's own draws are reused. */
static inline RAD_BLK_HD int rad_mtp_block_tau(const RadBlockPlan& pl, uint64_t seed, uint64_t pos0) {
for (int i = pl.g; i > 0; --i)
if (rad_spechub_uniform(seed, pos0, RAD_MTP_BLOCK_KEY_STOP + (uint64_t)i) < pl.h[i]) return i;
return 0;
}
/* One lane's partials of the residual draw: `off` the off-support masses p * (w / sum) (slots whose
* id is not among Q's), `all` the plain weights (the fallback draw from P itself), and the last
* positive id of each, in the lane's slot order. */
struct RadBlockLane { double off, all; int32_t last_off, last_all; };
static inline RAD_BLK_HD void rad_mtp_block_lane_add(RadBlockLane* a, const RadMtpCoupleState& s,
const RadBlockStat& t, double p, int32_t id,
float v, float top) {
const double w = ::exp((double)v - top);
a->all += w;
if (w > 0) a->last_all = id;
if (rad_mtp_block_find(s, id) >= s.count) {
const double m = p * (w / t.sum);
a->off += m;
if (m > 0) a->last_off = id;
}
}
/* Y ~ max(p P - Q, 0) normalised (state s, row r, stat t) with the uniform u in [0, 1). The mass
* is walked in a fixed order: the ids of Q (place k = 0 .. count-1, mass max(p pq[k] - q[k], 0)),
* then the other live slots lane by lane (the lanes of the tree above, each lane's slots in
* ascending order; the lane totals are added in lane order). The walk subtracts the masses from
* c = u * total and stops at the first negative; inside the lane it stops in, the walk restarts
* from the c at the lane's start, so the structure is exactly what the workgroup computes. When
* the total underflows to zero (FP64 cancellation with p = 1: P == Q) Y is drawn from P itself
* over all live slots in the same lane order, a branch that depends on (P, Q) only. False: no live
* candidate. */
static inline RAD_BLK_HD bool rad_mtp_block_resid_walk(const RadBlockRow& r,
const RadMtpCoupleState& s,
const RadBlockStat& t, double p, double u,
const RadBlockLane* lane, int32_t* out) {
double on[8];
double total = 0;
for (int k = 0; k < s.count; ++k) { on[k] = rad_spechub_positive(p * t.pq[k] - s.q[k]); total += on[k]; }
double offt = 0;
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) offt += lane[l].off;
total += offt;
const bool resid = total > 0 && rad_spechub_finite(total);
double c = resid ? u * total : u * t.sum;
int32_t last = -1;
if (resid) {
for (int k = 0; k < s.count; ++k)
if (on[k] > 0) { last = s.ids[k]; c -= on[k]; if (c < 0) { *out = last; return true; } }
}
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) {
const double T = resid ? lane[l].off : lane[l].all;
const int32_t ll = resid ? lane[l].last_off : lane[l].last_all;
if (!(T > 0)) continue;
if (ll >= 0) last = ll;
if (c - T < 0) {
double cl = c;
int32_t lastl = -1;
for (int64_t j = l; j < r.n; j += RAD_MTP_BLOCK_LANES) {
if (!rad_mtp_block_live(r.ids[j], r.val[j])) continue;
const double w = ::exp((double)r.val[j] - r.top);
double m;
if (resid) {
if (rad_mtp_block_find(s, r.ids[j]) < s.count) continue;
m = p * (w / t.sum);
} else {
m = w;
}
if (m > 0) { lastl = r.ids[j]; cl -= m; if (cl < 0) { *out = lastl; return true; } }
}
*out = lastl >= 0 ? lastl : ll;
return *out >= 0;
}
c -= T;
}
*out = last;
return last >= 0;
}
static inline RAD_BLK_HD bool rad_mtp_block_resid_draw(const RadBlockRow& r,
const RadMtpCoupleState& s,
const RadBlockStat& t, double p, double u,
int32_t* out) {
RadBlockLane lane[RAD_MTP_BLOCK_LANES];
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) lane[l] = RadBlockLane{ 0, 0, -1, -1 };
for (int64_t j = 0; j < r.n; ++j)
if (rad_mtp_block_live(r.ids[j], r.val[j]))
rad_mtp_block_lane_add(&lane[j % RAD_MTP_BLOCK_LANES], s, t, p, r.ids[j], r.val[j], r.top);
return rad_mtp_block_resid_walk(r, s, t, p, u, lane, out);
}
/* The whole decision on the host: rows[0 .. g-1] / st[0 .. g-1] are the block's verify rows and
* their coupled states (round i + 1 at row i), pos0 the first row's output position. Writes tau and
* *y; *y = -1 when tau == g (the g-th row's ordinary draw stands). False for an invalid target. */
static inline RAD_BLK_HD bool rad_mtp_block_decide(const RadMtpCoupleState* st,
const RadBlockRow* rows, int g, uint64_t seed,
uint64_t pos0, int* tau, int32_t* y) {
RadBlockStat stat[RAD_MTP_BLOCK_MAX];
RadBlockPlan pl;
if (g < 1 || g > RAD_MTP_BLOCK_MAX) return false;
for (int i = 0; i < g; ++i)
if (!rad_mtp_block_stat(rows[i], st[i], &stat[i])) return false;
rad_mtp_block_plan(st, stat, g, &pl);
const int t = rad_mtp_block_tau(pl, seed, pos0);
*tau = t;
*y = -1;
if (t >= g) return true;
return rad_mtp_block_resid_draw(rows[t], st[t], stat[t], pl.p[t],
rad_spechub_uniform(seed, pos0 + (uint64_t)t, RAD_SAMPLE_KEY_RESID), y);
}
#endif /* __cplusplus */
#endif /* RAD_MTP_BLOCK_H */
+426
View File
@@ -0,0 +1,426 @@
/* rad_mtp_rrs.h -- recursive rejection sampling over a node's SIBLING drafts under
* --draft-coupling on: the draft side (children sampled without replacement from Q) and the
* verify side (the walk over a node's children against the target's P), as plain code the host
* oracle, the device kernels and the tests share, so they cannot drift. Traversal verification
* (abi/rad_mtp_traversal.h) walks nodes that drafted several children; the serial head of this
* engine drafts one (nkids <= 1, the chain), so nothing in the engine draws siblings yet: the
* header is the verify side's definition and its tests (tests/mtp_rrs_test.cpp). The short proof:
*
* Draft. A node whose head pass left the law Q (the FP64 T1 softmax of the reranked top 8,
* rad_mtp_couple_build_q) drafts its children x_1, x_2, ... by Gumbel-top-k over log Q: add an
* independent Gumbel to every log q_i and take the entries in descending order. That is sampling
* without replacement (Plackett-Luce): x_1 ~ Q, x_2 ~ Q(. | not x_1), ... The first m of them are
* the node's children, m chosen by anything that does not read the values x_j it applies to
* (a fixed count, or a rule over the slot priorities, the j-th largest q of Q, never the drawn
* token).
*
* Verify (Sequoia, Chen et al. 2024, Alg. 1; SpecInfer's multi-step verification with the draft
* law renormalised after each removal). P_1 = the target's law, q_1 = Q. For i = 1..m:
* accept x_i with probability min(1, P_i(x_i) / q_i(x_i));
* on rejection P_{i+1} = norm(max(P_i - q_i, 0)), q_{i+1} = q_i with x_i removed, renormalised.
* All rejected: the token is a draw from P_{m+1}. Exactness (induction on m): after a rejection of
* the first draft the continuation depends on x_1 only through q_2, and P_2 = norm(max(P - q, 0))
* does not depend on x_1 at all, so by the hypothesis it emits ~ P_2 whatever x_1 was; then
* P(emit y) = sum_x q(x) min(1, P(x)/q(x)) [x = y] + P(reject) P_2(y) = min(P, q)(y) +
* max(P - q, 0)(y) = P(y). The emitted token is the accepted child's token, or a residual draw that
* has no mass on any rejected child (P_{i+1}(x_i) = 0 after a rejection), so the core's rule "follow
* the first child whose token is the sampler's token at the row" (ADV_ACCEPT) walks exactly the
* decision made here and needs no change.
*
* Wire: the node's RadMtpCoupleState holds Q (ids, q), the children in draft order in ids[0 ..
* nkids), x = ids[0]. A state with nkids <= 1 is the chain's (rad_mtp_couple_decide, bit for bit).
*/
#ifndef RAD_MTP_RRS_H
#define RAD_MTP_RRS_H
#include "rad_spechub.h"
#ifdef __cplusplus
#ifdef __HIPCC__
#define RAD_RRS_HD __host__ __device__
#else
#define RAD_RRS_HD
#endif
#define RAD_MTP_RRS_KEY_TREE 0x4d54524545474d42ull /* the draft's Gumbel stream */
#define RAD_MTP_RRS_KEY_ACCEPT 0x41435054ull
static inline RAD_RRS_HD uint64_t rad_mtp_rrs_mix(uint64_t z) {
z += 0x9e3779b97f4a7c15ull;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
return z ^ (z >> 31);
}
/* The open-interval uniform of candidate `c` of draft node `node`: (seed, base) name the draft
* stream (the request's seed and its pre-commit output length, which no later step reuses). */
static inline RAD_RRS_HD double rad_mtp_rrs_gumbel_u(uint64_t seed, uint64_t base,
uint64_t node, int c) {
uint64_t z = rad_mtp_rrs_mix(seed ^ RAD_MTP_RRS_KEY_TREE);
z = rad_mtp_rrs_mix(z ^ base);
z = rad_mtp_rrs_mix(z + node * 16u + (uint64_t)c);
return ((double)(z >> 11) + 0.5) * 0x1p-53;
}
/* Gumbel-top-k order of Q's support: order[0 .. s.count) are indices into s.ids, the draft order
* (descending of log q + Gumbel, ties to the lower index). Draws one uniform per support entry from
* the state's own draw, node `node`. */
static inline RAD_RRS_HD void rad_mtp_rrs_order(const RadMtpCoupleState& s, uint64_t node,
int* order) {
double key[8];
for (int i = 0; i < s.count; ++i) {
const double u = rad_mtp_rrs_gumbel_u(s.draw.seed, s.draw.base, node, i);
key[i] = ::log(s.q[i]) - ::log(-::log(u));
order[i] = i;
}
for (int i = 1; i < s.count; ++i) { /* insertion sort, stable */
const int o = order[i];
int j = i;
while (j > 0 && key[order[j - 1]] < key[o]) { order[j] = order[j - 1]; --j; }
order[j] = o;
}
}
/* Draw the node's children: reorder Q's support into the draft order (ids and q together), set
* x = ids[0] and nkids = `nkids`. */
static inline RAD_RRS_HD void rad_mtp_rrs_draw(RadMtpCoupleState* s, uint64_t node, int nkids) {
int order[8];
rad_mtp_rrs_order(*s, node, order);
int32_t ids[8];
double q[8];
for (int i = 0; i < s->count; ++i) { ids[i] = s->ids[order[i]]; q[i] = s->q[order[i]]; }
for (int i = 0; i < s->count; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
s->x = s->ids[0];
s->nkids = nkids < s->count ? nkids : s->count;
}
/* The SLOT priorities of a node's law: slot j carries the log of the j-th LARGEST q of Q
* (descending, ties by position), -inf past the support. They are a function of Q alone, never of
* which token was drawn into which slot, so a rule that reads only them admits children by a
* quantity independent of the values the children take. `s` is read before the draw reorders it
* or after (the multiset of q is the same). */
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq(const RadMtpCoupleState& s, float* ov) {
double qs[8];
const int n = s.count < 8 ? s.count : 8;
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
for (int i = 1; i < n; ++i) {
const double v = qs[i];
int j = i;
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
qs[j] = v;
}
for (int c = 0; c < 8; ++c) ov[c] = c < n ? (float)::log(qs[c]) : -INFINITY;
}
/* The longest prefix of the state's children that are the first `n` of `kid[]` (the tree's
* children of this row, in node order, repeats dropped): what a verify may keep when a window cut
* the tree short. 0 when even the first differs. */
static inline RAD_RRS_HD int rad_mtp_rrs_prefix(const RadMtpCoupleState& s, const int32_t* kid,
int n) {
const int have = s.nkids >= 1 ? s.nkids : 1;
int m = 0;
while (m < have && m < n && m < s.count && s.ids[m] == kid[m]) ++m;
return s.nkids >= 2 ? m : (n >= 1 && s.x == kid[0] ? 1 : 0);
}
/* The acceptance uniform of the i-th child at output position `pos`: the first is the chain's. */
static inline RAD_RRS_HD double rad_mtp_rrs_uaccept(uint64_t seed, uint64_t pos, int i) {
return rad_spechub_uniform(seed, pos, i == 0 ? (uint64_t)RAD_SAMPLE_KEY_ACCEPT
: RAD_MTP_RRS_KEY_ACCEPT ^ rad_mtp_rrs_mix((uint64_t)i));
}
/* The verify of a node with nkids >= 2 children: the recursion above over the sampler's surviving
* candidates (ids/val, n of them, FP64 P = softmax of val). Writes the emitted token to *out and
* returns true, or false for an invalid target (the row keeps the ordinary token).
*
* The decision reads the live candidates (id >= 0, value not -inf) in ascending order through a view
* `C::each(f)`, f(id, w, k) -> bool (false stops): w = exp(val - top) in FP64, k the id's slot in the
* state's support (the first match) or s.count when it is outside. The host view (RadRrsHostCands)
* computes them on the fly; the device verify (plugin/spechub/spechub.hip) compacts the live
* candidates and computes every w and k with the whole workgroup, then runs this same function on one
* lane over the stored values, so the ordered sums, and with them the token, are the host's. `pq_out`
* and `sum_out` (optional) hand back P's masses on the support and their normaliser (the export). */
template <class C>
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_over(const RadMtpCoupleState& s, const C& cs,
uint64_t seed, uint64_t pos, int32_t* out,
double* pq_out = nullptr,
double* sum_out = nullptr) {
double sum = 0, pq[8] = {}, wout = 0;
cs.each([&](int32_t, double w, int k) {
sum += w;
if (k < s.count) pq[k] += w; else wout += w;
return true;
});
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
if (pq_out) for (int k = 0; k < 8; ++k) pq_out[k] = pq[k];
if (sum_out) *sum_out = sum;
/* P over Q's support (normalised), and the off-support mass's scale `so` (P_i(y) = so * w / sum
* there). qr: the draft law with the drawn children removed. */
double r[8], qr[8], so = 1.0;
for (int k = 0; k < s.count; ++k) { r[k] = pq[k] / sum; qr[k] = s.q[k]; }
const double pout = wout / sum;
bool direct = false;
for (int i = 0; i < s.nkids && !direct; ++i) {
double sq = 0;
for (int k = 0; k < s.count; ++k) sq += qr[k];
if (!(sq > 0)) break;
const double qx = qr[i] / sq;
if (r[i] >= qx || rad_mtp_rrs_uaccept(seed, pos, i) * qx < r[i]) { *out = s.ids[i]; return true; }
double z = so * pout;
for (int k = 0; k < s.count; ++k) {
const double d = r[k] - qr[k] / sq;
r[k] = d > 0 ? d : 0;
z += r[k];
}
if (!(z > 0) || !rad_spechub_finite(z)) { direct = true; break; }
for (int k = 0; k < s.count; ++k) r[k] /= z;
so /= z;
qr[i] = 0;
}
const double u = rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID);
double c;
int32_t last = -1;
if (direct) {
c = u * sum;
bool hit = false;
cs.each([&](int32_t id, double w, int) {
if (w > 0) { last = id; c -= w; if (c < 0) { hit = true; return false; } }
return true;
});
*out = last;
(void)hit;
return true;
}
double total = 0;
for (int k = 0; k < s.count; ++k) total += r[k];
total += so * pout;
c = u * total;
unsigned seen = 0;
bool hit = false;
cs.each([&](int32_t id, double w, int k) {
double m;
if (k < s.count) {
if (seen & (1u << k)) return true;
seen |= 1u << k;
m = r[k];
} else {
m = so * (w / sum);
}
if (m > 0) { last = id; c -= m; if (c < 0) { hit = true; return false; } }
return true;
});
*out = last;
(void)hit;
return last >= 0;
}
/* The host view: the candidates as the sampler wrote them, weights computed as they are read. */
struct RadRrsHostCands {
const RadMtpCoupleState& s;
const int32_t* ids; const float* val; int64_t n; float top;
template <class F> RAD_RRS_HD void each(F&& f) const {
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
int k = 0;
while (k < s.count && ids[j] != s.ids[k]) ++k;
if (!f(ids[j], ::exp((double)val[j] - top), k)) return;
}
}
};
static inline RAD_RRS_HD bool rad_mtp_rrs_decide(const RadMtpCoupleState& s, const int32_t* ids,
const float* val, int64_t n, int64_t vocab,
uint64_t seed, uint64_t pos, int32_t* out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
if (top == -INFINITY) return false;
return rad_mtp_rrs_decide_over(s, RadRrsHostCands{ s, ids, val, n, top }, seed, pos, out);
}
/* ================================================================== RheoSampling siblings
*
* --draft-siblings rheo (--draft-rheo-m m). Hu et al. 2025 (arXiv 2502.18779, Thm 8, the greedy
* multi-draft verifier) and RheoSampling (arXiv 2609.21827): instead of Gumbel-top-k siblings, a node's
* children are
* T = the m tokens of largest Q, in descending q order (deterministic, rank slots 0 .. m-1), and
* u ~ Qt, ONE token sampled from the tail law Qt(x) = Q(x) / z over the support outside T,
* z = Q(outside T), in slot m;
* the draft order stored in the state is ids = [T..., u, the rest of the support in descending q],
* scheme = m + 1. A node whose support has no more than m tokens has no tail child (all of it is T).
*
* Verify (derived here, not quoted; the law is checked by tests/mtp_rrs_test.cpp by exhaustive
* enumeration). P = the target's law, children present = the first nkids of the draft order.
* tail child present (nkids > |T|, which with a prefix draft order means every T token is a child):
* accept u with probability min(1, P(u) / Qt(u)) -> emit u
* else emit y ~ R / |R|, R(y) = P(y) y in T or off Q's support,
* R(y) = max(P(y) - Qt(y), 0) y in the tail support (R(u) = 0 here)
* otherwise (the tail slot was pruned or cut by a window, or Q has no tail): emit y ~ P directly.
* Exactness: P(emit y) = min(P, Qt)(y) [y in tail] + (1 - A) R(y) / |R| with |R| = 1 - A,
* A = sum_tail min(P, Qt), and min(P, Qt) + R = P on the tail, R = P elsewhere: P(emit y) = P(y).
* It needs only that u ~ Qt independently of the verifier's uniforms (a separate draft stream), and
* that WHICH slots exist depends on Q and the tree's budget alone (never on the value of u): both
* hold, the slot priorities are rad_mtp_rrs_slot_logq_rheo. The emitted token is a child with
* probability P(T) + A = sum_T P + sum_tail min(P, Qt), Thm 8's value, and a residual draw never
* lands on u (R(u) = 0 when u was rejected), so the core's "follow the first child whose token is
* the sampler's" walks the decision made here.
* m = 0 is the single-draft maximal coupling of the chain (rad_mtp_couple_decide) with the sampled
* child in slot 0.
*/
#define RAD_MTP_RRS_KEY_TAIL_C 8 /* candidate index of the tail draw in the draft stream (0..7 are Gumbel's) */
/* Slot priorities of a rheo node (functions of Q alone, non-increasing): slots 0 .. m-1 carry the
* log of the j-th largest q, slot m RheoSampling's proxy log min{q_(m-1), z} (z = the tail mass; with
* m = 0, z = 1), -inf for the other slots and for slots past the support. */
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq_rheo(const RadMtpCoupleState& s, int m, float* ov) {
double qs[8];
const int n = s.count < 8 ? s.count : 8;
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
for (int i = 1; i < n; ++i) {
const double v = qs[i];
int j = i;
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
qs[j] = v;
}
const int nt = m < n ? m : n;
for (int c = 0; c < 8; ++c) ov[c] = c < nt ? (float)::log(qs[c]) : -INFINITY;
if (n > nt) {
double z = 0;
for (int i = nt; i < n; ++i) z += qs[i];
if (z > 1) z = 1;
const double ref = nt > 0 ? qs[nt - 1] : 1.0;
ov[nt] = (float)::log(z < ref ? z : ref);
}
}
/* Draw a rheo node's children: reorder Q's support into [top-m by q desc, the sampled tail child,
* the rest by q desc], set x = ids[0], scheme = m + 1 and nkids = min(nkids, children possible). The
* tail child is the inverse-CDF draw of Qt with the draft stream's uniform of (seed, base, node). */
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo_u(RadMtpCoupleState* s, double ut, int nkids, int m) {
int ord[8];
const int n = s->count;
for (int i = 0; i < n; ++i) ord[i] = i;
for (int i = 1; i < n; ++i) { /* descending q, stable */
const int o = ord[i];
int j = i;
while (j > 0 && s->q[ord[j - 1]] < s->q[o]) { ord[j] = ord[j - 1]; --j; }
ord[j] = o;
}
const int nt = m < n ? m : n;
if (n > nt) {
double z = 0;
for (int i = nt; i < n; ++i) z += s->q[ord[i]];
double c = ut * z;
int pick = n - 1;
for (int i = nt; i < n; ++i) { c -= s->q[ord[i]]; if (c < 0) { pick = i; break; } }
const int o = ord[pick];
for (int i = pick; i > nt; --i) ord[i] = ord[i - 1];
ord[nt] = o;
}
int32_t ids[8];
double q[8];
for (int i = 0; i < n; ++i) { ids[i] = s->ids[ord[i]]; q[i] = s->q[ord[i]]; }
for (int i = 0; i < n; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
const int cap = nt + (n > nt ? 1 : 0);
s->x = s->ids[0];
s->scheme = m + 1;
s->nkids = nkids < cap ? nkids : cap;
}
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo(RadMtpCoupleState* s, uint64_t node, int nkids, int m) {
rad_mtp_rrs_draw_rheo_u(s, rad_mtp_rrs_gumbel_u(s->draw.seed, s->draw.base, node, RAD_MTP_RRS_KEY_TAIL_C),
nkids, m);
}
/* The verify of a rheo node (any nkids >= 0): the rule above. Same contract as rad_mtp_rrs_decide. */
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo_u(const RadMtpCoupleState& s, const int32_t* ids,
const float* val, int64_t n, int64_t vocab,
double u_accept, double u_resid, int32_t* out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
if (top == -INFINITY) return false;
double sum = 0, pq[8] = {};
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
const double w = ::exp((double)val[j] - top);
sum += w;
for (int k = 0; k < s.count; ++k)
if (ids[j] == s.ids[k]) { pq[k] += w; break; }
}
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
const int m = s.scheme - 1;
const int nt = m < s.count ? m : s.count;
const bool tail = m >= 0 && s.count > nt && s.nkids > nt;
double qt[8] = {}, r[8] = {};
bool dominated = true;
for (int k = 0; k < s.count; ++k) pq[k] /= sum;
if (tail) {
double z = 0;
for (int k = nt; k < s.count; ++k) z += s.q[k];
for (int k = nt; k < s.count; ++k) {
const double v = nt == 0 ? s.q[k] : s.q[k] / z;
qt[k] = v > 1 ? 1 : v; /* clamp: rounding must not push a one-token tail past 1 */
dominated = dominated && pq[k] >= qt[k];
}
for (int k = 0; k < s.count; ++k) r[k] = k < nt ? pq[k] : rad_spechub_positive(pq[k] - qt[k]);
}
/* mass of candidate j in R (the tail case) or in P (otherwise); Q tokens count once. */
unsigned seen = 0;
auto mass = [&](int64_t j) -> double {
if (ids[j] < 0 || val[j] == -INFINITY) return 0;
for (int k = 0; k < s.count; ++k)
if (s.ids[k] == ids[j]) {
if (seen & (1u << k)) return 0;
seen |= 1u << k;
return tail ? r[k] : pq[k];
}
return ::exp((double)val[j] - top) / sum;
};
double resid = 0;
if (tail) {
for (int64_t j = 0; j < n; ++j) resid += mass(j);
seen = 0;
}
if (!tail || (!dominated && !(resid > 0 && rad_spechub_finite(resid)))) {
double c = u_resid * sum; /* P itself, in the sampler's candidate order */
int32_t last = -1;
for (int64_t j = 0; j < n; ++j)
if (ids[j] >= 0 && val[j] != -INFINITY) {
const double w = ::exp((double)val[j] - top);
if (w > 0) { last = ids[j]; c -= w; if (c < 0) { *out = last; return true; } }
}
*out = last;
return last >= 0;
}
const int iu = nt;
if (pq[iu] >= qt[iu] || u_accept * qt[iu] < pq[iu]) {
*out = s.ids[iu];
return true;
}
double c = u_resid * resid;
int32_t last = -1;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] == s.ids[iu]) continue;
const double mm = mass(j);
if (mm > 0) { last = ids[j]; c -= mm; if (c < 0) { *out = last; return true; } }
}
*out = last;
return last >= 0;
}
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo(const RadMtpCoupleState& s, const int32_t* ids,
const float* val, int64_t n, int64_t vocab,
uint64_t seed, uint64_t pos, int32_t* out) {
return rad_mtp_rrs_decide_rheo_u(s, ids, val, n, vocab,
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID), out);
}
#endif /* __cplusplus */
#endif /* RAD_MTP_RRS_H */
+549
View File
@@ -0,0 +1,549 @@
/* rad_mtp_traversal.h -- Traversal Verification (Weng et al., arXiv 2505.12398) of a draft under
* sampling (--draft-verify traversal, needs --draft-coupling on). The walk is defined on a tree; the
* serial head of this engine drafts a chain, a tree of one child a node, which the sampler stages
* (core/sample/sampler.cpp). Plain code shared by the host oracle, the device kernel and the tests;
* the short form of the argument:
*
* Row-wise verification (rad_mtp_rrs_decide) decides each node on its own. Traversal verification
* decides a whole ROOT-TO-LEAF PATH at once, bottom-up, and so can accept a longer prefix from the
* same tree (for a chain it is Block Verification, never worse than token-level rejection sampling).
*
* State of a node v during the walk: p_v (its acceptance rate, a sequence-level ratio), the target
* law M_b(.|v) restricted to what has not been rejected below it (r), and the law the NEXT child of
* v was drawn from.
* - A child c of v enters with p_c = min(1, p_v * r(c)/qn(c)), qn the law c was drawn from GIVEN
* the children tried before it.
* - The walk descends to the first leaf and tests eta < p_leaf. Accept: the path is accepted and
* the final token is drawn from that node's current residual law r (the plain target if none of
* its children was rejected). Reject: the leaf is deleted and its parent v is updated:
* S = sum_x [ p_v r(x) - qn(x) ]+
* p_v' = S / (S + 1 - p_v)
* r' = [ p_v r - qn ]+ / S
* and the walk continues with v's next child, or tests v itself once it has none.
* The walk keeps the PRODUCT m(x) = p_v r(x) (on the draft support per slot, and one number for
* everything off it, where qn is zero), which is all the rules read: p_c = min(1, m(c)/qn(c)), and
* the update is one division, m' = [m - qn]+ / (S + 1 - p_v), p_v' = S / (S + 1 - p_v), the
* off-support mass scaled alike; the final token is drawn in proportion to m. A node entered with
* rate p keeps its target law unscaled and the factor p beside it (sc) until its first child is
* rejected, so entering a node costs one division (the child's rate) and no pass over its law.
* Exactness (Theorem 3.3 of the paper, Lemma A.2 by induction over a node's descendants): the
* subtree of v is accepted with probability p_v and, given that, the token after v follows r. One
* step of the induction, for a child drawn from ANY law qn that may depend on the children before
* it: P(accepted through a child x) = qn(x) min(1, p_v r(x)/qn(x)) = min(qn(x), p_v r(x));
* P(the child's subtree is rejected) = 1 - p_v + S; the rest then accepts with p_v' and r', which
* adds (1 - p_v + S) p_v' r'(x) = [p_v r(x) - qn(x)]+, and the two sum to p_v r(x). It needs the
* tree's shape to be independent of the drawn tokens (a chain's is), and each child's own law:
* - Gumbel-top-k siblings (the default, Plackett-Luce without replacement): qn is the node's Q
* with the children already tried removed, renormalised;
* - RheoSampling siblings (state.scheme = m + 1, abi/rad_mtp_rrs.h): the
* sampled tail child is tried FIRST with qn = Qt, the tail law, then the deterministic top-q
* children in their order, each with qn = a point mass on its token. A point mass accepts with
* p_v r(c) and leaves r without c; tried in this order the node's children take
* sum_tail min(P, Qt) + P(T) of the target, the greedy multi-draft verifier's value (Hu et al.
* 2025, Thm 8).
* tests/mtp_rrs_test.cpp checks the walk by exact enumeration and by chi-square, and shows that
* plausible mistakes (token-level ratios, no (1 - p) term, with-replacement update for
* without-replacement drafts, a rheo node walked as a Gumbel one) fail the same statistic.
*
* THE TARGET LAW IN FIXED POINT. The walk reads a row's target law only through its mass on the
* node's draft support (eight ids), the mass off it and the total; the final token needs the
* off-support candidates in order. Each live candidate's weight is an INTEGER:
*
* m_j = floor(2^40 * e(val_j - top)), e(x) = rad_mtp_trav_mass's FP32 exponential
*
* (top the row's largest value; the scale drops a bit per doubling of the plane past 4096 slots so
* a row's total stays below 2^53). Integer addition is associative, so the sums are the same bits
* whatever order a workgroup adds them in: the device kernel (plugin/spechub/spechub.hip) splits a
* row over its threads any way it likes and still equals this header's serial loops, with no
* reduction tree to mirror. e() is basic FP32 arithmetic and integer shifts, identical on host and
* device (no libm call, no contraction: -ffp-contract=off, and the attribute below for a host
* build that enables FMA).
* Why FP32 suffices: the algorithm is exact for whatever positive weights define the law, as long as
* every decision reads the same ones, which the integers guarantee. The law it realises is
* P~(y) = m_y / sum m, within 2^-22 relative per candidate (e's error, tests/mtp_rrs_test.cpp checks
* it) plus 2^-40 absolute of the softmax of the sampler's FP32 candidates: the accuracy class of the
* uncoupled sample_pick (FP32 expf, FP32 running sum, a 24-bit uniform), which is the law a request
* gets without speculation. The 8-wide FP64 sums of the walk are a fixed tree (rad_mtp_trav_sum8),
* so a device may run them on one lane or across eight.
*
* Wire: no new state. The walk reads the same RadMtpCoupleState rows as the row-wise verify and
* writes the SAME plane the core already walks (ADV_ACCEPT: the first child whose token is the
* sampler's token at the row): on the accepted path every row's token is its path child's token and
* the last row's token is the final one; the other rows are not on the walk and keep the pick.
*/
#ifndef RAD_MTP_TRAVERSAL_H
#define RAD_MTP_TRAVERSAL_H
#include "rad_spechub.h"
#include "rad_mtp_rrs.h"
#ifdef __cplusplus
#define RAD_MTP_TRAV_MAX_DEPTH 16
#define RAD_MTP_TRAV_MAX_ROWS 64 /* rows of one request the walk reads (its first ones) */
#define RAD_MTP_TRAV_KEY 0x54524156ull /* "TRAV": the walk's acceptance uniforms */
#define RAD_MTP_TRAV_QBITS 40 /* the unit of a candidate's mass: 2^-40 of the top's */
/* A host build with FMA enabled must not contract the exponential's products into its sums: the
* device does not (-ffp-contract=off), and the masses have to be the same bits. */
#if defined(__GNUC__) && !defined(__clang__)
#define RAD_TRAV_STRICT __attribute__((optimize("fp-contract=off")))
#else
#define RAD_TRAV_STRICT
#endif
/* Test-only switches; the engine passes the zero value. */
struct RadMtpTravOpt {
int ctl = 0; /* negative controls: 1 token-level ratios, 2 no (1 - p) term, 3 q never
renormalised (the with-replacement update on without-replacement drafts),
4 a RheoSampling node walked as a Gumbel one */
/* Enumeration (tests): >= 0 replaces the uniforms -- test number `accept_at` (1-based) accepts
* and every earlier one rejects; `p_test[i]` receives the acceptance rate of test i + 1 and
* `*n_tests` their count. */
int accept_at = -1;
double* p_test = nullptr;
int* n_tests = nullptr;
int max_tests = 0;
double u_final = -1.0; /* >= 0: the final token's uniform (rad_mtp_trav_walk) */
};
struct RadMtpTravOut {
int n = 0; /* nodes on the path, root first */
int node[RAD_MTP_TRAV_MAX_DEPTH + 2] = {};
int32_t y = -1; /* the final token ... */
bool has_y = false; /* ... when the last node carries a valid state */
};
/* ---------------------------------------------------------------- the target law in fixed point */
/* The mass unit of a plane of n candidates: 2^-qbits of the top candidate's weight, so that a
* row's total stays below 2^53 (exact in FP64). */
static inline RAD_RRS_HD int rad_mtp_trav_qbits(int64_t n) {
int q = RAD_MTP_TRAV_QBITS;
for (int64_t c = 4096; c < n && q > 20; c <<= 1) --q;
return q;
}
/* floor(2^qbits * e^(v - top)) for a live candidate (v <= top, both finite): the FP32 exponential
* of Cephes' expf (argument reduction by n ln 2 in two parts, a degree-5 polynomial in the reduced
* argument), taken as a 24-bit mantissa and shifted. Zero below 2^-41 of the top. Basic IEEE FP32
* operations and integer shifts only. */
RAD_TRAV_STRICT static inline RAD_RRS_HD uint64_t rad_mtp_trav_mass(float v, float top, int qbits) {
#if defined(__clang__)
#pragma clang fp contract(off)
#endif
const float x = v - top;
if (!(x > -28.5f)) return 0;
const int n = (int)(x * 1.44269504088896341f - 0.5f); /* round(x / ln 2), x <= 0 */
const float fn = (float)n;
float r = x - fn * 0.693359375f;
r = r - fn * -2.12194440e-4f;
const float z = r * r;
float y = 1.9875691500e-4f;
y = y * r + 1.3981999507e-3f;
y = y * r + 8.3334519073e-3f;
y = y * r + 4.1665795894e-2f;
y = y * r + 1.6666665459e-1f;
y = y * r + 5.0000001201e-1f;
y = y * z + r;
y = y + 1.0f; /* e^r, in [0.70, 1.42] */
const uint32_t mant = (uint32_t)(y * 8388608.0f); /* y * 2^23, below 2^24 */
const int sh = qbits + n - 23;
if (sh >= 0) return (uint64_t)mant << sh;
return sh > -32 ? (uint64_t)(mant >> -sh) : 0;
}
/* An integer below 2^53 as a double, exactly, the same way on host and device. */
static inline RAD_RRS_HD double rad_mtp_trav_u2d(uint64_t x) {
return (double)(uint32_t)(x >> 32) * 4294967296.0 + (double)(uint32_t)x;
}
/* The integer part of a double in [0, 2^53). */
static inline RAD_RRS_HD uint64_t rad_mtp_trav_d2u(double d) {
const uint32_t hi = (uint32_t)(d * (1.0 / 4294967296.0));
const double lo = d - (double)hi * 4294967296.0;
return ((uint64_t)hi << 32) + (uint64_t)(uint32_t)lo;
}
/* Candidate id's slot in a node's support (the first match), or cnt when it is outside. */
static inline RAD_RRS_HD int rad_mtp_trav_slot(const int32_t* sid, int cnt, int32_t id) {
int k = 0;
while (k < cnt && id != sid[k]) ++k;
return k;
}
/* A row's validity and largest value, as rad_mtp_couple_decide scans them: false for an id past the
* vocabulary, a NaN or +inf among the ids >= 0, or no finite value at all. */
static inline RAD_RRS_HD bool rad_mtp_trav_row_top(const int32_t* ids, const float* val, int64_t n,
int64_t vocab, float* top_out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
*top_out = top;
return top != -INFINITY;
}
/* One row's target law over a node's support `sid[0 .. cnt)`: the masses on the support slots
* (duplicate candidates aggregated at the first matching slot), off it, and the total. The serial
* definition; a workgroup adds the same integers in its own order. */
struct RadTravLaw {
uint64_t pq[8];
uint64_t off, sum;
};
static inline RAD_RRS_HD void rad_mtp_trav_row_law(const int32_t* ids, const float* val, int64_t n,
float top, const int32_t* sid, int cnt,
RadTravLaw* o) {
const int qb = rad_mtp_trav_qbits(n);
for (int k = 0; k < 8; ++k) o->pq[k] = 0;
o->off = 0; o->sum = 0;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
o->sum += m;
const int k = rad_mtp_trav_slot(sid, cnt, ids[j]);
if (k < cnt) o->pq[k] += m; else o->off += m;
}
}
/* The off-support candidate that holds unit `t` of the off-support mass, candidates in ascending
* slot order (t < the row's off-support mass). -1 when there is none. */
static inline RAD_RRS_HD int32_t rad_mtp_trav_off_token(const int32_t* ids, const float* val,
int64_t n, float top, const int32_t* sid,
int cnt, uint64_t t) {
const int qb = rad_mtp_trav_qbits(n);
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
if (rad_mtp_trav_slot(sid, cnt, ids[j]) < cnt) continue;
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
if (t < m) return ids[j];
t -= m;
}
return -1;
}
/* ---------------------------------------------------------------- the prepared tree */
/* The eight-wide FP64 sums of the walk, as one fixed tree: the xor-4, xor-2, xor-1 butterfly of
* eight lanes (IEEE addition is commutative, so every lane of the butterfly ends with these bits). */
static inline RAD_RRS_HD double rad_mtp_trav_sum8(const double* v) {
return ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7]));
}
/* A node's draft side in the walk's canonical order: the children first, in draft order (a chain's
* one child is x). `nk` the children the walk may try, `nt` -1 for Gumbel-top-k siblings, else the
* number of deterministic top-q children of a RheoSampling node (its tail child is slot nt, `tail`
* whether the node carries it), `swap` the stored slot that changed places with slot 0 (a chain row
* whose x was not first; else 0).
* False when the state names no child (unreachable for a rad_mtp_couple_state_valid state). */
static inline RAD_RRS_HD bool rad_mtp_trav_canon(const RadMtpCoupleState& s, int ctl, int32_t* ids,
double* q, int* nk, int* nt, int* tail, int* swap) {
/* Every index below is a constant: a device lane keeps the state and the result in registers. */
*swap = 0;
*tail = 0;
if (s.scheme > 0 && ctl != 4) {
for (int k = 0; k < 8; ++k) {
ids[k] = k < s.count ? s.ids[k] : -1;
q[k] = k < s.count ? s.q[k] : 0.0;
}
const int m = s.scheme - 1;
const int t = m < s.count ? m : s.count;
const int cap = t + (s.count > t ? 1 : 0);
*nt = t;
*nk = s.nkids < cap ? (s.nkids > 0 ? s.nkids : 0) : cap;
*tail = *nk > t;
return true;
}
*nt = -1;
*nk = s.nkids >= 2 ? (s.nkids < s.count ? s.nkids : s.count) : 1;
/* a chain row: x to the front (the first slot that holds it changes places with slot 0) */
int kx = 0;
if (s.nkids < 2) {
kx = 8;
for (int k = 7; k >= 0; --k)
if (k < s.count && s.ids[k] == s.x) kx = k;
}
const bool found = kx < 8;
int32_t idx = -1;
double qx = 0.0;
for (int k = 0; k < 8; ++k) {
idx = k == kx ? s.ids[k] : idx;
qx = k == kx ? s.q[k] : qx;
}
for (int k = 0; k < 8; ++k) {
const bool in = found && k < s.count;
const int32_t idk = k == 0 ? idx : (k == kx ? s.ids[0] : s.ids[k]);
const double qk = k == 0 ? qx : (k == kx ? s.q[0] : s.q[k]);
ids[k] = in ? idk : -1;
q[k] = in ? qk : 0.0;
}
*swap = found ? kx : 0;
return found;
}
/* One request's tree as the walk reads it, node-indexed (node 0 the root, parents before
* children). Plain data: the device keeps it in LDS and fills it with a workgroup. */
struct RadTravTree {
int n; /* nodes */
int ok[RAD_MTP_TRAV_MAX_ROWS]; /* an eligible state with a valid target law */
int nk[RAD_MTP_TRAV_MAX_ROWS]; /* children the walk tries */
int nt[RAD_MTP_TRAV_MAX_ROWS]; /* -1 Gumbel; else a rheo node's deterministic children */
int tail[RAD_MTP_TRAV_MAX_ROWS]; /* a rheo node that carries its sampled tail child */
int ci[RAD_MTP_TRAV_MAX_ROWS]; /* children tried so far */
int child[RAD_MTP_TRAV_MAX_ROWS][8]; /* slot k's child node, or -1 */
int32_t ids[RAD_MTP_TRAV_MAX_ROWS][8]; /* the support, canonical order, -1 past it */
double qr[RAD_MTP_TRAV_MAX_ROWS][8]; /* the draft law (Gumbel: tried children zeroed) */
double m[RAD_MTP_TRAV_MAX_ROWS][8]; /* rate * residual on the support slots (the target's
law itself until the node is entered) */
double moff[RAD_MTP_TRAV_MAX_ROWS]; /* the same off the support, in all */
double sc[RAD_MTP_TRAV_MAX_ROWS]; /* the factor m and moff still owe: the node's rate from
its entry to its first rejected child, then 1 */
double p[RAD_MTP_TRAV_MAX_ROWS]; /* the node's acceptance rate */
uint64_t off[RAD_MTP_TRAV_MAX_ROWS]; /* the off-support mass in units (the final draw) */
float top[RAD_MTP_TRAV_MAX_ROWS]; /* the row's largest value */
int stack[RAD_MTP_TRAV_MAX_DEPTH + 1];
};
/* Node v's laws from its canonical draft side and its row's integer law (`valid`: the row scanned
* clean and its total is positive). */
static inline RAD_RRS_HD void rad_mtp_trav_set_law(RadTravTree* t, int v, bool valid, float top,
const RadTravLaw& w) {
const bool ok = valid && w.sum > 0;
const double sum = ok ? rad_mtp_trav_u2d(w.sum) : 1.0;
for (int k = 0; k < 8; ++k) t->m[v][k] = ok ? rad_mtp_trav_u2d(w.pq[k]) / sum : 0.0;
t->moff[v] = ok ? rad_mtp_trav_u2d(w.off) / sum : 0.0;
t->off[v] = ok ? w.off : 0;
t->top[v] = top;
t->ci[v] = 0;
t->ok[v] = ok;
}
/* The slot of node v's j-th tried child. Gumbel: the draft order. Rheo: the sampled tail child
* first (when the node carries it), then the deterministic ones. */
static inline RAD_RRS_HD int rad_mtp_trav_try_slot(const RadTravTree& t, int v, int j) {
const int nt = t.nt[v];
if (nt < 0) return j;
return t.tail[v] ? (j == 0 ? nt : j - 1) : j;
}
/* The law node v's j-th tried child was drawn from, at support slot k. `isq` is the reciprocal of
* rad_mtp_trav_try_norm: the sum of the node's remaining draft law (Gumbel) or of its tail's (rheo). */
static inline RAD_RRS_HD double rad_mtp_trav_try_norm(const RadTravTree& t, int v) {
const int nt = t.nt[v];
if (nt < 0) return rad_mtp_trav_sum8(t.qr[v]);
double tail[8];
for (int k = 0; k < 8; ++k) tail[k] = k >= nt ? t.qr[v][k] : 0.0;
return rad_mtp_trav_sum8(tail);
}
static inline RAD_RRS_HD double rad_mtp_trav_try_q(const RadTravTree& t, int v, int j, double isq,
int k) {
const int nt = t.nt[v];
if (nt < 0) return t.qr[v][k] * isq;
const int slot = rad_mtp_trav_try_slot(t, v, j);
if (slot != nt) return k == slot ? 1.0 : 0.0; /* a deterministic child: a point mass */
if (k < nt) return 0.0;
const double q = nt == 0 ? t.qr[v][k] : t.qr[v][k] * isq;
return q > 1.0 ? 1.0 : q; /* clamp: rounding must not push a one-token tail past 1 */
}
/* m / q for node v's j-th tried child at its own slot i, m the child's mass in the node's law: the
* child's rate before the cap, in one division (m * sq / qr rather than m / (qr / sq)). Negative
* when the law has no mass there (the child is not tried). */
static inline RAD_RRS_HD double rad_mtp_trav_try_ratio(const RadTravTree& t, int v, int j, int i,
double m) {
const int nt = t.nt[v];
const double q = t.qr[v][i];
if (nt >= 0 && i != nt) return m; /* a point mass */
if (!(q > 0)) return -1.0;
if (nt == 0) return q < 1.0 ? m / q : m;
const double sq = rad_mtp_trav_try_norm(t, v);
return q < sq ? m * sq / q : m; /* the law's value is at most 1 */
}
/* The walk over a prepared tree: the accepted path into path[0 .. *n_path). Returns false when
* nothing was decided (an invalid root state: every row keeps the pick). `pos0` is the root row's
* output position, the coordinate of the acceptance uniforms. Updates the tree in place: the last
* node's m / moff are its residual law (up to the node's factor sc), which
* rad_mtp_trav_final_pick reads. */
static inline RAD_RRS_HD bool rad_mtp_trav_walk_tree(RadTravTree& t, uint64_t seed, uint64_t pos0,
int* path, int* n_path,
const RadMtpTravOpt& opt = RadMtpTravOpt{}) {
int top = 0, tests = 0;
t.stack[0] = 0;
t.p[0] = 1.0;
t.sc[0] = 1.0; /* the root's m is the target's law itself */
*n_path = 0;
if (!t.ok[0]) return false;
for (;;) {
const int v = t.stack[top];
if (t.ok[v] && t.ci[v] < t.nk[v]) {
const int j = t.ci[v];
const int i = rad_mtp_trav_try_slot(t, v, j);
/* p_c = min(1, p_v r(c) / qn(c)); control 1 drops p_v (token-level ratios) */
const double f = opt.ctl == 1 ? (t.p[v] > 0 ? t.sc[v] / t.p[v] : 0.0) : t.sc[v];
const double ratio = rad_mtp_trav_try_ratio(t, v, j, i, f * t.m[v][i]);
const int c = top < RAD_MTP_TRAV_MAX_DEPTH && ratio >= 0 ? t.child[v][i] : -1;
if (c < 0) { t.nk[v] = j; continue; } /* a child the verify no longer carries: cut here */
const double pc = ratio < 1.0 ? ratio : 1.0;
t.p[c] = pc;
t.sc[c] = pc; /* the child's law becomes rate * law, when it is first needed */
t.stack[++top] = c;
continue;
}
/* a leaf: the sequence-level test */
++tests;
bool accept;
if (opt.accept_at >= 0) {
if (opt.p_test && tests <= opt.max_tests) opt.p_test[tests - 1] = t.p[v];
if (opt.n_tests) *opt.n_tests = tests;
accept = tests == opt.accept_at;
} else {
const double u = rad_spechub_uniform(
seed, pos0, RAD_MTP_TRAV_KEY ^ rad_mtp_rrs_mix((uint64_t)tests));
accept = u < t.p[v];
}
if (accept) {
*n_path = top + 1;
for (int i = 0; i <= top; ++i) path[i] = t.stack[i];
return true;
}
if (top == 0) return false; /* the root always accepts (p = 1); only roundoff gets here */
--top;
const int g = t.stack[top];
const int j = t.ci[g];
const double isq = 1.0 / rad_mtp_trav_try_norm(t, g);
const double pold = t.p[g], sc = t.sc[g];
double d[8];
for (int k = 0; k < 8; ++k) {
const double x = sc * t.m[g][k] - rad_mtp_trav_try_q(t, g, j, isq, k);
d[k] = x > 0 ? x : 0;
}
const double moff = sc * t.moff[g];
const double S = moff + rad_mtp_trav_sum8(d);
if (!(S > 0) || !rad_spechub_finite(S)) {
/* nothing of the target is left above the draft: this node cannot accept, nor a child of it */
t.p[g] = 0;
t.sc[g] = 0;
} else {
const double den = opt.ctl == 2 ? S : S + 1.0 - pold;
const double inv = 1.0 / den;
const double pn = S * inv;
t.p[g] = pn < 1.0 ? pn : 1.0; /* a rate is at most 1: rounding may not push it past */
for (int k = 0; k < 8; ++k) t.m[g][k] = d[k] * inv;
t.moff[g] = moff * inv;
t.sc[g] = 1.0;
}
/* Gumbel siblings are drawn WITHOUT replacement: the remaining Q renormalises */
if (t.nt[g] < 0 && opt.ctl != 3) t.qr[g][j] = 0;
++t.ci[g];
}
}
/* The final token of node v's residual law (in proportion to m on the support slots and moff off it:
* the node's factor sc is common to both and cancels), by the uniform
* u: the support slots first, in the canonical order, then the off-support candidates in slot
* order. kind 0: no token (the row keeps the pick); 1: the token of support slot `slot`; 2: the
* off-support candidate holding unit `t` of the row's off-support mass (rad_mtp_trav_off_token). */
struct RadTravPick {
int kind, slot;
uint64_t t;
};
static inline RAD_RRS_HD RadTravPick rad_mtp_trav_final_pick(const RadTravTree& t, int v, double u) {
RadTravPick o;
o.kind = 0; o.slot = -1; o.t = 0;
const double woff = t.moff[v];
const double total = rad_mtp_trav_sum8(t.m[v]) + woff;
if (!(total > 0) || !rad_spechub_finite(total)) return o;
double c = u * total;
int last = -1;
for (int k = 0; k < 8; ++k) {
const double m = t.m[v][k];
if (m > 0) {
last = k;
c -= m;
if (c < 0) { o.kind = 1; o.slot = k; return o; }
}
}
const uint64_t off = t.off[v];
if (woff > 0 && off > 0) {
const double frac = c / woff;
uint64_t tt = frac < 1.0 ? rad_mtp_trav_d2u(frac * rad_mtp_trav_u2d(off)) : off - 1;
if (tt >= off) tt = off - 1;
o.kind = 2; o.t = tt;
return o;
}
if (last >= 0) { o.kind = 1; o.slot = last; }
return o;
}
/* ---------------------------------------------------------------- a tree behind an interface
*
* The tree the walk reads (a Tree type provides):
* const RadMtpCoupleState* state(int v) the node's bound state, or null (node is a leaf)
* bool cand(int v, const int32_t** ids, const float** val, int64_t* n) target candidates
* int child(int v, int32_t token) the node's first child row with that token, or -1
* int64_t vocab()
* rad_mtp_trav_walk prepares the nodes the walk can reach (in discovery order, at most
* RAD_MTP_TRAV_MAX_ROWS), walks and draws the final token: the host reference and the tests. */
template <class Tree>
static inline bool rad_mtp_trav_walk(const Tree& T, int root, uint64_t seed, uint64_t pos0,
RadMtpTravOut* out, RadMtpTravOpt opt = RadMtpTravOpt{},
RadTravTree* keep = nullptr, int* ids_out = nullptr) {
RadTravTree local;
RadTravTree& t = keep ? *keep : local;
int id[RAD_MTP_TRAV_MAX_ROWS]; /* node -> the tree's own id */
struct Row { const int32_t* ids; const float* val; int64_t n; };
Row rows[RAD_MTP_TRAV_MAX_ROWS];
t.n = 1;
id[0] = root;
for (int a = 0; a < t.n; ++a) {
const int v = id[a];
t.ok[a] = 0; t.nk[a] = 0; t.nt[a] = -1; t.tail[a] = 0; t.ci[a] = 0;
t.moff[a] = 0; t.sc[a] = 1.0; t.p[a] = 0; t.off[a] = 0; t.top[a] = -INFINITY;
for (int k = 0; k < 8; ++k) { t.child[a][k] = -1; t.ids[a][k] = -1; t.qr[a][k] = 0; t.m[a][k] = 0; }
rows[a] = Row{ nullptr, nullptr, 0 };
const RadMtpCoupleState* sp = T.state(v);
if (!sp) continue;
int swap = 0;
if (!rad_mtp_trav_canon(*sp, opt.ctl, t.ids[a], t.qr[a], &t.nk[a], &t.nt[a], &t.tail[a], &swap)) continue;
const int32_t* ids = nullptr; const float* val = nullptr;
int64_t n = 0;
if (!T.cand(v, &ids, &val, &n)) continue;
rows[a] = Row{ ids, val, n };
float top = -INFINITY;
RadTravLaw w{};
const bool valid = rad_mtp_trav_row_top(ids, val, n, T.vocab(), &top);
if (valid) rad_mtp_trav_row_law(ids, val, n, top, t.ids[a], sp->count, &w);
rad_mtp_trav_set_law(&t, a, valid, top, w);
if (!t.ok[a]) continue;
for (int k = 0; k < t.nk[a]; ++k) {
const int c = T.child(v, t.ids[a][k]);
if (c < 0 || t.n >= RAD_MTP_TRAV_MAX_ROWS) continue;
t.child[a][k] = t.n;
id[t.n++] = c;
}
}
int path[RAD_MTP_TRAV_MAX_DEPTH + 1], np = 0;
if (ids_out) for (int a = 0; a < t.n; ++a) ids_out[a] = id[a];
if (!rad_mtp_trav_walk_tree(t, seed, pos0, path, &np, opt)) return false;
out->n = np;
for (int i = 0; i < np; ++i) out->node[i] = id[path[i]];
out->has_y = false;
const int f = path[np - 1];
if (t.ok[f]) {
const double ur = opt.u_final >= 0 ? opt.u_final
: rad_spechub_uniform(seed, pos0 + (uint64_t)(np - 1), RAD_SAMPLE_KEY_RESID);
const RadTravPick pk = rad_mtp_trav_final_pick(t, f, ur);
if (pk.kind == 1) { out->y = t.ids[f][pk.slot]; out->has_y = true; }
if (pk.kind == 2) {
int cnt = 0;
while (cnt < 8 && t.ids[f][cnt] >= 0) ++cnt;
out->y = rad_mtp_trav_off_token(rows[f].ids, rows[f].val, rows[f].n, t.top[f], t.ids[f], cnt, pk.t);
out->has_y = out->y >= 0;
}
}
return true;
}
#endif /* __cplusplus */
#endif /* RAD_MTP_TRAVERSAL_H */
+22 -1
View File
@@ -37,7 +37,23 @@ typedef struct RadMtpCoupleState {
int32_t status, round, x, count;
int32_t ids[8];
double q[8];
/* The node drafted `nkids` children, sampled without replacement from q, and ids[0 .. nkids) are
* them in draft order (x == ids[0]; ids[nkids .. count) the rest of the support). nkids <= 1 is
* the linear chain's single draw, whose ids keep the shortlist's order, and what the serial
* MTP head writes (abi/rad_mtp_rrs.h states the siblings' law; the traversal walk of
* abi/rad_mtp_traversal.h reads it). Zero from every writer that is not a sibling draw. */
int32_t nkids;
/* The sibling scheme of those children: 0 = Gumbel-top-k without replacement (the only one a
* writer in this engine produces), m + 1 = RheoSampling's m deterministic top-q children plus one
* sampled from the tail law (abi/rad_mtp_rrs.h). Zero from every other writer. */
int32_t scheme;
/* --draft-verify block (abi/rad_mtp_block.h): the length g of the block this row's chain is
* verified as one (the rows 0 .. g-1 bound to rounds 1 .. g, staged on every row of it); 0 for
* token-by-token verification. Written by the sampler's staging only; zero from the device. */
int32_t blk;
int32_t pad_;
} RadMtpCoupleState;
#define RAD_MTP_COUPLE_MAX_RHEO_M 7
#define RAD_MTP_COUPLE_DRAW_WORDS (sizeof(RadMtpCoupleDraw) / 4)
#define RAD_MTP_COUPLE_STATE_WORDS (sizeof(RadMtpCoupleState) / 4)
#define RAD_MTP_COUPLE_MAX_ROUNDS 8
@@ -46,7 +62,7 @@ typedef struct RadMtpCoupleState {
#define RAD_MTP_COUPLE_KEY_DRAFT 0x4d5450434f55504cull
#ifdef __cplusplus
static_assert(sizeof(RadMtpCoupleDraw) == 32, "MTP coupling draw wire");
static_assert(sizeof(RadMtpCoupleState) == 152, "MTP coupling state wire");
static_assert(sizeof(RadMtpCoupleState) == 168, "MTP coupling state wire");
static_assert(offsetof(RadMtpCoupleState, q) % 8 == 0, "MTP coupling q alignment");
#endif
@@ -101,6 +117,9 @@ static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleS
sum += s.q[i];
has_x |= s.ids[i] == s.x;
}
if (s.nkids < 0 || s.nkids > s.count || (s.nkids >= 2 && s.ids[0] != s.x)) return false;
if (s.scheme < 0 || s.scheme > RAD_MTP_COUPLE_MAX_RHEO_M + 1 || (s.scheme && s.nkids >= 1 && s.ids[0] != s.x))
return false;
return has_x && (sum - 1) <= 1e-12 && (1 - sum) <= 1e-12;
}
@@ -327,6 +346,8 @@ static inline RAD_SPECHUB_HD int32_t rad_dflash_couple_step(const float* sc, con
s->pos = 0;
s->round = round;
s->count = 0;
s->nkids = 0; /* a walk's position is one draw: the chain's wire */
s->scheme = 0;
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
if (d.mode != 1) {
s->status = 0;