diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 84dec006..396a2b4b 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -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: diff --git a/abi/rad_abi_layout_rows.h b/abi/rad_abi_layout_rows.h index 701ccebf..128beefd 100644 --- a/abi/rad_abi_layout_rows.h +++ b/abi/rad_abi_layout_rows.h @@ -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_) diff --git a/abi/rad_mtp_block.h b/abi/rad_mtp_block.h new file mode 100644 index 00000000..6d46da86 --- /dev/null +++ b/abi/rad_mtp_block.h @@ -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 */ diff --git a/abi/rad_mtp_rrs.h b/abi/rad_mtp_rrs.h new file mode 100644 index 00000000..3157382c --- /dev/null +++ b/abi/rad_mtp_rrs.h @@ -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 +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 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 */ diff --git a/abi/rad_mtp_traversal.h b/abi/rad_mtp_traversal.h new file mode 100644 index 00000000..454ff31f --- /dev/null +++ b/abi/rad_mtp_traversal.h @@ -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 +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 */ diff --git a/abi/rad_spechub.h b/abi/rad_spechub.h index eea82ed7..0c35e86b 100644 --- a/abi/rad_spechub.h +++ b/abi/rad_spechub.h @@ -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; diff --git a/core/config.cpp b/core/config.cpp index 41f4f5de..ffb26452 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -216,6 +216,13 @@ static const Flag g_flags[] = { " 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-verify", "MODE", "token (default, alias rowwise) | block | traversal -- how a coupled draft chain is\n" + " verified: token decides each row on its own (maximal coupling);\n" + " block decides the whole chain at once (Block Verification, arXiv\n" + " 2403.10444; switches --draft-coupling on); traversal decides a\n" + " root-to-leaf path bottom-up (Traversal Verification, arXiv\n" + " 2505.12398; needs --draft-coupling on). The same output law in\n" + " every mode, more drafts accepted per step in block and traversal" }, { "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" }, { "--host", "ADDR", "listen address" }, @@ -904,6 +911,19 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_E_INVAL; } } + else if (S("--draft-verify")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!std::strcmp(v, "token") || !std::strcmp(v, "rowwise")) { + c->draft_verify_block = false; + c->draft_verify_traversal = false; + } + else if (!std::strcmp(v, "block")) { c->draft_verify_block = true; c->draft_verify_traversal = false; } + else if (!std::strcmp(v, "traversal")) { c->draft_verify_block = false; c->draft_verify_traversal = true; } + else { + RAD_ERR("--draft-verify takes token (rowwise), block or traversal, not '%s'", v); + return RAD_E_INVAL; + } + } else if (S("--draft-model")) { /* Refused, not ignored: separate draft models are not supported (spec §10), and the * drafter comes from the container (rad-convert --draft-model merges one in; an MTP @@ -1411,6 +1431,21 @@ int config_parse(int argc, char** argv, Config* c) { RAD_ERR("--video-min-pixels is above --video-max-pixels"); return RAD_E_INVAL; } if (c->video_min_frames && c->video_max_frames && *c->video_min_frames > *c->video_max_frames) { RAD_ERR("--video-min-frames is above --video-max-frames"); return RAD_E_INVAL; } + /* --draft-verify block verifies a linear chain with the coupled drafting's states, so it + * switches the coupling on; traversal needs it and says so rather than switching it on. */ + if (c->draft_verify_block) { + if (c->given.count("--draft-coupling") && !c->draft_coupling) { + RAD_ERR("--draft-verify block needs the coupled drafting (--draft-coupling on); " + "--draft-coupling off contradicts it"); + return RAD_E_INVAL; + } + c->draft_coupling = true; + } + if (c->draft_verify_traversal && !c->draft_coupling) { + RAD_ERR("--draft-verify traversal requires --draft-coupling on: the walk needs the draft's " + "law Q, which only a coupled draft carries"); + return RAD_E_INVAL; + } /* --host-pool-mib is what the model pins for its weights in all; Config::host_pool_mib is a * rank's share of it, whichever of the two options came first. */ if (pool_all) c->host_pool_mib /= std::max(c->tp, 1); @@ -1536,6 +1571,8 @@ const ShowRow kShow[] = { return c.draft_short_from < 0 ? std::string("auto") : c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } }, { "--draft-coupling", [](const Config& c) { return onoff(c.draft_coupling); } }, + { "--draft-verify", [](const Config& c) { + return std::string(c.draft_verify_block ? "block" : c.draft_verify_traversal ? "traversal" : "token"); } }, { "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } }, { "--host", [](const Config& c) { return c.host; } }, { "--port", [](const Config& c) { return num(c.port); } }, diff --git a/core/engine.cpp b/core/engine.cpp index e63d2af6..b70981d5 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -880,6 +880,8 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool sc.rank = rank; sc.world_size = cfg_.tp; sc.draft_coupling = cfg_.draft_coupling; + sc.draft_verify_block = cfg_.draft_verify_block; + sc.draft_verify_traversal = cfg_.draft_verify_traversal; RAD_TRY(smp.declare(b, sc)); /* Where the chain writes the sampled ids. The engine declares it because rad-kbench drives the diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp index b516b789..4ca6f07e 100644 --- a/core/engine_draft.cpp +++ b/core/engine_draft.cpp @@ -59,6 +59,11 @@ int Engine::step_state_init() { * pinned staging beside them. A program without them is refused rather than served * uncoupled. */ mtp_couple_ = cfg_.draft_coupling; + if (cfg_.draft_verify_traversal && !mtp_couple_) { + RAD_ERR("--draft-verify traversal requires --draft-coupling on: the walk needs the draft's " + "law Q, which only a coupled draft carries"); + return RAD_E_INVAL; + } if (mtp_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 diff --git a/core/rad_core.h b/core/rad_core.h index 34ead20f..dbd1f526 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -1038,6 +1038,15 @@ struct Config { * (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; + /* --draft-verify token|block|traversal: how a coupled draft chain is verified. token (default): + * each row's maximal coupling (above). block: Block Verification (arXiv 2403.10444, + * abi/rad_mtp_block.h), the chain's drafts accepted jointly; the same output law, at least as + * many accepted tokens. block switches --draft-coupling on (the drafting half is shared). + * traversal: Traversal Verification (arXiv 2505.12398, abi/rad_mtp_traversal.h) walks the + * chain from its last draft back to its first; the same output law, never fewer accepted + * tokens than token-wise, and it needs --draft-coupling on. */ + bool draft_verify_block = false; + bool draft_verify_traversal = false; /* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ---------------- * diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp index 0e2f701d..54baac2d 100644 --- a/core/sample/sampler.cpp +++ b/core/sample/sampler.cpp @@ -164,6 +164,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { cfg_ = cfg; couple_ = cfg.draft_coupling; + trav_ = cfg.draft_coupling && cfg.draft_verify_traversal; if (cfg_.n_vocab_local <= 0) cfg_.n_vocab_local = cfg_.n_vocab / cfg_.world_size; /* The staged mask covers this rank's shard; the grammar's covers the whole vocabulary. @@ -223,6 +224,10 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { buf_couple_ = decl("sampler.mtp_couple", RAD_U32, rows, RAD_MTP_COUPLE_STATE_WORDS, RAD_BUF_PERSIST); if (!buf_couple_) return RAD_E_NOMEM; + if (trav_) { + buf_trav_ = decl("sampler.mtp_trav", RAD_I32, rows, 2, RAD_BUF_PERSIST); + if (!buf_trav_) return RAD_E_NOMEM; + } } buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT); buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT); @@ -304,8 +309,13 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { RadParam{ "n_cand", RAD_P_INT, (long long)ncand, 0, nullptr }, RadParam{ "n_vocab", RAD_P_INT, (long long)cfg_.n_vocab, 0, nullptr }, }; - op_couple_ = rad_decl_op(b, "mtp_couple_verify", pc, 3, nullptr, 0); - if (!op_couple_) return RAD_E_NOKERNEL; + if (trav_) { + op_trav_ = rad_decl_op(b, "mtp_trav_verify", pc, 3, nullptr, 0); + if (!op_trav_) return RAD_E_NOKERNEL; + } else { + op_couple_ = rad_decl_op(b, "mtp_couple_verify", pc, 3, nullptr, 0); + if (!op_couple_) return RAD_E_NOKERNEL; + } /* No rad_op_reads: the other sampler ops declare no lists, and a list on this op alone * would narrow the candidate planes' lifetime to it and refuse the first sample_topk. */ } @@ -391,6 +401,8 @@ int Sampler::stage_alloc() { if (couple_) couple_stage_ = (RadMtpCoupleState*)rad_dev_alloc( rows * (int64_t)sizeof(RadMtpCoupleState), RAD_MEM_HOST_PINNED); + if (trav_) + trav_stage_ = (int32_t*)rad_dev_alloc(rows * 2 * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED); /* Logprobs readback; only rank 0 reads it. */ if (cfg_.rank == 0) { @@ -407,7 +419,8 @@ int Sampler::stage_alloc() { } if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ || - !ngram_stage_ || !ngram_wl_stage_ || !mask_stage_ || (couple_ && !couple_stage_)) { + !ngram_stage_ || !ngram_wl_stage_ || !mask_stage_ || (couple_ && !couple_stage_) || + (trav_ && !trav_stage_)) { RAD_ERR("sampler: could not pin %s of staging", humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 + mask_words_ * 8 + 8)).c_str()); @@ -428,6 +441,8 @@ void Sampler::stage_free() { if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED); if (couple_stage_) rad_dev_free(couple_stage_, RAD_MEM_HOST_PINNED); couple_stage_ = nullptr; + if (trav_stage_) rad_dev_free(trav_stage_, RAD_MEM_HOST_PINNED); + trav_stage_ = nullptr; if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED); if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED); if (lp_cv_host_) rad_dev_free(lp_cv_host_, RAD_MEM_HOST_PINNED); @@ -790,6 +805,11 @@ int Sampler::build_step(const std::vector& reqs, int64_t step) { think = st->think; } const ReasoningCount think0 = think; + /* --draft-verify block: the chain rows bound from round 1 on, consecutively, are one block + * (abi/rad_mtp_block.h); each carries the block's length in `blk` so the verify's round-1 + * row decides them together. */ + int64_t blk_row0 = -1; + int blk_len = 0; for (int k = 0; k < n_pos; ++k) { /* Row k's drafts before it: 0..k-1 on a chain, its ancestors (root first) on a tree. */ @@ -822,6 +842,17 @@ int Sampler::build_step(const std::vector& reqs, int64_t step) { think.push(sp.reasoning, r->draft[k - 1]); } const int64_t row = n_seq_++; + /* The traversal verify's tree: this row's parent row in the step (-1 for the + * request's first row) and its own draft token. A chain's row k hangs off row k - 1. */ + if (trav_) { + int32_t pk = -1; + if (k > 0) { + pk = k - 1; + if (tpar) { const int32_t pj = tpar[k - 1]; if (pj >= 0 && pj < k) pk = pj; } + } + trav_stage_[2 * row] = pk < 0 ? -1 : (int32_t)(row - k + pk); + trav_stage_[2 * row + 1] = k > 0 && r->draft ? r->draft[k - 1] : 0; + } /* Row k verifies draft k against the state its round left. A row with no bound state * (the bonus row, a greedy row, an uncoupled step) gets a zeroed one, and the verify * leaves the pick's token alone. */ @@ -836,6 +867,13 @@ int Sampler::build_step(const std::vector& reqs, int64_t step) { if (rad_mtp_couple_binds(c, r->id, sp.seed, (uint64_t)n_out, k, r->draft[k], cfg_.n_vocab)) { couple_stage_[row] = c; + if (cfg_.draft_verify_block && !tpar) { + if (k == 0) { blk_row0 = row; blk_len = 0; } + if (blk_row0 >= 0 && k == blk_len) { + ++blk_len; + for (int64_t j = blk_row0; j <= row; ++j) couple_stage_[j].blk = blk_len; + } + } any_couple_ = true; ++couple_build_.rows; auto& q = couple_build_.seqs; @@ -1219,6 +1257,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { if (any_couple_) RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_couple_), couple_stage_, n_seq_ * (int64_t)sizeof(RadMtpCoupleState), s)); + if (any_couple_ && trav_) + RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_trav_), trav_stage_, + n_seq_ * 2 * (int64_t)sizeof(int32_t), s)); const RadOperand o_logits = opd_rows(logits, n_seq_); const RadOperand o_params = opd_rows(buf_params_, n_seq_); @@ -1317,7 +1358,11 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { /* After the pick, over the same plane: a coupled row replaces the pick's token and an unbound * row keeps it. The issued step is recorded for the evidence line. */ if (any_couple_) { - RAD_TRY(issue(op_couple_, { o_ci, o_cv, o_params, opd_rows(buf_couple_, n_seq_), o_tok })); + if (trav_) + RAD_TRY(issue(op_trav_, { o_ci, o_cv, o_params, opd_rows(buf_couple_, n_seq_), o_tok, + opd_rows(buf_trav_, n_seq_) })); + else + RAD_TRY(issue(op_couple_, { o_ci, o_cv, o_params, opd_rows(buf_couple_, n_seq_), o_tok })); couple_issued_step_ = couple_build_.step; } diff --git a/core/sample/sampler.h b/core/sample/sampler.h index 682cabb3..5e5c2b07 100644 --- a/core/sample/sampler.h +++ b/core/sample/sampler.h @@ -127,6 +127,12 @@ struct SamplerConfig { /* --draft-coupling: declare the coupled verify (`mtp_couple_verify`) behind the pick and the * per-row state plane it reads. */ bool draft_coupling = false; + /* --draft-verify block: the chain rows of a coupled request are verified as one block + * (abi/rad_mtp_block.h) instead of one at a time. Needs draft_coupling. */ + bool draft_verify_block = false; + /* --draft-verify traversal: `mtp_trav_verify` replaces the row-wise verify behind the pick + * (needs draft_coupling) and a per-row topology plane rides with the state plane. */ + bool draft_verify_traversal = false; }; /* ================================================================== the driver */ @@ -234,7 +240,7 @@ public: * verify op at all. Cleared by build_greedy: a gate for run(), not for evidence. */ bool staged_any_couple() const { return any_couple_; } /* The verify op the last build resolved, for naming its kernel in a log line. */ - rad_op staged_couple_op() const { return op_couple_; } + rad_op staged_couple_op() const { return trav_ ? op_trav_ : op_couple_; } /* What build_step staged for the coupled verify. build_greedy, which runs between that build * and the step's wait, clears any_couple_ but leaves this snapshot. */ @@ -303,6 +309,10 @@ private: rad_op op_allgather_ = RAD_NULL_HANDLE; rad_op op_merge_ = RAD_NULL_HANDLE; /* the candidate merge, under tensor parallel */ rad_op op_couple_ = RAD_NULL_HANDLE; /* --draft-coupling only */ + rad_op op_trav_ = RAD_NULL_HANDLE; /* --draft-verify traversal: replaces op_couple_ */ + rad_buf buf_trav_ = RAD_NULL_HANDLE; /* [rows, 2] i32: parent row (-1 root), draft token */ + int32_t* trav_stage_ = nullptr; /* pinned, 2 words a sampled row */ + bool trav_ = false; rad_op op_logprobs_ = RAD_NULL_HANDLE; /* summary of the raw distribution */ rad_op op_lp_gather_ = RAD_NULL_HANDLE; /* every rank's summary, under a split vocabulary */ diff --git a/docs/GUIDE.md b/docs/GUIDE.md index ac23b784..bafa2ee7 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2423,6 +2423,7 @@ switch is set with `true`. The fleet's own keys (a model's `aliases`, `priority` | `draft-window: MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, for a serial draft head or prompt lookup alone (§4.6) | | `draft-short-from: N` | auto | a block drafter that declares a shorter block runs it from N decoding sequences on, its own block again two below or at one sequence; 0 never; auto never for a chain and 2 for a tree drafter, which then verifies the short block's nodes (§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. 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 0.6 (fixed in `qwen35_fp8`, where acceptance peaked); on Qwen3.8-27B MXFP4 TP2 at 2x R9700 and request temperature 1, tokens per verify step +8% on held-out prompts at c4 (3.53 to 3.82) and decode +2..8% per stream at c1/c4. Any other drafter is refused at startup | +| `draft-verify: MODE` | token | how a coupled draft chain is verified: `token` decides each row on its own (maximal coupling); `block` decides the whole chain at once (Block Verification, arXiv 2403.10444) and switches `draft-coupling` on; `traversal` walks the chain bottom-up (Traversal Verification, arXiv 2505.12398) and needs `draft-coupling: on`. The output distribution is the same in all three, every draft a step accepts is one the target's own law would have produced, and `block` and `traversal` accept at least as many drafts a step as `token`. Sampled rows only: a greedy row is verified as before. The verify runs as one workgroup a request, with no scratch (§6) | | `draft-model: PATH` | | not implemented: merge the drafter at convert time | **Server** diff --git a/docs/IMPLEMENTATION.md b/docs/IMPLEMENTATION.md index 823a2c52..46b78ed4 100644 --- a/docs/IMPLEMENTATION.md +++ b/docs/IMPLEMENTATION.md @@ -43,7 +43,7 @@ libavx/ the same vocabulary in x86 SIMD, host domain: the production h built on every x86-64 build because the engine refuses to serve an op that resolves only to libref (without debug-accept-reference-kernels) libquant/ the built-in quantisers rad-convert's recipes name: grids, transforms, rtn, gptq -plugin/spechub/ the draft-coupling ops (`mtp_couple_propose`, `mtp_couple_verify`, +plugin/spechub/ the draft-coupling ops (`mtp_couple_propose`, `mtp_couple_verify`, `mtp_trav_verify`, `dflash_couple_propose`, `draft-coupling: on`): schemas and shapes on the host, launches on the card and in a host reference arch// one architecture plugin per directory diff --git a/docs/KERNELS.md b/docs/KERNELS.md index 35f1bd6b..3cc058ba 100644 --- a/docs/KERNELS.md +++ b/docs/KERNELS.md @@ -718,9 +718,11 @@ Rows declaring an optional hook (tuning, fusion, weight layout): | `ref_dflash_couple_propose` | `dflash_couple_propose` | | `ref_mtp_couple_propose` | `mtp_couple_propose` | | `ref_mtp_couple_verify` | `mtp_couple_verify` | +| `ref_mtp_trav_verify` | `mtp_trav_verify` | | `spechub_dflash_couple_propose` | `dflash_couple_propose` | | `spechub_mtp_couple_propose` | `mtp_couple_propose` | | `spechub_mtp_couple_verify` | `mtp_couple_verify` | +| `spechub_mtp_trav_verify` | `mtp_trav_verify` | `libref`: 179 row(s) not reached: @@ -1073,6 +1075,7 @@ on a marked row is a hole this model falls into. | `moe_scatter_inv` | | - | device | - | - | | `mtp_couple_propose` | | - | - | device+host | - | | `mtp_couple_verify` | | - | - | device+host | - | +| `mtp_trav_verify` | | - | - | device+host | - | | `mtp_enter` | | host | device | - | host | | `mul` | | host | device | - | host | | `mul_weight` | yes | host | device | - | host | diff --git a/docs/OPS.md b/docs/OPS.md index 2a1cee88..1de26f66 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2998,10 +2998,11 @@ 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 | +| `mtp_trav_verify` | `M`(range) `n_cand` `n_vocab` | `cand_idx`, `cand_val`, `params`, `state` → `token`:inout, `topo` | | `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`, `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 +`mtp_couple_propose`, `dflash_couple_propose`, `mtp_couple_verify` and `mtp_trav_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 @@ -3020,7 +3021,20 @@ token the target itself drew at that position, and otherwise the token is a draw residual `(P - Q)+`. Both use 53-bit uniforms at `params.pos`; a row whose state is not bound to that seed and position keeps the ordinary token. `P` is FP64-normalised where `sample_pick` is FP32/24-bit, so a coupled row realizes the ideal filtered target law and is **not** seed-identical -to the ordinary pick. +to the ordinary pick. A state whose `blk` is at least 1 is the first row of a block, which the same +op decides together with the rows after it (`draft-verify: block`, Block Verification, arXiv +2403.10444, abi/rad_mtp_block.h): the workgroup of its round-1 row writes the tokens of rows 0 .. +tau and the block's other rows return. + +`mtp_trav_verify` replaces `mtp_couple_verify` under `draft-verify: traversal` (Traversal +Verification, arXiv 2505.12398, abi/rad_mtp_traversal.h). Its sixth operand `topo` is `[M, 2]` int32 +per sampled row: the parent's row in the step (-1 for a request's first row, the root of its tree) +and the row's own draft token; the rows of a request are contiguous, root first, parents before +children. One workgroup a request, on its root row, decides the whole request: the target's law of +each row as integer masses of a fixed-point exponential, the walk from the last draft back to the +first in FP64, and the tokens of the accepted path and the final token written into `token`. Rows +whose state is not eligible are leaves and keep the ordinary token. Any `n_cand`. The kernel has no +scratch segment. It emits the same law as the row-wise verify and accepts at least as many drafts. `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 diff --git a/plugin/spechub/exports.cpp b/plugin/spechub/exports.cpp index 864207cc..4ba83d4c 100644 --- a/plugin/spechub/exports.cpp +++ b/plugin/spechub/exports.cpp @@ -78,6 +78,7 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { 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), + rad_spechub_row(3, rad_mine_mtp_trav_verify_launch), }; if (i >= 0 && i < RAD_SPECHUB_N_OPS) return &dev[i]; i -= RAD_SPECHUB_N_OPS; @@ -86,6 +87,7 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { 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"), + ref_row(3, rad_ref_mtp_trav_verify, "ref_mtp_trav_verify"), }; if (i < 0 || i >= RAD_SPECHUB_N_OPS) return nullptr; return &ref[i]; diff --git a/plugin/spechub/ref_spechub.cpp b/plugin/spechub/ref_spechub.cpp index 7a722ed2..3de3046d 100644 --- a/plugin/spechub/ref_spechub.cpp +++ b/plugin/spechub/ref_spechub.cpp @@ -21,6 +21,15 @@ int rad_ref_mtp_couple_verify(const RadArgs* a, RadStream) { return RAD_OK; } +/* The traversal walk, one request at a time: the definition the device kernel runs per root. */ +int rad_ref_mtp_trav_verify(const RadArgs* a, RadStream) { + RadMtpTravCall c{}; + const int rc = rad_mtp_trav_verify_args(a, &c); + if (rc != RAD_OK) return rc; + for (int64_t row = 0; row < c.v.M; ++row) rad_mtp_trav_verify_root(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) { diff --git a/plugin/spechub/spechub.cpp b/plugin/spechub/spechub.cpp index 5068ae6b..565d509b 100644 --- a/plugin/spechub/spechub.cpp +++ b/plugin/spechub/spechub.cpp @@ -42,6 +42,16 @@ const RadOperandSpec kVerifyOperands[] = { { "token", RAD_OPD_INOUT, 0 }, }; +/* Traversal verification: the verify's five operands and the step's tree. */ +const RadOperandSpec kTravOperands[] = { + { "cand_idx", RAD_OPD_IN, 0 }, + { "cand_val", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "state", RAD_OPD_IN, 0 }, + { "token", RAD_OPD_INOUT, 0 }, + { "topo", RAD_OPD_IN, 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[] = { @@ -65,7 +75,8 @@ const RadOpSchema kSchemas[] = { { "mtp_couple_verify", kVerifyParams, 3, kVerifyOperands, 5, "Maximal coupling of a bound mtp_couple state after sample_pick over all surviving target " "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 " + "r(x)=0; a state with `blk` >= 1 is the first row of a block, verified together with the rows after " + "it (Block Verification, arXiv 2403.10444). 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 " @@ -73,6 +84,17 @@ const RadOpSchema kSchemas[] = { "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)." }, + { "mtp_trav_verify", kVerifyParams, 3, kTravOperands, 6, + "Traversal Verification (arXiv 2505.12398) of a bound draft after sample_pick: per " + "request (a row whose topo parent is -1), the bottom-up sequence-level walk over its rows' " + "bound mtp_couple states and target candidates (the target's law as integer masses of an " + "FP32 exponential, the walk in FP64): a leaf is accepted with the path's cumulative ratio, a " + "rejected leaf updates its parent's acceptance, target residual and draft law (Gumbel " + "siblings without replacement; a RheoSampling node's tail child first, then its top-q " + "children as point masses). The accepted path's rows get their path child's token and the " + "last row the final token; rows whose state is not eligible (the row-wise gate) are leaves " + "and keep the pick; an eligible row whose draw asks for it gets P exported over its state. " + "topo is [M,2] int32: parent row (-1 root), draft token. Any n_cand." }, }; } /* namespace */ @@ -263,6 +285,40 @@ int rad_mtp_couple_verify_args(const RadArgs* a, RadMtpCoupleVerifyCall* out) { return RAD_OK; } +int rad_mtp_trav_verify_shape(const RadParam* p, int n, int i, RadOpdDesc* out) { + if (!out || i < 0 || i >= 6) return RAD_E_INVAL; + if (i < 5) return rad_mtp_couple_verify_shape(p, n, i, out); + int64_t M, v, nc; + int rc = couple_geometry(p, n, 1, true, &M, &v, &nc); + if (rc != RAD_OK) return rc; + RadOpdDesc d{}; + d.idx_const = -1; + d.dtype = RAD_I32; + d.rank = 2; + d.shape[0] = M; + d.shape[1] = 2; + *out = d; + return RAD_OK; +} + +int rad_mtp_trav_verify_args(const RadArgs* a, RadMtpTravCall* out) { + if (!out || !a || !a->t || a->n_t != 6) return RAD_E_INVAL; + RadArgs five = *a; + five.n_t = 5; + RadMtpTravCall c{}; + int rc = rad_mtp_couple_verify_args(&five, &c.v); + if (rc != RAD_OK) return rc; + const RadTensor& t = a->t[5]; + if (!t.data || (uintptr_t)t.data % 4) return RAD_E_INVAL; + if (t.dtype != RAD_I32) return RAD_E_DTYPE; + if (t.rank != 2 || t.shape[0] < c.v.M || t.shape[1] != 2) return RAD_E_SHAPE; + if (t.stride[1] != 1 || t.stride[0] < 2) return RAD_E_STRIDE; + c.topo = (const int32_t*)t.data; + c.ld_topo = t.stride[0]; + *out = c; + return RAD_OK; +} + /* ------------------------------------------------------------------ dflash_couple_propose */ namespace { @@ -402,6 +458,19 @@ RadKernelInfo rad_spechub_row(int i, RadLaunchFn launch) { r.opd_shape = rad_dflash_couple_shape; return r; } + if (i == 3) { + r.name = "spechub_mtp_trav_verify"; + r.op = "mtp_trav_verify"; + r.family = "draft"; + r.computes = "Traversal Verification of a coupled draft: integer target masses, FP64 walk"; + r.shape = "M,n_cand,n_vocab"; + r.dtypes = "f32,i32,u32"; + r.domain = RAD_DOMAIN_DEVICE; + r.priority = 100; + r.launch = launch; + r.opd_shape = rad_mtp_trav_verify_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"; diff --git a/plugin/spechub/spechub.h b/plugin/spechub/spechub.h index 886f3a1e..0312589a 100644 --- a/plugin/spechub/spechub.h +++ b/plugin/spechub/spechub.h @@ -10,6 +10,9 @@ #include "rad_abi.h" #include "rad_plugin.h" /* rad_param_geti/getdim: the pure readers, inline and total */ #include "rad_spechub.h" +#include "rad_mtp_rrs.h" +#include "rad_mtp_block.h" +#include "rad_mtp_traversal.h" #include #include @@ -44,6 +47,16 @@ struct RadMtpCoupleVerifyCall { int64_t M, n_cand, vocab, ld[5]; }; +/* The traversal verify's operands: the row-wise verify's, plus the step's tree. `topo` is + * [M, 2] int32 per sampled row: the parent's row in the step (-1 for a request's first row, its + * tree's root) and the row's own draft token. The rows of one request are contiguous, the root + * first, parents before children (core/sample/sampler.cpp stages it that way). */ +struct RadMtpTravCall { + RadMtpCoupleVerifyCall v; + const int32_t* topo; + int64_t ld_topo; +}; + /* 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. */ @@ -68,6 +81,8 @@ 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_mtp_trav_verify_shape(const RadParam*, int, int, RadOpdDesc*); +int rad_mtp_trav_verify_args(const RadArgs*, RadMtpTravCall*); int rad_dflash_couple_args(const RadArgs*, RadDflashCoupleCall*); /* The geometry/validation the shape hooks and the arg readers share. `op` 0 proposes, 1 verifies. */ @@ -75,7 +90,7 @@ int rad_couple_validate(const RadArgs*, int op, int64_t* M, int64_t* vocab, int6 /* 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 +#define RAD_SPECHUB_N_OPS 4 int rad_spechub_schema_count(); const RadOpSchema* rad_spechub_schema_at(int i); RadKernelInfo rad_spechub_row(int i, RadLaunchFn launch); @@ -86,6 +101,8 @@ 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_mine_mtp_trav_verify_launch(const RadArgs*, RadStream); +int rad_ref_mtp_trav_verify(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 @@ -115,7 +132,56 @@ static inline RAD_SPECHUB_HD void rad_mtp_couple_propose_row(const RadMtpCoupleP *reinterpret_cast(c.state + (c.round - 1) * c.st_round + row * c.st_row) = s; } +/* --draft-verify block (abi/rad_mtp_block.h). The sampler marks the chain rows of a request it + * verifies as one block by `blk` = the block's length g (the rows 0 .. g-1 bound to rounds 1 .. g, + * consecutive); the row of round 1 decides the whole block and writes the tokens of rows 0 .. tau, + * the other rows do nothing (their tokens are written by it). Row i of the block is admitted only + * if it is the state the sampler would have bound for it: same request, seed, round, position + * (pos0 + i) and a valid state; any other row ends the block's coupling (the ordinary picks + * stand, which is exact). */ +static inline RAD_SPECHUB_HD bool rad_mtp_block_row_ok(const RadMtpCoupleState& s0, + const RadMtpCoupleState& s, + const RadSampleParams& p0, + const RadSampleParams& p, int i, int g, + int64_t vocab) { + return s.status == 1 && s.blk == g && s.round == i + 1 && s.nkids <= 1 && + !(p.flags & RAD_SP_GREEDY) && s.draw.seed == p.seed && p.seed == p0.seed && + s.draw.seq == s0.draw.seq && s.pos == p.pos && p.pos == p0.pos + (uint64_t)i && + s.pos == s0.pos + (uint64_t)i && rad_mtp_couple_state_valid(s, vocab); +} + +/* The block's tokens: rows 0 .. tau of the block take the drafts and then Y. */ +static inline RAD_SPECHUB_HD void rad_mtp_block_write(const RadMtpCoupleVerifyCall& c, int64_t row, + const RadMtpCoupleState* st, int tau, int g, + int32_t y) { + for (int i = 0; i < tau; ++i) c.token[(row + i) * c.ld[4]] = st[i].x; + if (tau < g) c.token[(row + tau) * c.ld[4]] = y; +} + +static inline RAD_SPECHUB_HD void rad_mtp_block_verify_row(const RadMtpCoupleVerifyCall& c, + int64_t row) { + const auto& s0 = *reinterpret_cast(c.state + row * c.ld[3]); + const int g = s0.blk; + if (s0.round != 1 || g < 1 || g > RAD_MTP_BLOCK_MAX || row + g > c.M) return; + const auto& p0 = *reinterpret_cast(c.params + row * c.ld[2]); + RadMtpCoupleState st[RAD_MTP_BLOCK_MAX]; + RadBlockRow rows[RAD_MTP_BLOCK_MAX]; + for (int i = 0; i < g; ++i) { + st[i] = *reinterpret_cast(c.state + (row + i) * c.ld[3]); + const auto& p = *reinterpret_cast(c.params + (row + i) * c.ld[2]); + if (!rad_mtp_block_row_ok(s0, st[i], p0, p, i, g, c.vocab)) return; + rows[i] = RadBlockRow{ c.idx + (row + i) * c.ld[0], c.val + (row + i) * c.ld[1], + c.n_cand, 0, 0.0f }; + rad_mtp_block_scan(&rows[i], c.vocab); + } + int tau = 0; + int32_t y = -1; + if (!rad_mtp_block_decide(st, rows, g, p0.seed, p0.pos, &tau, &y)) return; + rad_mtp_block_write(c, row, st, tau, g, y); +} + /* One verify row, after sample_pick. A row without a valid bound state keeps the ordinary token. */ +template static inline RAD_SPECHUB_HD void rad_mtp_couple_verify_row(const RadMtpCoupleVerifyCall& c, int64_t row) { const auto& s = *reinterpret_cast(c.state + row * c.ld[3]); @@ -124,12 +190,93 @@ static inline RAD_SPECHUB_HD void rad_mtp_couple_verify_row(const RadMtpCoupleVe if ((p.flags & RAD_SP_GREEDY) || s.draw.seed != p.seed || s.pos != p.pos || !rad_mtp_couple_state_valid(s, c.vocab)) return; + if (s.blk >= 1) { + /* kBlock = false: the caller has decided block rows already; the block row's planes are + * big private arrays and would put the whole kernel's scratch request up. */ + if constexpr (kBlock) rad_mtp_block_verify_row(c, row); + return; + } int32_t out = -1; + /* A RheoSampling node (state.scheme, abi/rad_mtp_rrs.h): the greedy multi-draft verifier. */ + if (s.scheme != 0) { + if (rad_mtp_rrs_decide_rheo(s, c.idx + row * c.ld[0], c.val + row * c.ld[1], c.n_cand, c.vocab, + p.seed, p.pos, &out)) + c.token[row * c.ld[4]] = out; + return; + } + /* A tree node with several drafted children: recursive rejection sampling over them. */ + if (s.nkids >= 2) { + if (rad_mtp_rrs_decide(s, c.idx + row * c.ld[0], c.val + row * c.ld[1], c.n_cand, c.vocab, + p.seed, p.pos, &out)) { + c.token[row * c.ld[4]] = out; + } + return; + } if (rad_mtp_couple_decide(s, c.idx + row * c.ld[0], c.val + row * c.ld[1], c.n_cand, c.vocab, rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_ACCEPT), rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_RESID), &out)) c.token[row * c.ld[4]] = out; } +/* The row-wise verify's gate, which the traversal walk shares: a row is a node the walk may use + * only when the row-wise verify would have accepted its state, so a row that is greedy, unbound or + * stale is a leaf of the walk and keeps the pick's token. */ +static inline RAD_SPECHUB_HD bool rad_mtp_trav_eligible(const RadMtpCoupleState& s, + const RadSampleParams& p, int64_t vocab) { + return s.status == 1 && !(p.flags & RAD_SP_GREEDY) && s.draw.seed == p.seed && s.pos == p.pos && + rad_mtp_couple_state_valid(s, vocab); +} + +/* The rows of the request whose root is `row` that the walk reads: the root and the rows after it + * with a parent, at most RAD_MTP_TRAV_MAX_ROWS (a later row is a child no verify carries). */ +static inline RAD_SPECHUB_HD int64_t rad_mtp_trav_rows(const RadMtpTravCall& c, int64_t row) { + int64_t n = 1; + while (row + n < c.v.M && n < RAD_MTP_TRAV_MAX_ROWS && c.topo[(row + n) * c.ld_topo] >= 0) ++n; + return n; +} + +/* The traversal walk's view of one request's rows: node v is row `root + v`. */ +struct RadMtpTravRows { + const RadMtpTravCall& c; + int64_t root; + int64_t n; /* rows of the request */ + RAD_SPECHUB_HD const RadMtpCoupleState* state(int v) const { + const int64_t row = root + v; + const auto& s = *reinterpret_cast(c.v.state + row * c.v.ld[3]); + const auto& p = *reinterpret_cast(c.v.params + row * c.v.ld[2]); + return rad_mtp_trav_eligible(s, p, c.v.vocab) ? &s : nullptr; + } + RAD_SPECHUB_HD bool cand(int v, const int32_t** ids, const float** val, int64_t* nc) const { + *ids = c.v.idx + (root + v) * c.v.ld[0]; + *val = c.v.val + (root + v) * c.v.ld[1]; + *nc = c.v.n_cand; + return true; + } + RAD_SPECHUB_HD int child(int v, int32_t token) const { + for (int64_t u = (int64_t)v + 1; u < n; ++u) { + const int32_t* t = c.topo + (root + u) * c.ld_topo; + if (t[0] == (int32_t)(root + v) && t[1] == token) return (int)u; + } + return -1; + } + RAD_SPECHUB_HD int64_t vocab() const { return c.v.vocab; } +}; + +/* One request's tree, if `row` is its root: walk it and write the path's tokens. The host + * reference; the device kernel (spechub.hip, trav_verify) prepares the same tree with a workgroup + * and runs the same walk. */ +static inline void rad_mtp_trav_verify_root(const RadMtpTravCall& c, int64_t row) { + if (c.topo[row * c.ld_topo] >= 0) return; + const int64_t n = rad_mtp_trav_rows(c, row); + const RadMtpTravRows T{ c, row, n }; + const auto& p = *reinterpret_cast(c.v.params + row * c.v.ld[2]); + RadMtpTravOut o; + const bool walked = rad_mtp_trav_walk(T, 0, p.seed, p.pos, &o); + if (!walked) return; + for (int i = 0; i + 1 < o.n; ++i) + c.v.token[(row + o.node[i]) * c.v.ld[4]] = c.topo[(row + o.node[i + 1]) * c.ld_topo + 1]; + if (o.has_y) c.v.token[(row + o.node[o.n - 1]) * c.v.ld[4]] = o.y; +} + #undef RAD_SPECHUB_HD #endif /* RAD_PLUGIN_SPECHUB_H */ diff --git a/plugin/spechub/spechub.hip b/plugin/spechub/spechub.hip index 3229fa48..1c2a03af 100644 --- a/plugin/spechub/spechub.hip +++ b/plugin/spechub/spechub.hip @@ -85,6 +85,153 @@ __device__ void couple_live(const int32_t* ids, const float* val, int64_t n, int __syncthreads(); } +/* The live candidates of a row as the shared decisions read them (rad_mtp_rrs_decide_over, + * rad_mtp_trav_*): the sampler's ids, the compaction (`lj`, ascending candidate order), each live + * candidate's FP64 weight exp(val - top) and its slot in the node's support (count when outside), + * all computed by the workgroup and stored in LDS. */ +struct LiveCands { + const int32_t* ids; const short* lj; const double* w; const unsigned char* k; int L; + template __device__ void each(F&& f) const { + for (int i = 0; i < L; ++i) + if (!f(ids[lj[i]], w[i], (int)k[i])) return; + } +}; + +/* --draft-verify block (abi/rad_mtp_block.h). The workgroup of a block's round-1 row decides the + * whole block and writes the tokens of rows 0 .. tau; the block's other rows return. Every FP64 sum + * over a candidate plane is the header's fixed lane tree (slot j to lane j % 128, ascending within + * the lane, butterfly over each wave's 32 lanes, the four wave sums as ((0+1)+(2+3))): the + * workgroup computes all exps and lane partials in parallel and thread 0 only runs the 8-wide + * plan, so the result is the host reference's bit for bit (rad_mtp_block_decide). Called by every + * thread of the workgroup. */ +static_assert(kThreads == RAD_MTP_BLOCK_LANES && RAD_MTP_BLOCK_WAVE == 32, "the tree's shape"); + +__device__ void block_verify(const RadMtpCoupleVerifyCall& c, int64_t row) { + constexpr int kW = kThreads / 32; + __shared__ RadMtpCoupleState sst[RAD_MTP_BLOCK_MAX]; + __shared__ RadBlockStat sstat[RAD_MTP_BLOCK_MAX]; + __shared__ RadBlockPlan plan; + __shared__ float wmax[RAD_MTP_BLOCK_MAX][kW]; + __shared__ int wbad[RAD_MTP_BLOCK_MAX][kW]; + __shared__ double wacc[RAD_MTP_BLOCK_MAX][kW][10]; + __shared__ RadBlockLane lanes[kThreads]; + __shared__ int g_s, ok_s, tau_s; + __shared__ int32_t y_s; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + if (tid == 0) { + const auto& s0 = *reinterpret_cast(c.state + row * c.ld[3]); + g_s = s0.blk; + ok_s = s0.round == 1 && g_s >= 1 && g_s <= RAD_MTP_BLOCK_MAX && row + g_s <= c.M; + if (ok_s) { + const auto& p0 = *reinterpret_cast(c.params + row * c.ld[2]); + for (int i = 0; i < g_s && ok_s; ++i) { + sst[i] = *reinterpret_cast(c.state + (row + i) * c.ld[3]); + const auto& p = *reinterpret_cast(c.params + (row + i) * c.ld[2]); + ok_s = rad_mtp_block_row_ok(sst[0], sst[i], p0, p, i, g_s, c.vocab); + } + } + } + __syncthreads(); + if (!ok_s) return; + const int g = g_s; + const int64_t n = c.n_cand; + /* every row's validity and maximum */ + for (int i = 0; i < g; ++i) { + const int32_t* ids = c.idx + (row + i) * c.ld[0]; + const float* val = c.val + (row + i) * c.ld[1]; + int bad = 0; + float mx = -INFINITY; + for (int64_t j = tid; j < n; j += kThreads) { + const int32_t id = ids[j]; + const float v = val[j]; + if (id >= 0) { + if (id >= c.vocab || v != v || v == INFINITY) bad = 1; + else if (v > mx) mx = v; + } + } + for (int d = 16; d > 0; d >>= 1) { + bad |= __shfl_xor(bad, d); + mx = fmaxf(mx, __shfl_xor(mx, d)); + } + if (lane == 0) { wbad[i][wave] = bad; wmax[i][wave] = mx; } + } + __syncthreads(); + /* the lane partials and the butterfly of every row */ + for (int i = 0; i < g; ++i) { + const int32_t* ids = c.idx + (row + i) * c.ld[0]; + const float* val = c.val + (row + i) * c.ld[1]; + float top = wmax[i][0]; + int bad = wbad[i][0]; + for (int w = 1; w < kW; ++w) { top = fmaxf(top, wmax[i][w]); bad |= wbad[i][w]; } + if (bad || top == -INFINITY) return; /* uniform: the same LDS everywhere */ + RadBlockAcc a; + for (int k = 0; k < 10; ++k) a.v[k] = 0; + for (int64_t j = tid; j < n; j += kThreads) + if (rad_mtp_block_live(ids[j], val[j])) rad_mtp_block_acc_add(&a, sst[i], ids[j], val[j], top); + for (int d = 16; d > 0; d >>= 1) + for (int k = 0; k < 10; ++k) a.v[k] = a.v[k] + __shfl_xor(a.v[k], d); + if (lane == 0) + for (int k = 0; k < 10; ++k) wacc[i][wave][k] = a.v[k]; + } + __syncthreads(); + if (tid == 0) { + for (int i = 0; i < g && ok_s; ++i) { + RadBlockAcc t; + for (int k = 0; k < 10; ++k) + t.v[k] = (wacc[i][0][k] + wacc[i][1][k]) + (wacc[i][2][k] + wacc[i][3][k]); + float top = wmax[i][0]; + for (int w = 1; w < kW; ++w) top = fmaxf(top, wmax[i][w]); + if (!rad_mtp_block_stat_from(t, 1, top, sst[i], &sstat[i])) ok_s = 0; + } + if (ok_s) { + const auto& p0 = *reinterpret_cast(c.params + row * c.ld[2]); + rad_mtp_block_plan(sst, sstat, g, &plan); + tau_s = rad_mtp_block_tau(plan, p0.seed, p0.pos); + } + y_s = -1; + } + __syncthreads(); + if (!ok_s) return; + const int tau = tau_s; + const auto& p0 = *reinterpret_cast(c.params + row * c.ld[2]); + if (tau < g) { + const int32_t* ids = c.idx + (row + tau) * c.ld[0]; + const float* val = c.val + (row + tau) * c.ld[1]; + float top = wmax[tau][0]; + for (int w = 1; w < kW; ++w) top = fmaxf(top, wmax[tau][w]); + RadBlockLane a{ 0, 0, -1, -1 }; + for (int64_t j = tid; j < n; j += kThreads) + if (rad_mtp_block_live(ids[j], val[j])) + rad_mtp_block_lane_add(&a, sst[tau], sstat[tau], plan.p[tau], ids[j], val[j], top); + lanes[tid] = a; + __syncthreads(); + if (tid == 0) { + const RadBlockRow r{ ids, val, n, 1, top }; + if (!rad_mtp_block_resid_walk(r, sst[tau], sstat[tau], plan.p[tau], + rad_spechub_uniform(p0.seed, p0.pos + (uint64_t)tau, + RAD_SAMPLE_KEY_RESID), + lanes, &y_s)) + ok_s = 0; + } + __syncthreads(); + if (!ok_s) return; + } + if (tid == 0) rad_mtp_block_write(c, row, sst, tau, g, y_s); +} + +/* Above kMaxCand the LDS planes would overflow, so one thread runs the serial helper. The helper + * carries the block row's big private planes, which is why it is a kernel of its own: inside + * couple_verify it gave every launch of that kernel a 17.8 KB/lane scratch request (queue + * OUT_OF_RESOURCES on the first sampled tree). */ +__global__ void couple_verify_wide(const int32_t* idx, const float* values, const uint32_t* params, + const uint32_t* state, int32_t* token, int64_t M, int64_t n_cand, + int64_t vocab, int64_t ld0, int64_t ld1, int64_t ld2, int64_t ld3, + int64_t ld4) { + RadMtpCoupleVerifyCall c{ idx, values, params, state, token, M, n_cand, vocab, + { ld0, ld1, ld2, ld3, ld4 } }; + if (blockIdx.x < M && threadIdx.x == 0) rad_mtp_couple_verify_row(c, blockIdx.x); +} + __global__ void couple_verify(const int32_t* idx, const float* values, const uint32_t* params, const uint32_t* state, int32_t* token, int64_t M, int64_t n_cand, int64_t vocab, int64_t ld0, int64_t ld1, int64_t ld2, int64_t ld3, @@ -93,11 +240,7 @@ __global__ void couple_verify(const int32_t* idx, const float* values, const uin { ld0, ld1, ld2, ld3, ld4 } }; const int64_t row = blockIdx.x; if (row >= M) return; - /* Above kMaxCand the LDS planes would overflow, so one thread runs the serial helper. */ - if (n_cand > kMaxCand) { - if (threadIdx.x == 0) rad_mtp_couple_verify_row(c, row); - return; - } + /* n_cand <= kMaxCand here: the launch sends wider planes to couple_verify_wide. */ /* `weight` is P's unnormalised FP64 mass per live candidate and `mass` its residual (P-Q)+, * both indexed by the candidate's place in `lj`. */ __shared__ double weight[kMaxCand], mass[kMaxCand], pq[8], sum; @@ -115,10 +258,50 @@ __global__ void couple_verify(const int32_t* idx, const float* values, const uin s.pos == p.pos && rad_mtp_couple_state_valid(s, c.vocab); __syncthreads(); if (!eligible) return; + /* A chain row of a block-verified draft (--draft-verify block). */ + if (s.blk >= 1) { +#ifdef RAD_BLOCK_REPEAT + /* microbenchmark build: the block is decided RAD_BLOCK_REPEAT times back to back (idempotent) */ + for (int rep = 0; rep < RAD_BLOCK_REPEAT; ++rep) { block_verify(c, row); __syncthreads(); } +#else + block_verify(c, row); +#endif + return; + } + /* A RheoSampling node (abi/rad_mtp_rrs.h): one thread runs the shared serial helper, which is + * the host reference itself. Only a node with a RheoSampling scheme takes it. */ + if (s.scheme != 0) { + if (threadIdx.x == 0) rad_mtp_couple_verify_row(c, row); + return; + } couple_live(ids, val, c.n_cand, c.vocab, lj, &nl, &valid, &top); if (!valid || top == -INFINITY) return; const int L = nl; for (int i = threadIdx.x; i < L; i += blockDim.x) weight[i] = ::exp((double)val[lj[i]] - top); + /* A tree node with several drafted children (abi/rad_mtp_rrs.h, recursive rejection sampling): + * the workgroup has compacted the live candidates and computed every weight and every + * candidate's slot in the node's support; one lane then runs the host reference's own decision + * (rad_mtp_rrs_decide_over) over those stored values, in the same order, so the token is the + * host's bit for bit. */ + if (s.nkids >= 2) { + __shared__ unsigned char kslot[kMaxCand]; + __shared__ double pq_x[8], sum_x; + for (int i = threadIdx.x; i < L; i += blockDim.x) { + const int32_t id = ids[lj[i]]; + int k = 0; + while (k < s.count && id != s.ids[k]) ++k; + kslot[i] = (unsigned char)k; + } + __syncthreads(); + if (threadIdx.x == 0) { + int32_t out = -1; + if (rad_mtp_rrs_decide_over(s, LiveCands{ ids, lj, weight, kslot, L }, p.seed, p.pos, &out, + pq_x, &sum_x)) { + c.token[row * c.ld[4]] = out; + } + } + return; + } __syncthreads(); if (threadIdx.x == 0) { sum = 0; @@ -354,6 +537,8 @@ __global__ __launch_bounds__(kDfThreads) void dflash_couple( s.round = (int)l + 1; s.status = -1; s.count = 0; + s.nkids = 0; /* the 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; } for (int i = 0; i < sn; ++i) if (wq[i] > 0) { s.ids[s.count] = lid[i]; s.q[s.count++] = wq[i]; } @@ -402,12 +587,400 @@ int rad_mine_mtp_couple_propose_launch(const RadArgs* a, RadStream stream) { return R4D_EMIT(stream, propose, dim3((unsigned)((c.M + 63) / 64)), dim3(64), 0, c); } +/* ------------------------------------------------------------------ traversal verification + * + * abi/rad_mtp_traversal.h, one workgroup a row; only a request's root row (topo parent -1) does + * work, and it decides the whole request. Its four waves each take every fourth row of the request + * and need nothing from each other until the tree is complete: + * + * per row, one wave: lane 0 reads the row's state (the gate, the canonical draft side) into LDS + * and hands the wave what it needs of it in registers; a lane a later row finds the node's + * child rows in the step's topology; the wave reads the row's candidate + * plane a pass of 32 slots at a time, one slot a lane (a top_k 20 plane is one live pass): the + * largest value and the validity, reduced over the wave in registers, then the integer masses + * (rad_mtp_trav_mass) of the passes that have a live slot, summed in all and on the node's + * support slots and reduced the same way -- integer sums, so the order is free and the totals + * are the host's serial ones bit for bit; lanes 0..7 turn them into the node's law, mass / + * total, + * one barrier, the kernel's only one; + * wave 0, lane 0: the walk itself (rad_mtp_trav_walk_tree, the host's code over + * the tree in LDS: one FP64 division to enter a node, two and a few dozen multiply-adds when a + * child is rejected), the path's + * tokens and the final token's slot or off-support unit; then the wave finds the off-support + * candidate holding that unit (a prefix over the lanes of each pass, in registers). + * + * Lanes talk to each other in two ways only: through LDS ACROSS the barrier, and through registers + * (v_readlane, DPP) inside a wave. A lane never reads from LDS what another lane wrote since the last + * barrier: the hardware would order the two accesses of one wave, but the compiler, which sees a + * thread at a time, may move the read before the write. No candidate plane is copied, no lane walks a + * plane alone at any width, and the kernel has no scratch segment (nothing private is indexed at run + * time). Tokens and paths are the host reference's bit for bit (rad_mtp_trav_verify_root). */ +namespace { + +template +__device__ __forceinline__ uint32_t tv_xor_lane(uint32_t v) { + /* lane ^ N's value on DPP (row_xmask; 16 crosses the wave's two rows): every lane must be active */ + if constexpr (N < 16) + return (uint32_t)__builtin_amdgcn_update_dpp(0, (int)v, 0x160 | N, 0xf, 0xf, true); + else + return (uint32_t)__builtin_amdgcn_permlanex16((int)v, (int)v, 0x76543210u, 0xFEDCBA98u, false, false); +} +template +__device__ __forceinline__ uint64_t tv_xor_add(uint64_t v) { + return v + (((uint64_t)tv_xor_lane((uint32_t)(v >> 32)) << 32) | tv_xor_lane((uint32_t)v)); +} +/* The wave's sum of a 64-bit integer, in every lane (integers: the order is free). */ +__device__ __forceinline__ uint64_t tv_wave_sum(uint64_t v) { + v = tv_xor_add<16>(v); v = tv_xor_add<8>(v); v = tv_xor_add<4>(v); + v = tv_xor_add<2>(v); v = tv_xor_add<1>(v); + return v; +} +__device__ __forceinline__ uint32_t tv_wave_or(uint32_t v) { + v |= tv_xor_lane<16>(v); v |= tv_xor_lane<8>(v); v |= tv_xor_lane<4>(v); + v |= tv_xor_lane<2>(v); v |= tv_xor_lane<1>(v); + return v; +} +__device__ __forceinline__ float tv_fmax_lane(float a, uint32_t b) { return fmaxf(a, __uint_as_float(b)); } +__device__ __forceinline__ float tv_wave_max(float v) { + v = tv_fmax_lane(v, tv_xor_lane<16>(__float_as_uint(v))); + v = tv_fmax_lane(v, tv_xor_lane<8>(__float_as_uint(v))); + v = tv_fmax_lane(v, tv_xor_lane<4>(__float_as_uint(v))); + v = tv_fmax_lane(v, tv_xor_lane<2>(__float_as_uint(v))); + v = tv_fmax_lane(v, tv_xor_lane<1>(__float_as_uint(v))); + return v; +} +/* Lane 0's value in every lane of the wave (v_readlane): how one lane hands the wave a scalar + * without LDS. Every lane must be active. */ +__device__ __forceinline__ int32_t tv_lane0(int32_t v) { return __builtin_amdgcn_readlane(v, 0); } +__device__ __forceinline__ float tv_lane0f(float v) { + return __uint_as_float((uint32_t)__builtin_amdgcn_readlane((int)__float_as_uint(v), 0)); +} +/* A wave's inclusive prefix sum over its lanes (row_shr 1, 2, 4, 8 inside each row of sixteen, then + * the first row's total into the second). Every lane must be active; sums below 2^32. */ +__device__ __forceinline__ uint32_t tv_wave_prefix(uint32_t x, int lane) { + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x111, 0xF, 0xF, true); + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x112, 0xF, 0xF, true); + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x114, 0xF, 0xF, true); + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x118, 0xF, 0xF, true); + const uint32_t lo = (uint32_t)__builtin_amdgcn_readlane((int)x, 15); + return lane >= 16 ? x + lo : x; +} + +constexpr int kTravRows = RAD_MTP_TRAV_MAX_ROWS; +constexpr int kTravWaves = kThreads / 32; +constexpr int kTravPer = 8; /* passes a batch */ + +/* The op's operands as the kernel takes them: 32-bit geometry (the launch refuses anything wider), + * which is half the scalar registers of 64-bit strides. */ +struct TravArgs { + const int32_t* idx; + const float* val; + const uint32_t* params; + const uint32_t* state; + int32_t* token; + const int32_t* topo; + uint32_t M, n_cand, vocab, ld0, ld1, ld2, ld3, ld4, ld_topo; +}; + +/* Eight slots of a row's plane, in registers. Lane l's slots are l, l + 32, l + 64, ... (pass p is + * slots [32 p, 32 p + 32), one a lane), so the plane's live head -- 20 slots at top_k 20 -- is one + * pass of the wave whatever its width; a batch is eight passes, sixteen loads issued together (a loop + * that loaded a pass at a time would wait out a memory latency per pass). */ +struct TvBatch { + int32_t id[kTravPer]; + float v[kTravPer]; +}; +/* Passes p0 .. p0 + 8 of lane `lane` of a row of n slots; holes past the row's end. `full`: the batch + * lies inside the row for every lane, so the loads are unconditional. The ids first: a batch of holes + * (every batch but the first at top_k 20) is known from them alone, and its values are not read. Returns + * whether any lane of the wave has an id in the batch. */ +__device__ __forceinline__ bool tv_load(const int32_t* ids, const float* val, int lane, uint32_t p0, + uint32_t n, bool full, TvBatch* c) { + const uint32_t j = (uint32_t)lane + 32u * p0; + bool on = false; + if (full) { +#pragma unroll + for (int i = 0; i < kTravPer; ++i) { c->id[i] = ids[j + 32u * i]; on = on || c->id[i] >= 0; } + } else { +#pragma unroll + for (int i = 0; i < kTravPer; ++i) { + c->id[i] = -1; + if (j + 32u * i < n) c->id[i] = ids[j + 32u * i]; + on = on || c->id[i] >= 0; + } + } +#pragma unroll + for (int i = 0; i < kTravPer; ++i) c->v[i] = -INFINITY; + if (!__ballot(on)) return false; + if (full) { +#pragma unroll + for (int i = 0; i < kTravPer; ++i) c->v[i] = val[j + 32u * i]; + } else { +#pragma unroll + for (int i = 0; i < kTravPer; ++i) + if (j + 32u * i < n) c->v[i] = val[j + 32u * i]; + } + return true; +} + +/* One request, by its root row's workgroup. Called by every thread. */ +__device__ __forceinline__ void trav_request(const TravArgs& c, uint32_t row) { + __shared__ RadTravTree T; + __shared__ int32_t s_tok[kTravRows]; + __shared__ int s_path[RAD_MTP_TRAV_MAX_DEPTH + 1]; /* lane 0's alone */ + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const uint32_t avail = c.M - row < (uint32_t)kTravRows ? c.M - row : (uint32_t)kTravRows; + const uint32_t nc = c.n_cand; + const uint32_t npass = (nc + 31u) / 32u; + const int qb = rad_mtp_trav_qbits(nc); + + /* The rows of the request: the root and the rows after it that have a parent (a lane a row). */ + uint64_t has = 1; + for (uint32_t u0 = 0; u0 < avail; u0 += 32) { + const uint32_t u = u0 + (uint32_t)lane; + bool in = false; + if (u >= 1 && u < avail) in = c.topo[(uint64_t)(row + u) * c.ld_topo] >= 0; + has |= (uint64_t)(uint32_t)__ballot(in) << u0; + } + const int n = ~has ? (int)__builtin_ctzll(~has) : 64; + + /* This wave's rows: the node, the row's law. */ + for (int v = wave; v < n; v += kTravWaves) { + const uint64_t rr = (uint64_t)row + (uint32_t)v; + int elig = 0, nkv = 0; + int32_t cid[8]; + for (int k = 0; k < 8; ++k) cid[k] = -1; + if (lane == 0) { + s_tok[v] = c.topo[rr * c.ld_topo + 1]; + /* the state by value: its words are loaded together and stay in registers (nothing below + * indexes it at run time), instead of one load a check */ + const RadMtpCoupleState s = *reinterpret_cast(c.state + rr * c.ld3); + const RadSampleParams p = *reinterpret_cast(c.params + rr * c.ld2); + double q[8]; + int nk = 0, nt = -1, tail = 0, swap = 0; + elig = rad_mtp_trav_eligible(s, p, c.vocab) && + rad_mtp_trav_canon(s, 0, cid, q, &nk, &nt, &tail, &swap); + for (int k = 0; k < 8; ++k) { + if (!elig) cid[k] = -1; + T.ids[v][k] = cid[k]; + T.qr[v][k] = elig ? q[k] : 0.0; + } + nkv = elig ? nk : 0; + T.nk[v] = nkv; + T.nt[v] = nt; + T.tail[v] = tail; + T.ci[v] = 0; + } + /* lane 0's findings, to the wave in registers */ + elig = tv_lane0(elig); + nkv = tv_lane0(nkv); + int32_t sid[8]; + for (int k = 0; k < 8; ++k) sid[k] = tv_lane0(cid[k]); + /* the node's child rows: a lane a later row of the request, the first row under this node + * that carries the slot's token */ + int chrow[8]; + for (int k = 0; k < 8; ++k) chrow[k] = -1; + if (nkv > 0) { + for (int u0 = v + 1; u0 < n; u0 += 32) { + const int u = u0 + lane; + int32_t upar = -2, utok = -1; + if (u < n) { + upar = c.topo[((uint64_t)row + (uint32_t)u) * c.ld_topo]; + utok = c.topo[((uint64_t)row + (uint32_t)u) * c.ld_topo + 1]; + } + const bool under = u < n && upar == (int32_t)(row + (uint32_t)v); +#pragma unroll + for (int k = 0; k < 8; ++k) { + const uint32_t mk = (uint32_t)__ballot(under && utok == sid[k]); + if (mk && chrow[k] < 0 && k < nkv) chrow[k] = u0 + (int)__builtin_ctz(mk); + } + } + } + if (lane == 0) + for (int k = 0; k < 8; ++k) T.child[v][k] = chrow[k]; + const int32_t* ids = c.idx + rr * c.ld0; + const float* val = c.val + rr * c.ld1; + float top = -INFINITY; + uint32_t bad = 0; + uint64_t sum = 0, pk[8]; + for (int k = 0; k < 8; ++k) pk[k] = 0; + if (elig) { + /* the largest value and the validity */ + for (uint32_t p0 = 0; p0 < npass; p0 += kTravPer) { + TvBatch x; + if (!tv_load(ids, val, lane, p0, nc, 32u * (p0 + kTravPer) <= nc, &x)) continue; +#pragma unroll + for (int i = 0; i < kTravPer; ++i) { + const bool on = x.id[i] >= 0; + const bool inval = on && ((uint32_t)x.id[i] >= c.vocab || x.v[i] != x.v[i] || x.v[i] == INFINITY); + bad |= inval ? 1u : 0u; + top = on && !inval && x.v[i] > top ? x.v[i] : top; + } + } + top = tv_wave_max(top); + bad = tv_wave_or(bad); + /* the masses: in all, and on the support slots */ + if (!bad && top != -INFINITY) { + for (uint32_t p0 = 0; p0 < npass; p0 += kTravPer) { + TvBatch x; + /* a batch of holes (top_k 20: all but the first) adds nothing */ + if (!tv_load(ids, val, lane, p0, nc, 32u * (p0 + kTravPer) <= nc, &x)) continue; +#pragma unroll + for (int i = 0; i < kTravPer; ++i) { + const bool live = x.id[i] >= 0 && x.v[i] != -INFINITY; + if (!__ballot(live)) continue; /* nor does a pass with none (top_k 20: all but one) */ + const uint64_t m = live ? rad_mtp_trav_mass(x.v[i], top, qb) : 0; + sum += m; + /* the support's ids sit in a few slots of the plane: a pass none of them is in + * costs the eight compares */ + bool eq[8], anyeq = false; +#pragma unroll + for (int k = 0; k < 8; ++k) { eq[k] = x.id[i] == sid[k]; anyeq = anyeq || eq[k]; } + if (__ballot(anyeq)) { +#pragma unroll + for (int k = 0; k < 8; ++k) pk[k] += eq[k] ? m : 0; + } + } + } + } + sum = tv_wave_sum(sum); +#pragma unroll + for (int k = 0; k < 8; ++k) pk[k] = tv_wave_sum(pk[k]); + } + /* the node's law (rad_mtp_trav_set_law's values): lane k the support slot k, lane 0 the + * scalars; every word of the tree is written once, by one lane */ + if (lane < 8) { + const bool valid = elig && !bad && top != -INFINITY && sum > 0; + uint64_t on = 0, mine = 0; + for (int k = 0; k < 8; ++k) { on += pk[k]; mine = k == lane ? pk[k] : mine; } + const double dsum = valid ? rad_mtp_trav_u2d(sum) : 1.0; + const double rk = valid ? rad_mtp_trav_u2d(mine) / dsum : 0.0; + T.m[v][lane] = rk; + if (lane == 0) { + const uint64_t off = sum - on; + T.moff[v] = valid ? rad_mtp_trav_u2d(off) / dsum : 0.0; + T.off[v] = valid ? off : 0; + T.top[v] = top; + T.ok[v] = valid; + } + } + } + __syncthreads(); /* the tree is complete */ + if (wave != 0) return; + + /* Lane 0: the walk (the host's code over the tree in LDS), the path's tokens. */ + int kind = 0, fnode = 0; + uint32_t want_lo = 0, want_hi = 0; + float ftop = 0.0f; + int32_t fid[8]; + for (int k = 0; k < 8; ++k) fid[k] = -1; + if (lane == 0) { + const auto& p0 = *reinterpret_cast(c.params + (uint64_t)row * c.ld2); + const uint64_t seed = p0.seed, pos0 = p0.pos; + int np = 0; + if (rad_mtp_trav_walk_tree(T, seed, pos0, s_path, &np)) { + const int f = s_path[np - 1]; + for (int i = 0; i + 1 < np; ++i) + c.token[((uint64_t)row + (uint32_t)s_path[i]) * c.ld4] = s_tok[s_path[i + 1]]; + if (T.ok[f]) { + const RadTravPick pk = rad_mtp_trav_final_pick( + T, f, rad_spechub_uniform(seed, pos0 + (uint64_t)(np - 1), RAD_SAMPLE_KEY_RESID)); + if (pk.kind == 1) c.token[((uint64_t)row + (uint32_t)f) * c.ld4] = T.ids[f][pk.slot]; + if (pk.kind == 2) { + kind = 2; + fnode = f; + want_lo = (uint32_t)pk.t; + want_hi = (uint32_t)(pk.t >> 32); + ftop = T.top[f]; + for (int k = 0; k < 8; ++k) fid[k] = T.ids[f][k]; + } + } + } + } + if (tv_lane0(kind) != 2) return; + + /* The final token off the support: the candidate holding unit `want`, candidates in slot order + * (pass by pass, the lanes of a pass in order). Lane 0's finding goes to the wave in registers; a + * mass is split in two limbs so its prefix over the lanes is two 32-bit DPP scans. */ + { + const int f = tv_lane0(fnode); + const uint64_t want = ((uint64_t)(uint32_t)tv_lane0((int32_t)want_hi) << 32) | (uint32_t)tv_lane0((int32_t)want_lo); + const float top = tv_lane0f(ftop); + int32_t sid[8]; + for (int k = 0; k < 8; ++k) sid[k] = tv_lane0(fid[k]); + const uint64_t rr = (uint64_t)row + (uint32_t)f; + const int32_t* ids = c.idx + rr * c.ld0; + const float* val = c.val + rr * c.ld1; + uint64_t before = 0; /* the off-support mass of the passes already walked: the same in every lane */ + bool done = false; + for (uint32_t p0 = 0; p0 < npass && !done; p0 += kTravPer) { + TvBatch x; + if (!tv_load(ids, val, lane, p0, nc, 32u * (p0 + kTravPer) <= nc, &x)) continue; +#pragma unroll + for (int i = 0; i < kTravPer; ++i) { + bool off = x.id[i] >= 0 && x.v[i] != -INFINITY; +#pragma unroll + for (int k = 0; k < 8; ++k) off = off && x.id[i] != sid[k]; + if (done || !__ballot(off)) continue; + const uint64_t m = off ? rad_mtp_trav_mass(x.v[i], top, qb) : 0; + /* a mass is at most 2^41: limbs of 24 and 17 bits, whose prefixes over 32 lanes stay + * below 2^32 */ + const uint32_t plo = tv_wave_prefix((uint32_t)m & 0xffffffu, lane); + const uint32_t phi = tv_wave_prefix((uint32_t)(m >> 24), lane); + const uint64_t incl = ((uint64_t)phi << 24) + plo; + const uint64_t all = ((uint64_t)(uint32_t)__builtin_amdgcn_readlane((int)phi, 31) << 24) + + (uint32_t)__builtin_amdgcn_readlane((int)plo, 31); + const uint64_t base = before + incl - m; + const bool mine = m > 0 && want >= base && want - base < m; + if (mine) c.token[rr * c.ld4] = x.id[i]; + done = __ballot(mine) != 0; + before += all; + } + } + } +} + +} /* namespace */ + +__global__ __launch_bounds__(kThreads) void trav_verify( + const int32_t* idx, const float* values, const uint32_t* params, const uint32_t* state, + int32_t* token, const int32_t* topo, uint32_t M, uint32_t n_cand, uint32_t vocab, uint32_t ld0, + uint32_t ld1, uint32_t ld2, uint32_t ld3, uint32_t ld4, uint32_t ld_topo) { + const uint32_t row = blockIdx.x; + if (row >= M) return; + if (topo[(uint64_t)row * ld_topo] >= 0) return; /* not a request's root */ + const TravArgs c{ idx, values, params, state, token, topo, M, n_cand, vocab, ld0, ld1, ld2, ld3, ld4, ld_topo }; +#ifdef RAD_TRAV_REPEAT + /* microbenchmark build: the request is decided RAD_TRAV_REPEAT times back to back (idempotent) */ + for (int rep = 0; rep < RAD_TRAV_REPEAT; ++rep) { trav_request(c, row); __syncthreads(); } +#else + trav_request(c, row); +#endif +} + +int rad_mine_mtp_trav_verify_launch(const RadArgs* a, RadStream stream) { + RadMtpTravCall c{}; + const int rc = rad_mtp_trav_verify_args(a, &c); + if (rc != RAD_OK) return rc; + /* the kernel's geometry is 32-bit */ + for (int i = 0; i < 5; ++i) + if (c.v.ld[i] < 0 || c.v.ld[i] > INT32_MAX) return RAD_E_UNSUPPORTED; + if (c.ld_topo < 0 || c.ld_topo > INT32_MAX) return RAD_E_UNSUPPORTED; + return R4D_EMIT(stream, trav_verify, dim3((unsigned)c.v.M), dim3(kThreads), 0, + c.v.idx, c.v.val, c.v.params, c.v.state, c.v.token, c.topo, c.v.M, c.v.n_cand, + c.v.vocab, c.v.ld[0], c.v.ld[1], c.v.ld[2], c.v.ld[3], c.v.ld[4], c.ld_topo); +} + int rad_mine_mtp_couple_verify_launch(const RadArgs* a, RadStream stream) { RadMtpCoupleVerifyCall c{}; const int rc = rad_mtp_couple_verify_args(a, &c); if (rc != RAD_OK) return rc; /* Separate pointer arguments let graph replay rebind each operand address independently: a * struct on the host would freeze the addresses it was built with. */ + if (c.n_cand > kMaxCand) + return R4D_EMIT(stream, couple_verify_wide, dim3((unsigned)c.M), dim3(1), 0, + c.idx, c.val, c.params, c.state, c.token, c.M, c.n_cand, c.vocab, + c.ld[0], c.ld[1], c.ld[2], c.ld[3], c.ld[4]); return R4D_EMIT(stream, couple_verify, dim3((unsigned)c.M), dim3(kThreads), 0, c.idx, c.val, c.params, c.state, c.token, c.M, c.n_cand, c.vocab, c.ld[0], c.ld[1], c.ld[2], c.ld[3], c.ld[4]); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c24b9322..ad70bc54 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -89,6 +89,7 @@ set_target_properties(harness_fixture PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAK # Binaries registered as several entries, _shard running ` --shard k/n`, so their # cases run in parallel and no entry is the fast tier's long pole. set(RAD_TEST_SHARDS_gbnf_test 4) +set(RAD_TEST_SHARDS_mtp_rrs_test 8) # chi-square statistics: eight ctest entries of under a minute each # ------------------------------------------------------------------ the environment of every test # @@ -132,6 +133,8 @@ set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} "ROCR_VISIBLE_DEVICES=99") # Binaries that need more CPU than the default budget, and what costs it. Lower an entry when its # cost comes down, so the tripwire stays tight. +set(RAD_TEST_CPU_BUDGET_mtp_rrs_test 100) # chi-square over 2e5..4e5 seeds a case +set(RAD_TEST_CPU_BUDGET_mtp_block_test 40) # exact enumeration (g up to 4) plus ~1.6e6 chi-square steps over the real shared verify code set(RAD_TEST_CPU_BUDGET_quant_ggml_test 25) # llama.cpp's iq1_s and iq2_* grid searches, ~13 s set(RAD_TEST_CPU_BUDGET_tokenizer_test 20) # the reference encoder over every corpus: ~3 s built by GCC 16, ~10.5 s by GCC 14 (the image's Ubuntu) set(RAD_TEST_CPU_BUDGET_arch_test 15) # every plugin's graph declared; ~10.8 s with the batched-tower case @@ -350,6 +353,12 @@ if(TARGET spechub) target_compile_definitions(spechub_wiring_test PRIVATE RAD_SPECHUB_WITH_DEVICE=1) endif() add_dependencies(spechub_wiring_test spechub) + # spechub_device_test runs the plugin's device verify rows against their host rows on a card + # (skips without one); it needs the same library path. + target_link_libraries(spechub_device_test PRIVATE ${CMAKE_DL_LIBS}) + target_compile_definitions(spechub_device_test PRIVATE + RAD_SPECHUB_LIB="${RAD_PLUGIN_OUT}/kernels/spechub.so") + add_dependencies(spechub_device_test spechub) # sample_test's coupling case declares a Sampler with draft_coupling set and needs the verify # op the spechub plugin carries (its host row); it skips when the library is absent. add_dependencies(sample_test spechub) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index f2a363a0..65cb674d 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -1,4 +1,4 @@ -/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 40 and +/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 41 and * RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot * of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it * from the test's printout only together with a version bump. */ @@ -936,7 +936,7 @@ { "RadMtpCoupleDraw", "seq", 16, 8 }, { "RadMtpCoupleDraw", "card", 24, 4 }, { "RadMtpCoupleDraw", "mode", 28, 4 }, -{ "RadMtpCoupleState", "", 0, 152 }, +{ "RadMtpCoupleState", "", 0, 168 }, { "RadMtpCoupleState", "draw", 0, 32 }, { "RadMtpCoupleState", "pos", 32, 8 }, { "RadMtpCoupleState", "status", 40, 4 }, @@ -945,3 +945,7 @@ { "RadMtpCoupleState", "count", 52, 4 }, { "RadMtpCoupleState", "ids", 56, 32 }, { "RadMtpCoupleState", "q", 88, 64 }, +{ "RadMtpCoupleState", "nkids", 152, 4 }, +{ "RadMtpCoupleState", "scheme", 156, 4 }, +{ "RadMtpCoupleState", "blk", 160, 4 }, +{ "RadMtpCoupleState", "pad_", 164, 4 }, diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index bbbd3de5..82ed71c2 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -58,8 +58,8 @@ std::vector cpp_rows() { }; } -/* The layout at RAD_ABI_VERSION 40 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 40, kTableFormat = 2; +/* The layout at RAD_ABI_VERSION 41 / RAD_FORMAT_VER 2 (see the file header). */ +constexpr uint32_t kTableAbi = 41, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 1d8de0e7..82a639c0 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -587,7 +587,7 @@ const std::map>& legal_values() { { "--num-speculative-tokens", { "2" } }, { "--spec-ngram", { "4" } }, { "--spec-ngram-min", { "1" } }, { "--spec-ngram-max", { "6" } }, { "--draft-window", { "fixed" } }, { "--draft-short-from", { "4" } }, - { "--draft-coupling", { "on" } }, + { "--draft-coupling", { "on" } }, { "--draft-verify", { "block" } }, { "--host", { "127.0.0.1" } }, { "--port", { "8001" } }, { "--api-key", { "k" } }, { "--api-key-env", { "RAD_KEY_ENV_INVENTORY" } }, { "--allow-host", { "box" } }, @@ -1037,6 +1037,36 @@ TEST(the_draft_window_is_fixed_or_adaptive) { CHECK_EQ(std::string(draft_window_name(DraftWindow::Fixed)), std::string("fixed")); } +/* --draft-verify is token (alias rowwise) unless asked for; block and traversal parse. block + * implies the coupled drafting and refuses coupling off; traversal needs the coupling and says so. */ +TEST(the_draft_verify_is_token_block_or_traversal) { + Config d; + CHECK_EQ(parse({}, &d), RAD_OK); + CHECK(!d.draft_verify_block); + CHECK(!d.draft_verify_traversal); + Config c; + CHECK_EQ(parse({ "--draft-verify", "block" }, &c), RAD_OK); + CHECK(c.draft_verify_block); + CHECK(!c.draft_verify_traversal); + CHECK(c.draft_coupling); + Config t; + CHECK_EQ(parse({ "--draft-coupling", "on", "--draft-verify", "traversal" }, &t), RAD_OK); + CHECK(t.draft_verify_traversal); + CHECK(!t.draft_verify_block); + CHECK_EQ(parse({ "--draft-verify", "rowwise" }, &t), RAD_OK); + CHECK(!t.draft_verify_traversal); + CHECK_EQ(parse({ "--draft-verify", "token" }, &t), RAD_OK); + CHECK(!t.draft_verify_block); + Config b; + for (const char* bad : { "Block", "Traversal", "on", "" }) + CHECK_EQ(parse({ "--draft-verify", bad }, &b), RAD_E_INVAL); + CHECK_EQ(parse({ "--draft-verify" }, &b), RAD_E_INVAL); + Config off; + CHECK_EQ(parse({ "--draft-verify", "block", "--draft-coupling", "off" }, &off), RAD_E_INVAL); + Config nocouple; + CHECK_EQ(parse({ "--draft-verify", "traversal" }, &nocouple), RAD_E_INVAL); +} + /* --draft-coupling is off unless asked for, and only off and on parse: a misspelt value must not * start a server on the other path. */ TEST(the_draft_coupling_is_off_or_on) { @@ -1634,7 +1664,7 @@ TEST(usage_names_every_flag_it_documents) { * for, so a flag added without a help line is caught. */ const std::string text = stderr_of([] { config_usage("radiance"); }); for (const char* f : { "--model", "--host-pool-mib", "--kv-cache-dtype", - "--num-speculative-tokens", "--draft-window", "--draft-coupling", + "--num-speculative-tokens", "--draft-window", "--draft-coupling", "--draft-verify", "--checkpoint-policy", "--prefix-cache-mib", "--prefix-cache-ttl", "--tp-wire", "--embedding-placement", "--ngram-placement", diff --git a/tests/mtp_block_test.cpp b/tests/mtp_block_test.cpp new file mode 100644 index 00000000..49c1b835 --- /dev/null +++ b/tests/mtp_block_test.cpp @@ -0,0 +1,578 @@ +/* tests/mtp_block_test.cpp -- Block Verification of a linear MTP draft chain (--draft-verify block, + * abi/rad_mtp_block.h, arXiv 2403.10444), checked against its own law. + * + * The property: whatever the head's law Q and the chain's length g, the tokens a verify step commits + * are a prefix of a sample of the TARGET's autoregressive law, and the step commits at least as many + * tokens as the token-wise (maximal coupling) verify of the same drafts. Tests: + * + * exact enumeration every draft of a toy chain, the rule written out densely and independently + * of the header, the law of the first three committed tokens summed in + * closed form: equals the target's product law to 1e-12 (g = 1..4, three + * head qualities); and the header's h_i equal the dense ones + * chi-square the real shared code (the propose row, rad_mtp_couple_verify_row with the + * block marking, the core's token-comparison walk) over 3e5 seeds: the joint + * law of the first three tokens and the first token's marginal + * negative control the same code with h_i nudged (a wrong acceptance rule) is NOT exact and + * the same statistic sees it + * dominance the mean committed tokens per step of block verification is at least the + * token-wise verify's on the same drafts + * inert rows a stale or non-consecutive state leaves the ordinary picks alone; rows + * after the first of a block write nothing; a greedy row is untouched + */ +#include "rad_test.h" + +#include "rad_mtp_block.h" +#include "../plugin/spechub/spechub.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int V = 12; /* larger than the head's top 8: the target has mass off Q's support */ + +uint64_t H(uint64_t a) { return rad_mtp_rrs_mix(a); } + +struct Law { + int32_t pid[V]; float pval[V]; int pn = 0; + double p[V]; + int32_t qid[8]; float qval[8]; +}; + +Law law_at(uint64_t prefix_hash, double head_noise) { + Law L; + float lt[V], lq[V]; + for (int i = 0; i < V; ++i) { + lt[i] = (float)((H(prefix_hash * 131 + (uint64_t)i * 977 + 1) >> 40) % 3000) / 1000.0f - 1.5f; + const float nz = (float)((H(prefix_hash * 257 + (uint64_t)i * 331 + 7) >> 40) % 3000) / 1000.0f - 1.5f; + lq[i] = 0.75f * lt[i] + (float)head_noise * nz; + } + const uint64_t h = H(prefix_hash + 99); + const int drop = h % 3 == 0 ? (int)((h >> 8) % V) : -1; + double z = 0; + for (int i = 0; i < V; ++i) { L.p[i] = 0; if (i != drop) { L.pid[L.pn] = i; L.pval[L.pn++] = lt[i]; } } + for (int j = 0; j < L.pn; ++j) z += std::exp((double)L.pval[j]); + for (int j = 0; j < L.pn; ++j) L.p[L.pid[j]] = std::exp((double)L.pval[j]) / z; + int ord[V]; + for (int i = 0; i < V; ++i) ord[i] = i; + std::stable_sort(ord, ord + V, [&](int a, int b) { return lq[a] > lq[b]; }); + for (int i = 0; i < 8; ++i) { L.qid[i] = ord[i]; L.qval[i] = lq[ord[i]]; } + return L; +} + +uint64_t child_hash(uint64_t ph, int tok) { return H(ph * 1000003ull + (uint64_t)tok + 17); } + +int sample_law(const Law& L, uint64_t seed, uint64_t pos, uint64_t key) { + double u = rad_spechub_uniform(seed, pos, key); + int last = 0; + for (int i = 0; i < V; ++i) { + if (L.p[i] <= 0) continue; + last = i; + u -= L.p[i]; + if (u < 0) return i; + } + return last; +} + +RadMtpCoupleDraw make_draw(uint64_t seed, uint64_t base) { + RadMtpCoupleDraw d{}; + d.seed = seed; d.base = base; d.seq = 1; d.card = 0; d.mode = 1; + return d; +} + +/* ------------------------------------------------------------------ a drafted chain */ + +struct Chain { + int g = 0; + int tok[8] = {}; /* X_1 .. X_g */ + uint64_t hash[9] = {}; /* the prefix hash after X^i, i = 0 .. g */ + RadMtpCoupleState st[8] = {}; /* row i's coupled state (round i + 1) */ +}; + +/* The chain drafted by the real propose row, round by round, over the head's law at the chain's own + * prefix (x ~ Q at the draw's (seed, base, KEY_DRAFT + round)). */ +void draft_chain(Chain* t, uint64_t seed, uint64_t base, int g, double noise, uint64_t h0 = 1) { + uint64_t h = h0; + t->g = g; + t->hash[0] = h; + for (int r = 1; r <= g; ++r) { + const Law law = law_at(h, noise); + int32_t idx[8]; + float val[8]; + for (int i = 0; i < 8; ++i) { idx[i] = law.qid[i]; val[i] = law.qval[i]; } + const RadMtpCoupleDraw draw = make_draw(seed, base); + const int32_t card = 0; + RadMtpCoupleProposeCall c{}; + c.idx = idx; c.val = val; c.card = &card; + c.draw = reinterpret_cast(&draw); + RadMtpCoupleState rows[8] = {}; + c.state = reinterpret_cast(rows); + c.M = 1; c.vocab = 1000; + c.ld_idx = 8; c.ld_val = 8; c.ld_draw = RAD_MTP_COUPLE_DRAW_WORDS; + c.st_round = RAD_MTP_COUPLE_STATE_WORDS; c.st_row = 0; + c.round = r; + rad_mtp_couple_propose_row(c, 0); + t->st[r - 1] = rows[r - 1]; + t->tok[r - 1] = idx[0]; + h = child_hash(h, idx[0]); + t->hash[r] = h; + } +} + +enum Mode { TOKEN, BLOCK, CONTROL }; + +/* The control's wrong rule: every inner h_i raised by a quarter (clipped at 1). */ +void nudge(RadBlockPlan* pl) { + for (int i = 1; i < pl->g; ++i) pl->h[i] = std::min(1.0, pl->h[i] * 1.25); +} + +/* The sampler's planes of one step: g + 1 rows, the last the bonus row with no state. */ +struct Planes { + int32_t ids[9 * V]; + float val[9 * V]; + uint32_t params[9 * 24]; + RadMtpCoupleState st[9]; + int32_t tok[9]; +}; + +RadMtpCoupleVerifyCall call_of(Planes* pl, int g) { + RadMtpCoupleVerifyCall c{}; + c.idx = pl->ids; c.val = pl->val; c.params = pl->params; + c.state = reinterpret_cast(pl->st); + c.token = pl->tok; + c.M = g + 1; c.n_cand = V; c.vocab = 1000; + c.ld[0] = V; c.ld[1] = V; c.ld[2] = 24; c.ld[3] = RAD_MTP_COUPLE_STATE_WORDS; c.ld[4] = 1; + return c; +} + +/* One verify step over the chain, walked as the core does: the verify op's rows over the sampler's + * planes, then the rule "a row's token that equals its draft accepts it". Writes the committed + * tokens, extended to `want` by exact draws from the target. Returns the committed count before the + * extension. */ +int step(const Chain& t, uint64_t seed, uint64_t n_out, double noise, Mode mode, int want, int* out) { + const int g = t.g; + Planes pl; + std::memset(&pl, 0, sizeof pl); + for (int i = 0; i <= g; ++i) { + const Law L = law_at(t.hash[i], noise); + for (int j = 0; j < V; ++j) { + pl.ids[i * V + j] = j < L.pn ? L.pid[j] : -1; + pl.val[i * V + j] = j < L.pn ? L.pval[j] : 0.0f; + } + RadSampleParams* p = reinterpret_cast(pl.params + i * 24); + p->seed = seed; + p->pos = n_out + (uint64_t)i; + pl.tok[i] = sample_law(L, seed, n_out + (uint64_t)i, 0); /* the ordinary pick */ + if (i < g) { + pl.st[i] = t.st[i]; + pl.st[i].pos = rad_mtp_couple_verify_pos(n_out, i + 1); + pl.st[i].blk = mode == TOKEN ? 0 : g; + } + } + const RadMtpCoupleVerifyCall c = call_of(&pl, g); + if (mode == CONTROL) { + RadBlockRow rows[8]; + RadBlockStat stat[8]; + for (int i = 0; i < g; ++i) { + rows[i] = RadBlockRow{ pl.ids + i * V, pl.val + i * V, V, 0, 0.0f }; + rad_mtp_block_scan(&rows[i], 1000); + CHECK(rad_mtp_block_stat(rows[i], pl.st[i], &stat[i])); + } + RadBlockPlan bp; + rad_mtp_block_plan(pl.st, stat, g, &bp); + nudge(&bp); + const int tau = rad_mtp_block_tau(bp, seed, n_out); + int32_t y = -1; + if (tau < g) + CHECK(rad_mtp_block_resid_draw(rows[tau], pl.st[tau], stat[tau], bp.p[tau], + rad_spechub_uniform(seed, n_out + (uint64_t)tau, + RAD_SAMPLE_KEY_RESID), &y)); + rad_mtp_block_write(c, 0, pl.st, tau, g, y); + } else { + for (int i = 0; i < g; ++i) rad_mtp_couple_verify_row(c, i); + } + int len = 0; + for (int i = 0; i <= g; ++i) { + out[len++] = pl.tok[i]; + if (i == g || pl.tok[i] != t.tok[i]) break; + } + const int committed = len; + uint64_t ph = t.hash[0]; + for (int i = 0; i < len; ++i) ph = child_hash(ph, out[i]); + while (len < want) { + const Law L = law_at(ph, noise); + const int y = sample_law(L, seed ^ 0xabcdef1234ull, n_out + (uint64_t)len, 1); + out[len++] = y; + ph = child_hash(ph, y); + } + return committed; +} + +double zscore(const std::vector& counts, const std::vector& expect, double n) { + double chi = 0, pool_c = 0, pool_e = 0; + int cells = 0; + for (size_t i = 0; i < counts.size(); ++i) { + const double e = expect[i] * n; + if (e < 20) { pool_c += counts[i]; pool_e += e; continue; } + chi += (counts[i] - e) * (counts[i] - e) / e; + ++cells; + } + if (pool_e >= 5) { chi += (pool_c - pool_e) * (pool_c - pool_e) / pool_e; ++cells; } + const double df = cells - 1; + return (chi - df) / std::sqrt(2.0 * df); +} + +struct Result { double z, first_z, mean_len, var_len; }; + +Result run(Mode mode, int g, int trials, double noise) { + std::vector cnt3((size_t)V * V * V, 0), cnt1((size_t)V, 0); + double sum = 0, sq = 0; + for (int s = 0; s < trials; ++s) { + const uint64_t seed = 0x1234567ull + (uint64_t)s * 7919ull; + Chain t; + draft_chain(&t, seed, 0, g, noise); + int out[16]; + const int len = step(t, seed, 0, noise, mode, 3, out); + ++cnt1[(size_t)out[0]]; + ++cnt3[(size_t)((out[0] * V + out[1]) * V + out[2])]; + sum += len; sq += (double)len * len; + } + std::vector e1((size_t)V, 0), e3((size_t)V * V * V, 0); + const Law l0 = law_at(1, noise); + for (int a = 0; a < V; ++a) { + e1[(size_t)a] = l0.p[a]; + const Law l1 = law_at(child_hash(1, a), noise); + for (int b = 0; b < V; ++b) { + const Law l2 = law_at(child_hash(child_hash(1, a), b), noise); + for (int c = 0; c < V; ++c) e3[(size_t)((a * V + b) * V + c)] = l0.p[a] * l1.p[b] * l2.p[c]; + } + } + const double mean = sum / trials; + return { zscore(cnt3, e3, trials), zscore(cnt1, e1, trials), mean, sq / trials - mean * mean }; +} + +/* ------------------------------------------------------------------ the exact law */ + +/* The rule written densely, independent of the header: P_i, Q_{i+1} as length-V vectors. */ +struct Dense { double P[V], Q[V]; }; + +void dense_h(const std::vector& d, const int* x, int g, double* h, double* p) { + p[0] = 1; + for (int i = 1; i <= g; ++i) + p[i] = std::min(1.0, p[i - 1] * d[(size_t)i - 1].P[x[i - 1]] / d[(size_t)i - 1].Q[x[i - 1]]); + h[g] = p[g]; + for (int i = 0; i < g; ++i) { + double S = 0; + for (int v = 0; v < V; ++v) S += std::max(p[i] * d[(size_t)i].P[v] - d[(size_t)i].Q[v], 0.0); + h[i] = S / (S + 1.0 - p[i]); + } +} + +/* The exact law of the first three committed tokens (the step, then the target's own draws), by + * summing over every draft, tau and Y. Also compares the header's weights with the dense ones. */ +double exact_error(int gmax, double noise, double* h_err, int adaptive = 0) { + std::map, double> emit; /* committed sequence -> probability */ + *h_err = 0; + std::vector x((size_t)gmax); + std::vector hash((size_t)gmax + 1); + hash[0] = 1; + std::function rec = [&](int i, double pr) { + /* adaptive: the draft stage stops after X_i when a function of the drafted prefix says so + * (what confidence pruning does); the block's length g is then draft-dependent. */ + const bool stop_here = adaptive && i >= 1 && i < gmax && (H(hash[(size_t)i] + 5) % 3) < (uint64_t)adaptive; + const int g = i; + if (i < gmax && !stop_here) { + const Law L = law_at(hash[(size_t)i], noise); + RadMtpCoupleState s{}; + CHECK(rad_mtp_couple_build_q(L.qid, L.qval, 1000, &s)); + for (int k = 0; k < s.count; ++k) { + x[(size_t)i] = s.ids[k]; + hash[(size_t)i + 1] = child_hash(hash[(size_t)i], s.ids[k]); + rec(i + 1, pr * s.q[k]); + } + return; + } + std::vector d((size_t)g); + std::vector laws; + std::vector st((size_t)g); + std::vector rows((size_t)g); + for (int j = 0; j < g; ++j) laws.push_back(law_at(hash[(size_t)j], noise)); + for (int j = 0; j < g; ++j) { + CHECK(rad_mtp_couple_build_q(laws[(size_t)j].qid, laws[(size_t)j].qval, 1000, &st[(size_t)j])); + st[(size_t)j].x = x[(size_t)j]; + for (int v = 0; v < V; ++v) { d[(size_t)j].P[v] = laws[(size_t)j].p[v]; d[(size_t)j].Q[v] = 0; } + for (int k = 0; k < st[(size_t)j].count; ++k) + d[(size_t)j].Q[st[(size_t)j].ids[k]] = st[(size_t)j].q[k]; + rows[(size_t)j] = RadBlockRow{ laws[(size_t)j].pid, laws[(size_t)j].pval, + laws[(size_t)j].pn, 0, 0.0f }; + rad_mtp_block_scan(&rows[(size_t)j], 1000); + } + double h[9], p[9]; + dense_h(d, x.data(), g, h, p); + RadBlockStat stat[8]; + for (int j = 0; j < g; ++j) CHECK(rad_mtp_block_stat(rows[(size_t)j], st[(size_t)j], &stat[j])); + RadBlockPlan bp; + rad_mtp_block_plan(st.data(), stat, g, &bp); + for (int j = 0; j <= g; ++j) *h_err = std::max(*h_err, std::fabs(bp.h[j] - h[j])); + double stop = 1; /* probability that no larger i has accepted */ + for (int tau = g; tau >= 0; --tau) { + const double pt = stop * h[tau]; + stop *= 1 - h[tau]; + if (pt <= 0) continue; + std::vector e(x.begin(), x.begin() + tau); + if (tau == g) { + const Law Lg = law_at(hash[(size_t)g], noise); + for (int z = 0; z < V; ++z) { + if (Lg.p[z] <= 0) continue; + std::vector e2 = e; e2.push_back(z); + emit[e2] += pr * pt * Lg.p[z]; + } + continue; + } + double S = 0, r[V]; + for (int v = 0; v < V; ++v) { + r[v] = std::max(p[tau] * d[(size_t)tau].P[v] - d[(size_t)tau].Q[v], 0.0); + S += r[v]; + } + if (!(S > 0)) { for (int v = 0; v < V; ++v) r[v] = d[(size_t)tau].P[v]; S = 1; } + for (int v = 0; v < V; ++v) { + if (r[v] <= 0) continue; + std::vector e2 = e; e2.push_back(v); + emit[e2] += pr * pt * r[v] / S; + } + } + }; + rec(0, 1.0); + /* extend every committed sequence to three tokens with the target's conditionals */ + std::vector got((size_t)V * V * V, 0); + for (const auto& kv : emit) { + const std::vector& e = kv.first; + std::function&, uint64_t, double)> ext = + [&](std::vector& w, uint64_t h, double pr) { + if (w.size() == 3) { got[(size_t)((w[0] * V + w[1]) * V + w[2])] += pr; return; } + const Law L = law_at(h, noise); + for (int v = 0; v < V; ++v) { + if (L.p[v] <= 0) continue; + w.push_back(v); + ext(w, child_hash(h, v), pr * L.p[v]); + w.pop_back(); + } + }; + std::vector w(e.begin(), e.begin() + (long)std::min(e.size(), 3)); + uint64_t h = 1; + for (int t : w) h = child_hash(h, t); + ext(w, h, kv.second); + } + const Law l0 = law_at(1, noise); + double err = 0, tot = 0; + for (int a = 0; a < V; ++a) { + const Law l1 = law_at(child_hash(1, a), noise); + for (int b = 0; b < V; ++b) { + const Law l2 = law_at(child_hash(child_hash(1, a), b), noise); + for (int c = 0; c < V; ++c) { + const size_t i = (size_t)((a * V + b) * V + c); + const double want = l0.p[a] * l1.p[b] * l2.p[c]; + err = std::max(err, std::fabs(got[i] - want)); + tot += got[i]; + } + } + } + CHECK_NEAR(tot, 1.0, 1e-12); + return err; +} + +} /* namespace */ + +TEST(block_verification_emits_exactly_the_target_law_by_enumeration) { + for (double noise : { 0.3, 1.0, 3.0 }) + for (int g = 1; g <= 4; ++g) { + double h_err = 0; + const double err = exact_error(g, noise, &h_err); + std::printf(" g=%d noise=%.1f max |law - target| = %.2e max |h - h_dense| = %.2e\n", g, + noise, err, h_err); + CHECK(err < 1e-12); + CHECK(h_err < 1e-12); + } +} + +/* A draft stage that stops by a function of the drafted prefix (confidence pruning, dynamic rows) + * makes the block length draft-dependent. Printed, and checked to be exact. */ +TEST(block_verification_with_a_draft_dependent_chain_length_is_exact) { + for (double noise : { 0.3, 1.0, 3.0 }) + for (int adaptive : { 1, 2 }) { + double h_err = 0; + const double err = exact_error(4, noise, &h_err, adaptive); + std::printf(" adaptive stop (%d/3 of prefixes) noise=%.1f: max |law - target| = %.2e\n", + adaptive, noise, err); + CHECK(err < 1e-12); + } +} + +TEST(the_chain_verify_with_block_marking_commits_the_target_law) { + const Result a = run(BLOCK, 3, 300000, 1.0); + std::printf(" g=3 noise 1.0: z=%.2f first=%.2f mean tokens %.4f\n", a.z, a.first_z, a.mean_len); + CHECK(a.z < 4.5); CHECK(a.first_z < 4.5); + const Result b = run(BLOCK, 3, 150000, 3.0); + std::printf(" g=3 noise 3.0: z=%.2f first=%.2f mean tokens %.4f\n", b.z, b.first_z, b.mean_len); + CHECK(b.z < 4.5); CHECK(b.first_z < 4.5); + const Result c = run(BLOCK, 5, 150000, 0.3); + std::printf(" g=5 noise 0.3: z=%.2f first=%.2f mean tokens %.4f\n", c.z, c.first_z, c.mean_len); + CHECK(c.z < 4.5); CHECK(c.first_z < 4.5); +} + +/* The same statistic sees a wrong acceptance rule. */ +TEST(a_block_rule_with_nudged_weights_is_not_exact) { + const Result r = run(CONTROL, 3, 300000, 1.0); + std::printf(" nudged h (known wrong): z=%.1f first=%.1f\n", r.z, r.first_z); + CHECK(r.z > 8.0); +} + +/* Block verification commits at least as many tokens as the token-wise verify of the same drafts, + * and both are exact (the token-wise one is the existing coupling). */ +TEST(block_verification_commits_at_least_as_many_tokens_as_token_wise) { + for (double noise : { 0.3, 1.0, 3.0 }) { + const int trials = 200000; + const Result tk = run(TOKEN, 3, trials, noise); + const Result bl = run(BLOCK, 3, trials, noise); + const double se = std::sqrt((tk.var_len + bl.var_len) / trials); + std::printf(" noise %.1f: token-wise %.4f tokens/step (z=%.2f), block %.4f (z=%.2f), +%.4f\n", + noise, tk.mean_len, tk.z, bl.mean_len, bl.z, bl.mean_len - tk.mean_len); + CHECK(tk.z < 4.5); + CHECK(bl.z < 4.5); + CHECK(bl.mean_len > tk.mean_len - 4 * se); + } +} + +/* A state that is not the one the sampler would have bound, or a block that is not consecutive, + * leaves the ordinary picks alone; only the first row of a block writes. */ +TEST(block_rows_that_do_not_bind_keep_their_ordinary_picks) { + const int g = 3; + Chain t; + draft_chain(&t, 77, 0, g, 1.0); + auto build = [&](Planes* pl, uint64_t seed) { + std::memset(pl, 0, sizeof *pl); + for (int i = 0; i <= g; ++i) { + const Law L = law_at(t.hash[i], 1.0); + for (int j = 0; j < V; ++j) { + pl->ids[i * V + j] = j < L.pn ? L.pid[j] : -1; + pl->val[i * V + j] = j < L.pn ? L.pval[j] : 0.0f; + } + RadSampleParams* p = reinterpret_cast(pl->params + i * 24); + p->seed = seed; p->pos = 10 + (uint64_t)i; + pl->tok[i] = 1000 + i; /* a marker no verify could write */ + if (i < g) { pl->st[i] = t.st[i]; pl->st[i].pos = 10 + (uint64_t)i; pl->st[i].blk = g; } + } + }; + auto verify = [&](Planes* pl, int row0, int rows) { + const RadMtpCoupleVerifyCall c = call_of(pl, g); + for (int i = row0; i < row0 + rows; ++i) rad_mtp_couple_verify_row(c, i); + }; + auto untouched = [&](const Planes& pl) { + for (int i = 0; i <= g; ++i) if (pl.tok[i] != 1000 + i) return false; + return true; + }; + Planes pl; + build(&pl, 77); + verify(&pl, 0, g); + CHECK(!untouched(pl)); /* the block binds and writes */ + build(&pl, 77); + verify(&pl, 1, g - 1); + CHECK(untouched(pl)); /* rows after the first write nothing */ + build(&pl, 77); + pl.st[1].round = 3; + verify(&pl, 0, g); + CHECK(untouched(pl)); /* a row of the wrong round ends the block's coupling */ + build(&pl, 77); + pl.st[2].draw.seq = 9; + verify(&pl, 0, g); + CHECK(untouched(pl)); /* another request's state */ + build(&pl, 77); + pl.st[2].pos += 1; + verify(&pl, 0, g); + CHECK(untouched(pl)); /* a stale position */ + build(&pl, 77); + reinterpret_cast(pl.params + 2 * 24)->flags = RAD_SP_GREEDY; + verify(&pl, 0, g); + CHECK(untouched(pl)); /* a greedy row */ + build(&pl, 78); + verify(&pl, 0, g); + CHECK(untouched(pl)); /* a seed the state was not drawn under */ + build(&pl, 77); + pl.st[1].nkids = 2; + verify(&pl, 0, g); + CHECK(untouched(pl)); /* a tree node is not a chain row */ +} + + +/* The residual draw over a plane WIDER than the workgroup's 128 lanes (several slots per lane, ids + * on and off Q's support, holes): the lane-ordered walk of rad_mtp_block_resid_draw must still + * sample max(p P - Q, 0) normalised. Chi-square over the plane's ids against the dense closed + * form; the negative control draws from a residual with Q's mass halved (a wrong law) and the same + * statistic must see it. Also the tree sum: stat over the wide plane equals a plain ascending sum + * to rounding (the tree is a different order, not a different value). */ +TEST(the_lane_ordered_residual_draw_over_a_wide_plane_is_exact) { + const int N = 700; + std::vector ids((size_t)N); + std::vector val((size_t)N); + for (int j = 0; j < N; ++j) { + ids[(size_t)j] = j % 11 == 5 ? -1 : 2 * j + 3; + val[(size_t)j] = j % 11 == 5 ? -INFINITY : (float)((H((uint64_t)j * 7919 + 5) >> 40) % 4000) / 1000.0f - 2.0f; + } + int32_t qid[8]; float qv[8]; + for (int k = 0; k < 8; ++k) { qid[k] = 2 * (k * 83 + 1) + 3; qv[k] = 1.5f - 0.3f * (float)k; } + RadMtpCoupleState st{}; + CHECK(rad_mtp_couple_build_q(qid, qv, 100000, &st)); + st.x = st.ids[1]; + RadBlockRow r{ ids.data(), val.data(), N, 0, 0.0f }; + rad_mtp_block_scan(&r, 100000); + RadBlockStat t; + CHECK(rad_mtp_block_stat(r, st, &t)); + double ref = 0, top = r.top; + for (int j = 0; j < N; ++j) if (ids[(size_t)j] >= 0) ref += std::exp((double)val[(size_t)j] - top); + CHECK(std::fabs(t.sum - ref) <= 1e-12 * ref); + const double p = 0.8; + std::map want; + double tot = 0; + for (int j = 0; j < N; ++j) { + if (ids[(size_t)j] < 0) continue; + const double P = std::exp((double)val[(size_t)j] - top) / ref; + double Q = 0; + for (int k = 0; k < st.count; ++k) if (st.ids[k] == ids[(size_t)j]) Q = st.q[k]; + const double m = std::max(p * P - Q, 0.0); + want[ids[(size_t)j]] = m; tot += m; + } + const int D = 400000; + std::map got, bad; + for (int d = 0; d < D; ++d) { + const double u = (double)(H((uint64_t)d * 2654435761ull + 11) >> 11) / 9007199254740992.0; + int32_t y = -1; + CHECK(rad_mtp_block_resid_draw(r, st, t, p, u, &y)); + got[y] += 1; + /* control: the walk with the uniform skewed (a wrong law) */ + int32_t yb = -1; + CHECK(rad_mtp_block_resid_draw(r, st, t, p, u * u, &yb)); + bad[yb] += 1; + } + auto chi = [&](std::map& c) { + double x = 0, pc = 0, pe = 0; int cells = 0; + for (auto& kv : want) { + const double e = D * kv.second / tot, o = c.count(kv.first) ? c[kv.first] : 0; + if (e < 5) { pc += o; pe += e; continue; } + x += (o - e) * (o - e) / e; ++cells; + } + if (pe >= 5) { x += (pc - pe) * (pc - pe) / pe; ++cells; } + return (x - (cells - 1)) / std::sqrt(2.0 * (cells - 1)); /* z of chi-square */ + }; + for (auto& kv : got) CHECK(want.count(kv.first) && want[kv.first] > 0); + const double z = chi(got), zb = chi(bad); + fprintf(stderr, " wide plane residual draw: z=%.2f negative control z=%.1f\n", z, zb); + CHECK(std::fabs(z) < 4.5); + CHECK(zb > 20); +} + +RAD_TEST_MAIN() diff --git a/tests/mtp_rrs_test.cpp b/tests/mtp_rrs_test.cpp new file mode 100644 index 00000000..eccb5b8c --- /dev/null +++ b/tests/mtp_rrs_test.cpp @@ -0,0 +1,1146 @@ +/* tests/mtp_rrs_test.cpp -- the verifications of a coupled draft (--draft-coupling on), checked + * against their own law: recursive rejection sampling over a node's siblings (abi/rad_mtp_rrs.h) and + * Traversal Verification (--draft-verify traversal, abi/rad_mtp_traversal.h). + * + * The property: whatever the head's law Q and the draft's shape, the tokens a verify step commits + * are a prefix of a sample of the TARGET's autoregressive law. The tests run the real shared code + * (the propose row, the verify row, the walk) over a toy model with a known target P(. | prefix) and + * a different head Q(. | prefix), many seeds, and compare the empirical law of the emitted tokens + * with the exact one (chi-square, deterministic seeds), or enumerate every draft tree of a small + * model and compare the walk's law with the target's to 1e-10: + * + * one node, 2..4 children the first emitted token ~ P (single-node recursion, exact) + * chain, chain + siblings R = 3 rounds, with and without three sibling drafts at the root, + * walked by traversal (for a chain it is Block Verification's case) + * negative controls the with-replacement verify, token-level ratios, no (1 - p) term and + * a q that is never renormalised are NOT exact, and the same statistic + * sees each of them + * degenerate Q == P accepts the first child; disjoint supports reject all and emit + * from P + * fixed point the walk's integer exponential tracks exp to 2^-22, its law is the + * softmax to FP32 accuracy, and by enumeration the walk emits exactly + * the law it reads + * + * The step is walked the way the core walks it: the verify row writes the sampler's token for each + * visited node and ADV_ACCEPT's rule (the first child whose token is that token) follows it; after + * the step, the sequence continues from the exact target so the first three tokens of every trial + * have a known joint law. + */ +#include "rad_test.h" + +#include "rad_mtp_rrs.h" +#include "rad_mtp_traversal.h" +#include "../plugin/spechub/spechub.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int V = 12; /* the toy vocabulary: larger than the head's top 8, so the target has mass off Q's support */ + +uint64_t H(uint64_t a) { return rad_mtp_rrs_mix(a); } + +/* The target's candidate plane at a prefix (ids and logits; some prefixes drop a token, as a + * top-k / top-p would) and the head's shortlist (all V tokens, logits). The head is a noisy + * version of the target, so acceptance is neither 0 nor 1. */ +struct Law { + int32_t pid[V]; float pval[V]; int pn = 0; /* target candidates */ + double p[V]; /* the exact target law over tokens */ + int32_t qid[8]; float qval[8]; /* the head's shortlist */ +}; + +double g_sharp = 1.0; /* the laws' inverse temperature: a peaked target (T = 0.7 and a top-p) is the engine's regime */ + +Law law_at(uint64_t prefix_hash, double head_noise) { + Law L; + float lt[V], lq[V]; + for (int i = 0; i < V; ++i) { + lt[i] = (float)g_sharp * ((float)((H(prefix_hash * 131 + (uint64_t)i * 977 + 1) >> 40) % 3000) / 1000.0f - 1.5f); + const float nz = (float)((H(prefix_hash * 257 + (uint64_t)i * 331 + 7) >> 40) % 3000) / 1000.0f - 1.5f; + lq[i] = 0.75f * lt[i] + (float)(head_noise * g_sharp) * nz; + } + const uint64_t h = H(prefix_hash + 99); + const int drop = h % 3 == 0 ? (int)((h >> 8) % V) : -1; /* a target token the filters removed */ + double z = 0; + for (int i = 0; i < V; ++i) { L.p[i] = 0; if (i != drop) { L.pid[L.pn] = i; L.pval[L.pn++] = lt[i]; } } + for (int j = 0; j < L.pn; ++j) z += std::exp((double)L.pval[j]); + for (int j = 0; j < L.pn; ++j) L.p[L.pid[j]] = std::exp((double)L.pval[j]) / z; + /* the head reports its 8 best (descending, ties to the lower id): the rest of the vocabulary is + * off Q's support, where the target keeps its mass */ + int ord[V]; + for (int i = 0; i < V; ++i) ord[i] = i; + std::stable_sort(ord, ord + V, [&](int a, int b) { return lq[a] > lq[b]; }); + for (int i = 0; i < 8; ++i) { L.qid[i] = ord[i]; L.qval[i] = lq[ord[i]]; } + return L; +} + +uint64_t child_hash(uint64_t ph, int tok) { return H(ph * 1000003ull + (uint64_t)tok + 17); } + +/* A draw from the target law at the prefix: the ordinary pick. */ +int sample_law(const Law& L, uint64_t seed, uint64_t pos, uint64_t key) { + double u = rad_spechub_uniform(seed, pos, key); + int last = 0; + for (int i = 0; i < V; ++i) { + if (L.p[i] <= 0) continue; + last = i; + u -= L.p[i]; + if (u < 0) return i; + } + return last; +} + +RadMtpCoupleDraw make_draw(uint64_t seed, uint64_t base) { + RadMtpCoupleDraw d{}; + d.seed = seed; d.base = base; d.seq = 1; d.card = 0; d.mode = 1; + return d; +} + +/* The verify row of the real plugin code over one candidate plane and one bound state. */ +int verify(const RadMtpCoupleState& st, const Law& L, uint64_t seed, uint64_t pos, int fallback) { + uint32_t params[24] = {}; + RadSampleParams* p = reinterpret_cast(params); + p->seed = seed; + p->pos = pos; + int32_t tok = fallback; + RadMtpCoupleVerifyCall c{}; + c.idx = L.pid; c.val = L.pval; c.params = params; + c.state = reinterpret_cast(&st); + c.token = &tok; + c.M = 1; c.n_cand = L.pn; c.vocab = 1000; + c.ld[0] = L.pn; c.ld[1] = L.pn; c.ld[2] = 24; c.ld[3] = RAD_MTP_COUPLE_STATE_WORDS; c.ld[4] = 1; + rad_mtp_couple_verify_row(c, 0); + return tok; +} + +/* ------------------------------------------------------------------ a toy drafted tree */ + +struct Tree { + int n = 0; /* nodes 1..n */ + int tok[64] = {}, par[64] = {}; + uint64_t hash[64] = {}; /* the prefix hash of every node, node 0 the root */ + RadMtpCoupleState st[64] = {}; /* row k's coupled state (status 0: none) */ +}; + +enum Kind { CHAIN, STAGE1 }; +int g_scheme = 0; /* sibling scheme of the root's drafts: 0 Gumbel-top-k, m + 1 RheoSampling */ + +/* The chain's drafting, through the real propose row: round r over the head's law at the chain + * prefix. With L > 0 the root also drafts L siblings of its first child, sampled without + * replacement from the same law (Gumbel-top-k, or RheoSampling's scheme), as a draft tree's root + * does; its state then lists the children in draft order (abi/rad_mtp_rrs.h). */ +void draft_chain(Tree* t, uint64_t seed, uint64_t base, int R, int L, double noise, uint64_t h0 = 1) { + uint64_t h = h0; + t->hash[0] = h; + int n = 0; + std::vector leaves; + for (int r = 1; r <= R; ++r) { + const Law law = law_at(h, noise); + int32_t idx[8]; + float val[8]; + for (int i = 0; i < 8; ++i) { idx[i] = law.qid[i]; val[i] = law.qval[i]; } + const RadMtpCoupleDraw draw = make_draw(seed, base); + const int32_t card = 0; + RadMtpCoupleProposeCall c{}; + c.idx = idx; c.val = val; c.card = &card; + c.draw = reinterpret_cast(&draw); + RadMtpCoupleState rows[8] = {}; + c.state = reinterpret_cast(rows); + c.M = 1; c.vocab = 1000; + c.ld_idx = 8; c.ld_val = 8; c.ld_draw = RAD_MTP_COUPLE_DRAW_WORDS; + c.st_round = RAD_MTP_COUPLE_STATE_WORDS; c.st_row = 0; + c.round = r; + rad_mtp_couple_propose_row(c, 0); + RadMtpCoupleState s = rows[r - 1]; + if (r == 1 && L > 0 && s.status == 1) { + if (g_scheme > 0) rad_mtp_rrs_draw_rheo(&s, 0, 1 + L, g_scheme - 1); + else rad_mtp_rrs_draw(&s, 0, 1 + L); + s.status = 1; + for (int i = 0; i < 8; ++i) idx[i] = i < s.nkids ? s.ids[i] : -1; + } + t->st[r - 1] = s; + const int pick = idx[0]; + if (r == 1) + for (int i = 1; i < 8; ++i) { + const int32_t id = idx[i]; + if (id < 0 || id >= 1000 || id == pick || (int)leaves.size() >= L) continue; + if (std::find(leaves.begin(), leaves.end(), id) == leaves.end()) leaves.push_back(id); + } + ++n; + t->tok[n] = pick; t->par[n] = n - 1; + h = child_hash(h, pick); + t->hash[n] = h; + } + for (int32_t id : leaves) { + ++n; + t->tok[n] = id; t->par[n] = 0; + t->hash[n] = child_hash(t->hash[0], id); + } + t->n = n; +} + +/* One verify step over the drafted tree, walked as the core does. Returns the emitted tokens + * (the accepted nodes' tokens and the final one), extended by direct target draws to `want`. */ +int walk(const Tree& t, uint64_t seed, uint64_t n_out, double noise, int want, int* out, + int* accepted) { + int len = 0, cur = 0, depth = 0; + uint64_t h = t.hash[0]; + *accepted = 0; + for (;;) { + const Law law = law_at(h, noise); + const uint64_t pos = n_out + (uint64_t)depth; + /* the row's children, in node order, without repeats */ + int32_t kid[64]; + int nk = 0; + for (int j = cur + 1; j <= t.n; ++j) { + if (t.par[j] != cur) continue; + bool dup = false; + for (int q = 0; q < nk; ++q) dup = dup || kid[q] == t.tok[j]; + if (!dup) kid[nk++] = t.tok[j]; + } + int y = sample_law(law, seed, pos, 0); /* the ordinary pick; an unbound row keeps it */ + const RadMtpCoupleState& c = t.st[cur]; + if (nk > 0 && c.status == 1) { + const int kept = rad_mtp_rrs_prefix(c, kid, nk); + if (kept > 0 && c.round == depth + 1 && c.x == kid[0]) { + RadMtpCoupleState b = c; + b.pos = rad_mtp_couple_verify_pos(n_out, depth + 1); + if (c.nkids >= 2 || c.scheme) b.nkids = kept; + y = verify(b, law, seed, pos, y); + } + } + out[len++] = y; + int nxt = -1; + for (int j = cur + 1; j <= t.n && nxt < 0; ++j) + if (t.par[j] == cur && t.tok[j] == y) nxt = j; + if (nxt < 0) break; + cur = nxt; ++depth; ++*accepted; + h = child_hash(h, y); + } + /* the steps after this one: exact draws from the target given what was committed */ + uint64_t ph = t.hash[0]; + for (int i = 0; i < len; ++i) ph = child_hash(ph, out[i]); + while (len < want) { + const Law law = law_at(ph, noise); + const int y = sample_law(law, seed ^ 0xabcdef1234ull, n_out + (uint64_t)len, 1); + out[len++] = y; + ph = child_hash(ph, y); + } + return len; +} + +/* Chi-square of the empirical first-`m`-token law against the target's, cells with too little + * expected mass pooled; returns (chi2 - df) / sqrt(2 df). */ +double zscore(const std::vector& counts, const std::vector& expect, double n) { + double chi = 0, pool_c = 0, pool_e = 0; + int cells = 0; + for (size_t i = 0; i < counts.size(); ++i) { + const double e = expect[i] * n; + if (e < 20) { pool_c += counts[i]; pool_e += e; continue; } + chi += (counts[i] - e) * (counts[i] - e) / e; + ++cells; + } + if (pool_e >= 5) { chi += (pool_c - pool_e) * (pool_c - pool_e) / pool_e; ++cells; } + const double df = cells - 1; + return (chi - df) / std::sqrt(2.0 * df); +} + +struct Result { double z; double mean_acc; double first_z; }; + +/* Run `trials` steps of one drafted-tree kind and compare the first three emitted tokens' joint + * law (and the first token's marginal) with the target's. */ +Result run_kind(Kind kind, int trials, double noise, + const std::function* hook = nullptr) { + std::vector cnt3((size_t)V * V * V, 0), cnt1((size_t)V, 0); + double acc = 0; + for (int s = 0; s < trials; ++s) { + const uint64_t seed = 0x1234567ull + (uint64_t)s * 7919ull; + Tree t; + if (kind == CHAIN) draft_chain(&t, seed, 0, 3, 0, noise); + else if (kind == STAGE1) draft_chain(&t, seed, 0, 3, 3, noise); + if (hook) (*hook)(&t, s); + int out[64], accepted = 0; + walk(t, seed, 0, noise, 3, out, &accepted); + ++cnt1[(size_t)out[0]]; + ++cnt3[(size_t)((out[0] * V + out[1]) * V + out[2])]; + acc += accepted; + } + std::vector e1((size_t)V, 0), e3((size_t)V * V * V, 0); + const uint64_t h0 = 1; + const Law l0 = law_at(h0, noise); + for (int a = 0; a < V; ++a) { + e1[(size_t)a] = l0.p[a]; + const Law l1 = law_at(child_hash(h0, a), noise); + for (int b = 0; b < V; ++b) { + const Law l2 = law_at(child_hash(child_hash(h0, a), b), noise); + for (int c = 0; c < V; ++c) e3[(size_t)((a * V + b) * V + c)] = l0.p[a] * l1.p[b] * l2.p[c]; + } + } + return { zscore(cnt3, e3, trials), acc / trials, zscore(cnt1, e1, trials) }; +} + + +/* ------------------------------------------------------------------ traversal verification */ + +/* The walk's view of a drafted toy tree: the bound states exactly as `walk` binds them. */ +struct TravTree { + const Tree& t; + double noise; + uint64_t seed, n_out; + Law laws[64]; + RadMtpCoupleState bound[64]; + bool has[64] = {}; + int depth[64] = {}; + TravTree(const Tree& tr, uint64_t sd, uint64_t no, double nz) : t(tr), noise(nz), seed(sd), n_out(no) { + depth[0] = 0; + for (int j = 0; j <= t.n; ++j) { + if (j > 0) depth[j] = depth[t.par[j]] + 1; + laws[j] = law_at(t.hash[j], noise); + const RadMtpCoupleState& c = t.st[j]; + int32_t kid[64]; + int nk = 0; + for (int q = j + 1; q <= t.n; ++q) { + if (t.par[q] != j) continue; + bool dup = false; + for (int z = 0; z < nk; ++z) dup = dup || kid[z] == t.tok[q]; + if (!dup) kid[nk++] = t.tok[q]; + } + if (nk > 0 && c.status == 1) { + const int kept = rad_mtp_rrs_prefix(c, kid, nk); + if (kept > 0 && c.round == depth[j] + 1 && c.x == kid[0]) { + bound[j] = c; + bound[j].pos = rad_mtp_couple_verify_pos(n_out, depth[j] + 1); + if (c.nkids >= 2 || c.scheme) bound[j].nkids = kept; + has[j] = true; + } + } + } + } + const RadMtpCoupleState* state(int v) const { return has[v] ? &bound[v] : nullptr; } + bool cand(int v, const int32_t** ids, const float** val, int64_t* n) const { + *ids = laws[v].pid; *val = laws[v].pval; *n = laws[v].pn; + return true; + } + int child(int v, int32_t token) const { + for (int j = v + 1; j <= t.n; ++j) + if (t.par[j] == v && t.tok[j] == token) return j; + return -1; + } + int64_t vocab() const { return 1000; } +}; + +/* One step walked by traversal verification, then continued from the exact target. */ +int walk_trav(const Tree& t, uint64_t seed, uint64_t n_out, double noise, int want, int* out, + int* accepted, RadMtpTravOpt opt) { + TravTree T(t, seed, n_out, noise); + RadMtpTravOut o; + int len = 0; + *accepted = 0; + if (rad_mtp_trav_walk(T, 0, seed, n_out, &o, opt)) { + for (int i = 1; i < o.n; ++i) out[len++] = t.tok[o.node[i]]; + *accepted = o.n - 1; + const int last = o.node[o.n - 1]; + out[len++] = o.has_y ? o.y : sample_law(T.laws[last], seed, n_out + (uint64_t)(o.n - 1), 0); + } else { + out[len++] = sample_law(T.laws[0], seed, n_out, 0); + } + uint64_t ph = t.hash[0]; + for (int i = 0; i < len; ++i) ph = child_hash(ph, out[i]); + while (len < want) { + const Law law = law_at(ph, noise); + const int y = sample_law(law, seed ^ 0xabcdef1234ull, n_out + (uint64_t)len, 1); + out[len++] = y; + ph = child_hash(ph, y); + } + return len; +} + +Result run_trav(Kind kind, int trials, double noise, RadMtpTravOpt opt) { + std::vector cnt3((size_t)V * V * V, 0), cnt1((size_t)V, 0); + double acc = 0; + for (int s = 0; s < trials; ++s) { + const uint64_t seed = 0x1234567ull + (uint64_t)s * 7919ull; + Tree t; + if (kind == CHAIN) draft_chain(&t, seed, 0, 3, 0, noise); + else if (kind == STAGE1) draft_chain(&t, seed, 0, 3, 3, noise); + int out[64], accepted = 0; + walk_trav(t, seed, 0, noise, 3, out, &accepted, opt); + ++cnt1[(size_t)out[0]]; + ++cnt3[(size_t)((out[0] * V + out[1]) * V + out[2])]; + acc += accepted; + } + std::vector e1((size_t)V, 0), e3((size_t)V * V * V, 0); + const uint64_t h0 = 1; + const Law l0 = law_at(h0, noise); + for (int a = 0; a < V; ++a) { + e1[(size_t)a] = l0.p[a]; + const Law l1 = law_at(child_hash(h0, a), noise); + for (int b = 0; b < V; ++b) { + const Law l2 = law_at(child_hash(child_hash(h0, a), b), noise); + for (int c = 0; c < V; ++c) e3[(size_t)((a * V + b) * V + c)] = l0.p[a] * l1.p[b] * l2.p[c]; + } + } + return { zscore(cnt3, e3, trials), acc / trials, zscore(cnt1, e1, trials) }; +} + +/* The first FOUR emitted tokens' joint: the fourth is the final token of a three-deep accepted path, + * drawn from the walk's residual law, which the three-token statistic never reads. */ +double run_trav4(Kind kind, int trials, double noise) { + std::vector cnt((size_t)V * V * V * V, 0), ex((size_t)V * V * V * V, 0); + for (int s = 0; s < trials; ++s) { + const uint64_t seed = 0x2468ace1ull + (uint64_t)s * 6151ull; + Tree t; + if (kind == CHAIN) draft_chain(&t, seed, 0, 3, 0, noise); + else if (kind == STAGE1) draft_chain(&t, seed, 0, 3, 3, noise); + int out[64], accepted = 0; + walk_trav(t, seed, 0, noise, 4, out, &accepted, RadMtpTravOpt{}); + ++cnt[(size_t)(((out[0] * V + out[1]) * V + out[2]) * V + out[3])]; + } + const uint64_t h0 = 1; + const Law l0 = law_at(h0, noise); + for (int a = 0; a < V; ++a) { + const uint64_t ha = child_hash(h0, a); const Law l1 = law_at(ha, noise); + for (int b = 0; b < V; ++b) { + const uint64_t hb = child_hash(ha, b); const Law l2 = law_at(hb, noise); + for (int c = 0; c < V; ++c) { + const Law l3 = law_at(child_hash(hb, c), noise); + for (int d = 0; d < V; ++d) + ex[(size_t)(((a * V + b) * V + c) * V + d)] = l0.p[a] * l1.p[b] * l2.p[c] * l3.p[d]; + } + } + } + return zscore(cnt, ex, trials); +} + +} /* namespace */ + +/* A whole generation: steps drafted at the committed prefix (base = the output length so far, the + * engine's), each walked as the core walks it, until `want` tokens are out. The joint law of tokens + * [1, 4) -- spanning the step boundaries, with token 0 and everything after marginalised -- and of + * tokens [0, 3) must be the target's: this is what a draft or verify stream reused across steps + * would break. */ +Result run_steps(Kind kind, int trials, double noise, bool trav = false) { + const int want = 6; + std::vector cnt_a((size_t)V * V * V, 0), cnt_b((size_t)V * V * V, 0); + double steps = 0; + for (int s = 0; s < trials; ++s) { + const uint64_t seed = 0x7654321ull + (uint64_t)s * 104729ull; + int out[64], len = 0; + uint64_t h = 1; + while (len < want) { + Tree t; + if (kind == CHAIN) draft_chain(&t, seed, (uint64_t)len, 3, 0, noise, h); + else if (kind == STAGE1) draft_chain(&t, seed, (uint64_t)len, 3, 3, noise, h); + int step_out[64], accepted = 0; + const int n = trav ? walk_trav(t, seed, (uint64_t)len, noise, 0, step_out, &accepted, RadMtpTravOpt{}) + : walk(t, seed, (uint64_t)len, noise, 0, step_out, &accepted); + for (int i = 0; i < n; ++i) { out[len++] = step_out[i]; h = child_hash(h, step_out[i]); } + ++steps; + } + ++cnt_a[(size_t)((out[0] * V + out[1]) * V + out[2])]; + ++cnt_b[(size_t)((out[1] * V + out[2]) * V + out[3])]; + } + /* expected: token 0 marginalised for (1,2,3) */ + std::vector ea((size_t)V * V * V, 0), eb((size_t)V * V * V, 0); + const uint64_t h0 = 1; + const Law l0 = law_at(h0, noise); + for (int a = 0; a < V; ++a) { + const uint64_t ha = child_hash(h0, a); + const Law l1 = law_at(ha, noise); + for (int b = 0; b < V; ++b) { + const uint64_t hb = child_hash(ha, b); + const Law l2 = law_at(hb, noise); + for (int c = 0; c < V; ++c) { + const uint64_t hc = child_hash(hb, c); + const Law l3 = law_at(hc, noise); + ea[(size_t)((a * V + b) * V + c)] = l0.p[a] * l1.p[b] * l2.p[c]; + for (int d = 0; d < V; ++d) + eb[(size_t)((b * V + c) * V + d)] += l0.p[a] * l1.p[b] * l2.p[c] * l3.p[d]; + } + } + } + return { zscore(cnt_a, ea, trials), steps / trials, zscore(cnt_b, eb, trials) }; +} + +TEST(a_generation_over_several_steps_keeps_the_target_law) { + const int trials = 150000; + const Kind kinds[] = { CHAIN, STAGE1 }; + const char* names[] = { "chain", "stage1" }; + for (int k = 0; k < 2; ++k) { + const Result r = run_steps(kinds[k], trials, 1.0); + std::printf(" %-8s steps=%.3f z[0..3)=%.2f z[1..4)=%.2f\n", names[k], r.mean_acc, r.z, r.first_z); + CHECK(r.z < 4.5); + CHECK(r.first_z < 4.5); + } +} + +/* The single-node recursion: m = 1..4 children drawn without replacement from Q, verified in draft + * order, emit ~ P for every (P, Q) pair, including a P that lacks some of Q's tokens. */ +TEST(one_node_with_several_children_emits_the_target_law) { + const int trials = 400000; + for (int m = 2; m <= 4; ++m) + for (int pair = 0; pair < 6; ++pair) { + const Law L = law_at(1000 + (uint64_t)pair, 1.0 + 0.4 * pair); + std::vector cnt((size_t)V, 0); + for (int s = 0; s < trials; ++s) { + RadMtpCoupleState st{}; + CHECK(rad_mtp_couple_build_q(L.qid, L.qval, 1000, &st)); + st.draw = make_draw(0x9e3779b97f4a7c15ull * (uint64_t)(s + 1), (uint64_t)s); + st.status = 1; st.round = 1; st.pos = 5; + rad_mtp_rrs_draw(&st, 0, m); + CHECK(rad_mtp_couple_state_valid(st, 1000)); + CHECK_EQ(st.nkids, std::min(m, st.count)); + const int y = verify(st, L, st.draw.seed, 5, -1); + CHECK(y >= 0 && y < V); + ++cnt[(size_t)y]; + } + std::vector e(L.p, L.p + V); + const double z = zscore(cnt, e, trials); + if (z > 4.5) std::printf(" m=%d pair=%d z=%.2f\n", m, pair, z); + CHECK(z < 4.5); + } +} + +/* The negative control: SpecInfer's with-replacement verify (q not removed or renormalised) on + * drafts drawn without replacement is not exact, and the same statistic sees it. */ +TEST(the_with_replacement_verify_is_not_exact_for_without_replacement_drafts) { + const int trials = 400000, m = 3; + const Law L = law_at(1002, 1.0); + std::vector cnt((size_t)V, 0); + for (int s = 0; s < trials; ++s) { + RadMtpCoupleState st{}; + rad_mtp_couple_build_q(L.qid, L.qval, 1000, &st); + st.draw = make_draw(0x9e3779b97f4a7c15ull * (uint64_t)(s + 1), (uint64_t)s); + rad_mtp_rrs_draw(&st, 0, m); + double r[V], q[V]; + for (int i = 0; i < V; ++i) { r[i] = L.p[i]; q[i] = 0; } + for (int k = 0; k < st.count; ++k) q[st.ids[k]] = st.q[k]; + int out = -1; + for (int i = 0; i < m && out < 0; ++i) { + const int x = st.ids[i]; + const double u = rad_mtp_rrs_uaccept(st.draw.seed, 5, i); + if (r[x] >= q[x] || u * q[x] < r[x]) { out = x; break; } + double z = 0; + for (int k = 0; k < V; ++k) { r[k] = std::max(r[k] - q[k], 0.0); z += r[k]; } + for (int k = 0; k < V; ++k) r[k] /= z; /* q never renormalised, the child never removed */ + } + if (out < 0) { + double u = rad_spechub_uniform(st.draw.seed, 5, RAD_SAMPLE_KEY_RESID); + out = 0; + for (int k = 0; k < V; ++k) { if (r[k] <= 0) continue; out = k; u -= r[k]; if (u < 0) break; } + } + ++cnt[(size_t)out]; + } + std::vector e(L.p, L.p + V); + const double z = zscore(cnt, e, trials); + CHECK(z > 20.0); +} + +TEST(a_chain_and_a_chain_with_root_siblings_emit_the_target_law) { + const int trials = 300000; + const Result chain = run_kind(CHAIN, trials, 1.0); + const Result s1 = run_kind(STAGE1, trials, 1.0); + std::printf(" chain z=%.2f acc=%.3f | root siblings z=%.2f acc=%.3f\n", chain.z, chain.mean_acc, s1.z, s1.mean_acc); + CHECK(chain.z < 4.5); CHECK(chain.first_z < 4.5); + CHECK(s1.z < 4.5); CHECK(s1.first_z < 4.5); + /* siblings are drafted to be accepted: they accept at least as many drafts as the chain */ + CHECK(s1.mean_acc > chain.mean_acc); + /* and a head far from the target changes the acceptance, never the law */ + const Result far = run_kind(STAGE1, 150000, 3.0); + CHECK(far.z < 4.5); +} + +/* Q == P: the first child is accepted whatever the seed; disjoint supports: nothing drafted is + * accepted and the token is a draw from P. */ +TEST(degenerate_laws) { + const Law L = law_at(77, 1.0); + /* P exactly the head's law: a plane equal to the shortlist */ + Law same = L; + same.pn = 0; + for (int i = 0; i < 8; ++i) { same.pid[same.pn] = L.qid[i]; same.pval[same.pn++] = L.qval[i]; } + for (int s = 0; s < 2000; ++s) { + RadMtpCoupleState st{}; + CHECK(rad_mtp_couple_build_q(L.qid, L.qval, 1000, &st)); + st.draw = make_draw(31ull * (uint64_t)(s + 1), 0); + st.status = 1; st.round = 1; st.pos = 0; + rad_mtp_rrs_draw(&st, 0, 3); + CHECK_EQ(verify(st, same, st.draw.seed, 0, -7), st.ids[0]); + } + /* disjoint: the target lives on tokens the head never reports */ + Law dis{}; + dis.pn = 2; dis.pid[0] = 20; dis.pid[1] = 21; dis.pval[0] = 0.3f; dis.pval[1] = -0.4f; + const double p20 = 1.0 / (1.0 + std::exp(-0.7)); + int n20 = 0; + const int trials = 100000; + for (int s = 0; s < trials; ++s) { + RadMtpCoupleState st{}; + CHECK(rad_mtp_couple_build_q(L.qid, L.qval, 1000, &st)); + st.draw = make_draw(77ull * (uint64_t)(s + 1), 0); + st.status = 1; st.round = 1; st.pos = 3; + rad_mtp_rrs_draw(&st, 0, 4); + const int y = verify(st, dis, st.draw.seed, 3, -7); + CHECK(y == 20 || y == 21); + n20 += y == 20; + } + CHECK(std::fabs((double)n20 / trials - p20) < 5 * std::sqrt(p20 * (1 - p20) / trials)); +} + +TEST(traversal_verification_emits_the_target_law_and_accepts_more) { + const int trials = 200000; + const RadMtpTravOpt ok{}; + const Result chain = run_trav(CHAIN, trials, 1.0, ok); + const Result s1 = run_trav(STAGE1, trials, 1.0, ok); + const Result rchain = run_kind(CHAIN, trials, 1.0); + const Result rs1 = run_kind(STAGE1, trials, 1.0); + std::printf(" traversal chain z=%.2f acc=%.3f (rowwise %.3f) | root siblings z=%.2f acc=%.3f (rowwise %.3f)\n", + chain.z, chain.mean_acc, rchain.mean_acc, s1.z, s1.mean_acc, rs1.mean_acc); + CHECK(chain.z < 4.5); CHECK(chain.first_z < 4.5); + CHECK(s1.z < 4.5); CHECK(s1.first_z < 4.5); + CHECK(chain.mean_acc > rchain.mean_acc); + CHECK(s1.mean_acc > rs1.mean_acc); + const Result far = run_trav(STAGE1, 100000, 3.0, ok); + CHECK(far.z < 4.5); +} + +/* Each mistake the walk could make is caught by the same statistic: token-level ratios (1), no + * (1 - p) term (2), the draft law never renormalised after a rejection (3). */ +TEST(traversal_verification_mistakes_are_not_exact) { + for (int ctl = 1; ctl <= 3; ++ctl) { + RadMtpTravOpt o; o.ctl = ctl; + const Result r = run_trav(STAGE1, 100000, 1.0, o); + std::printf(" negative control %d: z=%.2f first_z=%.2f\n", ctl, r.z, r.first_z); + CHECK(r.z > 20.0 || r.first_z > 20.0); + } +} + +/* The walk's final token (the fourth of a three-deep path) and a generation over several steps (no + * uniform reused across steps). */ +TEST(traversal_verification_final_token_and_steps_are_exact) { + const Kind kinds[] = { CHAIN, STAGE1 }; + const char* names[] = { "chain", "root siblings" }; + for (int k = 0; k < 2; ++k) { + const double z4 = run_trav4(kinds[k], 300000, 1.0); + const Result r = run_steps(kinds[k], 100000, 1.0, true); + std::printf(" trav %-14s z4=%.2f steps=%.3f z[0..3)=%.2f z[1..4)=%.2f\n", names[k], z4, r.mean_acc, r.z, r.first_z); + CHECK(z4 < 4.5); + CHECK(r.z < 4.5); + CHECK(r.first_z < 4.5); + } +} + +/* Peaked laws: the target's inverse temperature 3 and 6 (a few tokens carry the mass, the acceptance + * ratios sit at or above one on the trunk), where a cap or rounding at p = 1 would show. */ +TEST(traversal_verification_is_exact_on_peaked_laws) { + const double old = g_sharp; + for (double sh : { 3.0, 6.0 }) { + g_sharp = sh; + for (Kind k : { CHAIN, STAGE1 }) { + const Result r = run_trav(k, 150000, 1.0, RadMtpTravOpt{}); + const double z4 = run_trav4(k, 200000, 1.0); + std::printf(" trav sharp=%.0f kind=%d z=%.2f first=%.2f z4=%.2f acc=%.3f\n", sh, (int)k, r.z, r.first_z, z4, r.mean_acc); + CHECK(r.z < 4.5); CHECK(r.first_z < 4.5); CHECK(z4 < 4.5); + } + } + g_sharp = old; +} + +namespace { + +constexpr int SV = 8; /* toy vocab bound: tokens 0 .. V-1 with V <= 6 here */ + +struct SLaw { + int V = 0; + int32_t pid[SV]; float pval[SV]; int pn = 0; /* the target's candidate plane (its nucleus) */ + double p[SV] = {}; /* its exact law over tokens 0 .. V-1 */ + int32_t qid[8]; float qval[8]; /* the head's shortlist, holes = -1 / -inf */ +}; + +/* A target over `psup` of the V tokens (the others have no candidate, as after top-p) and a head over + * `qsup` of them, independently chosen: the supports may differ, nest or be disjoint. */ +SLaw small_law(uint64_t h, int V, int qsup, int psup, double qspread = 1.0) { + SLaw L; + L.V = V; + int perm[SV], perm2[SV]; + for (int i = 0; i < V; ++i) { perm[i] = i; perm2[i] = i; } + for (int i = V - 1; i > 0; --i) { + std::swap(perm[i], perm[(int)(H(h * 31 + (uint64_t)i) % (uint64_t)(i + 1))]); + std::swap(perm2[i], perm2[(int)(H(h * 37 + 5 + (uint64_t)i) % (uint64_t)(i + 1))]); + } + double z = 0; + for (int j = 0; j < psup; ++j) { + const float lg = (float)((H(h * 131 + (uint64_t)j * 977 + 1) >> 40) % 4000) / 1000.0f - 2.0f; + L.pid[L.pn] = perm[j]; L.pval[L.pn++] = lg; + } + for (int j = 0; j < L.pn; ++j) z += std::exp((double)L.pval[j]); + for (int j = 0; j < L.pn; ++j) L.p[L.pid[j]] = std::exp((double)L.pval[j]) / z; + for (int i = 0; i < 8; ++i) { L.qid[i] = -1; L.qval[i] = -INFINITY; } + for (int j = 0; j < qsup; ++j) { + L.qid[j] = perm2[j]; + L.qval[j] = (float)(qspread * (((H(h * 257 + (uint64_t)j * 331 + 7) >> 40) % 4000) / 1000.0 - 2.0)); + } + return L; +} + +/* The step function f(u), u in [0, 1): its pieces (token, length) in order, found by bisection. */ +std::vector> pieces(const std::function& f) { + std::vector> out; + double lo = 0; + const double last = 1.0 - 0x1p-53; + while (lo < 1) { + const int t = f(lo); + double b = 1.0; + if (f(last) != t) { + double a = lo, bb = last; + for (int it = 0; it < 80; ++it) { + const double mid = 0.5 * (a + bb); + if (f(mid) == t) a = mid; else bb = mid; + } + b = bb; + } + out.emplace_back(t, b - lo); + if (b >= 1.0) break; + lo = b; + } + return out; +} + +} /* namespace */ + +/* ==================================================================================================== + * Traversal verification, checked EXACTLY and on its own arithmetic (abi/rad_mtp_traversal.h). + * + * The walk reads the target through integer masses (rad_mtp_trav_mass: an FP32 exponential in fixed + * point), so the law it realises for a row is P~ = masses / their sum, a fixed function of the row. + * The tests below check (1) that P~ is the softmax to FP32 accuracy; (2) by ENUMERATION that the walk + * emits P~ exactly: every draft tree of a small model is built with its probability (Plackett-Luce + * prefixes for Gumbel siblings, the tail draw's pieces for rheo), the walk's tests are scripted (test + * t accepts with its own rate after t - 1 rejections, which the walk reports), and the law of the + * first two emitted tokens comes out as P~(x1) P~(x2 | x1) to 1e-11; the with-replacement update, the + * missing (1 - p) term and a rheo node walked as a Gumbel one miss by percents; (3) that the final + * token's uniform maps onto the residual law (support slots, then the off-support candidates by + * integer units) on a 700-slot plane; (4) the rheo walk by chi-square through the real drafters. + * ================================================================================================== */ +namespace { + +/* The law the walk realises for a candidate plane: its integer masses over the tokens. */ +void trav_int_law(const SLaw& L, double* p) { + for (int x = 0; x < SV; ++x) p[x] = 0; + if (L.pn <= 0) return; + float top = -INFINITY; + for (int j = 0; j < L.pn; ++j) top = std::max(top, L.pval[j]); + uint64_t m[SV] = {}, sum = 0; + for (int j = 0; j < L.pn; ++j) m[L.pid[j]] += rad_mtp_trav_mass(L.pval[j], top, RAD_MTP_TRAV_QBITS); + for (int x = 0; x < SV; ++x) sum += m[x]; + for (int x = 0; x < SV; ++x) p[x] = (double)m[x] / (double)sum; +} + +struct ETree { + int n = 1; + int par[40] = {}; + int32_t tok[40] = {}; + bool has[40] = {}; + RadMtpCoupleState st[40] = {}; + const SLaw* law[40] = {}; + const RadMtpCoupleState* state(int v) const { return has[v] ? &st[v] : nullptr; } + bool cand(int v, const int32_t** ids, const float** val, int64_t* nn) const { + *ids = law[v]->pid; *val = law[v]->pval; *nn = law[v]->pn; + return true; + } + int child(int v, int32_t token) const { + for (int j = v + 1; j < n; ++j) + if (par[j] == v && tok[j] == token) return j; + return -1; + } + int64_t vocab() const { return 1000; } +}; + +struct EDraft { double w = 0; RadMtpCoupleState st{}; int nk = 0; int32_t kid[4] = {}; }; + +/* Every way a node with the head's law of `L` drafts `want` children, with its probability: the + * ordered prefixes of sampling without replacement (scheme 0), or the pieces of the rheo tail draw + * (scheme m + 1). Empty when the head has no law (the node drafts nothing). */ +std::vector edrafts(const SLaw& L, int scheme, int want, int round) { + std::vector out; + RadMtpCoupleState s0{}; + if (want <= 0 || !rad_mtp_couple_build_q(L.qid, L.qval, 1000, &s0)) return out; + s0.draw = make_draw(77, 3); s0.status = 1; s0.round = round; s0.pos = 5; + if (scheme > 0) { + const int m = scheme - 1; + auto drawn = [&](double ut) { RadMtpCoupleState s = s0; rad_mtp_rrs_draw_rheo_u(&s, ut, want, m); return s; }; + std::vector> pc; + if (s0.count > m) pc = pieces([&](double ut) { return (int)drawn(ut).ids[m]; }); + else pc.emplace_back(0, 1.0); + double lo = 0; + for (const auto& x : pc) { + EDraft d; + d.w = x.second; + d.st = drawn(lo + 0.5 * x.second); + lo += x.second; + d.nk = d.st.nkids; + for (int k = 0; k < d.nk; ++k) d.kid[k] = d.st.ids[k]; + out.push_back(d); + } + return out; + } + const int a = std::min(want, s0.count); + int idx[4] = {}; + std::function rec = [&](int depth, double w, double used) { + if (depth == a) { + EDraft d; + d.w = w; + d.st = s0; + if (a >= 2) { + bool taken[8] = {}; + int n = 0; + for (int i = 0; i < a; ++i) { d.st.ids[n] = s0.ids[idx[i]]; d.st.q[n++] = s0.q[idx[i]]; taken[idx[i]] = true; } + for (int i = 0; i < s0.count; ++i) + if (!taken[i]) { d.st.ids[n] = s0.ids[i]; d.st.q[n++] = s0.q[i]; } + d.st.x = d.st.ids[0]; + d.st.nkids = a; + } else { + d.st.x = s0.ids[idx[0]]; /* the chain's wire: x anywhere in the shortlist's order */ + d.st.nkids = 0; + } + d.nk = a; + for (int i = 0; i < a; ++i) d.kid[i] = s0.ids[idx[i]]; + out.push_back(d); + return; + } + for (int i = 0; i < s0.count; ++i) { + bool dup = false; + for (int j = 0; j < depth; ++j) dup = dup || idx[j] == i; + if (dup) continue; + idx[depth] = i; + rec(depth + 1, w * s0.q[i] / (1.0 - used), used + s0.q[i]); + } + }; + rec(0, 1.0, 0.0); + return out; +} + +/* The law of the token a walk emits at a path's last node, from the walked tree: the node's + * residual (support slots, then its off-support candidates by their integer masses), or the plain + * target when the node carries no law. */ +void etree_final_law(const RadTravTree& kt, int c, const SLaw& L, double* law) { + for (int x = 0; x < SV; ++x) law[x] = 0; + double tot = 0; + if (kt.ok[c]) { + const double woff = kt.moff[c]; + tot = rad_mtp_trav_sum8(kt.m[c]) + woff; + if (tot > 0) { + for (int k = 0; k < 8; ++k) + if (kt.ids[c][k] >= 0) law[kt.ids[c][k]] += kt.m[c][k] / tot; + if (woff > 0 && kt.off[c] > 0) + for (int j = 0; j < L.pn; ++j) { + bool on = false; + for (int k = 0; k < 8; ++k) on = on || kt.ids[c][k] == L.pid[j]; + if (!on) + law[L.pid[j]] += woff / tot * + (double)rad_mtp_trav_mass(L.pval[j], kt.top[c], RAD_MTP_TRAV_QBITS) / (double)kt.off[c]; + } + } + } + if (!(tot > 0)) trav_int_law(L, law); +} + +/* Adds w * P(the first two emitted tokens = (x1, x2) | this draft tree) to `joint`. */ +void etree_joint(const ETree& T, const SLaw* kid, int V, double w, double joint[SV][SV], int ctl, + double* leak) { + double pt[64]; + int nt = 0; + RadMtpTravOpt o; + o.ctl = ctl; o.accept_at = 0; o.p_test = pt; o.n_tests = &nt; o.max_tests = 64; + RadMtpTravOut out; + rad_mtp_trav_walk(T, 0, 1, 1, &out, o); /* every test rejects: the rates of tests 1 .. nt */ + double kidlaw[SV][SV]; + for (int x = 0; x < V; ++x) trav_int_law(kid[x], kidlaw[x]); + double surv = 1; + for (int t = 1; t <= nt; ++t) { + const double pa = surv * pt[t - 1]; + surv *= 1.0 - pt[t - 1]; + if (!(pa > 0)) continue; + RadTravTree kt; + int ids[RAD_MTP_TRAV_MAX_ROWS]; + RadMtpTravOpt o2; + o2.ctl = ctl; o2.accept_at = t; o2.u_final = 0.5; + RadMtpTravOut po; + CHECK(rad_mtp_trav_walk(T, 0, 1, 1, &po, o2, &kt, ids)); + const int f = po.node[po.n - 1]; + int c = 0; + while (ids[c] != f) ++c; + double fl[SV]; + etree_final_law(kt, c, *T.law[f], fl); + if (po.n == 1) { + for (int y = 0; y < V; ++y) + for (int b = 0; b < V; ++b) joint[y][b] += w * pa * fl[y] * kidlaw[y][b]; + } else if (po.n == 2) { + const int x1 = T.tok[po.node[1]]; + for (int b = 0; b < V; ++b) joint[x1][b] += w * pa * fl[b]; + } else { + joint[T.tok[po.node[1]]][T.tok[po.node[2]]] += w * pa; + } + } + *leak += w * surv; /* the root accepts with rate 1: nothing may be left */ +} + +/* The exact joint law of the first two emitted tokens for a root that drafts `a` children, each + * drafting `b`; returns the largest deviation from P~(x1) P~(x2 | x1). */ +double trav_enum_case(const SLaw& root, const SLaw* kid, int V, int scheme, int a, int b, int ctl, long* trees) { + double joint[SV][SV] = {}, leak = 0, wsum = 0; + const std::vector roots = edrafts(root, scheme, a, 1); + CHECK(!roots.empty()); + for (const EDraft& r0 : roots) { + std::vector cd[4]; + for (int i = 0; i < r0.nk; ++i) cd[i] = edrafts(kid[r0.kid[i]], scheme, b, 2); + int sel[4] = {}; + for (;;) { + ETree T; + T.has[0] = true; T.st[0] = r0.st; T.law[0] = &root; T.par[0] = -1; + CHECK(rad_mtp_couple_state_valid(r0.st, 1000)); + double w = r0.w; + for (int i = 0; i < r0.nk; ++i) { + const int v = T.n++; + T.par[v] = 0; T.tok[v] = r0.kid[i]; T.law[v] = &kid[r0.kid[i]]; + T.has[v] = !cd[i].empty(); + if (T.has[v]) { T.st[v] = cd[i][(size_t)sel[i]].st; w *= cd[i][(size_t)sel[i]].w; } + } + for (int i = 0; i < r0.nk; ++i) { + if (cd[i].empty()) continue; + const EDraft& d = cd[i][(size_t)sel[i]]; + for (int g = 0; g < d.nk; ++g) { + const int v = T.n++; + T.par[v] = 1 + i; T.tok[v] = d.kid[g]; T.law[v] = &kid[d.kid[g]]; + } + } + etree_joint(T, kid, V, w, joint, ctl, &leak); + wsum += w; + ++*trees; + int i = 0; + for (; i < r0.nk; ++i) { + if (cd[i].empty()) continue; + if (++sel[i] < (int)cd[i].size()) break; + sel[i] = 0; + } + if (i >= r0.nk) break; + } + } + CHECK(std::fabs(wsum - 1.0) < 1e-11); + double p0[SV], worst = ctl ? 0.0 : std::fabs(leak); + trav_int_law(root, p0); + for (int x1 = 0; x1 < V; ++x1) { + double p1[SV]; + trav_int_law(kid[x1], p1); + for (int x2 = 0; x2 < V; ++x2) worst = std::max(worst, std::fabs(joint[x1][x2] - p0[x1] * p1[x2])); + } + return worst; +} + +} /* namespace */ + +/* (1) The fixed-point exponential against libm's, the integer conversions, and the law they give. */ +TEST(the_walks_fixed_point_exponential_tracks_exp) { + const double unit = (double)(1ull << RAD_MTP_TRAV_QBITS); + double worst = 0; + CHECK_EQ(rad_mtp_trav_mass(3.25f, 3.25f, RAD_MTP_TRAV_QBITS), 1ull << RAD_MTP_TRAV_QBITS); + CHECK_EQ(rad_mtp_trav_mass(-INFINITY, 0.0f, RAD_MTP_TRAV_QBITS), 0ull); + CHECK_EQ(rad_mtp_trav_mass(-30.0f, 0.0f, RAD_MTP_TRAV_QBITS), 0ull); + const int N = 3000000; + for (int i = 0; i <= N; ++i) { + /* a dense sweep of the whole range, and the same arguments reached from other tops */ + const float x = -28.6f * (float)i / (float)N; + const float top = i % 3 == 0 ? 0.0f : (float)((int)(H((uint64_t)i) % 6000) - 3000) / 100.0f; + const float v = top + x; + const float xr = v - top; /* the argument the mass sees */ + const uint64_t m = rad_mtp_trav_mass(v, top, RAD_MTP_TRAV_QBITS); + const double want = xr > -28.5f ? std::exp((double)xr) * unit : 0.0; + const double err = std::fabs((double)m - want); + CHECK(err <= want * 0x1p-22 + 1.0); + if (want > 0x1p32) worst = std::max(worst, err / want); /* where the floor's one unit is below 2^-32 */ + /* a coarser unit is the floor of the finer one */ + if (i % 16 == 0) CHECK_EQ(rad_mtp_trav_mass(v, top, 31), m >> 9); + } + std::printf(" fixed-point exp: worst relative error %.3g (2^-22 = %.3g) over %d arguments\n", worst, 0x1p-22, N); + CHECK(worst < 0x1p-22); + CHECK_EQ(rad_mtp_trav_qbits(20), 40); CHECK_EQ(rad_mtp_trav_qbits(1024), 40); + CHECK_EQ(rad_mtp_trav_qbits(4096), 40); CHECK_EQ(rad_mtp_trav_qbits(4097), 39); + CHECK_EQ(rad_mtp_trav_qbits(8192), 39); CHECK_EQ(rad_mtp_trav_qbits(1ll << 31), 21); + for (int i = 0; i < 200000; ++i) { + const uint64_t x = H((uint64_t)i * 77 + 5) >> (11 + (i % 40)); + CHECK(rad_mtp_trav_u2d(x) == (double)x); + CHECK_EQ(rad_mtp_trav_d2u(rad_mtp_trav_u2d(x)), x); + if (x < (1ull << 50)) CHECK_EQ(rad_mtp_trav_d2u(rad_mtp_trav_u2d(x) + 0.75), x); + } + /* the law of a plane: the softmax, to FP32 accuracy */ + double wl = 0; + for (int t = 0; t < 2000; ++t) { + const Law L = law_at(31000 + (uint64_t)t, 1.0); + float top = -INFINITY; + CHECK(rad_mtp_trav_row_top(L.pid, L.pval, L.pn, 1000, &top)); + int32_t sid[8]; + for (int k = 0; k < 8; ++k) sid[k] = L.qid[k]; + RadTravLaw w; + rad_mtp_trav_row_law(L.pid, L.pval, L.pn, top, sid, 8, &w); + uint64_t on = 0; + for (int k = 0; k < 8; ++k) { + on += w.pq[k]; + wl = std::max(wl, std::fabs((double)w.pq[k] / (double)w.sum - L.p[sid[k]])); + } + CHECK_EQ(on + w.off, w.sum); + } + std::printf(" integer law against the FP64 softmax: worst |dp| = %.3g\n", wl); + CHECK(wl < 5e-7); +} + +/* (2) The walk emits the law it reads, exactly: Gumbel siblings and rheo (m = 1, 2), roots with one + * to three children, children with none to two, supports that nest, differ or are disjoint. */ +TEST(traversal_two_deep_joint_law_is_exact_by_enumeration) { + double worst = 0; + long trees = 0; + int cases = 0; + const struct { int scheme, a, b; } shapes[] = { + { 0, 1, 0 }, { 0, 1, 1 }, { 0, 2, 0 }, { 0, 2, 1 }, { 0, 2, 2 }, { 0, 3, 1 }, { 0, 1, 2 }, + { 0, 3, 2 }, { 0, 2, 3 }, + { 2, 1, 1 }, { 2, 2, 1 }, { 2, 2, 2 }, { 3, 2, 1 }, { 3, 3, 1 }, { 3, 3, 3 }, { 1, 1, 1 }, { 4, 4, 2 }, + }; + for (int V = 4; V <= 6; ++V) + for (int cfg = 0; cfg < 24; ++cfg) { + const int qs0 = 1 + (cfg * 2 + 1) % V, ps0 = 1 + (cfg * 3 + 2) % V; + const SLaw root = small_law((uint64_t)(61000 + V * 50 + cfg), V, qs0, ps0, cfg % 3 == 2 ? 2.5 : 1.0); + SLaw kid[SV]; + for (int x = 0; x < V; ++x) + kid[x] = small_law((uint64_t)(67000 + V * 70 + cfg * 13 + x), V, 1 + (cfg + x) % V, + 1 + (cfg + 2 * x + 1) % V); + for (const auto& sh : shapes) { + const double w = trav_enum_case(root, kid, V, sh.scheme, sh.a, sh.b, 0, &trees); + worst = std::max(worst, w); + if (!(w < 1e-11)) + std::printf(" ENUM FAIL V=%d cfg=%d qs0=%d ps0=%d scheme=%d a=%d b=%d: %g\n", V, cfg, qs0, ps0, + sh.scheme, sh.a, sh.b, w); + CHECK(w < 1e-11); + ++cases; + } + } + std::printf(" traversal enumeration: %d cases, %ld draft trees, worst |joint - P P| = %.2e\n", cases, trees, worst); + /* the same statistic sees the mistakes */ + const SLaw root = small_law(61333, 5, 5, 5, 1.0); + SLaw kid[SV]; + for (int x = 0; x < 5; ++x) kid[x] = small_law((uint64_t)(67333 + x), 5, 4, 5); + long t2 = 0; + const double good = trav_enum_case(root, kid, 5, 0, 2, 2, 0, &t2); + const double c1 = trav_enum_case(root, kid, 5, 0, 2, 2, 1, &t2); + const double c2 = trav_enum_case(root, kid, 5, 0, 2, 2, 2, &t2); + const double c3 = trav_enum_case(root, kid, 5, 0, 2, 2, 3, &t2); + const double rgood = trav_enum_case(root, kid, 5, 2, 2, 2, 0, &t2); + const double c4 = trav_enum_case(root, kid, 5, 2, 2, 2, 4, &t2); + std::printf(" controls: exact %.1e | token-level ratios %.3f | no (1 - p) %.3f | no renormalisation %.3f | " + "rheo exact %.1e, rheo walked as gumbel %.3f\n", good, c1, c2, c3, rgood, c4); + CHECK(good < 1e-11); CHECK(rgood < 1e-11); + CHECK(c1 > 1e-3); CHECK(c2 > 1e-3); CHECK(c3 > 1e-3); CHECK(c4 > 1e-3); +} + +/* (3) The final token's uniform against the residual law, on a 700-slot plane (holes, a state whose + * support is partly off the plane): after both children are rejected the root accepts, and the pieces + * of u -> token have the lengths the walked tree's residual gives each token. */ +TEST(the_traversals_final_draw_is_the_residual_law_on_a_wide_plane) { + constexpr int NC = 700, NV = 5000; + int mixed = 0; /* cases where the support slots and the off-support candidates both carry mass */ + for (int rep = 0; rep < 3; ++rep) { + static int32_t ids[NC]; + static float val[NC]; + int live = 0; + for (int c = 0; c < NC; ++c) { + const uint64_t h = H(900000 + (uint64_t)rep * 7919 + (uint64_t)c); + if (h % 11 == 0) { ids[c] = -1; val[c] = -INFINITY; continue; } + ids[c] = 1 + c * 7; /* distinct */ + /* a peaked head and a long tail that still carries a few percent */ + val[c] = (h % 13 == 1) ? -INFINITY + : c < 16 ? 6.0f - 0.9f * (float)c - (float)((h >> 20) % 1000) * 0.0005f + : 1.5f - 0.012f * (float)c - (float)((h >> 20) % 1000) * 0.002f; + ++live; + } + int32_t qid[8]; + float qv[8]; + for (int k = 0; k < 8; ++k) { + qid[k] = k < 5 ? 1 + k * 7 : NV - 10 - k; /* five on the plane's head, three off it */ + qv[k] = 2.0f - (rep == 0 ? 0.35f : rep == 1 ? 0.6f : 0.15f) * (float)k; + } + struct WTree { + RadMtpCoupleState st; int32_t c1, c2; + const RadMtpCoupleState* state(int v) const { return v == 0 ? &st : nullptr; } + bool cand(int, const int32_t** i, const float** v, int64_t* n) const { *i = ids; *v = val; *n = NC; return true; } + int child(int v, int32_t t) const { return v == 0 ? (t == c1 ? 1 : t == c2 ? 2 : -1) : -1; } + int64_t vocab() const { return NV; } + } T; + CHECK(rad_mtp_couple_build_q(qid, qv, NV, &T.st)); + T.st.draw = make_draw(4242 + (uint64_t)rep, 3); T.st.status = 1; T.st.round = 1; T.st.pos = 5; + rad_mtp_rrs_draw(&T.st, 0, 2); + T.c1 = T.st.ids[0]; T.c2 = T.st.ids[1]; + RadTravTree kt; + int map[RAD_MTP_TRAV_MAX_ROWS]; + RadMtpTravOpt o; + o.accept_at = 3; o.u_final = 0.25; /* the two leaves reject, the root accepts */ + RadMtpTravOut out; + CHECK(rad_mtp_trav_walk(T, 0, 1, 1, &out, o, &kt, map)); + CHECK_EQ(out.n, 1); + CHECK(out.has_y); + const double woff = kt.moff[0], tot = rad_mtp_trav_sum8(kt.m[0]) + woff; + std::vector want((size_t)NV, 0.0), got((size_t)NV, 0.0); + for (int k = 0; k < 8; ++k) want[(size_t)kt.ids[0][k]] += kt.m[0][k] / tot; + for (int c = 0; c < NC; ++c) { + if (ids[c] < 0 || val[c] == -INFINITY) continue; + bool on = false; + for (int k = 0; k < 8; ++k) on = on || kt.ids[0][k] == ids[c]; + if (!on) want[(size_t)ids[c]] += woff / tot * (double)rad_mtp_trav_mass(val[c], kt.top[0], RAD_MTP_TRAV_QBITS) / (double)kt.off[0]; + } + const auto pc = pieces([&](double u) { + RadMtpTravOpt q; + q.accept_at = 3; q.u_final = u; + RadMtpTravOut po; + rad_mtp_trav_walk(T, 0, 1, 1, &po, q); + return (int)po.y; + }); + for (const auto& x : pc) { CHECK(x.first >= 0 && x.first < NV); got[(size_t)x.first] += x.second; } + double worst = 0, off_mass = 0; + int support = 0; + for (int y = 0; y < NV; ++y) { + worst = std::max(worst, std::fabs(got[(size_t)y] - want[(size_t)y])); + support += want[(size_t)y] > 0; + } + off_mass = woff / tot; + std::printf(" wide final draw %d: %d live slots, %d tokens with mass, off-support share %.3f, %zu pieces, worst |dp| = %.2e\n", + rep, live, support, off_mass, pc.size(), worst); + CHECK(worst < 1e-10); + CHECK(pc.size() > 300); + mixed += off_mass > 0.01 && off_mass < 0.99; + } + CHECK(mixed >= 2); +} + +/* (4) RheoSampling siblings through the walk: the real propose row drafts the root's siblings, the + * walk tries the tail child first and the deterministic ones as point masses. Exact; the same trees + * walked as Gumbel ones (what a walk that ignores the scheme does) are not. */ +TEST(traversal_verification_of_rheo_siblings_is_exact) { + const int trials = 200000; + double worst_bad = 0; + for (int m = 1; m <= 2; ++m) { + g_scheme = m + 1; + const Result r = run_trav(STAGE1, trials, 1.0, RadMtpTravOpt{}); + const double z4 = run_trav4(STAGE1, trials, 1.0); + const Result row = run_kind(STAGE1, trials, 1.0); + RadMtpTravOpt bad; + bad.ctl = 4; + const Result b = run_trav(STAGE1, trials, 1.0, bad); + g_scheme = 0; + std::printf(" trav rheo m=%d z=%.2f first=%.2f z4=%.2f acc=%.3f (rowwise %.3f) | walked as gumbel: z=%.1f first=%.1f\n", + m, r.z, r.first_z, z4, r.mean_acc, row.mean_acc, b.z, b.first_z); + CHECK(r.z < 4.5); CHECK(r.first_z < 4.5); CHECK(z4 < 4.5); + worst_bad = std::max(worst_bad, std::max(b.z, b.first_z)); + } + CHECK(worst_bad > 20.0); +} + +RAD_TEST_MAIN() diff --git a/tests/sample_test.cpp b/tests/sample_test.cpp index 1f2d10cf..e52ce7d9 100644 --- a/tests/sample_test.cpp +++ b/tests/sample_test.cpp @@ -1528,7 +1528,7 @@ struct HostChain { HostChain(int64_t n_vocab, int64_t max_seqs, int max_spec, const VocabView* vocab = nullptr, int64_t max_candidates = 8, const char* second_plugin = nullptr, - bool draft_coupling = false) + bool draft_coupling = false, bool verify_block = false, bool verify_traversal = false) : nv(n_vocab) { /* libref alone: it is the implementation under test, and a directory scan would also * pick up whatever else was built beside it. */ @@ -1571,6 +1571,8 @@ struct HostChain { cfg.max_hist = 64; cfg.max_candidates = max_candidates; cfg.draft_coupling = draft_coupling; + cfg.draft_verify_block = verify_block; + cfg.draft_verify_traversal = verify_traversal; if (s.declare(&b, cfg) < 0) return; if (b.finish() < 0) return; prog = std::move(b.program()); @@ -3597,6 +3599,101 @@ TEST(the_coupled_evidence_survives_the_drafters_greedy_build) { CHECK_EQ(ev.rows, (int64_t)6); } +/* --draft-verify block: the chain rows bound from round 1 on, consecutively, carry the block's + * length in `blk` (what the verify's round-1 row decides from); the bonus row and a row after a + * gap do not, and without the flag nothing is marked. */ +TEST(block_verification_marks_the_consecutive_bound_rows_of_a_chain) { + HostChain ch(64, 2, 3, nullptr, 8, "spechub.so", true, true); + if (!ch.ok) { + fprintf(stderr, " SKIP %s: libref/spechub did not load from %s/kernels\n", + ::radtest::current(), home().c_str()); + return; + } + SamplingParams sp; + sp.temp = 1.0f; + const int32_t draft[3] = { 21, 22, 23 }; + Request r = make_req(7, { 1, 2, 3 }, sp); + r.draft = draft; + r.n_draft = 3; + std::string err; + CHECK_OK(ch.s.begin_request(r.id, r.sp, &err)); + const uint64_t n_out = r.output.size(); + RadMtpCoupleState bound[3]; + couple_states(r.id, r.sp.seed, draft, 3, rad_mtp_couple_verify_pos(n_out, 1), bound); + CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3)); + std::vector reqs = { &r }; + CHECK_OK(ch.s.build_step(reqs)); + for (int k = 0; k < 3; ++k) CHECK_EQ(ch.s.staged_couple(k).blk, 3); + CHECK_EQ(ch.s.staged_couple(3).blk, 0); + + /* row 1 stale: the block is row 0 alone; row 2 is bound but past the gap, so token-wise */ + bound[1].pos += 1; + CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3)); + CHECK_OK(ch.s.build_step(reqs)); + CHECK_EQ(ch.s.staged_couple(0).blk, 1); + CHECK_EQ(ch.s.staged_couple(1).round, 0); + CHECK_EQ(ch.s.staged_couple(2).round, 3); + CHECK_EQ(ch.s.staged_couple(2).blk, 0); + + /* the same chain without the flag is not marked */ + HostChain plain(64, 2, 3, nullptr, 8, "spechub.so", true, false); + CHECK(plain.ok); + CHECK_OK(plain.s.begin_request(r.id, r.sp, &err)); + couple_states(r.id, r.sp.seed, draft, 3, rad_mtp_couple_verify_pos(n_out, 1), bound); + CHECK_OK(plain.s.set_mtp_couple(r.id, bound, 3)); + CHECK_OK(plain.s.build_step(reqs)); + for (int k = 0; k < 3; ++k) CHECK_EQ(plain.s.staged_couple(k).blk, 0); +} + +/* TRAVERSAL VERIFICATION THROUGH THE SAMPLER (--draft-verify traversal, abi/rad_mtp_traversal.h). + * + * The chain 21, 22, 23 with a point-mass draft law at every round. The sampler stages the per-row + * topology plane (parent row, draft token) and issues `mtp_trav_verify` instead of the row-wise + * verify. With the target peaked on 31 at every row the walk rejects the chain (the first draft's + * ratio is ~e^-20) and the root row's token comes from the residual law, 31; with the target + * peaked on each draft the walk accepts the whole chain and the final token is the bonus row's + * own pick. */ +TEST(traversal_verification_walks_the_staged_chain_through_the_sampler) { + HostChain ch(64, 2, 3, nullptr, 8, "spechub.so", true, false, true); + if (!ch.ok) { + fprintf(stderr, " SKIP %s: libref/spechub did not load from %s/kernels\n", + ::radtest::current(), home().c_str()); + return; + } + CHECK(ch.s.staged_couple_op() != RAD_NULL_HANDLE); + SamplingParams sp; + sp.temp = 1.0f; + const int32_t draft[3] = { 21, 22, 23 }; + Request r = make_req(7, { 1, 2, 3 }, sp); + r.draft = draft; + r.n_draft = 3; + std::string err; + CHECK_OK(ch.s.begin_request(r.id, r.sp, &err)); + const uint64_t n_out = r.output.size(); + RadMtpCoupleState bound[3]; + couple_states(r.id, r.sp.seed, draft, 3, rad_mtp_couple_verify_pos(n_out, 1), bound); + CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3)); + + std::vector lg(4 * 64, 0.0f); + for (int row = 0; row < 4; ++row) lg[(size_t)row * 64 + 31] = 20.0f; + std::vector tok; + CHECK_OK(ch.step({ &r }, lg, &tok)); + REQUIRE_EQ(tok.size(), (size_t)4); + CHECK_EQ(tok[0], 31); /* the chain is rejected at its first draft: the residual's token */ + + CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3)); + std::vector lg2(4 * 64, 0.0f); + lg2[0 * 64 + 21] = 20.0f; + lg2[1 * 64 + 22] = 20.0f; + lg2[2 * 64 + 23] = 20.0f; + lg2[3 * 64 + 9] = 20.0f; + CHECK_OK(ch.step({ &r }, lg2, &tok)); + CHECK_EQ(tok[0], 21); + CHECK_EQ(tok[1], 22); + CHECK_EQ(tok[2], 23); + CHECK_EQ(tok[3], 9); +} + /* The planes are sized for the rows a step can sample: one per token the step carries, so never * more than max_tok, and never fewer than max_seqs (a drafter's greedy pass). */ TEST(the_sampler_rows_are_bounded_by_the_steps_tokens) { diff --git a/tests/spechub_couple_test.cpp b/tests/spechub_couple_test.cpp index d6db8cfc..dbda541a 100644 --- a/tests/spechub_couple_test.cpp +++ b/tests/spechub_couple_test.cpp @@ -276,9 +276,9 @@ TEST(the_coupling_uniform_is_the_specified_53_bit_draw) { * shift every later operand of a plane the host writes and the device reads. */ TEST(the_coupling_wire_rows_keep_their_layout) { CHECK_EQ(sizeof(RadMtpCoupleDraw), (size_t)32); - CHECK_EQ(sizeof(RadMtpCoupleState), (size_t)152); + CHECK_EQ(sizeof(RadMtpCoupleState), (size_t)168); CHECK_EQ(RAD_MTP_COUPLE_DRAW_WORDS, (size_t)8); - CHECK_EQ(RAD_MTP_COUPLE_STATE_WORDS, (size_t)38); + CHECK_EQ(RAD_MTP_COUPLE_STATE_WORDS, (size_t)42); CHECK_EQ(offsetof(RadMtpCoupleState, q) % 8, (size_t)0); } diff --git a/tests/spechub_device_test.cpp b/tests/spechub_device_test.cpp new file mode 100644 index 00000000..e4daa7f4 --- /dev/null +++ b/tests/spechub_device_test.cpp @@ -0,0 +1,879 @@ +/* tests/spechub_device_test.cpp -- the spechub plugin's DEVICE verify rows against their host rows, + * on a card. + * + * mtp_couple_verify rows whose state drafted 1..4 children (the chain's maximal coupling for one + * child, recursive rejection sampling for several, abi/rad_mtp_rrs.h), and + * --draft-verify block's chains of 1..8 rows (abi/rad_mtp_block.h) + * mtp_trav_verify --draft-verify traversal, abi/rad_mtp_traversal.h: requests of 1..21 rows + * + * The device rows and the host rows run the same shared header code, so the outputs must agree + * token for token. The traversal walk and the block decision are also compared bit for bit in + * what they write. Skipped without a card (the host backend), or without the device rows in the + * plugin. Two tests read the plugin's code object (no card needed): the verify kernels' private + * segment, since the queue sizes its scratch by it. Run on a card under the shared lock: + * flock gpu.lock build/tests/spechub_device_test + */ +#include "rad_test.h" +#include "device/aql.h" + +#include "rad_abi.h" +#include "rad_device.h" +#include "rad_mtp_rrs.h" +#include "rad_mtp_traversal.h" +#include "rad_sample.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef RAD_SPECHUB_LIB +#define RAD_SPECHUB_LIB "" +#endif + +namespace { + +struct Plugin { + void* handle = nullptr; + int (*count)() = nullptr; + const RadKernelInfo* (*at)(int) = nullptr; + bool open(const char* path) { + if (const char* o = std::getenv("RAD_SPECHUB_LIB_OVERRIDE")) path = o; /* a baseline build, for RAD_BENCH */ + handle = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (!handle) return false; + count = (int (*)())dlsym(handle, "rad_kernel_count"); + at = (const RadKernelInfo* (*)(int))dlsym(handle, "rad_kernel_at"); + return count && at; + } + const RadKernelInfo* row(const char* name) const { + for (int i = 0; i < count(); ++i) { + const RadKernelInfo* r = at(i); + if (r && r->name && std::string(r->name) == name) return r; + } + return nullptr; + } + ~Plugin() { if (handle) dlclose(handle); } +}; + +/* A tensor over a host buffer or its device twin. */ +struct Buf { + std::vector host; + void* dev = nullptr; + RadTensor t{}; + Buf(uint32_t dtype, std::vector shape, size_t elem) { + t.dtype = dtype; + t.rank = (uint32_t)shape.size(); + int64_t n = 1; + for (size_t i = 0; i < shape.size(); ++i) { t.shape[i] = shape[i]; n *= shape[i]; } + int64_t acc = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { t.stride[i] = acc; acc *= shape[i]; } + host.assign((size_t)n * elem + 16, 0); + } + ~Buf() { if (dev) rad_dev_free(dev, RAD_MEM_DEVICE); } + RadTensor on_host() { RadTensor x = t; x.data = host.data(); return x; } + RadTensor on_dev(RadStream s) { + if (!dev) dev = rad_dev_alloc((int64_t)host.size(), RAD_MEM_DEVICE); + rad_memcpy_async(dev, host.data(), (int64_t)host.size(), s); + RadTensor x = t; x.data = dev; return x; + } + void fetch(RadStream s) { rad_memcpy_async(host.data(), dev, (int64_t)host.size(), s); } +}; + +RadParam P(const char* k, long long v) { return RAD_INT(k, v); } + +uint32_t g_seed = 424242; +uint32_t rnd() { g_seed = g_seed * 1664525u + 1013904223u; return (g_seed >> 8) & 0xffffff; } + +RadMtpCoupleDraw make_draw(uint64_t seed, uint64_t base, uint64_t seq, int card, uint32_t mode) { + RadMtpCoupleDraw d{}; + d.seed = seed; d.base = base; d.seq = seq; d.card = card; d.mode = mode; + return d; +} + +} /* namespace */ + +/* The queue's scratch is sized by a kernel's private segment times every lane it may run: couple_verify + * once carried the block row's planes (17.8 KB a lane, with a workgroup of 128 lanes of which one + * works) and the first sampled tree (>= 5 rows) faulted the queue with OUT_OF_RESOURCES once + * HSA_NO_SCRATCH_RECLAIM kept the scratch resident. Pin the code object: the workgroup kernel keeps + * a small private segment (the serial helper that needs the big one is a kernel of its own). Runs + * without a card: it reads the plugin's own code object. */ +TEST(the_verify_kernels_ask_for_little_scratch) { + FILE* f = std::fopen(RAD_SPECHUB_LIB, "rb"); + if (!f) { fprintf(stderr, " SKIP: %s not readable\n", RAD_SPECHUB_LIB); return; } + std::vector img; + unsigned char buf[65536]; + for (size_t n; (n = std::fread(buf, 1, sizeof buf, f)) > 0;) img.insert(img.end(), buf, buf + n); + std::fclose(f); + static const char kMagic[] = "__CLANG_OFFLOAD_BUNDLE__"; + auto at = std::search(img.begin(), img.end(), kMagic, kMagic + sizeof kMagic - 1); + if (at == img.end()) { fprintf(stderr, " SKIP: no device code in the plugin\n"); return; } + const void* co = nullptr; + size_t cosz = 0; + std::string why; + REQUIRE(rad::aql::bundle_code_object(&*at, { "hipv4-amdgcn-amd-amdhsa--gfx1201", "hip-amdgcn-amd-amdhsa--gfx1201", + "amdgcn-amd-amdhsa--gfx1201" }, &co, &cosz, &why)); + std::vector ks; + REQUIRE(rad::aql::code_object_kernels(co, cosz, &ks, &why)); + int seen = 0, seen_trav = 0; + for (const auto& k : ks) { + if (k.symbol.find("trav_verify") != std::string::npos) { + /* the traversal verify keeps a request in registers and LDS: no scratch at all, so its + * dispatch never waits for the queue's scratch */ + ++seen_trav; + CHECK_EQ((unsigned)k.private_size, 0u); + fprintf(stderr, " trav_verify private segment %u bytes\n", (unsigned)k.private_size); + continue; + } + if (k.symbol.find("couple_verify") == std::string::npos || k.symbol.find("wide") != std::string::npos) + continue; + ++seen; + CHECK(k.private_size <= 256u); + fprintf(stderr, " couple_verify private segment %u bytes\n", (unsigned)k.private_size); + } + CHECK_EQ(seen, 1); + CHECK_EQ(seen_trav, 1); +} + +TEST(the_device_verify_row_agrees_with_the_host_row) { + RadDeviceProps dp{}; + if (rad_dev_count() < 1 || rad_dev_props(0, &dp) != RAD_OK || dp.is_host_backend) { + fprintf(stderr, " SKIP %s: no card\n", ::radtest::current()); + return; + } + Plugin pl; + if (!pl.open(RAD_SPECHUB_LIB)) { fprintf(stderr, " SKIP: %s did not load\n", RAD_SPECHUB_LIB); return; } + const RadKernelInfo* dver = pl.row("spechub_mtp_couple_verify"); + const RadKernelInfo* hver = pl.row("ref_mtp_couple_verify"); + if (!dver) { fprintf(stderr, " SKIP: the plugin has no device rows\n"); return; } + REQUIRE(hver); + RadStream s{}; + REQUIRE_EQ(rad_stream_create(&s, 0), RAD_OK); + const int SW = (int)RAD_MTP_COUPLE_STATE_WORDS; + const int64_t VOC = 50000; + + /* ---- verify over states with 1..4 children, at a 24-slot plane and at the sampler's full 1024-slot + * plane (top_k 0: every slot live on even rows, 40 live slots and holes on odd rows) -- the + * workgroup's compaction and weights over several chunks, then the host's decision over them */ + for (const int NC : { 24, 1024, 1100 }) { + const int M = 64; + const bool wide = NC > 64; /* 1100: past the workgroup's plane, one lane decides */ + Buf cid(RAD_I32, { M, NC }, 4), cval(RAD_F32, { M, NC }, 4), prm(RAD_U32, { M, 24 }, 4); + Buf sts(RAD_U32, { M, SW }, 4), tok(RAD_I32, { M }, 4); + int32_t* pi = (int32_t*)cid.host.data(); + float* pv = (float*)cval.host.data(); + RadSampleParams* pp = (RadSampleParams*)prm.host.data(); + RadMtpCoupleState* ps_ = (RadMtpCoupleState*)sts.host.data(); + int32_t* pt = (int32_t*)tok.host.data(); + for (int m = 0; m < M; ++m) { + const int live = !wide || m % 2 == 0 ? NC : 40; + for (int c = 0; c < NC; ++c) { + if (c >= live) { pi[m * NC + c] = -1; pv[m * NC + c] = -INFINITY; continue; } + int id; + bool dup; + do { + id = (int)(rnd() % (wide ? VOC : 40)); + dup = false; + for (int q = 0; q < c; ++q) dup = dup || pi[m * NC + q] == id; + } while (dup); + pi[m * NC + c] = id; + pv[m * NC + c] = 2.0f - (wide ? 0.01f : 0.25f) * c - (rnd() % 100) * 0.01f; + } + int32_t qid[8]; + float qv[8]; + for (int c = 0; c < 8; ++c) { + /* Q's support among the candidates (wide) or the 40-token universe */ + qid[c] = wide ? pi[m * NC + (int)(rnd() % (uint32_t)(live < 60 ? live : 60))] : (int)(rnd() % 40); + qv[c] = 2.0f - 0.3f * c; + } + for (int c = 0; c < 8; ++c) + for (int q = 0; q < c; ++q) if (qid[q] == qid[c]) qid[c] = 100 + c; + RadMtpCoupleState s0{}; + rad_mtp_couple_build_q(qid, qv, VOC, &s0); + s0.draw = make_draw(0x900ull + (uint64_t)m, 3, 1, 0, 1u); + s0.status = 1; s0.round = 1; s0.pos = 11 + (uint64_t)m; + const int nk = 1 + m % 4; + if (nk >= 2) rad_mtp_rrs_draw(&s0, 0, nk); else s0.x = s0.ids[0]; + ps_[m] = s0; + pp[m].seed = s0.draw.seed; + pp[m].pos = s0.pos; + pp[m].flags = m % 16 == 15 ? RAD_SP_GREEDY : 0; + pt[m] = -9; + } + const std::vector pr = { P("M", M), P("n_cand", NC), P("n_vocab", (int)VOC) }; + Buf htok = tok, hst2 = sts; + { + RadTensor ts[5] = { cid.on_host(), cval.on_host(), prm.on_host(), hst2.on_host(), htok.on_host() }; + RadArgs a{}; a.t = ts; a.n_t = 5; a.p = pr.data(); a.n_p = (int)pr.size(); + REQUIRE_EQ(hver->launch(&a, s), RAD_OK); + } + { + RadTensor ts[5] = { cid.on_dev(s), cval.on_dev(s), prm.on_dev(s), sts.on_dev(s), tok.on_dev(s) }; + RadArgs a{}; a.t = ts; a.n_t = 5; a.p = pr.data(); a.n_p = (int)pr.size(); + REQUIRE_EQ(dver->launch(&a, s), RAD_OK); + tok.fetch(s); + sts.fetch(s); + REQUIRE_EQ(rad_stream_sync(s), RAD_OK); + } + int multi = 0, kept = 0; + for (int m = 0; m < M; ++m) { + const int32_t g = ((int32_t*)tok.host.data())[m], w = ((int32_t*)htok.host.data())[m]; + CHECK_EQ(g, w); + /* the verify leaves the state plane alone */ + RadMtpCoupleState dg, hw; + std::memcpy(&dg, sts.host.data() + (size_t)m * SW * 4, sizeof dg); + std::memcpy(&hw, hst2.host.data() + (size_t)m * SW * 4, sizeof hw); + CHECK(std::memcmp(&dg, &hw, sizeof dg) == 0); + multi += ps_[m].nkids >= 2 && w != -9; + kept += w == -9; + } + CHECK(multi >= 20); + CHECK_EQ(kept, 4); /* the greedy rows keep the ordinary token */ + } + rad_stream_destroy(s); +} + +/* --draft-verify block (abi/rad_mtp_block.h): the device verify row decides a whole chain from its + * round-1 row and writes the tokens of rows 0 .. tau; the host row is the same shared code over the + * dense plane. Blocks of 1..8 rows, planes of 24 (the common case), 1000 (live slots compacted over + * several chunks of the workgroup) and 1100 (past the LDS plane: one thread runs the helper) slots, + * with holes; tokens must agree row for row, rows the block does not decide keep their sentinel. */ +TEST(the_device_block_verify_agrees_with_the_host_row) { + RadDeviceProps dp{}; + if (rad_dev_count() < 1 || rad_dev_props(0, &dp) != RAD_OK || dp.is_host_backend) { + fprintf(stderr, " SKIP %s: no card\n", ::radtest::current()); + return; + } + Plugin pl; + if (!pl.open(RAD_SPECHUB_LIB)) { fprintf(stderr, " SKIP: %s did not load\n", RAD_SPECHUB_LIB); return; } + const RadKernelInfo* dver = pl.row("spechub_mtp_couple_verify"); + const RadKernelInfo* hver = pl.row("ref_mtp_couple_verify"); + if (!dver) { fprintf(stderr, " SKIP: the plugin has no device rows\n"); return; } + REQUIRE(hver); + RadStream s{}; + REQUIRE_EQ(rad_stream_create(&s, 0), RAD_OK); + const int SW = (int)RAD_MTP_COUPLE_STATE_WORDS; + const int64_t VOC = 50000; + int shortened = 0, whole = 0, writes = 0; + for (int NC : { 24, 1000, 1100, 1001 }) { /* 1001: wide, 300..500 live slots a row */ + const bool wide = NC == 1001; + const int NSEQ = 40, MAXROWS = 9; + const int M = NSEQ * MAXROWS; + Buf cid(RAD_I32, { M, NC }, 4), cval(RAD_F32, { M, NC }, 4), prm(RAD_U32, { M, 24 }, 4); + Buf sts(RAD_U32, { M, SW }, 4), tok(RAD_I32, { M }, 4); + int32_t* pi = (int32_t*)cid.host.data(); + float* pv = (float*)cval.host.data(); + RadSampleParams* pp = (RadSampleParams*)prm.host.data(); + RadMtpCoupleState* ps_ = (RadMtpCoupleState*)sts.host.data(); + int32_t* pt = (int32_t*)tok.host.data(); + for (int m = 0; m < M; ++m) { pt[m] = -9; for (int c = 0; c < NC; ++c) { pi[m * NC + c] = -1; pv[m * NC + c] = -INFINITY; } } + int row = 0; + for (int q = 0; q < NSEQ; ++q) { + const int g = 1 + q % 8; + const uint64_t seed = 0xb10c0000ull + (uint64_t)q, pos0 = 20 + 3 * (uint64_t)q; + for (int i = 0; i <= g; ++i, ++row) { + /* live candidates at random slots */ + const int nlive = wide ? 300 + (int)(rnd() % 200) : 6 + (int)(rnd() % 19); + int ids[512]; + for (int c = 0; c < nlive; ++c) { + bool dup; + do { + ids[c] = (int)(rnd() % (wide ? 20000u : 40u)); + dup = false; + for (int k = 0; k < c; ++k) dup = dup || ids[k] == ids[c]; + } while (dup); + int slot; + do { slot = (int)(rnd() % NC); } while (pi[row * NC + slot] >= 0); + pi[row * NC + slot] = ids[c]; + pv[row * NC + slot] = wide ? 3.0f - 0.02f * c - (rnd() % 100) * 0.01f : 3.0f - 0.35f * c - (rnd() % 100) * 0.01f; + } + pp[row].seed = seed; + pp[row].pos = pos0 + (uint64_t)i; + if (i == g) continue; + int32_t qid[8]; + float qv[8]; + const int nq = 3 + (int)(rnd() % 6); + for (int c = 0; c < 8; ++c) { + qid[c] = c < nq ? (c < nlive && rnd() % 4 ? ids[c] : (int)(rnd() % 40)) : -1; + qv[c] = c < nq ? 2.5f - 0.4f * c - (rnd() % 100) * 0.01f : -INFINITY; + for (int k = 0; k < c; ++k) if (qid[c] >= 0 && qid[k] == qid[c]) qid[c] = 100 + c; + } + RadMtpCoupleState st{}; + REQUIRE(rad_mtp_couple_build_q(qid, qv, VOC, &st)); + st.draw = make_draw(seed, pos0, 7 + (uint64_t)q, 0, 1u); + st.status = 1; st.round = i + 1; st.pos = pos0 + (uint64_t)i; st.blk = g; + st.x = st.ids[rnd() % (uint32_t)st.count]; + ps_[row] = st; + } + } + const std::vector pr = { P("M", M), P("n_cand", NC), P("n_vocab", (int)VOC) }; + Buf htok = tok; + { + RadTensor ts[5] = { cid.on_host(), cval.on_host(), prm.on_host(), sts.on_host(), htok.on_host() }; + RadArgs a{}; a.t = ts; a.n_t = 5; a.p = pr.data(); a.n_p = (int)pr.size(); + REQUIRE_EQ(hver->launch(&a, s), RAD_OK); + } + { + RadTensor ts[5] = { cid.on_dev(s), cval.on_dev(s), prm.on_dev(s), sts.on_dev(s), tok.on_dev(s) }; + RadArgs a{}; a.t = ts; a.n_t = 5; a.p = pr.data(); a.n_p = (int)pr.size(); + REQUIRE_EQ(dver->launch(&a, s), RAD_OK); + tok.fetch(s); + REQUIRE_EQ(rad_stream_sync(s), RAD_OK); + } + row = 0; + for (int q = 0; q < NSEQ; ++q) { + const int g = 1 + q % 8; + int written = 0; + for (int i = 0; i <= g; ++i) { + const int32_t gv = ((int32_t*)tok.host.data())[row + i], wv = ((int32_t*)htok.host.data())[row + i]; + CHECK_EQ(gv, wv); + written += wv != -9; + } + writes += written > 0; + whole += written == g; /* tau == g: every draft written, the bonus row alone untouched */ + shortened += written > 0 && written < g; + row += g + 1; + } + } + CHECK(writes >= 100); + CHECK(shortened >= 10); + CHECK(whole >= 10); + rad_stream_destroy(s); +} + +/* Traversal verification (abi/rad_mtp_traversal.h): the device row against the host row, over + * requests whose rows form a small tree (a root with two children, one of them with two, and a + * chain below the other). The device prepares the tree with a workgroup (integer masses, whose sums + * do not depend on the order) and runs the header's walk over it, so the tokens must be identical; + * planes of 12, 1024 and 1100 slots. */ +TEST(the_device_traversal_verify_agrees_with_the_host_row) { + RadDeviceProps dp{}; + if (rad_dev_count() < 1 || rad_dev_props(0, &dp) != RAD_OK || dp.is_host_backend) { + fprintf(stderr, " SKIP %s: no card\n", ::radtest::current()); + return; + } + Plugin pl; + if (!pl.open(RAD_SPECHUB_LIB)) { fprintf(stderr, " SKIP: %s did not load\n", RAD_SPECHUB_LIB); return; } + const RadKernelInfo* dtr = pl.row("spechub_mtp_trav_verify"); + const RadKernelInfo* htr = pl.row("ref_mtp_trav_verify"); + if (!dtr) { fprintf(stderr, " SKIP: the plugin has no traversal device row\n"); return; } + REQUIRE(htr); + RadStream s{}; + REQUIRE_EQ(rad_stream_create(&s, 0), RAD_OK); + const int SW = (int)RAD_MTP_COUPLE_STATE_WORDS; + const int64_t VOC = 50000; + for (const int NC : { 12, 1024, 1100 }) { + const bool wide = NC > 64; + const int RQ = 12, NR = 7, M = RQ * NR; + const int par[NR] = { -1, 0, 0, 1, 1, 2, 5 }; + const int nkid[NR] = { 2, 2, 1, 0, 0, 1, 0 }; + Buf cid(RAD_I32, { M, NC }, 4), cval(RAD_F32, { M, NC }, 4), prm(RAD_U32, { M, 24 }, 4); + Buf sts(RAD_U32, { M, SW }, 4), tok(RAD_I32, { M }, 4), topo(RAD_I32, { M, 2 }, 4); + int32_t* pi = (int32_t*)cid.host.data(); + float* pv = (float*)cval.host.data(); + RadSampleParams* pp = (RadSampleParams*)prm.host.data(); + RadMtpCoupleState* ps_ = (RadMtpCoupleState*)sts.host.data(); + int32_t* pt = (int32_t*)tok.host.data(); + int32_t* ptopo = (int32_t*)topo.host.data(); + for (int q = 0; q < RQ; ++q) { + const uint64_t seed = 0x700ull + (uint64_t)q, p0 = 20 + (uint64_t)q; + int depth[NR] = {}; + int32_t childtok[NR][4] = {}; + for (int n = 0; n < NR; ++n) { + const int m = q * NR + n; + depth[n] = n ? depth[par[n]] + 1 : 0; + /* wide: the sampler's full plane at top_k 0 on even requests, 40 live slots and holes on odd */ + const int live = !wide || q % 2 == 0 ? NC : 40; + for (int c = 0; c < NC; ++c) { + if (wide && c >= live) { pi[m * NC + c] = -1; pv[m * NC + c] = -INFINITY; continue; } + int id; + bool dup; + do { + id = (int)(rnd() % (wide ? VOC : 14)); + dup = false; + for (int z = 0; z < c; ++z) dup = dup || pi[m * NC + z] == id; + } while (dup); + pi[m * NC + c] = id; + pv[m * NC + c] = wide ? 2.0f - 0.01f * c - (rnd() % 100) * 0.01f + : (c < 10 ? 2.0f - 0.25f * c : -INFINITY) - (rnd() % 100) * 0.01f; + } + int32_t qid[8]; + float qv[8]; + for (int c = 0; c < 8; ++c) { + qid[c] = wide ? pi[m * NC + (int)(rnd() % (uint32_t)(live < 60 ? live : 60))] : (int)(rnd() % 14); + qv[c] = 2.0f - 0.3f * c - (rnd() % 50) * 0.01f; + } + for (int c = 0; c < 8; ++c) + for (int z = 0; z < c; ++z) if (qid[z] == qid[c]) qid[c] = 100 + c; + RadMtpCoupleState s0{}; + rad_mtp_couple_build_q(qid, qv, VOC, &s0); + s0.draw = make_draw(seed, 3, 1, 0, 1u); + s0.status = 1; s0.round = depth[n] + 1; s0.pos = p0 + (uint64_t)depth[n]; + if (nkid[n] >= 2) rad_mtp_rrs_draw(&s0, (uint64_t)n, nkid[n]); + else { s0.x = s0.ids[0]; s0.nkids = 0; } + for (int c = 0; c < nkid[n]; ++c) childtok[n][c] = s0.ids[c]; + if (nkid[n] > 0) ps_[m] = s0; else ps_[m].status = 0; + pp[m].seed = seed; + pp[m].pos = p0 + (uint64_t)depth[n]; + pp[m].flags = q == 5 ? RAD_SP_GREEDY : 0; /* one request is greedy: untouched */ + pt[m] = -9; + } + int seen[NR] = {}; + for (int n = 0; n < NR; ++n) { + const int m = q * NR + n; + ptopo[2 * m] = n ? q * NR + par[n] : -1; + ptopo[2 * m + 1] = n ? childtok[par[n]][seen[par[n]]++] : 0; + } + } + const std::vector pr = { P("M", M), P("n_cand", NC), P("n_vocab", (int)VOC) }; + Buf htok = tok; + { + RadTensor ts[6] = { cid.on_host(), cval.on_host(), prm.on_host(), sts.on_host(), htok.on_host(), + topo.on_host() }; + RadArgs a{}; a.t = ts; a.n_t = 6; a.p = pr.data(); a.n_p = (int)pr.size(); + REQUIRE_EQ(htr->launch(&a, s), RAD_OK); + } + { + RadTensor ts[6] = { cid.on_dev(s), cval.on_dev(s), prm.on_dev(s), sts.on_dev(s), tok.on_dev(s), + topo.on_dev(s) }; + RadArgs a{}; a.t = ts; a.n_t = 6; a.p = pr.data(); a.n_p = (int)pr.size(); + REQUIRE_EQ(dtr->launch(&a, s), RAD_OK); + tok.fetch(s); + REQUIRE_EQ(rad_stream_sync(s), RAD_OK); + } + int written = 0, greedy_kept = 0; + for (int m = 0; m < M; ++m) { + const int32_t g = ((int32_t*)tok.host.data())[m], w = ((int32_t*)htok.host.data())[m]; + CHECK_EQ(g, w); + written += w != -9; + if (m / NR == 5) greedy_kept += w == -9; + } + CHECK(written >= RQ); + CHECK_EQ(greedy_kept, NR); + } + rad_stream_destroy(s); +} + +/* The traversal verify over what a step can stage, device against host, bit for bit: requests of 1, + * 4, 11 and 21 rows in one launch (a workgroup's four waves each take every fourth row; a lone bonus + * row; a tree wider than a wave's share), Gumbel and RheoSampling nodes, chain rows whose x is not + * the shortlist's first id, greedy and stale rows, targets that + * lack draft tokens, and planes of 24, 1024 (the sampler's), 2048 (two passes a lane), 1100 and 4100 + * slots (no whole chunks; the fixed-point unit one bit coarser) with holes and -inf entries. */ +TEST(the_device_traversal_verify_agrees_with_the_host_row_on_mixed_requests) { + RadDeviceProps dp{}; + if (rad_dev_count() < 1 || rad_dev_props(0, &dp) != RAD_OK || dp.is_host_backend) { + fprintf(stderr, " SKIP %s: no card\n", ::radtest::current()); + return; + } + Plugin pl; + if (!pl.open(RAD_SPECHUB_LIB)) { fprintf(stderr, " SKIP: %s did not load\n", RAD_SPECHUB_LIB); return; } + const RadKernelInfo* dtr = pl.row("spechub_mtp_trav_verify"); + const RadKernelInfo* htr = pl.row("ref_mtp_trav_verify"); + if (!dtr) { fprintf(stderr, " SKIP: the plugin has no traversal device row\n"); return; } + REQUIRE(htr); + RadStream s{}; + REQUIRE_EQ(rad_stream_create(&s, 0), RAD_OK); + const int SW = (int)RAD_MTP_COUPLE_STATE_WORDS; + const int64_t VOC = 60000; + /* the request shapes: parents by row (root -1) */ + struct Shape { int nr; int par[24]; }; + const Shape shapes[] = { + { 1, { -1 } }, + { 4, { -1, 0, 1, 2 } }, + { 11, { -1, 0, 0, 1, 1, 2, 3, 3, 5, 6, 6 } }, + { 21, { -1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4 } }, + { 7, { -1, 0, 1, 2, 0, 1, 2 } }, + }; + long written = 0, paths3 = 0, finals = 0, rheo_nodes = 0; + for (const int NC : { 24, 1024, 2048, 1100, 4100 }) { + const int REPS = NC > 2048 ? 6 : 24; + int M = 0; + for (int r = 0; r < REPS; ++r) M += shapes[r % 5].nr; + Buf cid(RAD_I32, { M, NC }, 4), cval(RAD_F32, { M, NC }, 4), prm(RAD_U32, { M, 24 }, 4); + Buf sts(RAD_U32, { M, SW }, 4), tok(RAD_I32, { M }, 4), topo(RAD_I32, { M, 2 }, 4); + int32_t* pi = (int32_t*)cid.host.data(); + float* pv = (float*)cval.host.data(); + RadSampleParams* pp = (RadSampleParams*)prm.host.data(); + RadMtpCoupleState* ps_ = (RadMtpCoupleState*)sts.host.data(); + int32_t* pt = (int32_t*)tok.host.data(); + int32_t* ptopo = (int32_t*)topo.host.data(); + int row0 = 0; + for (int r = 0; r < REPS; ++r) { + const Shape& sh = shapes[r % 5]; + const uint64_t seed = 0x51000ull + 977ull * (uint64_t)r + (uint64_t)NC, pos0 = 40 + (uint64_t)r; + const int kind = r % 4; /* 0 close laws, 1 flat Q with a token the target lacks, 2 Q off the target, 3 close */ + const int rheo = r % 6 == 4 ? 2 : r % 6 == 5 ? 3 : 0; /* scheme of the nodes with several children */ + int depth[24] = {}, nkid[24] = {}, seen[24] = {}; + int32_t childtok[24][8] = {}; + for (int n = 1; n < sh.nr; ++n) ++nkid[sh.par[n]]; + for (int n = 0; n < sh.nr; ++n) { + const int m = row0 + n; + depth[n] = n ? depth[sh.par[n]] + 1 : 0; + /* the plane: a peaked head, a long tail, holes and -inf entries at random slots */ + const int live = NC <= 24 ? 14 : (r % 3 == 0 ? 20 : NC - NC / 7); + std::vector ids((size_t)NC, -1); + for (int c = 0; c < NC; ++c) { pi[(size_t)m * NC + c] = -1; pv[(size_t)m * NC + c] = -INFINITY; } + for (int c = 0, placed = 0; c < NC && placed < live; ++c) { + if (NC > 24 && r % 3 != 0 && rnd() % 7 == 0) continue; /* a hole */ + bool dup; + int id; + do { id = (int)(rnd() % (uint32_t)(VOC - 2000)); dup = false; + for (int k = 0; k < c; ++k) dup = dup || ids[(size_t)k] == id; } while (dup); + ids[(size_t)c] = id; + pi[(size_t)m * NC + c] = id; + pv[(size_t)m * NC + c] = rnd() % 23 == 0 ? -INFINITY + : placed < 20 ? 9.0f - 0.8f * (float)placed - (rnd() % 100) * 0.01f + : 1.0f - 0.003f * (float)placed - (rnd() % 100) * 0.01f; + ++placed; + } + pp[m].seed = seed; pp[m].pos = pos0 + (uint64_t)depth[n]; + pp[m].flags = r == 7 ? RAD_SP_GREEDY : 0; + pt[m] = -9; + ps_[m] = RadMtpCoupleState{}; + if (nkid[n] == 0) continue; + int32_t qid[8]; + float qv[8]; + int have = 0; + for (int c = 0; c < NC && have < 8; ++c) + if (ids[(size_t)c] >= 0) qid[have++] = ids[(size_t)c]; + for (int c = have; c < 8; ++c) qid[c] = (int)(VOC - 100 + c); + for (int c = 0; c < 8; ++c) { + if (kind == 2) qid[c] = (int)(VOC - 1000 + 8 * n + c); + qv[c] = (kind == 1 ? 7.0f - 0.4f * c : 8.0f - 0.8f * c) - (rnd() % 100) * 0.01f; + } + if (kind == 1) qid[1 + n % 3] = (int)(VOC - 500 + n); + RadMtpCoupleState st{}; + REQUIRE(rad_mtp_couple_build_q(qid, qv, VOC, &st)); + st.draw = make_draw(seed, pos0, 7 + (uint64_t)r, 0, 1u); + st.status = 1; st.round = depth[n] + 1; st.pos = pos0 + (uint64_t)depth[n]; + if (nkid[n] >= 2 && rheo) { rad_mtp_rrs_draw_rheo(&st, (uint64_t)n, nkid[n], rheo - 1); ++rheo_nodes; } + else if (nkid[n] >= 2) rad_mtp_rrs_draw(&st, (uint64_t)n, nkid[n]); + else { st.x = st.ids[rad_mtp_couple_pick(st, rad_spechub_uniform(seed, pos0, 77 + (uint64_t)n))]; st.nkids = 0; } + const int nk_real = st.nkids >= 1 ? st.nkids : 1; + for (int c = 0; c < nkid[n]; ++c) childtok[n][c] = c < nk_real ? (st.nkids >= 1 ? st.ids[c] : st.x) : (int)(VOC - 50 + c); + if (r == 9 && n == 1) st.pos += 3; /* a stale state: a leaf of the walk */ + ps_[m] = st; + } + for (int n = 0; n < sh.nr; ++n) { + const int m = row0 + n; + ptopo[2 * m] = n ? row0 + sh.par[n] : -1; + ptopo[2 * m + 1] = n ? childtok[sh.par[n]][seen[sh.par[n]]++] : 0; + } + row0 += sh.nr; + } + const std::vector pr = { P("M", M), P("n_cand", NC), P("n_vocab", (int)VOC) }; + Buf htok = tok, hst = sts; + { + RadTensor ts[6] = { cid.on_host(), cval.on_host(), prm.on_host(), hst.on_host(), htok.on_host(), topo.on_host() }; + RadArgs a{}; a.t = ts; a.n_t = 6; a.p = pr.data(); a.n_p = (int)pr.size(); + REQUIRE_EQ(htr->launch(&a, s), RAD_OK); + } + { + RadTensor ts[6] = { cid.on_dev(s), cval.on_dev(s), prm.on_dev(s), sts.on_dev(s), tok.on_dev(s), topo.on_dev(s) }; + RadArgs a{}; a.t = ts; a.n_t = 6; a.p = pr.data(); a.n_p = (int)pr.size(); + REQUIRE_EQ(dtr->launch(&a, s), RAD_OK); + tok.fetch(s); + sts.fetch(s); + REQUIRE_EQ(rad_stream_sync(s), RAD_OK); + } + row0 = 0; + for (int r = 0; r < REPS; ++r) { + const Shape& sh = shapes[r % 5]; + int wr = 0; + for (int n = 0; n < sh.nr; ++n) { + const int m = row0 + n; + const int32_t g = ((int32_t*)tok.host.data())[m], w = ((int32_t*)htok.host.data())[m]; + CHECK_EQ(g, w); + wr += w != -9; + RadMtpCoupleState dg, hw; + std::memcpy(&dg, sts.host.data() + (size_t)m * SW * 4, sizeof dg); + std::memcpy(&hw, hst.host.data() + (size_t)m * SW * 4, sizeof hw); + CHECK(std::memcmp(&dg, &hw, sizeof dg) == 0); /* the walk leaves the plane alone */ + } + if (r == 7) CHECK_EQ(wr, 0); /* the greedy request keeps every pick */ + written += wr; + paths3 += wr >= 3; + finals += wr >= 1; + row0 += sh.nr; + } + } + fprintf(stderr, " mixed requests: %ld tokens written, %ld requests decided, %ld with a path of 2+ drafts, %ld rheo nodes\n", + written, finals, paths3, rheo_nodes); + CHECK(written >= 100); + CHECK(paths3 >= 10); + CHECK(rheo_nodes >= 10); + rad_stream_destroy(s); +} + +/* Microbenchmark of the block verify op (set RAD_BLOCK_BENCH=1; RAD_BENCH_LIB= to time + * another build of the plugin). Wall time per launch over back-to-back launches of one block (g + * drafts plus the bonus row, one sequence as at max-num-seqs 1), minus the same launch over rows the + * op ignores (the launch floor). Planes of 1024 slots with `live` live candidates: 20 (top_k 20) + * or 1024 (top_k 0). Eight different blocks are cycled. */ +TEST(block_verify_microbenchmark) { + if (!getenv("RAD_BLOCK_BENCH")) return; + RadDeviceProps dp{}; + if (rad_dev_count() < 1 || rad_dev_props(0, &dp) != RAD_OK || dp.is_host_backend) return; + Plugin pl; + const char* lib = getenv("RAD_BENCH_LIB") ? getenv("RAD_BENCH_LIB") : RAD_SPECHUB_LIB; + REQUIRE(pl.open(lib)); + const RadKernelInfo* dver = pl.row("spechub_mtp_couple_verify"); + REQUIRE(dver); + RadStream s{}; + REQUIRE_EQ(rad_stream_create(&s, 0), RAD_OK); + const int SW = (int)RAD_MTP_COUPLE_STATE_WORDS; + const int64_t VOC = 150000; + const int NC = 1024, NV = 8; + const int nrep = getenv("RAD_BENCH_REPS") ? atoi(getenv("RAD_BENCH_REPS")) : 400; + const int divide = getenv("RAD_BENCH_DIV") ? atoi(getenv("RAD_BENCH_DIV")) : 1; /* the plugin's in-kernel repeat count */ + for (int live : { 20, 1024 }) for (int g : { 3, 5, 7 }) { + const int M = g + 1; + struct Var { Buf cid, cval, prm, sts, tok; Var(int M, int NC, int SW) : + cid(RAD_I32, { M, NC }, 4), cval(RAD_F32, { M, NC }, 4), prm(RAD_U32, { M, 24 }, 4), + sts(RAD_U32, { M, SW }, 4), tok(RAD_I32, { M }, 4) {} }; + std::vector vars; + for (int v = 0; v < NV; ++v) { + Var* x = new Var(M, NC, SW); + vars.push_back(x); + int32_t* pi = (int32_t*)x->cid.host.data(); + float* pv = (float*)x->cval.host.data(); + RadSampleParams* pp = (RadSampleParams*)x->prm.host.data(); + RadMtpCoupleState* ps_ = (RadMtpCoupleState*)x->sts.host.data(); + for (int m = 0; m < M; ++m) for (int c = 0; c < NC; ++c) { pi[m * NC + c] = -1; pv[m * NC + c] = -INFINITY; } + const uint64_t seed = 0xbe00ull + (uint64_t)v, pos0 = 100; + for (int i = 0; i < M; ++i) { + int ids[1024]; + for (int c = 0; c < live; ++c) { + bool dup; + do { ids[c] = (int)(rnd() % VOC); dup = false; + for (int k = 0; k < c; ++k) dup = dup || ids[k] == ids[c]; } while (dup); + pi[i * NC + c] = ids[c]; + pv[i * NC + c] = 12.0f - 0.9f * (float)c * (20.0f / (float)live) - (rnd() % 100) * 0.01f; + } + pp[i].seed = seed; pp[i].pos = pos0 + (uint64_t)i; + if (i == g) continue; + int32_t qid[8]; float qv[8]; + for (int c = 0; c < 8; ++c) { qid[c] = ids[c]; qv[c] = 11.0f - 0.9f * c - (rnd() % 100) * 0.01f; } + RadMtpCoupleState st{}; + REQUIRE(rad_mtp_couple_build_q(qid, qv, VOC, &st)); + st.draw = make_draw(seed, pos0, 7 + (uint64_t)v, 0, 1u); + st.status = 1; st.round = i + 1; st.pos = pos0 + (uint64_t)i; st.blk = g; + st.x = st.ids[rnd() % 3u]; + ps_[i] = st; + } + } + const std::vector pr = { P("M", M), P("n_cand", NC), P("n_vocab", (int)VOC) }; + std::vector ts[NV]; + std::vector tn[NV]; + for (int v = 0; v < NV; ++v) { + Var* x = vars[(size_t)v]; + ts[v] = { x->cid.on_dev(s), x->cval.on_dev(s), x->prm.on_dev(s), x->sts.on_dev(s), x->tok.on_dev(s) }; + } + /* the floor: the same launch with every state inert (status 0) */ + std::vector inert; + for (int v = 0; v < NV; ++v) { + Var* x = new Var(M, NC, SW); + memcpy(x->cid.host.data(), vars[(size_t)v]->cid.host.data(), x->cid.host.size()); + memcpy(x->cval.host.data(), vars[(size_t)v]->cval.host.data(), x->cval.host.size()); + memcpy(x->prm.host.data(), vars[(size_t)v]->prm.host.data(), x->prm.host.size()); + inert.push_back(x); + tn[v] = { x->cid.on_dev(s), x->cval.on_dev(s), x->prm.on_dev(s), x->sts.on_dev(s), x->tok.on_dev(s) }; + } + auto run = [&](std::vector* t, int reps) { + const auto t0 = std::chrono::steady_clock::now(); + for (int r = 0; r < reps; ++r) { + RadArgs a{}; a.t = t[r % NV].data(); a.n_t = 5; a.p = pr.data(); a.n_p = (int)pr.size(); + if (dver->launch(&a, s) != RAD_OK) return -1.0; + } + rad_stream_sync(s); + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / reps; + }; + run(ts, 50); run(tn, 50); + double best = 1e9, floor_ = 1e9; + for (int rep = 0; rep < 5; ++rep) { best = std::min(best, run(ts, nrep)); floor_ = std::min(floor_, run(tn, nrep)); } + fprintf(stderr, " BENCH live=%4d g=%d block %.1f us/call floor %.1f us net per block decision %.1f us\n", live, g, best, floor_, (best - floor_) / divide); + for (auto* x : vars) delete x; + for (auto* x : inert) delete x; + } + rad_stream_destroy(s); +} + +/* Microbenchmark of the traversal verify op (RAD_TRAV_BENCH=1). One request a launch (max-num-seqs 1): + * a chain of 3 drafts and trees of 4, 6 and 10 nodes, on the sampler's 1024-slot plane with 20 live + * candidates (top_k 20) or all of them (top_k 0); three kinds of data: `acc` (Q close to P: the walk + * accepts its first leaf most of the time), `mix` (a flatter Q with one token the target lacks) and `rej` + * (Q's support is off the target's: every node is visited and rejected, and the final token is an + * off-support draw at the root -- the longest walk a tree has). Eight requests of a kind are cycled. + * + * RAD_BENCH_LIB is the plugin timed; RAD_BENCH_LIB_REP the same sources built with + * -DRAD_TRAV_REPEAT=RAD_BENCH_REP, whose kernel decides the request that many times in one launch: + * (t_rep - t_one) / (REP - 1) is the kernel's time per decision with the launch, the queue and the sync + * taken out (the AQL backend reports no kernel times). Tokens of the timed plugin are checked against + * the host row first. */ +namespace { +struct TravShape { const char* name; int nr; int par[16]; }; +const TravShape kTravShapes[] = { + { "chain3", 4, { -1, 0, 1, 2 } }, + { "tree4", 5, { -1, 0, 1, 2, 0 } }, /* chain 3 + a sibling of its first node */ + { "tree6", 7, { -1, 0, 1, 2, 0, 1, 2 } }, /* chain 3 + a sibling at every depth */ + { "tree10", 11, { -1, 0, 0, 1, 1, 2, 3, 3, 5, 6, 6 } }, /* a width-2 grower's tree */ +}; +struct TravReq { + Buf cid, cval, prm, sts, tok, topo; + TravReq(int M, int NC, int SW) + : cid(RAD_I32, { M, NC }, 4), cval(RAD_F32, { M, NC }, 4), prm(RAD_U32, { M, 24 }, 4), + sts(RAD_U32, { M, SW }, 4), tok(RAD_I32, { M }, 4), topo(RAD_I32, { M, 2 }, 4) {} +}; +/* kind 0 acc, 1 mix, 2 rej, 3 inert (no bound state: the op's early out) */ +void fill_trav_req(TravReq* x, const TravShape& sh, int NC, int live, int kind, uint64_t seed, int64_t VOC, + int deep = -1) { + const int NR = sh.nr; + int32_t* pi = (int32_t*)x->cid.host.data(); + float* pv = (float*)x->cval.host.data(); + RadSampleParams* pp = (RadSampleParams*)x->prm.host.data(); + RadMtpCoupleState* ps_ = (RadMtpCoupleState*)x->sts.host.data(); + int32_t* pt = (int32_t*)x->tok.host.data(); + int32_t* ptopo = (int32_t*)x->topo.host.data(); + int depth[16] = {}, nkid[16] = {}, seen[16] = {}; + int32_t childtok[16][8] = {}; + for (int n = 1; n < NR; ++n) ++nkid[sh.par[n]]; + const uint64_t pos0 = 100; + for (int n = 0; n < NR; ++n) { + depth[n] = n ? depth[sh.par[n]] + 1 : 0; + int ids[1024]; + for (int c = 0; c < NC; ++c) { pi[n * NC + c] = -1; pv[n * NC + c] = -INFINITY; } + for (int c = 0; c < live; ++c) { + bool dup; + do { ids[c] = (int)(rnd() % (uint32_t)(VOC - 1000)); dup = false; + for (int k = 0; k < c; ++k) dup = dup || ids[k] == ids[c]; } while (dup); + pi[n * NC + c] = ids[c]; + /* a peaked head of 20 and, at top_k 0, a long flat tail carrying about 6 % of the mass */ + pv[n * NC + c] = c < 20 ? 12.0f - 0.9f * (float)c - (rnd() % 100) * 0.01f + : 3.0f - 0.004f * (float)(c - 20) - (rnd() % 100) * 0.01f; + /* `deep`: the row's mass in one candidate of pass `deep` (the final draw's scan, by depth); + * RAD_TRAV_BENCH_DEEP=2 gives every other candidate a small mass of its own (2e-9 of it), so + * that no pass of the scan is one of zero masses */ + if (deep >= 0) + pv[n * NC + c] = c == 32 * deep + 5 ? 12.0f : (atoi(getenv("RAD_TRAV_BENCH_DEEP")) == 2 ? -8.0f : -30.0f); + } + pp[n].seed = seed; pp[n].pos = pos0 + (uint64_t)depth[n]; pp[n].flags = 0; + pt[n] = -9; + ps_[n] = RadMtpCoupleState{}; + if (nkid[n] == 0 || kind == 3) continue; + int32_t qid[8]; float qv[8]; + for (int c = 0; c < 8; ++c) { + qid[c] = kind == 2 ? (int)(VOC - 1000 + 8 * n + c) : ids[c]; + qv[c] = kind == 1 ? 11.0f - 0.5f * c - (rnd() % 100) * 0.01f : 11.0f - 0.9f * c - (rnd() % 100) * 0.01f; + } + if (kind == 1) qid[1 + n % 3] = (int)(VOC - 500 + n); /* a draft token the target lacks */ + RadMtpCoupleState st{}; + REQUIRE(rad_mtp_couple_build_q(qid, qv, VOC, &st)); + st.draw = make_draw(seed, pos0, 7, 0, 1u); + st.status = 1; st.round = depth[n] + 1; st.pos = pos0 + (uint64_t)depth[n]; + if (nkid[n] >= 2) rad_mtp_rrs_draw(&st, (uint64_t)n, nkid[n]); + else { st.x = st.ids[rad_mtp_couple_pick(st, rad_spechub_uniform(seed, pos0, 77 + (uint64_t)n))]; st.nkids = 0; } + for (int c = 0; c < nkid[n]; ++c) childtok[n][c] = nkid[n] >= 2 ? st.ids[c] : st.x; + ps_[n] = st; + } + for (int n = 0; n < NR; ++n) { + ptopo[2 * n] = n ? sh.par[n] : -1; + ptopo[2 * n + 1] = n ? childtok[sh.par[n]][seen[sh.par[n]]++] : 0; + } +} +} /* namespace */ + +TEST(trav_verify_microbenchmark) { + if (!getenv("RAD_TRAV_BENCH")) return; + RadDeviceProps dp{}; + if (rad_dev_count() < 1 || rad_dev_props(0, &dp) != RAD_OK || dp.is_host_backend) return; + Plugin pl, plr; + const char* lib = getenv("RAD_BENCH_LIB") ? getenv("RAD_BENCH_LIB") : RAD_SPECHUB_LIB; + REQUIRE(pl.open(lib)); + const RadKernelInfo* dtr = pl.row("spechub_mtp_trav_verify"); + const RadKernelInfo* htr = pl.row("ref_mtp_trav_verify"); + REQUIRE(dtr && htr); + const RadKernelInfo* drep = nullptr; + const int rep = getenv("RAD_BENCH_REP") ? atoi(getenv("RAD_BENCH_REP")) : 0; + if (getenv("RAD_BENCH_LIB_REP") && rep > 1) { + REQUIRE(plr.open(getenv("RAD_BENCH_LIB_REP"))); + drep = plr.row("spechub_mtp_trav_verify"); + REQUIRE(drep); + } + RadStream s{}; + REQUIRE_EQ(rad_stream_create(&s, 0), RAD_OK); + const int SW = (int)RAD_MTP_COUPLE_STATE_WORDS; + const int64_t VOC = 150000; + const int NC = 1024, NV = 8; + const int nrep = getenv("RAD_BENCH_REPS") ? atoi(getenv("RAD_BENCH_REPS")) : 200; + const char* kinds[] = { "acc", "mix", "rej", "inert" }; + /* RAD_TRAV_BENCH_DEEP=1: instead, the chain's final draw off the support with the drawn candidate in + * pass 0, 7, 8, .. 31 of a 1024-slot plane: what the scan for it costs by depth. */ + const bool deep_series = getenv("RAD_TRAV_BENCH_DEEP") != nullptr; + const int deeps[] = { 0, 3, 7, 8, 15, 16, 23, 24, 31 }; + for (int live : { 20, 1024 }) for (const TravShape& sh : kTravShapes) for (int kind = 0; kind < 4; ++kind) + for (int di = 0; di < (deep_series ? 9 : 1); ++di) { + const int deep = deep_series ? deeps[di] : -1; + if (deep_series && (live != 1024 || kind != 2 || &sh != &kTravShapes[0])) continue; + const int M = sh.nr; + std::vector vars; + std::vector ts[NV]; + const std::vector pr = { P("M", M), P("n_cand", NC), P("n_vocab", (int)VOC) }; + int path_rows = 0, mism = 0; + for (int v = 0; v < NV; ++v) { + TravReq* x = new TravReq(M, NC, SW); + vars.push_back(x); + fill_trav_req(x, sh, NC, live, kind, 0x7a00ull + 131ull * (uint64_t)v + (uint64_t)live, VOC, deep); + /* the host row, on copies */ + Buf htok = x->tok, hst = x->sts; + RadTensor th[6] = { x->cid.on_host(), x->cval.on_host(), x->prm.on_host(), hst.on_host(), htok.on_host(), x->topo.on_host() }; + RadArgs ah{}; ah.t = th; ah.n_t = 6; ah.p = pr.data(); ah.n_p = (int)pr.size(); + REQUIRE_EQ(htr->launch(&ah, s), RAD_OK); + ts[v] = { x->cid.on_dev(s), x->cval.on_dev(s), x->prm.on_dev(s), x->sts.on_dev(s), x->tok.on_dev(s), x->topo.on_dev(s) }; + RadArgs a{}; a.t = ts[v].data(); a.n_t = 6; a.p = pr.data(); a.n_p = (int)pr.size(); + REQUIRE_EQ(dtr->launch(&a, s), RAD_OK); + x->tok.fetch(s); + REQUIRE_EQ(rad_stream_sync(s), RAD_OK); + for (int m = 0; m < M; ++m) { + const int32_t g = ((int32_t*)x->tok.host.data())[m], w = ((int32_t*)htok.host.data())[m]; + mism += g != w; + path_rows += w != -9; + } + } + CHECK_EQ(mism, 0); + auto run = [&](const RadKernelInfo* k, int reps) { + const auto t0 = std::chrono::steady_clock::now(); + for (int r = 0; r < reps; ++r) { + RadArgs a{}; a.t = ts[r % NV].data(); a.n_t = 6; a.p = pr.data(); a.n_p = (int)pr.size(); + if (k->launch(&a, s) != RAD_OK) return -1.0; + } + rad_stream_sync(s); + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / reps; + }; + run(dtr, 40); + if (drep) run(drep, 10); + double one = 1e9, many = 1e9; + for (int it = 0; it < 5; ++it) { + one = std::min(one, run(dtr, nrep)); + if (drep) many = std::min(many, run(drep, std::max(8, nrep / 4))); + } + if (deep_series) fprintf(stderr, " TRAVBENCH final draw in pass %2d:", deep); + if (drep) + fprintf(stderr, " TRAVBENCH live=%4d %-6s %-5s rows=%2d launch %.1f us x%d %.1f us kernel per decision %.2f us (path rows/req %.2f, mism %d)\n", + live, sh.name, kinds[kind], M, one, rep, many, (many - one) / (rep - 1), (double)path_rows / NV, mism); + else + fprintf(stderr, " TRAVBENCH live=%4d %-6s %-5s rows=%2d launch %.1f us (path rows/req %.2f, mism %d)\n", + live, sh.name, kinds[kind], M, one, (double)path_rows / NV, mism); + for (auto* x : vars) delete x; + } + rad_stream_destroy(s); +} + +RAD_TEST_MAIN() diff --git a/tests/spechub_wiring_test.cpp b/tests/spechub_wiring_test.cpp index 432a85a5..2cd51145 100644 --- a/tests/spechub_wiring_test.cpp +++ b/tests/spechub_wiring_test.cpp @@ -94,11 +94,11 @@ 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, 3); - CHECK_EQ(host, 3); + CHECK_EQ(dev, 4); + CHECK_EQ(host, 4); #else CHECK_EQ(dev, 0); - CHECK_EQ(host, 3); + CHECK_EQ(host, 4); #endif /* Every op must have at least one production row on a device build. This is the property the