Archived
feat(sampler): port linear MTP coupling and cooperative verify upstream
Port GitHub PRs #12 and #13 onto Codeberg upstream main, retaining upstream kernel-chain handling. Include the source Clang target-attribute fixes required by the host build; omit the KFD header workaround and unrelated fork work. Co-Authored-By: Claude Code <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
1 parent
123c439684
commit
d912c694f3
37 files changed
+3730
-23
No files matched your search
@@ -305,6 +305,10 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
|
||||
add_subdirectory(libavx)
|
||||
endif()
|
||||
add_subdirectory(arch)
|
||||
# spechub: the linear-MTP coupling kernels (RADIANCE_MTP_COUPLED), the one in-tree plugin directory
|
||||
# the experimental line owns. Built by default so the flag's kernels exist in the same tree that
|
||||
# enables it; a deployment that never sets the flag loads a library whose rows it never resolves.
|
||||
add_subdirectory(plugin/spechub)
|
||||
add_subdirectory(tools)
|
||||
if(RAD_BUILD_TESTS)
|
||||
enable_testing()
|
||||
|
||||
+13
-1
@@ -549,9 +549,21 @@ typedef int (*RadKernelCollectiveFn)(int i);
|
||||
* - the engine refuses to serve a model with an op only a reference library implements, unless
|
||||
* given --debug-accept-reference-kernels;
|
||||
* - rad-kbench checks every other library against it.
|
||||
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`. */
|
||||
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`.
|
||||
*
|
||||
* It is a whole-library answer, because a library is usually one implementation of one thing. A
|
||||
* plugin that ships a device row AND the host oracle beside it is not: marking the library would
|
||||
* mark its device rows too, and the engine would refuse to serve an op that has a real kernel.
|
||||
* Such a plugin exports `rad_kernel_reference` below and leaves this one 0. */
|
||||
typedef int (*RadPluginReferenceFn)(void);
|
||||
|
||||
/* Optional, per row: nonzero says kernel `i` of rad_kernel_at is that row's reference
|
||||
* implementation. Overrides `rad_plugin_reference` for the rows it is exported for, so one
|
||||
* library can declare a device row (0) and its host oracle (1) side by side. A plugin that
|
||||
* exports neither leaves every row classified by `rad_plugin_reference`. Symbol name:
|
||||
* `rad_kernel_reference`. */
|
||||
typedef int (*RadKernelReferenceFn)(int i);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
/* rad_spechub.h -- the linear-MTP coupling wire row.
|
||||
*
|
||||
* These rows are what a kernel plugin reads and the core writes, so their layout is part of the ABI
|
||||
* and belongs here rather than in a plugin header: the core may include an abi/ header and a plugin
|
||||
* may not include a core one. Everything in this file is header-only and total -- nothing
|
||||
* allocates, holds state or calls back into the core -- so the host reference, the GPU kernel and
|
||||
* the sampler read one definition of the wire AND of the arithmetic that turns it into a token.
|
||||
*
|
||||
* The row is a U32 plane with an eight-byte aligned base and row strides, which is what makes the
|
||||
* state wire safe to load whole on the device.
|
||||
*/
|
||||
#ifndef RAD_SPECHUB_H
|
||||
#define RAD_SPECHUB_H
|
||||
|
||||
#include <math.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* The verify reads a parameter row, so this header carries the row's definition: a plugin that had
|
||||
* to include two abi/ headers, in the right order, to read one row would get it wrong eventually. */
|
||||
#include "rad_sample.h"
|
||||
|
||||
/* Linear MTP coupling (RADIANCE_MTP_COUPLED=1). One draw per drafting row, staged before the
|
||||
* serial passes; one state per (temporal round, row). `base` is the request's PRE-commit output
|
||||
* size, so (base, round) names one draft stream that no later step reuses. `card` is the step slot
|
||||
* the advance writes, checked against RadBatch::seq_ids. `mode` 1 samples x~Q; 0 keeps the greedy
|
||||
* proposal (temperature 0 or top_k 1). */
|
||||
typedef struct RadMtpCoupleDraw {
|
||||
uint64_t seed, base, seq;
|
||||
int32_t card;
|
||||
uint32_t mode;
|
||||
} RadMtpCoupleDraw;
|
||||
/* status 1: x sampled from the exact q[] stored here; 0: greedy proposal kept; -1: malformed
|
||||
* shortlist or row identity, greedy proposal kept. `pos` is the verify row's output position, bound
|
||||
* by the host after commit; the device writes 0. ids[count..7] = -1, q[count..7] = 0. */
|
||||
typedef struct RadMtpCoupleState {
|
||||
RadMtpCoupleDraw draw;
|
||||
uint64_t pos;
|
||||
int32_t status, round, x, count;
|
||||
int32_t ids[8];
|
||||
double q[8];
|
||||
} RadMtpCoupleState;
|
||||
#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
|
||||
/* Draft stream of round r: seed ^ (KEY_DRAFT + r) at coordinate `base`. Acceptance and the
|
||||
* residual draw use RAD_SAMPLE_KEY_ACCEPT / RAD_SAMPLE_KEY_RESID at the verify position. */
|
||||
#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(offsetof(RadMtpCoupleState, q) % 8 == 0, "MTP coupling q alignment");
|
||||
#endif
|
||||
|
||||
/* ================================================================== the shared arithmetic
|
||||
*
|
||||
* NUMERICS ARE THE CONTRACT. Q is the FP64 softmax of an FP32 shortlist at temperature 1; P is the
|
||||
* FP64 softmax of the sampler's FP32 candidate logits. Both are same-or-higher precision than the
|
||||
* ordinary FP32/24-bit sample_pick, so a coupled row realizes the ideal filtered target law to FP64
|
||||
* rounding, NOT the FP32 pick's finite law, and is NOT seed-identical to it. Uniforms are 53-bit.
|
||||
*/
|
||||
#ifdef __cplusplus
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_SPECHUB_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_SPECHUB_HD
|
||||
#endif
|
||||
|
||||
static inline RAD_SPECHUB_HD double rad_spechub_positive(double a) { return a > 0 ? a : 0; }
|
||||
static inline RAD_SPECHUB_HD bool rad_spechub_finite(double x) {
|
||||
return x == x && x <= 1.7976931348623157e308 && x >= -1.7976931348623157e308;
|
||||
}
|
||||
|
||||
/* THE 53-BIT UNIFORM IN [0, 1): splitmix64 over (seed ^ key, pos), then the top 53 bits scaled by
|
||||
* 2^-53. A seed and a position name one number whoever computes it. */
|
||||
static inline RAD_SPECHUB_HD double rad_spechub_uniform(uint64_t seed, uint64_t pos, uint64_t key) {
|
||||
uint64_t z = (seed ^ key) * 0x9e3779b97f4a7c15ull + pos + 0x9e3779b97f4a7c15ull;
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
|
||||
z ^= z >> 31;
|
||||
return (double)(z >> 11) * 0x1p-53;
|
||||
}
|
||||
|
||||
/* Is `s` a state the coupling's propose kernel could have written for a sampled row? The verifier
|
||||
* and the engine's bind check refuse a row by this rule, on the device and on the host. */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleState& s,
|
||||
int64_t vocab) {
|
||||
if (s.status != 1 || s.draw.mode != 1 || s.count < 1 || s.count > 8 || s.round < 1 ||
|
||||
s.round > RAD_MTP_COUPLE_MAX_ROUNDS)
|
||||
return false;
|
||||
double sum = 0;
|
||||
bool has_x = false;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (i >= s.count) {
|
||||
if (s.ids[i] != -1 || s.q[i] != 0) return false;
|
||||
continue;
|
||||
}
|
||||
if (s.ids[i] < 0 || s.ids[i] >= vocab || !rad_spechub_finite(s.q[i]) || !(s.q[i] > 0) ||
|
||||
s.q[i] > 1)
|
||||
return false;
|
||||
for (int j = 0; j < i; ++j)
|
||||
if (s.ids[j] == s.ids[i]) return false;
|
||||
sum += s.q[i];
|
||||
has_x |= s.ids[i] == s.x;
|
||||
}
|
||||
return has_x && (sum - 1) <= 1e-12 && (1 - sum) <= 1e-12;
|
||||
}
|
||||
|
||||
/* THE VERIFY POSITION OF A COUPLED ROUND, and the one coordinate the engine's bind and the
|
||||
* sampler's row check must agree on.
|
||||
*
|
||||
* The sampler stages row k of a request at output position `n_out + k`, where `n_out` is that
|
||||
* request's committed output length WHEN THE STEP IS BUILT. A coupled round r (1-based) is the
|
||||
* draft verified at row k = r - 1, so its state carries `pos = n_out + (r - 1)`. The acceptance
|
||||
* and residual uniforms are drawn at exactly this position (KEY_ACCEPT / KEY_RESID), which is what
|
||||
* makes the verify's draw the draw the propose's law describes.
|
||||
*
|
||||
* `n_out` is the length the verify step will actually see -- read from the request after the
|
||||
* drafting step's commit, never reconstructed from a pre-commit base plus a slot counter: those
|
||||
* two drift apart whenever the commit emits fewer tokens than the card accepted (a max_tokens or
|
||||
* context cut) or a request's step is carried. `base` stays the DRAFT's coordinate, which is a
|
||||
* different number and must not be reused here. */
|
||||
static inline RAD_SPECHUB_HD uint64_t rad_mtp_couple_verify_pos(uint64_t n_out, int round) {
|
||||
return n_out + (round > 0 ? (uint64_t)(round - 1) : 0);
|
||||
}
|
||||
|
||||
/* Would the verify row for draft index `k` (0-based) of a request with committed output length
|
||||
* `n_out` take `c` as its coupled state? Same request and seed, the round this row's draft came
|
||||
* from, the position it samples, the very token it proposes, and a state the proposer could have
|
||||
* written. Anything else is a stale state from another step, and coupling against it would apply a
|
||||
* law this step never drew.
|
||||
*
|
||||
* Asked by the sampler's step build, against the state the engine bound. The engine's own bind
|
||||
* does not call it: it checks the readback against the card (draw, round, x, status) and writes
|
||||
* the position with rad_mtp_couple_verify_pos, the formula here that both sides must agree on. */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_binds(const RadMtpCoupleState& c, uint64_t seq,
|
||||
uint64_t seed, uint64_t n_out, int k,
|
||||
int32_t draft_x, int64_t vocab) {
|
||||
return c.status == 1 && c.draw.seq == seq && c.draw.seed == seed && c.round == k + 1 &&
|
||||
c.pos == rad_mtp_couple_verify_pos(n_out, k + 1) && c.x == draft_x &&
|
||||
rad_mtp_couple_state_valid(c, vocab);
|
||||
}
|
||||
|
||||
/* Build the stored Q from a shortlist of eight (id, score) slots.
|
||||
*
|
||||
* Holes (id < 0) and -inf scores carry no mass. An entry whose FP64 weight or normalized q
|
||||
* underflows to zero is DROPPED, so the stored q[] is exactly the law the draw walks. False on an
|
||||
* out-of-range id, NaN/+inf score, duplicate id or empty support (s->count = 0). */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_build_q(const int32_t* ids, const float* val,
|
||||
int64_t vocab, RadMtpCoupleState* s) {
|
||||
int32_t kid[8];
|
||||
float kv[8];
|
||||
int n = 0;
|
||||
s->count = 0;
|
||||
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (ids[i] < 0) continue;
|
||||
if (ids[i] >= vocab || val[i] != val[i] || val[i] == INFINITY) return false;
|
||||
if (val[i] == -INFINITY) continue;
|
||||
for (int j = 0; j < n; ++j)
|
||||
if (kid[j] == ids[i]) return false;
|
||||
kid[n] = ids[i];
|
||||
kv[n++] = val[i];
|
||||
}
|
||||
if (!n) return false;
|
||||
float top = kv[0];
|
||||
for (int j = 1; j < n; ++j)
|
||||
if (kv[j] > top) top = kv[j];
|
||||
double w[8], sum = 0;
|
||||
for (int j = 0; j < n; ++j) { w[j] = ::exp((double)kv[j] - top); sum += w[j]; }
|
||||
for (int j = 0; j < n; ++j) {
|
||||
const double q = w[j] / sum;
|
||||
if (q > 0) { s->ids[s->count] = kid[j]; s->q[s->count++] = q; }
|
||||
}
|
||||
return s->count > 0;
|
||||
}
|
||||
|
||||
/* Inverse CDF over the stored q with a uniform in [0, 1); index into ids. */
|
||||
static inline RAD_SPECHUB_HD int rad_mtp_couple_pick(const RadMtpCoupleState& s, double u) {
|
||||
double total = 0;
|
||||
for (int i = 0; i < s.count; ++i) total += s.q[i];
|
||||
double c = u * total;
|
||||
for (int i = 0; i < s.count; ++i) { c -= s.q[i]; if (c < 0) return i; }
|
||||
return s.count - 1;
|
||||
}
|
||||
|
||||
/* Residual mass r(y) = max(0, P(y) - Q(y)) of one candidate. Q tokens use their P aggregated over
|
||||
* duplicate candidates, counted once at the first occurrence (`seen`). */
|
||||
static inline RAD_SPECHUB_HD double rad_mtp_couple_mass(const RadMtpCoupleState& s, const double* pq,
|
||||
int32_t id, float v, float top, double sum,
|
||||
unsigned* seen) {
|
||||
if (id < 0 || v == -INFINITY) return 0;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (s.ids[k] == id) {
|
||||
if (*seen & (1u << k)) return 0;
|
||||
*seen |= 1u << k;
|
||||
return rad_spechub_positive(pq[k] - s.q[k]);
|
||||
}
|
||||
return ::exp((double)v - top) / sum;
|
||||
}
|
||||
|
||||
/* THE MAXIMAL COUPLING. Emits into *out and returns true, or returns false for an invalid/empty
|
||||
* target. Needs u_accept, u_resid in [0, 1).
|
||||
*
|
||||
* A DRAFT TOKEN IS ACCEPTED WHEN IT EQUALS THE TOKEN THE TARGET ITSELF DREW AT THAT POSITION: the
|
||||
* target's own law over the surviving candidates is P, the draft's is Q, x is the draft, and the
|
||||
* rule is `u * Q(x) < P(x)`, after the case where P dominates Q everywhere. On rejection the
|
||||
* emitted token is a draw from the residual (P - Q)+, which is what makes the composed law the
|
||||
* target's and nothing else.
|
||||
*
|
||||
* If FP64 cancellation leaves R = 0 while some Q token has P < Q, sample P directly in FP64 with
|
||||
* the independent residual uniform. The fallback decision reads (P, Q) only -- never x or either
|
||||
* uniform -- and must not restore sample_pick's FP32/24-bit law.
|
||||
*
|
||||
* R sums r over every candidate INCLUDING x. The residual walk runs only when P(x) < Q(x), where
|
||||
* r(x) = max(0, P(x) - Q(x)) is exactly +0 (distinct doubles never subtract to 0), so the walk --
|
||||
* which skips x explicitly, residual at x exactly zero -- has total R bit for bit. */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_decide(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;
|
||||
int ix = -1;
|
||||
bool dominated = true;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
pq[k] /= sum;
|
||||
dominated = dominated && pq[k] >= s.q[k];
|
||||
if (s.ids[k] == s.x) ix = k;
|
||||
}
|
||||
if (ix < 0) return false; /* unreachable for a rad_mtp_couple_state_valid state */
|
||||
unsigned seen = 0;
|
||||
double resid = 0;
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
resid += rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen);
|
||||
if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) {
|
||||
double c = u_resid * sum;
|
||||
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 true;
|
||||
}
|
||||
if (pq[ix] >= s.q[ix] || u_accept * s.q[ix] < pq[ix]) { *out = s.x; return true; }
|
||||
/* Rejected, so P(x) < Q(x): not dominated, resid > 0, and some y != x has mass > 0 below. */
|
||||
double c = u_resid * resid;
|
||||
int32_t last = -1;
|
||||
seen = 0;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] == s.x) continue;
|
||||
const double m = rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen);
|
||||
if (m > 0) { last = ids[j]; c -= m; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
*out = last;
|
||||
return true;
|
||||
}
|
||||
|
||||
#undef RAD_SPECHUB_HD
|
||||
#endif /* __cplusplus */
|
||||
#endif /* RAD_SPECHUB_H */
|
||||
@@ -73,6 +73,8 @@
|
||||
#include "rad_block_hc.h"
|
||||
#include "rad_block_moe_fp8.h"
|
||||
#include "rad_block_mtp_fp8.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */
|
||||
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire */
|
||||
#include "rad_spechub_config.h" /* RADIANCE_MTP_COUPLED */
|
||||
#include "rad_qsa.h"
|
||||
#include "rad_block_vit.h"
|
||||
|
||||
@@ -108,6 +110,9 @@ struct MtpHcBlock {
|
||||
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
|
||||
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
|
||||
rad_buf dpair = 0, dgath = 0;
|
||||
/* RADIANCE_MTP_COUPLED: [max_seqs] draws and [depth, max_seqs] states, both PERSIST across
|
||||
* the serial passes (round 1 resets the logical stream, not the plane). */
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
AttnGatedFP8::Wire attn{};
|
||||
MoeFP8::Wire mlp{};
|
||||
QsaIndexer::Wire qsa{};
|
||||
@@ -158,6 +163,9 @@ struct MtpHcBlock {
|
||||
rad_op op_dsel = 0, op_dback = 0;
|
||||
rad_op op_logits = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0;
|
||||
/* RADIANCE_MTP_COUPLED: one op a round. The ABI freezes `round` as a parameter, so a round
|
||||
* cannot be an operand and each gets its own declared op. */
|
||||
rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
|
||||
|
||||
/* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
|
||||
* planes. */
|
||||
@@ -422,6 +430,29 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
if (!op_dgather || !op_dmerge) return RAD_E_INVAL;
|
||||
}
|
||||
if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
|
||||
/* THE LINEAR COUPLED PROPOSAL: one op a round (the ABI freezes `round` as a parameter, so a
|
||||
* round cannot be an operand), after the final rerank/merge, on the shortlist that would
|
||||
* otherwise give column 0.
|
||||
*
|
||||
* LINEAR CHAIN ONLY. A coupled row's Q is the head's own top-8 at temperature 1, and x is a
|
||||
* TOKEN; a tree takes column 0 as a parent index, so coupling and branching cannot share a
|
||||
* pass. The engine refuses that combination before this runs; the test here keeps a
|
||||
* declaration that disagrees with it from silently proposing tokens into a tree plane. */
|
||||
if (mtp_coupled_enabled()) {
|
||||
if (!w.couple_draws || !w.couple_state || depth < 1 ||
|
||||
depth > RAD_MTP_COUPLE_MAX_ROUNDS || !op_drerank || (g.world > 1 && !op_dmerge))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
for (int round = 1; round <= depth; ++round) {
|
||||
op_couple[round - 1] = rw(b, RAD_OP(b, "mtp_couple_propose",
|
||||
/* The WHOLE vocabulary: `row_topk` reports global ids (its `vocab_off`) and
|
||||
* the merge keeps them, while `g.n_vocab` is this rank's shard. */
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("round", round), RAD_INT("max_rounds", depth)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.didx, w.dval, w.couple_draws }, { w.didx, w.couple_state });
|
||||
if (!op_couple[round - 1]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Keep the carry `hin` live through the head's last op: it is written before the mixer and
|
||||
* lm_head run, and the planner could otherwise give its bytes to them (silently lowering
|
||||
@@ -429,6 +460,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{
|
||||
rad_op last = op_logits;
|
||||
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
|
||||
if (op_couple[0]) last = op_couple[depth - 1];
|
||||
if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -524,6 +556,19 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
|
||||
brows(w.didx, L), brows(w.dval, L), RAD_NONE);
|
||||
}
|
||||
/* THE COUPLED PROPOSAL, after the FINAL reranked shortlist: column 0 is what ADV_TAKE reads,
|
||||
* and a sampled row replaces it with its own x. Round 1 is carried by the history pass
|
||||
* (r < 0), every later round by its own pass, exactly as the carry above is. */
|
||||
if (op_couple[0]) {
|
||||
const int round = r < 0 ? 1 : r;
|
||||
if (round < 1 || round > depth) {
|
||||
rad_step_fail(c, "MTP coupled round exceeds the declared draft depth");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_couple[round - 1], L, brows(w.didx, L), brows(w.dval, L),
|
||||
praw(batch->seq_ids, RAD_I32, batch->n_seq),
|
||||
brows(w.couple_draws, L), RAD_B(w.couple_state));
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/* rad_spechub_config.h -- the opt-in switches the coupling reads.
|
||||
*
|
||||
* Here rather than in core/ because both the architecture plugin and the sampler read them: an
|
||||
* arch plugin may not include a core header, and a switch that the arch and the sampler disagree
|
||||
* about is exactly the failure these functions exist to prevent. Header-only and total.
|
||||
*/
|
||||
#ifndef RAD_SPECHUB_CONFIG_H
|
||||
#define RAD_SPECHUB_CONFIG_H
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* RADIANCE_MTP_COUPLED=1: the linear builtin MTP drafter samples x~Q each round and the target
|
||||
* sampler applies the maximal coupling (docs/OPS.md, `mtp_couple_propose`/`mtp_couple_verify`).
|
||||
* Unset or "0" is the ordinary path.
|
||||
*
|
||||
* Nothing here enumerates the drafter configurations the coupling cannot serve. Drafting is
|
||||
* switched off by asking for no speculative window (`--num-speculative-tokens 0`), which leaves
|
||||
* `RadDrafterDecl::kind == RAD_DRAFT_NONE`; a block drafter declares RAD_DRAFT_BLOCK. Both are
|
||||
* read from the declaration by the engine (Engine::step_state_init), which is where they are
|
||||
* known. An environment variable that no other code reads cannot enforce either. */
|
||||
inline bool mtp_coupled_enabled() {
|
||||
const char* value = std::getenv("RADIANCE_MTP_COUPLED");
|
||||
return value && !std::strcmp(value, "1");
|
||||
}
|
||||
|
||||
/* A value other than unset/0/1 is REFUSED, not read as off: a deployment that asked for coupling
|
||||
* and got a typo must not be served the uncoupled path while believing otherwise. The refusal is
|
||||
* RAD_E_INVAL out of Sampler::declare (and out of the architecture's own check where it makes one),
|
||||
* both before the first request. */
|
||||
inline bool mtp_coupled_config_valid() {
|
||||
const char* value = std::getenv("RADIANCE_MTP_COUPLED");
|
||||
return !value || !std::strcmp(value, "0") || !std::strcmp(value, "1");
|
||||
}
|
||||
|
||||
} // namespace rad
|
||||
#endif
|
||||
@@ -174,6 +174,10 @@ struct Model {
|
||||
rad_buf b_mtp_hin = 0, b_mtp_hw = 0, b_mtp_e = 0, b_mtp_hout = 0;
|
||||
rad_buf b_mtp_dq = 0, b_mtp_ds = 0, b_mtp_dsum = 0;
|
||||
rad_buf b_mtp_dlog = 0, b_mtp_didx = 0, b_mtp_dval = 0;
|
||||
/* RADIANCE_MTP_COUPLED: [max_seqs] draws staged before the serial passes and [max_spec,
|
||||
* max_seqs] states read back after them. PERSIST: the engine writes them from the host and the
|
||||
* head writes the states on the card, across a step boundary. */
|
||||
rad_buf b_mtp_couple_draws = 0, b_mtp_couple_state = 0;
|
||||
rad_buf b_mtp_dpair = 0, b_mtp_dgath = 0;
|
||||
|
||||
HcEnter enter;
|
||||
@@ -1261,6 +1265,38 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* vocab-parallel all-gather a 16-byte row (rad_block_mtp_hc.h, kDraftTopR). */
|
||||
m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_logit_rows, kDraftTopR});
|
||||
m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_logit_rows, kDraftTopR});
|
||||
|
||||
/* RADIANCE_MTP_COUPLED. The coupling needs the 2-bit candidate head's reranked top-8,
|
||||
* because Q is that shortlist's own law; a plain bf16 head leaves one candidate and
|
||||
* there is nothing to couple over. The drafter SHAPE (a linear serial chain, never a
|
||||
* block drafter) is checked by the engine, which is where the declaration is in hand:
|
||||
* the switches that once named tree drafters do not exist in this tree, and testing
|
||||
* their environment variables here enforced nothing. */
|
||||
if (!rad::mtp_coupled_config_valid()) {
|
||||
rad_note(b, "RADIANCE_MTP_COUPLED accepts 0|1 (or unset); any other value is "
|
||||
"refused, not treated as off");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (rad::mtp_coupled_enabled()) {
|
||||
if (!m.b_mtp_didx || g.max_spec < 1 || g.max_spec > RAD_MTP_COUPLE_MAX_ROUNDS) {
|
||||
rad_note(b, "RADIANCE_MTP_COUPLED requires the 2-bit candidate head's reranked "
|
||||
"top8 and max_spec 1..%d",
|
||||
RAD_MTP_COUPLE_MAX_ROUNDS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.b_mtp_couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
|
||||
{g.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
m.b_mtp_couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
|
||||
{g.max_spec, g.max_seqs,
|
||||
RAD_MTP_COUPLE_STATE_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
if (!m.b_mtp_couple_draws || !m.b_mtp_couple_state) return RAD_E_INVAL;
|
||||
rad_note(b, "MTP coupled: the head samples x~Q from its reranked top8 each round "
|
||||
"(FP64), and the sampler couples the target's own draw to it; %lld "
|
||||
"round(s), fixed-seed tokens are NOT preserved",
|
||||
(long long)g.max_spec);
|
||||
}
|
||||
}
|
||||
|
||||
MtpHcBlock::Wire tw{};
|
||||
@@ -1270,6 +1306,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
tw.dq = m.b_mtp_dq; tw.ds = m.b_mtp_ds; tw.dsum = m.b_mtp_dsum;
|
||||
tw.dlog = m.b_mtp_dlog; tw.didx = m.b_mtp_didx; tw.dval = m.b_mtp_dval;
|
||||
tw.dpair = m.b_mtp_dpair; tw.dgath = m.b_mtp_dgath;
|
||||
tw.couple_draws = m.b_mtp_couple_draws; tw.couple_state = m.b_mtp_couple_state;
|
||||
/* The head reuses the trunk's working buffers, all dead by the time a draft round runs (a
|
||||
* second set would be 150 MiB). Only the wide stream and the carry are its own, since
|
||||
* they must survive the round that produced them. */
|
||||
|
||||
+4
-1
@@ -530,7 +530,7 @@ int Engine::step_loop() {
|
||||
}
|
||||
if (t_on) phase_mark(PH_BEGIN);
|
||||
for (auto& rk : ranks_) {
|
||||
const int s = rk->sampler.build_step(so.reqs);
|
||||
const int s = rk->sampler.build_step(so.reqs, b->step);
|
||||
if (s < 0) { RAD_ERR("sampler build_step: %s", rad_strerror(s)); return s; }
|
||||
/* A request the sampler could not serve is cancelled; the step goes on. */
|
||||
for (uint64_t id : rk->sampler.take_failed()) cancel.push_back(id);
|
||||
@@ -717,6 +717,9 @@ int Engine::step_loop() {
|
||||
st = embedding_ ? collect_pooled(b, so) : collect_step(b, so);
|
||||
if (t_on) phase_mark(PH_COLLECT);
|
||||
if (st < 0) return fail_loop(st);
|
||||
/* The step's sampler chain, verify op included, has returned: one line at the first
|
||||
* coupled verify that actually completed. */
|
||||
couple_verify_evidence(b->step);
|
||||
if (cfg_.kld()) {
|
||||
st = score_rows(b, so);
|
||||
if (st < 0) return fail_loop(st);
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "rad_spechub.h" /* RadMtpCoupleDraw/State: the coupled MTP wire rows */
|
||||
#include "cvec.h"
|
||||
#include <map>
|
||||
#include <set>
|
||||
@@ -396,6 +397,25 @@ private:
|
||||
void step_state_fini();
|
||||
StepSlot* slots_host_ = nullptr;
|
||||
|
||||
/* RADIANCE_MTP_COUPLED (engine_draft.cpp). The head declares `mtp_couple_draws` and
|
||||
* `mtp_couple_state`; the engine stages one draw per drafting row before the serial passes and
|
||||
* reads the states back once, then binds each to the verify row it will be coupled at. */
|
||||
bool mtp_couple_ = false;
|
||||
rad_buf couple_draws_buf_ = 0, couple_state_buf_ = 0;
|
||||
int64_t couple_rows_ = 0; /* the state plane's rows per round */
|
||||
RadMtpCoupleDraw* couple_draw_stage_ = nullptr; /* pinned [max_seqs] */
|
||||
RadMtpCoupleState* couple_readback_ = nullptr; /* pinned [rounds, couple_rows_] */
|
||||
std::vector<RadMtpCoupleDraw> couple_by_card_; /* the plan's draw per card slot */
|
||||
RadMtpCoupleState couple_bound_[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
|
||||
bool couple_evidence_ = false; /* the completed-verify line was written (once a process) */
|
||||
bool couple_host_note_ = false; /* the host-domain counterpart was written (once) */
|
||||
int stage_couple_draws(int n);
|
||||
/* One INFO line at the first coupled verify that completed: the step, the live requests whose
|
||||
* rows carried a bound state, the kernel and its domain. Read off the sampler's build snapshot
|
||||
* after collect_step's wait, so it reports an issued, finished verify -- not an enqueue, not a
|
||||
* LIVE flag, and not a host row read as a device one. */
|
||||
void couple_verify_evidence(int step);
|
||||
|
||||
/* Step-time attribution, Debug only (see the barrier in step_loop): time per scheduler phase.
|
||||
* The nine phases sum to the whole step, including the readback, commit and drafter after the
|
||||
* join. */
|
||||
|
||||
+166
-2
@@ -6,6 +6,10 @@
|
||||
*/
|
||||
#include "engine_priv.h"
|
||||
|
||||
#include "../arch/common/rad_spechub_config.h"
|
||||
#include "sample/mtp_couple_evidence.h"
|
||||
#include "sched/mtp_couple_bind.h"
|
||||
#include "sched/mtp_couple_plan.h"
|
||||
#include "sched/scheduler.h"
|
||||
#include "device/device.h"
|
||||
|
||||
@@ -13,6 +17,7 @@
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -48,6 +53,64 @@ int Engine::step_state_init() {
|
||||
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0]->device));
|
||||
slots_host_ = static_cast<StepSlot*>(rad_dev_alloc(slot_bytes, RAD_MEM_HOST_PINNED));
|
||||
if (!slots_host_) return RAD_E_NOMEM;
|
||||
|
||||
/* RADIANCE_MTP_COUPLED: the head's two planes, found by name in the program it declared, and
|
||||
* the pinned staging the step path needs beside them. A program without them has no coupled
|
||||
* path, so the flag's absence and its contradiction are told apart here: the flag is on and the
|
||||
* head declared nothing means the architecture refused it (it returns RAD_E_UNSUPPORTED at its
|
||||
* own declare), and a silent no-op would serve uncoupled drafts while the flag said otherwise. */
|
||||
mtp_couple_ = mtp_coupled_enabled();
|
||||
if (mtp_couple_) {
|
||||
/* THE DRAFTER SHAPE IS CHECKED HERE, where the declaration is in hand, not against
|
||||
* environment variables nobody else reads. Coupling is defined on a LINEAR chain: a block
|
||||
* drafter proposes a whole block at once from one pass and writes it to its proposal
|
||||
* buffer, so there is no per-round draw to couple and no per-round state to read back.
|
||||
* Left unchecked, a block drafter would silently serve uncoupled drafts while the flag
|
||||
* said otherwise. */
|
||||
if (drafter_.kind != RAD_DRAFT_SERIAL || drafter_.depth <= 0) {
|
||||
RAD_ERR("RADIANCE_MTP_COUPLED requires the linear serial draft chain (RAD_DRAFT_SERIAL "
|
||||
"with depth > 0); this model declares drafter '%s' kind %d depth %d, which has "
|
||||
"no per-round draw to couple",
|
||||
drafter_.name ? drafter_.name : "(none)", drafter_.kind, drafter_.depth);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const Program& prog = ranks_[0]->program;
|
||||
for (size_t i = 0; i < prog.buffers.size(); ++i) {
|
||||
const std::string& name = prog.buffers[i].name;
|
||||
auto ends = [&](const char* suffix) {
|
||||
const size_t n = std::strlen(suffix);
|
||||
return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0;
|
||||
};
|
||||
if (ends("mtp_couple_draws")) couple_draws_buf_ = (rad_buf)i;
|
||||
if (ends("mtp_couple_state")) couple_state_buf_ = (rad_buf)i;
|
||||
}
|
||||
if (!couple_draws_buf_ || !couple_state_buf_) {
|
||||
RAD_ERR("RADIANCE_MTP_COUPLED is set but the architecture declared no coupled MTP "
|
||||
"planes; the flag and the model disagree");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const RadBufDecl& sd = prog.buffers[couple_state_buf_].decl;
|
||||
if (sd.rank != 3 || sd.shape[2] != (int64_t)RAD_MTP_COUPLE_STATE_WORDS) {
|
||||
RAD_ERR("RADIANCE_MTP_COUPLED: 'mtp_couple_state' is not the [rounds, rows, %d]-word "
|
||||
"plane the coupling reads", (int)RAD_MTP_COUPLE_STATE_WORDS);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
couple_rows_ = sd.shape[1];
|
||||
/* ONE ENTRY PER CARD SLOT, indexed by StepEntry::card exactly as slots_host_ is: the plan
|
||||
* names a request's sequence on the slot the advance writes, and the draft row carries the
|
||||
* same `card`. A vector left empty makes every lookup miss, so the first step that drafts
|
||||
* would refuse with "has no plan entry on its card" instead of staging its draw. */
|
||||
couple_by_card_.assign((size_t)n_slot, RadMtpCoupleDraw{});
|
||||
couple_draw_stage_ = static_cast<RadMtpCoupleDraw*>(
|
||||
rad_dev_alloc(n_slot * (int64_t)sizeof(RadMtpCoupleDraw), RAD_MEM_HOST_PINNED));
|
||||
couple_readback_ = static_cast<RadMtpCoupleState*>(rad_dev_alloc(
|
||||
(int64_t)drafter_.depth * couple_rows_ * (int64_t)sizeof(RadMtpCoupleState),
|
||||
RAD_MEM_HOST_PINNED));
|
||||
if (!couple_draw_stage_ || !couple_readback_) return RAD_E_NOMEM;
|
||||
RAD_INFO("MTP coupled LIVE: %d linear round(s), x~Q from the final reranked top8, maximal "
|
||||
"coupling at the verify; fixed-seed tokens are NOT preserved", drafter_.depth);
|
||||
}
|
||||
|
||||
RAD_TRY(rad_event_create_as(&step_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -62,6 +125,10 @@ void Engine::step_state_fini() {
|
||||
}
|
||||
if (slots_host_) rad_dev_free(slots_host_, RAD_MEM_HOST_PINNED);
|
||||
slots_host_ = nullptr;
|
||||
if (couple_draw_stage_) rad_dev_free(couple_draw_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (couple_readback_) rad_dev_free(couple_readback_, RAD_MEM_HOST_PINNED);
|
||||
couple_draw_stage_ = nullptr;
|
||||
couple_readback_ = nullptr;
|
||||
if (step_end_) rad_event_destroy(step_end_);
|
||||
step_end_ = nullptr;
|
||||
}
|
||||
@@ -142,6 +209,8 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
|
||||
if (rounds <= 0) return RAD_OK;
|
||||
serial_rounds_ = rounds;
|
||||
serial_rows_ = n;
|
||||
/* Before ANY serial pass reads a draw: the round-1 pass is the history pass below. */
|
||||
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(n));
|
||||
|
||||
/* RADIANCE_DEBUG_STAGE: running means of a draft pass's host time: batch + advance, greedy
|
||||
* sampler chain, barrier release and issue. They cost the step nothing until their sum exceeds
|
||||
@@ -213,6 +282,16 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
|
||||
* history (Scheduler::serial_batch). */
|
||||
RAD_TRY(advance_all(ADV_TAKE, serial_done_, true, n));
|
||||
Rank& r0 = *ranks_[0];
|
||||
if (mtp_couple_) {
|
||||
/* Rounds 1..done of the drafting rows, in the SAME stream order as the slots below: the
|
||||
* states come back behind the proposal that they were drawn beside. */
|
||||
const void* state = r0.ctx.buf_ptr(couple_state_buf_);
|
||||
if (!state || serial_done_ > (int)drafter_.depth) return RAD_E_STATE;
|
||||
const int64_t pitch = couple_rows_ * (int64_t)sizeof(RadMtpCoupleState);
|
||||
RAD_TRY(rad_memcpy_2d_async(couple_readback_, pitch, state, pitch,
|
||||
(int64_t)n * (int64_t)sizeof(RadMtpCoupleState), serial_done_,
|
||||
r0.ctx.stream()));
|
||||
}
|
||||
RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots,
|
||||
(int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream()));
|
||||
return RAD_OK;
|
||||
@@ -253,8 +332,93 @@ int Engine::finish_serial_drafter(const StepOut& so) {
|
||||
/* No draft for a request the sampler will not speculate on (a constraining grammar that
|
||||
* cannot snapshot its state); the sampler would refuse the next step otherwise. */
|
||||
if (!r0.sampler.allows_speculation(serial_row_[(size_t)i].seq)) continue;
|
||||
sched_.set_draft(serial_row_[(size_t)i].seq,
|
||||
&draft_out_[(size_t)i * (size_t)rounds], done);
|
||||
const uint64_t seq = serial_row_[(size_t)i].seq;
|
||||
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)rounds], done);
|
||||
if (!mtp_couple_) continue;
|
||||
/* BOUND ONLY FOR A REQUEST STILL RUNNING. A truncated publication keeps a prefix, whose
|
||||
* rows carry their own rounds' states; a request this commit finished (a max_tokens or
|
||||
* context cut), or one the scheduler refused, binds nothing -- its rows are carried
|
||||
* terminal work and will never sample again. set_mtp_couple(…, 0) clears what an earlier
|
||||
* step left, and for a request already gone from the sampler it is RAD_E_NOTFOUND.
|
||||
*
|
||||
* The position coordinate is the request's committed output length AFTER this commit -- the
|
||||
* value the next build_step reads as its n_out. It comes from the scheduler's commit
|
||||
* snapshot, not from the plan's Request pointer: reap() may have destroyed that already.
|
||||
* The rule is mtp_couple_bind_rounds (sched/mtp_couple_bind.h), where it is driven against
|
||||
* a real commit without an Engine. */
|
||||
MtpCoupleBindPoint bp;
|
||||
bp.found = sched_.committed_seq(seq, &bp.n_out, &bp.live);
|
||||
if (!bp.found)
|
||||
RAD_WARN("MTP coupled: serial row for sequence %llu is not in the committed step; "
|
||||
"clearing its coupling", (unsigned long long)seq);
|
||||
int n_bound = 0;
|
||||
std::string why;
|
||||
const int bs = mtp_couple_bind_rounds(
|
||||
bp, couple_draw_stage_[(size_t)i], &couple_readback_[(size_t)i], (int)couple_rows_,
|
||||
done, slots_host_[serial_row_[(size_t)i].card], meta_.n_vocab, couple_bound_,
|
||||
&n_bound, &why);
|
||||
if (bs < 0) { RAD_ERR("%s", why.c_str()); return bs; }
|
||||
for (auto& rk : ranks_) {
|
||||
const int st = rk->sampler.set_mtp_couple(seq, couple_bound_,
|
||||
rc == RAD_OK ? n_bound : 0);
|
||||
if (st < 0 && st != RAD_E_NOTFOUND) return st;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One line, once, at the first coupled verify that completed. What makes it evidence is where it
|
||||
* reads: the snapshot build_step froze for the step whose wait just returned (sample/
|
||||
* mtp_couple_evidence.h), the verify op run() actually issued for that build, and the op's domain.
|
||||
* build_greedy -- the drafter's greedy passes, issued between that build and the wait -- clears
|
||||
* any_couple_ but not the snapshot; gating on the former is why the line never appeared in the
|
||||
* coupled path. Sequences are re-checked as Running after the wait under the scheduler's lock, so a
|
||||
* request that left in between is not counted. Request numbers, the row count and the kernel name
|
||||
* only: no tokens, no keys, no logits. A host-domain row prints the same line marked as not device
|
||||
* evidence -- an oracle run must not be read as one. */
|
||||
void Engine::couple_verify_evidence(int step) {
|
||||
if (!mtp_couple_ || couple_evidence_) return;
|
||||
Sampler& smp = ranks_[0]->sampler;
|
||||
const rad_op op = smp.staged_couple_op();
|
||||
const MtpCoupleEvidence ev = mtp_couple_evidence(
|
||||
smp.couple_build(), step, ranks_[0]->ctx.op_domain(op),
|
||||
[this](uint64_t seq) { return sched_.running(seq); });
|
||||
if (ev.rows <= 0 || smp.staged_couple_issued_step() != step) return;
|
||||
const char* kernel = ranks_[0]->ctx.ip_kernel_name(op);
|
||||
if (ev.device) {
|
||||
couple_evidence_ = true;
|
||||
RAD_INFO("MTP coupled verify completed: step %d, %lld bound row(s) over request(s) [%s], "
|
||||
"kernel %s, domain device", step, (long long)ev.rows, ev.seqs.c_str(), kernel);
|
||||
} else if (!couple_host_note_) {
|
||||
couple_host_note_ = true;
|
||||
RAD_INFO("MTP coupled verify completed on the host domain: step %d, %lld bound row(s) over "
|
||||
"request(s) [%s], kernel %s -- not device evidence", step, (long long)ev.rows,
|
||||
ev.seqs.c_str(), kernel);
|
||||
}
|
||||
}
|
||||
|
||||
/* RADIANCE_MTP_COUPLED: the draw for every drafting row, before any serial pass reads it.
|
||||
*
|
||||
* The coordinate is the PRE-commit output size, which strictly grows between two steps that draft
|
||||
* one request (each commits at least one token), so (base, round) never repeats a draft stream. The
|
||||
* card is the slot the advance writes, and the plugin refuses a row whose staged draw names another
|
||||
* -- which is what makes a stale draw a refusal here rather than a wrong token later. The rule
|
||||
* itself is sched/mtp_couple_plan.h, where it is checked without a card. */
|
||||
int Engine::stage_couple_draws(int n) {
|
||||
std::string why;
|
||||
const int stg = mtp_couple_plan_stage(sched_.plan(),
|
||||
(int)(cfg_.max_seqs > 0 ? cfg_.max_seqs : 1),
|
||||
serial_row_.data(), n, &couple_by_card_,
|
||||
couple_draw_stage_, &why);
|
||||
if (stg < 0) {
|
||||
RAD_ERR("MTP coupled: %s", why.c_str());
|
||||
return stg;
|
||||
}
|
||||
for (auto& rk : ranks_) {
|
||||
void* dst = rk->ctx.buf_ptr(couple_draws_buf_);
|
||||
if (!dst) return RAD_E_STATE;
|
||||
RAD_TRY(rad_memcpy_async(dst, couple_draw_stage_,
|
||||
n * (int64_t)sizeof(RadMtpCoupleDraw), rk->ctx.stream()));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -442,6 +442,9 @@ int Registry::commit_(Staged& s, int order) {
|
||||
const auto concurrent = dl_fn<RadKernelConcurrentFn>(s.handle, "rad_kernel_concurrent");
|
||||
const auto collective = dl_fn<RadKernelCollectiveFn>(s.handle, "rad_kernel_collective");
|
||||
const auto chainable = dl_fn<RadKernelChainFn>(s.handle, "rad_kernel_chain");
|
||||
/* Per row when exported, else the library's own answer: a plugin that ships a device row and
|
||||
* its host oracle in one library must not have the oracle's status leak onto the device row. */
|
||||
const auto kern_ref = dl_fn<RadKernelReferenceFn>(s.handle, "rad_kernel_reference");
|
||||
for (const auto& sr : staged_rows) {
|
||||
KernelRow row;
|
||||
row.info = sr.first;
|
||||
@@ -452,7 +455,7 @@ int Registry::commit_(Staged& s, int order) {
|
||||
const int coll = collective ? collective(sr.second) : 0;
|
||||
row.collective = coll != 0;
|
||||
row.releases_link = coll == 2;
|
||||
row.reference = p.reference;
|
||||
row.reference = kern_ref ? kern_ref(sr.second) != 0 : p.reference;
|
||||
row.chain = chainable && chainable(sr.second) != 0;
|
||||
rows_.push_back(row);
|
||||
}
|
||||
|
||||
+3
-1
@@ -546,6 +546,9 @@ public:
|
||||
/* Backs rad_step_fail(): stops the step like an operand rejection, with the caller's
|
||||
* message. */
|
||||
int step_fail(const char* what);
|
||||
/* The device kernel `h` resolved to on this rank ("?" if it resolved none). For log
|
||||
* attribution only. */
|
||||
const char* ip_kernel_name(rad_op h) const;
|
||||
private:
|
||||
[[noreturn]] void fatal_issue(rad_op h, int64_t n, const char* why) const;
|
||||
|
||||
@@ -572,7 +575,6 @@ private:
|
||||
* byte-compares the two results, finding kernels that are not a function of their inputs,
|
||||
* which a host-vs-device comparison cannot detect. */
|
||||
void oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd);
|
||||
const char* ip_kernel_name(rad_op h) const;
|
||||
/* The reference library's host plan for (op, band): the band's own host plan when a reference
|
||||
* library won it, else one resolved from `registry_` on first use. Null when none exists. */
|
||||
const IssuePlan* oracle_reference(rad_op h, int band);
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/* mtp_couple_evidence.h -- what the completed-verify line may claim.
|
||||
*
|
||||
* The line is evidence only if all of it holds: the build that staged bound rows belongs to the
|
||||
* step whose wait just returned, at least one of its sequences is still live at that point, and
|
||||
* the op that ran is a DEVICE op. Each of these was wrong in the first version of the line:
|
||||
*
|
||||
* - It gated on Sampler::staged_any_couple(), which the drafter's build_greedy had already
|
||||
* cleared between the build and the wait -- so the line never appeared in the coupled path.
|
||||
* It reads Sampler::couple_build() now, the snapshot build_step froze.
|
||||
* - It listed the rows of whatever build was last staged. The snapshot carries its step, and
|
||||
* the line is written only for the step being collected.
|
||||
* - It printed a kernel name without the domain, so a host reference row read like a device
|
||||
* verify. The domain is decided here and printed on the line.
|
||||
* - It listed sequences that were live at build time. `live` is asked after the wait (under the
|
||||
* scheduler's lock), and only those rows count.
|
||||
*
|
||||
* A pure function of the snapshot, a liveness predicate and the op's domain, so the decision can
|
||||
* be driven without an Engine (tests/sample_test.cpp).
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "sampler.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct MtpCoupleEvidence {
|
||||
int64_t rows = 0; /* bound rows of sequences still live after the wait */
|
||||
bool device = false; /* the op that ran is a device op */
|
||||
std::string seqs; /* those sequences, comma separated, in build order */
|
||||
};
|
||||
|
||||
/* `live(seq)` answers whether the sequence is still Running; the engine passes a predicate over
|
||||
* Scheduler::running(), the tests a set. Empty (rows == 0) when the snapshot is not this step's,
|
||||
* or nothing it staged is still live. */
|
||||
template <class Live>
|
||||
MtpCoupleEvidence mtp_couple_evidence(const Sampler::CoupleBuild& b, int64_t step, int domain,
|
||||
Live&& live) {
|
||||
MtpCoupleEvidence e;
|
||||
if (b.step != step) return e;
|
||||
e.device = domain == RAD_DOMAIN_DEVICE;
|
||||
for (const auto& s : b.seqs)
|
||||
if (live(s.first)) {
|
||||
e.rows += s.second;
|
||||
if (!e.seqs.empty()) e.seqs += ",";
|
||||
e.seqs += std::to_string(s.first);
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
} // namespace rad
|
||||
+106
-2
@@ -4,6 +4,8 @@
|
||||
#include "sampler.h"
|
||||
#include "gbnf.h"
|
||||
|
||||
#include "../../arch/common/rad_spechub_config.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
@@ -133,6 +135,14 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
}
|
||||
|
||||
cfg_ = cfg;
|
||||
/* A value other than unset/0/1 is refused, not read as off: a deployment that asked for the
|
||||
* coupling and got a typo must not be served the uncoupled path while believing otherwise. */
|
||||
if (!mtp_coupled_config_valid()) {
|
||||
RAD_ERR("RADIANCE_MTP_COUPLED accepts 0|1 (or unset); refusing the start rather than "
|
||||
"serving the uncoupled path");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
couple_ = mtp_coupled_enabled();
|
||||
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.
|
||||
@@ -179,6 +189,14 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
* penalised). Resolved on the host, which has the vocabulary. */
|
||||
buf_brk_ = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST);
|
||||
buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
|
||||
/* THE COUPLED STATE PLANE, one row per sampled position PERSIST because it is filled by an upload
|
||||
* before the run phase issues anything. A draft round's state is bound to the verify row that
|
||||
* follows it, not to the request, which is why it rides the sampler's own row array. */
|
||||
if (couple_) {
|
||||
buf_couple_ = decl("sampler.mtp_couple", RAD_U32, rows, RAD_MTP_COUPLE_STATE_WORDS,
|
||||
RAD_BUF_PERSIST);
|
||||
if (!buf_couple_) 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);
|
||||
if (vocab_parallel()) {
|
||||
@@ -249,6 +267,22 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_typical_ = op_cand("sample_typical");
|
||||
op_xtc_ = op_cand("sample_xtc");
|
||||
op_pick_ = op_cand("sample_pick");
|
||||
/* THE COUPLING'S VERIFY, over the SAME candidate plane the pick just read. A row whose state is
|
||||
* not bound keeps the pick's token, so an uncoupled batch issues nothing and pays nothing; a
|
||||
* coupled one pays one more launch over its candidate width, not its vocabulary. */
|
||||
if (couple_) {
|
||||
RadParam pc[3] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
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;
|
||||
/* No rad_op_reads here: the sampler's buffers are shared by ops that declare no lists
|
||||
* (topk, topp, pick), so declaring only this one would narrow the candidate planes to
|
||||
* its own op and the first sample_topk issue would be refused as outside their
|
||||
* lifetime. They stay live for the whole program, as before the coupling. */
|
||||
}
|
||||
/* The temperature kernel again, over the candidate plane: `n_vocab` is only a row length to
|
||||
* it, so the candidate width works. */
|
||||
{
|
||||
@@ -308,6 +342,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
|
||||
int Sampler::stage_alloc() {
|
||||
const int64_t rows = rows_for(cfg_);
|
||||
/* At most one entry per request; reserved here so a coupled step never allocates. */
|
||||
couple_build_.seqs.reserve((size_t)cfg_.max_seqs);
|
||||
|
||||
/* Pinned: uploaded every step, and a pageable source turns the async copy into a staged one
|
||||
* with a host bounce (spec §8). */
|
||||
@@ -321,6 +357,11 @@ int Sampler::stage_alloc() {
|
||||
hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED);
|
||||
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
|
||||
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
|
||||
/* The coupled rows, pinned: uploaded every coupled step, and a pageable source would turn the
|
||||
* async copy into a staged one with a host bounce (spec §8). */
|
||||
if (couple_)
|
||||
couple_stage_ = (RadMtpCoupleState*)rad_dev_alloc(
|
||||
rows * (int64_t)sizeof(RadMtpCoupleState), RAD_MEM_HOST_PINNED);
|
||||
|
||||
/* Logprobs readback; only rank 0 reads it. */
|
||||
if (cfg_.rank == 0) {
|
||||
@@ -337,7 +378,7 @@ int Sampler::stage_alloc() {
|
||||
}
|
||||
|
||||
if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ ||
|
||||
!mask_stage_) {
|
||||
!mask_stage_ || (couple_ && !couple_stage_)) {
|
||||
RAD_ERR("sampler: could not pin %s of staging",
|
||||
humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
|
||||
mask_words_ * 4)).c_str());
|
||||
@@ -354,6 +395,8 @@ void Sampler::stage_free() {
|
||||
if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED);
|
||||
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 (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);
|
||||
@@ -573,7 +616,22 @@ bool Sampler::speculation_fixed(uint64_t req_id) const {
|
||||
|
||||
/* ================================================================== the step path */
|
||||
|
||||
int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
/* BIND THE DRAFT'S OWN STATES. Every row must name this request and the round it belongs to: a state
|
||||
* that arrived under another request's id, or at another round, would be coupled against a law this
|
||||
* step never drew, and the verify would silently apply the wrong Q. */
|
||||
int Sampler::set_mtp_couple(uint64_t req_id, const RadMtpCoupleState* states, int n) {
|
||||
if (!couple_ || n < 0 || n > RAD_MTP_COUPLE_MAX_ROUNDS || (n && !states)) return RAD_E_STATE;
|
||||
const auto it = seqs_.find(req_id);
|
||||
if (it == seqs_.end()) return RAD_E_NOTFOUND;
|
||||
for (int i = 0; i < n; ++i)
|
||||
if (states[i].draw.seq != req_id || states[i].round != i + 1) return RAD_E_STATE;
|
||||
SeqState& s = it->second;
|
||||
for (int i = 0; i < n; ++i) s.couple[i] = states[i];
|
||||
s.couple_n = n;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
|
||||
if (!declared_) return RAD_E_STATE;
|
||||
|
||||
const auto t_build = std::chrono::steady_clock::now();
|
||||
@@ -581,8 +639,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
n_seq_ = 0;
|
||||
any_brk_ = false;
|
||||
any_late_ = false;
|
||||
any_couple_ = false;
|
||||
cur_stage_ = params_stage_;
|
||||
lp_rows_.clear();
|
||||
/* The evidence snapshot this build owns; build_greedy never touches it. */
|
||||
couple_build_.step = step;
|
||||
couple_build_.rows = 0;
|
||||
couple_build_.seqs.clear();
|
||||
|
||||
/* DRY's host half for one row whose history `h[0, take)` is staged. Over the window the
|
||||
* kernel uses (the tail of the row, `dry_penalty_last_n` long when positive) it computes the
|
||||
@@ -669,6 +732,35 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true;
|
||||
if (budget && k > 0) think.push(sp.reasoning, r->draft[k - 1]);
|
||||
const int64_t row = n_seq_++;
|
||||
/* THE COUPLED ROW. `k` is this sampled position's index in the window, so draft row k
|
||||
* verifies against the state the draft that produced it left behind. 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. */
|
||||
if (couple_) {
|
||||
couple_stage_[row] = RadMtpCoupleState{};
|
||||
const auto sit = seqs_.find(r->id);
|
||||
if (sit != seqs_.end() && !sp.greedy() && r->draft && k + 1 < n_pos &&
|
||||
k < sit->second.couple_n) {
|
||||
const RadMtpCoupleState& c = sit->second.couple[k];
|
||||
/* BIND TO THIS ROW: same request and seed, the round this row's draft came
|
||||
* from, the position it samples, and the very token it proposes. Anything else
|
||||
* is a stale state from another step, and coupling against it would apply a law
|
||||
* this step never drew. The rule is rad_mtp_couple_binds (abi/rad_spechub.h);
|
||||
* its position term is rad_mtp_couple_verify_pos, the formula the engine binds
|
||||
* by (core/sched/mtp_couple_bind.h). */
|
||||
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;
|
||||
any_couple_ = true;
|
||||
++couple_build_.rows;
|
||||
auto& q = couple_build_.seqs;
|
||||
size_t j = 0;
|
||||
while (j < q.size() && q[j].first != r->id) ++j;
|
||||
if (j == q.size()) q.emplace_back(r->id, 1);
|
||||
else ++q[j].second;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DeviceSampleParams& p = params_stage_[row];
|
||||
std::memset(&p, 0, sizeof p);
|
||||
@@ -881,6 +973,7 @@ int Sampler::build_greedy(int64_t n) {
|
||||
n_seq_ = n;
|
||||
any_brk_ = false;
|
||||
any_late_ = false;
|
||||
any_couple_ = false;
|
||||
cur_stage_ = greedy_stage_;
|
||||
if (greedy_ready_) return RAD_OK;
|
||||
for (int64_t i = 0; i < cap; ++i) {
|
||||
@@ -951,6 +1044,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
if (any_mask)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_mask_), mask_stage_,
|
||||
n_seq_ * mask_words_ * 4, s));
|
||||
if (any_couple_)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_couple_), couple_stage_,
|
||||
n_seq_ * (int64_t)sizeof(RadMtpCoupleState), s));
|
||||
|
||||
const RadOperand o_logits = opd_rows(logits, n_seq_);
|
||||
const RadOperand o_params = opd_rows(buf_params_, n_seq_);
|
||||
@@ -1027,6 +1123,14 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
RAD_TRY(issue(op_temp_late_, { o_cv, opd_rows(buf_params_late_, n_seq_) }));
|
||||
|
||||
RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
|
||||
/* AFTER the pick, over the same plane: a coupled row replaces the pick's token with the
|
||||
* coupling's, and an unbound row leaves it. The issue is what the evidence line reads: the op
|
||||
* and the build step it belongs to are recorded together, so a staged row set is never
|
||||
* mistaken for an issued verify. */
|
||||
if (any_couple_) {
|
||||
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;
|
||||
}
|
||||
|
||||
/* Copy the logprobs rows to the host behind the pick, on rank 0 only (collect_step asks
|
||||
* it): the summary and the candidate planes, which logprobs_for reads when the summary lacks
|
||||
|
||||
+44
-2
@@ -71,6 +71,7 @@
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_sample.h"
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include "../rad_core.h"
|
||||
#include "grammar.h"
|
||||
@@ -80,6 +81,7 @@
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
@@ -160,13 +162,18 @@ public:
|
||||
/* Whether allows_speculation's answer can no longer change. It changes only when a grammar
|
||||
* whose backend cannot rewind starts to constrain (on a commit). */
|
||||
bool speculation_fixed(uint64_t req_id) const;
|
||||
/* RADIANCE_MTP_COUPLED: bind the per-round states of the linear draft just published, `n` of
|
||||
* them (0 clears). Each must name this request, the round it belongs to, and a `draw.mode` the
|
||||
* row actually ran. RAD_E_NOTFOUND for a request already ended here. */
|
||||
int set_mtp_couple(uint64_t req_id, const RadMtpCoupleState* states, int n);
|
||||
|
||||
/* ---------------------------------------------------------- step path */
|
||||
|
||||
/* Stage this step's parameter rows, penalty history and grammar bitmasks into pinned memory.
|
||||
* Scheduler thread, before the rank threads are released at the barrier. Allocates nothing;
|
||||
* every buffer was sized at declare against max_seqs (spec §3.1). */
|
||||
int build_step(const std::vector<Request*>& reqs);
|
||||
* every buffer was sized at declare against max_seqs (spec §3.1). `step` is the engine's step
|
||||
* the build stages for, carried into the coupling snapshot. */
|
||||
int build_step(const std::vector<Request*>& reqs, int64_t step = -1);
|
||||
|
||||
/* Stage `n` greedy rows for a drafter: no penalties, mask or history, and no RNG use, so
|
||||
* only the argmax runs. Draft output is a proposal checked by a greedy verifier
|
||||
@@ -200,6 +207,29 @@ public:
|
||||
* meaningful only where the row carries RAD_SP_MASK. */
|
||||
const uint32_t* staged_mask(int64_t row) const { return mask_stage_ + row * mask_words_; }
|
||||
int64_t mask_words() const { return mask_words_; }
|
||||
/* Staged row `row`'s bound coupled state, as `run` uploads it: all-zero where the row carries
|
||||
* none (bonus row, greedy row, uncoupled step). Lets a build be checked without a device. */
|
||||
const RadMtpCoupleState& staged_couple(int64_t row) const { return couple_stage_[row]; }
|
||||
/* Whether any row of the last build carries a bound state, i.e. whether `run` issues the
|
||||
* 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_; }
|
||||
|
||||
/* What build_step staged for the coupled verify, frozen there: build_greedy (the drafter's
|
||||
* greedy passes, issued between that build and the step's wait) clears any_couple_ and
|
||||
* replaces cur_stage_/n_seq_, but must not make the evidence unreadable. */
|
||||
struct CoupleBuild {
|
||||
int64_t step = -1; /* the engine step this build staged */
|
||||
int64_t rows = 0; /* bound rows */
|
||||
/* The distinct sequences among them, with their bound rows. */
|
||||
std::vector<std::pair<uint64_t, int64_t>> seqs;
|
||||
};
|
||||
const CoupleBuild& couple_build() const { return couple_build_; }
|
||||
/* The engine step whose build this sampler's run() last issued the verify op for, or -1. The
|
||||
* op and the build it belongs to are recorded together, so an evidence read can tell an
|
||||
* actually issued verify from a staged row set. */
|
||||
int64_t staged_couple_issued_step() const { return couple_issued_step_; }
|
||||
|
||||
private:
|
||||
/* Whether the vocabulary is split, judged by this rank's logit width rather than the rank
|
||||
@@ -218,6 +248,11 @@ private:
|
||||
* newly committed tokens only. Read only when the request carries a thinking budget. */
|
||||
ReasoningCount think;
|
||||
size_t think_seen = 0;
|
||||
/* RADIANCE_MTP_COUPLED: the linear draft's per-round states for the window the scheduler
|
||||
* published, bound by set_mtp_couple and consumed by build_step. `couple_n` is how many of
|
||||
* `couple` are live; 0 for a request whose drafts carry no coupled proposal. */
|
||||
RadMtpCoupleState couple[RAD_MTP_COUPLE_MAX_ROUNDS]{};
|
||||
int couple_n = 0;
|
||||
};
|
||||
|
||||
/* Mask staged row `row` to the reasoning block's close token, once the budget is spent
|
||||
@@ -244,6 +279,7 @@ private:
|
||||
rad_op op_argmax_ = RAD_NULL_HANDLE;
|
||||
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; /* RADIANCE_MTP_COUPLED only */
|
||||
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 */
|
||||
|
||||
@@ -259,6 +295,12 @@ private:
|
||||
rad_buf buf_pairs_ = RAD_NULL_HANDLE; /* this rank's candidates as (global id, logit) */
|
||||
rad_buf buf_lp_ = RAD_NULL_HANDLE; /* sample_logprobs' stats, [rows, lp_width()] */
|
||||
rad_buf buf_lp_g_ = RAD_NULL_HANDLE; /* and every rank's side by side */
|
||||
rad_buf buf_couple_ = RAD_NULL_HANDLE; /* [rows, RAD_MTP_COUPLE_STATE_WORDS], flag only */
|
||||
RadMtpCoupleState* couple_stage_ = nullptr; /* pinned, one row per sampled position */
|
||||
bool couple_ = false; /* RADIANCE_MTP_COUPLED */
|
||||
bool any_couple_ = false; /* does any row this step carry a bound state? */
|
||||
CoupleBuild couple_build_{}; /* what the last build_step staged, for the evidence line */
|
||||
int64_t couple_issued_step_ = -1; /* step whose verify op run() last issued */
|
||||
|
||||
/* Pinned staging, allocated once at declare. */
|
||||
DeviceSampleParams* params_stage_ = nullptr;
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/* mtp_couple_bind.h -- the engine's post-commit binding step for a serial drafting row.
|
||||
*
|
||||
* Engine::finish_serial_drafter calls this after the step's commit, once the card's proposal states
|
||||
* have been read back. It answers two questions the position contract turns on:
|
||||
*
|
||||
* - WHICH LENGTH the next build will stage the row at. That is the request's committed output
|
||||
* length AFTER this commit -- the value the next build_step reads -- and nothing else. It is
|
||||
* deliberately not rebuilt from the draw's pre-commit base plus the slot counter (n_acc): the
|
||||
* two agree only while the commit emits as many tokens as the card accepted, and a max_tokens
|
||||
* or context cut emits fewer.
|
||||
* - WHETHER the row may bind at all. A sequence the plan no longer names, or whose request is no
|
||||
* longer Running, will not sample again: its rows are terminal work (a carried ahead step, a
|
||||
* request that finished on this commit). Binding them would put a coupled verify on the card
|
||||
* for a request that has already left the sampler, which reads as a live coupled round in any
|
||||
* log and is not one.
|
||||
*
|
||||
* The answer comes from Scheduler::committed_seq(), which commit fills under the scheduler lock.
|
||||
* It is deliberately NOT read off the plan's StepEntry::req: after commit that Request may already
|
||||
* have been reaped (release_locked destroys it), and a serial bind that dereferenced it would read
|
||||
* freed memory.
|
||||
*
|
||||
* Here rather than in engine_draft.cpp so the rule can be driven against a real scheduler commit
|
||||
* and the sampler's own build (tests/sched_test.cpp, tests/sample_test.cpp) without an Engine.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "advance.h"
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Where the next build will sample this sequence, after the current step's commit. */
|
||||
struct MtpCoupleBindPoint {
|
||||
bool found = false; /* the committed step carried the sequence */
|
||||
bool live = false; /* and its request was still Running (not finished/cancelled/failed) */
|
||||
uint64_t n_out = 0; /* its committed output length: what the next build reads as n_out */
|
||||
};
|
||||
|
||||
/* Bind `done` rounds of this row's draw to the positions the next build samples. `rb` is round 1
|
||||
* of this row in the engine's readback (stride `rb_stride` states), `tok[rd]` the card's token for
|
||||
* round rd, `S` the card's slot. Fills `out[0, done)` and sets `*n_bound = done`; a sequence that
|
||||
* is not live binds nothing (`*n_bound = 0`, RAD_OK) and leaves `out` untouched. RAD_E_STATE with
|
||||
* `why` for a readback that is not this draw's, or is not a state the proposer could have written.
|
||||
* `base` is never read here: it is the draft's coordinate, not the verify's. */
|
||||
inline int mtp_couple_bind_rounds(const MtpCoupleBindPoint& p, const RadMtpCoupleDraw& d,
|
||||
const RadMtpCoupleState* rb, int rb_stride, int done,
|
||||
const StepSlot& S, int64_t vocab, RadMtpCoupleState* out,
|
||||
int* n_bound, std::string* why) {
|
||||
*n_bound = 0;
|
||||
if (!p.live) return RAD_OK;
|
||||
const bool sampled = d.mode == 1;
|
||||
for (int rd = 1; rd <= done; ++rd) {
|
||||
const RadMtpCoupleState& st = rb[(size_t)(rd - 1) * (size_t)rb_stride];
|
||||
if (std::memcmp(&st.draw, &d, sizeof d) || st.round != rd || st.x != S.tok[rd] ||
|
||||
st.status != (sampled ? 1 : 0) ||
|
||||
(sampled && !rad_mtp_couple_state_valid(st, vocab))) {
|
||||
*why = "MTP coupled: sequence " + std::to_string(d.seq) + " round " +
|
||||
std::to_string(rd) + " returned status " + std::to_string(st.status) +
|
||||
" round " + std::to_string(st.round) + " x " + std::to_string(st.x) +
|
||||
" for card token " + std::to_string(S.tok[rd]) + " (draw " +
|
||||
(std::memcmp(&st.draw, &d, sizeof d) ? "stale" : "current") +
|
||||
"); refusing the step";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RadMtpCoupleState b = st;
|
||||
b.pos = rad_mtp_couple_verify_pos(p.n_out, rd);
|
||||
out[rd - 1] = b;
|
||||
}
|
||||
*n_bound = done;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace rad
|
||||
@@ -0,0 +1,56 @@
|
||||
/* mtp_couple_plan.h -- which draw the engine stages for each serial drafting row.
|
||||
*
|
||||
* Engine::stage_couple_draws (core/engine_draft.cpp) reads two things off the step plan: the draw
|
||||
* of every sequence on its card, and, for each drafting row, the plan entry that names the row's
|
||||
* sequence on the row's card. Both are pure host bookkeeping over StepPlan/SerialRow, so they live
|
||||
* here and are checked against a plan without a card.
|
||||
*
|
||||
* ONE ENTRY PER CARD SLOT. `by_card` is indexed by StepEntry::card, whose range is [0, max_seqs) --
|
||||
* the same range as the StepSlots the advance reads. A plane sized for fewer slots makes every
|
||||
* lookup miss and the first step that drafts refuses with "has no plan entry on its card"; a plane
|
||||
* sized from cfg_.max_seqs is what lets a coupled run stage its first draw.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "batch.h"
|
||||
#include "scheduler.h" /* Scheduler::SerialRow */
|
||||
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Fills `by_card[0, n_card)` from the plan and writes one draw per drafting row to `stage[0, n)`.
|
||||
* RAD_OK, or RAD_E_STATE with `why` set: the plane is too small for the card slots, or a drafting
|
||||
* row's card carries no plan entry naming its sequence (a stale row -- the plugin would refuse the
|
||||
* staged draw, so it is refused here where the row can be named). */
|
||||
inline int mtp_couple_plan_stage(const StepPlan& plan, int n_card, const Scheduler::SerialRow* rows,
|
||||
int n, std::vector<RadMtpCoupleDraw>* by_card,
|
||||
RadMtpCoupleDraw* stage, std::string* why) {
|
||||
if (!by_card || !stage || !why) return RAD_E_INVAL;
|
||||
if ((int)by_card->size() < n_card) {
|
||||
*why = "the draw plane holds " + std::to_string(by_card->size()) +
|
||||
" card slot(s), the step can use " + std::to_string(n_card);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
for (int c = 0; c < n_card; ++c) (*by_card)[(size_t)c] = RadMtpCoupleDraw{};
|
||||
for (const StepEntry& e : plan.e)
|
||||
if (e.req && e.card >= 0 && e.card < n_card)
|
||||
(*by_card)[(size_t)e.card] = { e.req->sp.seed, (uint64_t)e.req->output.size(), e.seq,
|
||||
e.card, e.req->sp.greedy() ? 0u : 1u };
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const Scheduler::SerialRow& row = rows[i];
|
||||
if (row.card < 0 || row.card >= n_card || (*by_card)[(size_t)row.card].seq != row.seq) {
|
||||
*why = "drafting row " + std::to_string(i) + " (sequence " + std::to_string(row.seq) +
|
||||
", card " + std::to_string(row.card) + ") has no plan entry on its card";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
stage[i] = (*by_card)[(size_t)row.card];
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace rad
|
||||
@@ -188,6 +188,7 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
free_cards_[(size_t)c] = (int32_t)(cfg.max_seqs - 1 - c); /* 0 is taken first */
|
||||
reqs_.reserve((size_t)cfg.max_seqs);
|
||||
completed_.reserve((size_t)cfg.max_seqs);
|
||||
committed_.reserve((size_t)cfg.max_seqs);
|
||||
by_id_.reserve((size_t)cfg.max_seqs * 2);
|
||||
hit_blocks_.resize(prog.kv_groups.size());
|
||||
for (auto& v : hit_blocks_) v.reserve(64);
|
||||
@@ -307,6 +308,25 @@ Request* Scheduler::find(uint64_t id) {
|
||||
return it == by_id_.end() ? nullptr : reqs_[(size_t)it->second]->req.get();
|
||||
}
|
||||
|
||||
bool Scheduler::running(uint64_t id) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = by_id_.find(id);
|
||||
if (it == by_id_.end()) return false;
|
||||
const SchedReq& s = *reqs_[(size_t)it->second];
|
||||
return s.req && s.req->state == ReqState::Running;
|
||||
}
|
||||
|
||||
bool Scheduler::committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
for (const CommittedSeq& c : committed_)
|
||||
if (c.seq == seq) {
|
||||
if (n_out) *n_out = c.n_out;
|
||||
if (live) *live = c.live;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = by_id_.find(id);
|
||||
@@ -1804,6 +1824,10 @@ int Scheduler::commit(const StepResult& res) {
|
||||
}
|
||||
step_open_ = false;
|
||||
|
||||
/* What the serial bind reads after commit, copied here while the Requests are still held:
|
||||
* reap() may release a finished one before finish_serial_drafter runs. */
|
||||
committed_.clear();
|
||||
|
||||
const int32_t W = conv_window();
|
||||
|
||||
/* A mixed step leaves decode rows the same replay factors as a decode step (recurrent path
|
||||
@@ -1826,6 +1850,7 @@ int Scheduler::commit(const StepResult& res) {
|
||||
s.pending_free = false;
|
||||
--n_deferred_;
|
||||
}
|
||||
committed_.push_back({e.seq, (uint64_t)r.output.size(), false});
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1982,6 +2007,7 @@ int Scheduler::commit(const StepResult& res) {
|
||||
} else if (eos) {
|
||||
close_request(s, ReqState::Finished, "stop", carried);
|
||||
}
|
||||
committed_.push_back({e.seq, (uint64_t)r.output.size(), r.state == ReqState::Running});
|
||||
}
|
||||
|
||||
m_.prefill_tokens += step_prefill_tok_;
|
||||
|
||||
@@ -133,6 +133,16 @@ public:
|
||||
const int32_t* first_row = nullptr; /* [n_seq] */
|
||||
};
|
||||
|
||||
/* What commit left a sequence at: the length it was committed at and whether it was still
|
||||
* Running when its entry was retired. Copied under the lock in commit because reap() may
|
||||
* destroy the Request before the serial bind reads it; the plan's StepEntry::req must not be
|
||||
* dereferenced after commit. */
|
||||
struct CommittedSeq {
|
||||
uint64_t seq = 0;
|
||||
uint64_t n_out = 0;
|
||||
bool live = false;
|
||||
};
|
||||
|
||||
/* `geo` is the already-resolved chunk geometry. The engine resolves it once because
|
||||
* PrefixCache::configure runs first and needs its checkpoint interval; pass nullptr to
|
||||
* resolve one here. */
|
||||
@@ -161,6 +171,12 @@ public:
|
||||
* under exactly the load that cancels. */
|
||||
int cancel(uint64_t id);
|
||||
Request* find(uint64_t id);
|
||||
/* Whether the request is still admitted and Running, read under the lock. For an evidence
|
||||
* line written after a step's wait, where the staging that named it is older than the wait. */
|
||||
bool running(uint64_t id) const;
|
||||
/* What the step just committed left for `seq`, copied by commit under the lock. False when
|
||||
* that step carried no such sequence. */
|
||||
bool committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const;
|
||||
|
||||
/* Requests that reached a terminal state since the last call, oldest first, swapped into
|
||||
* `out` under the lock (old contents discarded). Only the engine consumes it, to drop
|
||||
@@ -616,6 +632,8 @@ private:
|
||||
* covered, both decayed with the same time constant, so their ratio is tokens over time. */
|
||||
double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0;
|
||||
bool step_open_ = false;
|
||||
/* The step just committed: its sequences' committed length and liveness, in plan order. */
|
||||
std::vector<CommittedSeq> committed_;
|
||||
/* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */
|
||||
DecodeFloor decode_floor_;
|
||||
|
||||
|
||||
+24
@@ -2495,6 +2495,30 @@ resolutions of one op. The one exception is `sample_chain` (below).
|
||||
| `sample_argmax` | `M`(range) `n_vocab` | `logits`, `params` → `token` |
|
||||
| `sample_merge_topk` | `M`(range) `n_cand` | `gathered`, `params` → `cand_idx`, `cand_val` |
|
||||
| `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_couple_propose` and `mtp_couple_verify` are the linear-MTP coupling (`RADIANCE_MTP_COUPLED=1`),
|
||||
and nothing else in the engine knows about coupling. The switch takes `1`, `0` or nothing; any other
|
||||
value refuses the start rather than serving the uncoupled path. Turning coupling on requires the
|
||||
linear serial draft chain: a block drafter (`RAD_DRAFT_BLOCK`) or no drafter at all is refused at
|
||||
bringup, because neither has a per-round draw to couple. The `spechub` plugin ships both rows and
|
||||
their host oracle in one library and marks them per row, so the device rows count as production
|
||||
kernels while the oracle is what the reference gate knows about — on a machine with no card only
|
||||
the oracle is left, and the gate refuses the coupling there. A `RADIANCE_KERNELS` list is exclusive:
|
||||
if it is set, it must name `spechub` or the coupled ops are not loaded at all.
|
||||
|
||||
`mtp_couple_propose` runs on a draft round's
|
||||
final reranked top-8 and samples the proposal `x ~ Q`, where `Q` is the FP64 softmax of those
|
||||
scores at temperature 1; it writes `x` into column 0 of `idx` and one state row per round. A row
|
||||
whose `seq_ids` does not name the card its draw was staged for, or whose shortlist is malformed,
|
||||
leaves column 0 alone with `status = -1`. `mtp_couple_verify` runs after `sample_pick`, over the same
|
||||
final candidate plane, and applies the maximal coupling: the draft is accepted when it equals the
|
||||
token the target itself drew at that position, and otherwise the token is a draw from the FP64
|
||||
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.
|
||||
|
||||
`sample_mask` is where a GBNF grammar lands: the state machine stays on the host, and what crosses
|
||||
is a token bitmask per sequence (~19 KB at a 151K vocab), cheap enough to upload every step. A set
|
||||
|
||||
+13
-9
@@ -528,6 +528,18 @@ AVX_BF16_TARGET static inline void pv_rows(float* acc, int64_t D, const uint32_t
|
||||
for (int v = 0; v < 4; ++v) _mm512_storeu_ps(acc + i * D + c0 + 16 * v, o[i][v]);
|
||||
}
|
||||
|
||||
/* P row (64 floats) to bf16 pairs. Kept out of attn_dense_bf16's OpenMP loop: clang's OpenMP
|
||||
* outlining drops the enclosing function's target attribute, and a bf16 intrinsic in the
|
||||
* outlined body then crashes the backend. The outlined function calls this, as it already calls
|
||||
* qk_rows and pv_rows. */
|
||||
AVX_BF16_TARGET static inline void p_to_bf16_pairs(const float* sr, uint32_t* pr) {
|
||||
_mm512_storeu_si512((void*)pr, (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16),
|
||||
_mm512_loadu_ps(sr)));
|
||||
_mm512_storeu_si512((void*)(pr + 16),
|
||||
(__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48),
|
||||
_mm512_loadu_ps(sr + 32)));
|
||||
}
|
||||
|
||||
AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor* k,
|
||||
const RadTensor* v, const RadTensor* cu,
|
||||
const RadTensor* o, int64_t D, int64_t gqa,
|
||||
@@ -687,15 +699,7 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
|
||||
}
|
||||
}
|
||||
/* P to bf16, round to nearest even: a row's 64 values become its 32 key pairs. */
|
||||
for (int64_t r = 0; r < R; ++r) {
|
||||
const float* sr = S + r * KT;
|
||||
uint32_t* pr = ppack + r * 32;
|
||||
_mm512_storeu_si512((void*)pr, (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16),
|
||||
_mm512_loadu_ps(sr)));
|
||||
_mm512_storeu_si512((void*)(pr + 16),
|
||||
(__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48),
|
||||
_mm512_loadu_ps(sr + 32)));
|
||||
}
|
||||
for (int64_t r = 0; r < R; ++r) p_to_bf16_pairs(S + r * KT, ppack + r * 32);
|
||||
for (int64_t c0 = 0; c0 < D; c0 += 64) {
|
||||
int64_t r = 0;
|
||||
for (; r + 6 <= R; r += 6) pv_rows<6>(acc + r * D, D, ppack + r * 32, vpack, K2, c0);
|
||||
|
||||
@@ -261,7 +261,10 @@ AVX_QB_TARGET static void qb_codes(const QbTab& q, const uint8_t* src, int64_t n
|
||||
* of the j-th 32 codes. A code minus its zero lies in [-31, 31], exact in bf16: `t` holds bf16(i -
|
||||
* 32) for i < 64, which one vpermt2w indexes by code - zero + 32. u5 codes are 40 bits for each
|
||||
* eight, deposited into bytes by pdep (BMI2, which the caller checked). */
|
||||
AVX_QB_TARGET __attribute__((target("bmi2"))) static void qb_codes_zp(
|
||||
/* One target list, not AVX_QB_TARGET plus a second attribute: clang keeps only the last target
|
||||
* attribute on a declaration and would then compile this without the AVX-512 features its
|
||||
* intrinsics need. GCC merges the two; the combined list is the form both accept. */
|
||||
__attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16,bmi2"))) static void qb_codes_zp(
|
||||
const uint8_t* row, int bits, int64_t n, int64_t npad, uint16_t* dst, const int32_t* zr,
|
||||
const __m512i* t) {
|
||||
for (int64_t i = 0; i < npad; i += 32) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# spechub -- the linear-MTP coupling kernels.
|
||||
#
|
||||
# A kernel plugin and nothing else: abi/ is the whole contract, so this builds in radiance's tree or
|
||||
# standalone against an installed prefix
|
||||
# (`cmake -S spechub -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`; see cmake/RadAddPlugin.cmake).
|
||||
#
|
||||
# It declares TWO ops, `mtp_couple_propose` and `mtp_couple_verify`, with one device row and one host
|
||||
# reference row each. The coupling's arithmetic is NOT here: abi/rad_spechub.h defines it inline, host
|
||||
# and device, so the reference, the kernel above it and the engine's own checks are one definition.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(spechub LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
set(SPECHUB_COMMON
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/spechub.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/ref_spechub.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/exports.cpp)
|
||||
|
||||
if(NOT RAD_HIP_FOUND)
|
||||
message(STATUS "spechub: this radiance has no device build -- only the host reference is built")
|
||||
rad_add_plugin(spechub kernels SOURCES ${SPECHUB_COMMON})
|
||||
else()
|
||||
# The owning project must enable HIP itself; enable_language() is project scope. The top-level tree
|
||||
# does it with -DRAD_WITH_HIP=ON, and a standalone build must do the same after project().
|
||||
get_property(spechub_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
|
||||
if(NOT "HIP" IN_LIST spechub_langs)
|
||||
message(FATAL_ERROR "spechub: HIP_SOURCES need `enable_language(HIP)` in this project (set "
|
||||
"-DRAD_WITH_HIP=ON, or enable it after project()).")
|
||||
endif()
|
||||
rad_add_plugin(spechub kernels SOURCES ${SPECHUB_COMMON}
|
||||
HIP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/spechub.hip)
|
||||
target_compile_definitions(spechub PRIVATE RAD_SPECHUB_WITH_DEVICE=1)
|
||||
endif()
|
||||
|
||||
# -ffp-contract=off is a correctness flag here, not a tuning choice: the coupling sums FP64 masses in
|
||||
# ascending candidate order and compares them against a 53-bit uniform, so an FMA that fused a
|
||||
# multiply into one of those sums would move the answer off the reference the tests check.
|
||||
target_compile_options(spechub PRIVATE -ffp-contract=off)
|
||||
@@ -0,0 +1,103 @@
|
||||
/* plugin/spechub/exports.cpp -- the plugin's export block.
|
||||
*
|
||||
* The whole kernel-plugin set (schema count/at, kernel count/at, ABI version, info) and nothing else.
|
||||
* The rows themselves, their schemas and their argument readers are in spechub.cpp; the launches are
|
||||
* spechub.hip (device) and ref_spechub.cpp (host).
|
||||
*
|
||||
* REFERENCE IS PER ROW HERE, not per library. This library carries a real device kernel AND the
|
||||
* host oracle beside it; `rad_plugin_reference` is a whole-library answer, so returning 1 would
|
||||
* mark the device rows as reference too and the engine's reference gate would refuse to serve the
|
||||
* coupled path at all (RAD_E_NOKERNEL before the first request). The device rows therefore report
|
||||
* 0 and the host rows 1 through `rad_kernel_reference`, and `rad_plugin_reference` stays 0 so the
|
||||
* library is not ranked below the kernel libraries it belongs with. On a machine with no card only
|
||||
* the two reference rows exist, and the gate then correctly refuses the coupling: there is no
|
||||
* device kernel to serve it.
|
||||
*
|
||||
* What puts a coupled row into serving is the architecture declaring the op, which it only does
|
||||
* with RADIANCE_MTP_COUPLED=1; the plugin and the loader never read that switch.
|
||||
*/
|
||||
#include "spechub.h"
|
||||
|
||||
#include "../../libr4d/r4d_emit.h" /* only for the three globals it declares */
|
||||
|
||||
/* THE DISPATCH LOG IS THIS DSO'S OWN. r4d_emit.h routes every launch through this recorder so a test
|
||||
* can name the functions it dispatched, but the loader maps plugins RTLD_LOCAL: a plugin cannot
|
||||
* import libr4d's copy, and an unresolved symbol refuses the whole library at load. Defining them
|
||||
* here gives r4d_emit.h exactly what it declares and leaves the recorder inert -- nothing in this
|
||||
* plugin sets the log. It is a tool's, never consulted on a serving path. */
|
||||
const void** r4d_dispatch_log = nullptr;
|
||||
int r4d_dispatch_cap = 0;
|
||||
int r4d_dispatch_n = 0;
|
||||
|
||||
namespace {
|
||||
const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, "spechub", "0.1.0",
|
||||
"Linear-MTP maximal coupling: a Q draw per round and the coupled target verify", "gfx1201",
|
||||
};
|
||||
} /* namespace */
|
||||
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
|
||||
/* Mixed library: 0, and the per-row answer below does the classifying. */
|
||||
extern "C" int rad_plugin_reference(void) { return 0; }
|
||||
|
||||
/* Row layout is [device 0, device 1, ref 0, ref 1] with a card, [ref 0, ref 1] without. The
|
||||
* device rows are the production kernels; the host rows are the oracle rad-kbench checks them
|
||||
* against and the only thing a card-less machine can run. */
|
||||
extern "C" int rad_kernel_reference(int i) {
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
return (i == 0 || i == 1) ? 0 : 1;
|
||||
#else
|
||||
(void)i;
|
||||
return 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" int rad_kernel_schema_count(void) { return rad_spechub_schema_count(); }
|
||||
extern "C" const RadOpSchema* rad_kernel_schema_at(int i) { return rad_spechub_schema_at(i); }
|
||||
|
||||
/* Two device rows and the two host references beside them, in that order. A card-less machine loads
|
||||
* the same library and resolves only the reference rows. */
|
||||
extern "C" int rad_kernel_count(void) {
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
return 4;
|
||||
#else
|
||||
return 2;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" const RadKernelInfo* rad_kernel_at(int i) {
|
||||
const int op = i & 1;
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
if (i == 0 || i == 1) {
|
||||
static const RadKernelInfo r[2] = {
|
||||
rad_spechub_row(0, rad_mine_mtp_couple_propose_launch),
|
||||
rad_spechub_row(1, rad_mine_mtp_couple_verify_launch),
|
||||
};
|
||||
return &r[i];
|
||||
}
|
||||
#endif
|
||||
static const RadKernelInfo ref[2] = {
|
||||
[] {
|
||||
RadKernelInfo x = rad_spechub_row(0, rad_ref_mtp_couple_propose);
|
||||
x.name = "ref_mtp_couple_propose";
|
||||
x.domain = RAD_DOMAIN_HOST;
|
||||
x.priority = 0;
|
||||
return x;
|
||||
}(),
|
||||
[] {
|
||||
RadKernelInfo x = rad_spechub_row(1, rad_ref_mtp_couple_verify);
|
||||
x.name = "ref_mtp_couple_verify";
|
||||
x.domain = RAD_DOMAIN_HOST;
|
||||
x.priority = 0;
|
||||
return x;
|
||||
}(),
|
||||
};
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
if (i < 2 || i > 3) return nullptr;
|
||||
return &ref[op];
|
||||
#else
|
||||
if (i < 0 || i > 1) return nullptr;
|
||||
return &ref[i];
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/* plugin/spechub/ref_spechub.cpp -- the two coupling ops on the host.
|
||||
*
|
||||
* ONE ROW AT A TIME, in the same order and with the same arithmetic as the kernel: these functions
|
||||
* call the very same abi/rad_spechub.h helpers the device launch is built from, so an op and its
|
||||
* reference cannot drift. What they add is the row loop and the same eligibility gate.
|
||||
*
|
||||
* This is the oracle rad-kbench checks the device rows against, and the only implementation a
|
||||
* machine with no card can run.
|
||||
*/
|
||||
#include "spechub.h"
|
||||
|
||||
int rad_ref_mtp_couple_propose(const RadArgs* a, RadStream) {
|
||||
RadMtpCoupleProposeCall c{};
|
||||
const int rc = rad_mtp_couple_propose_args(a, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
for (int64_t row = 0; row < c.M; ++row) rad_mtp_couple_propose_row(c, row);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int rad_ref_mtp_couple_verify(const RadArgs* a, RadStream) {
|
||||
RadMtpCoupleVerifyCall c{};
|
||||
const int rc = rad_mtp_couple_verify_args(a, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
for (int64_t row = 0; row < c.M; ++row) rad_mtp_couple_verify_row(c, row);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
/* plugin/spechub/spechub.cpp -- the two coupling ops' schemas, shapes and argument validation.
|
||||
*
|
||||
* Shape hooks and geometry only: the arithmetic is in abi/rad_spechub.h (inline, host and device) and
|
||||
* the launches are in spechub.hip and ref_spechub.cpp. This file is host C++ and compiles with no
|
||||
* card, which is what lets a card-less machine check the plugin's schema and shapes.
|
||||
*/
|
||||
#include "spechub.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstddef>
|
||||
|
||||
namespace {
|
||||
|
||||
#define PI(k) { k, RAD_P_INT, RAD_REQUIRED, 0 }
|
||||
const RadParamSpec kProposeParams[] = {
|
||||
PI("M"), PI("n_vocab"), PI("round"), PI("max_rounds"),
|
||||
};
|
||||
const RadParamSpec kVerifyParams[] = { PI("M"), PI("n_cand"), PI("n_vocab") };
|
||||
#undef PI
|
||||
|
||||
/* `idx` is INOUT: the round's proposal IS the head's column 0, and a sampled row overwrites it. */
|
||||
const RadOperandSpec kProposeOperands[] = {
|
||||
{ "idx", RAD_OPD_INOUT, 0 },
|
||||
{ "val", RAD_OPD_IN, 0 },
|
||||
{ "seq_ids", RAD_OPD_IN, 0 },
|
||||
{ "draw", RAD_OPD_IN, 0 },
|
||||
{ "state", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
|
||||
/* The verify runs after the ordinary pick over the SAME final candidate plane, so its operands are
|
||||
* the sampler's own: candidates, parameter rows, coupled state rows, and the token plane the pick
|
||||
* already wrote. */
|
||||
const RadOperandSpec kVerifyOperands[] = {
|
||||
{ "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 },
|
||||
};
|
||||
|
||||
const RadOpSchema kSchemas[] = {
|
||||
{ "mtp_couple_propose", kProposeParams, 4, kProposeOperands, 5,
|
||||
"Linear MTP round `round`: x~Q, Q = FP64 T1 softmax of the final top8 scores; x into idx "
|
||||
"column 0 and the state into state[round-1][row]. mode0 rows keep column 0 (status 0); bad "
|
||||
"ids/scores or seq_ids != draw.card keep it too (status -1)." },
|
||||
{ "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 "
|
||||
"(P,Q) admit no coupling keep the ordinary token." },
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int rad_spechub_schema_count() { return 2; }
|
||||
const RadOpSchema* rad_spechub_schema_at(int i) {
|
||||
return i >= 0 && i < 2 ? &kSchemas[i] : nullptr;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* The geometry both hooks and the arg readers agree on. `op` 0 proposes, 1 verifies. A RANGE `M`
|
||||
* reads as its high bound, which is what a shape hook must do: it sizes buffers before selection has
|
||||
* collapsed anything, so it describes the whole band. */
|
||||
int couple_geometry(const RadParam* p, int n, int op, bool range, int64_t* M, int64_t* vocab,
|
||||
int64_t* n_cand) {
|
||||
if (!p) return RAD_E_INVAL;
|
||||
*M = range ? rad_param_getdim(p, n, "M", 0) : rad_param_geti(p, n, "M", 0);
|
||||
*vocab = rad_param_geti(p, n, "n_vocab", 0);
|
||||
*n_cand = op ? rad_param_geti(p, n, "n_cand", 0) : 8;
|
||||
if (*M < 1 || *M > INT32_MAX || *vocab < 1 || *vocab > INT32_MAX) return RAD_E_UNSUPPORTED;
|
||||
if (*n_cand < 1 || *n_cand > INT32_MAX) return RAD_E_UNSUPPORTED;
|
||||
if (!op) {
|
||||
const int64_t round = rad_param_geti(p, n, "round", 0);
|
||||
const int64_t rounds = rad_param_geti(p, n, "max_rounds", 0);
|
||||
if (rounds < 1 || rounds > RAD_MTP_COUPLE_MAX_ROUNDS || round < 1 || round > rounds)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Does one operand's extent fit the shape its hook declares? A row-owning kernel reads a whole row,
|
||||
* so the last axis is structural and every leading one is a row count. */
|
||||
int span(const RadTensor& t, const RadOpdDesc& d, uint64_t* bytes) {
|
||||
if (!t.data || (uintptr_t)t.data % 4) return RAD_E_INVAL;
|
||||
if (t.dtype != d.dtype) return RAD_E_DTYPE;
|
||||
if (t.rank != d.rank) return RAD_E_SHAPE;
|
||||
uint64_t words = 1;
|
||||
for (int j = (int)d.rank - 1; j >= 0; --j) {
|
||||
if (t.shape[j] < 1 || t.shape[j] > INT32_MAX || (d.shape[j] > 0 && t.shape[j] != d.shape[j]))
|
||||
return RAD_E_SHAPE;
|
||||
if (t.stride[j] < 1 || (j == (int)d.rank - 1 && t.stride[j] != 1) ||
|
||||
(j < (int)d.rank - 1 && (uint64_t)t.stride[j] < words))
|
||||
return RAD_E_STRIDE;
|
||||
const uint64_t extent = (uint64_t)(t.shape[j] - 1);
|
||||
if (extent && (uint64_t)t.stride[j] > (INT64_MAX / 4 - words) / extent) return RAD_E_SHAPE;
|
||||
words += extent * (uint64_t)t.stride[j];
|
||||
}
|
||||
*bytes = words * 4;
|
||||
if ((uintptr_t)t.data > UINTPTR_MAX - *bytes) return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int rad_mtp_couple_propose_shape(const RadParam* p, int n, int i, RadOpdDesc* out) {
|
||||
if (!out || i < 0 || i >= 5) return RAD_E_INVAL;
|
||||
int64_t M, v, nc;
|
||||
int rc = couple_geometry(p, n, 0, 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] = 8;
|
||||
if (i == 0) { d.fill = RAD_FILL_INDEX; d.idx_max = (int32_t)v; }
|
||||
if (i == 1) d.dtype = RAD_F32;
|
||||
if (i == 2) { d.rank = 1; d.fill = RAD_FILL_INDEX; d.idx_max = (int32_t)M; }
|
||||
if (i == 3) { d.dtype = RAD_U32; d.shape[1] = RAD_MTP_COUPLE_DRAW_WORDS; }
|
||||
if (i == 4) {
|
||||
/* Rounds are the state plane's leading axis, and `max_rounds` is exactly the bound the caller
|
||||
* sized it at. */
|
||||
const int64_t rounds = rad_param_geti(p, n, "max_rounds", 1);
|
||||
d.dtype = RAD_U32;
|
||||
d.rank = 3;
|
||||
d.shape[0] = rounds;
|
||||
d.shape[1] = M;
|
||||
d.shape[2] = RAD_MTP_COUPLE_STATE_WORDS;
|
||||
}
|
||||
*out = d;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int rad_mtp_couple_verify_shape(const RadParam* p, int n, int i, RadOpdDesc* out) {
|
||||
if (!out || i < 0 || i >= 5) return RAD_E_INVAL;
|
||||
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] = nc;
|
||||
if (i == 1) d.dtype = RAD_F32;
|
||||
if (i == 2 || i == 3) {
|
||||
d.dtype = RAD_U32;
|
||||
d.shape[1] = i == 2 ? 24 : RAD_MTP_COUPLE_STATE_WORDS;
|
||||
}
|
||||
if (i == 4) d.rank = 1;
|
||||
*out = d;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The resolved `M` is the arena band's ceiling; this issue may carry fewer live rows, and both
|
||||
* kernels take the row count from operand 0. Dim 0 is narrowed to the live rows before each
|
||||
* operand's extent is checked, the wire planes must be eight-byte aligned with an even row stride,
|
||||
* and separate storage is part of the contract: an aliased pair would let a write land on a read. */
|
||||
int rad_couple_validate(const RadArgs* a, int op, int64_t* M, int64_t* vocab, int64_t* n_cand) {
|
||||
if (!a || !a->t || a->n_t != 5) return RAD_E_INVAL;
|
||||
int rc = couple_geometry(a->p, a->n_p, op, false, M, vocab, n_cand);
|
||||
if (rc != RAD_OK) return rc;
|
||||
const int64_t live = a->t[0].rank ? a->t[0].shape[0] : 0;
|
||||
if (live < 1 || live > *M) return RAD_E_SHAPE;
|
||||
*M = live;
|
||||
const int64_t rounds = op ? 1 : rad_param_geti(a->p, a->n_p, "max_rounds", 1);
|
||||
uint64_t bytes[5] = {};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
RadOpdDesc d{};
|
||||
rc = op ? rad_mtp_couple_verify_shape(a->p, a->n_p, i, &d)
|
||||
: rad_mtp_couple_propose_shape(a->p, a->n_p, i, &d);
|
||||
if (rc != RAD_OK) return rc;
|
||||
d.shape[0] = *M;
|
||||
/* `seq_ids` covers the whole batch and the state plane is [rounds, rows]; both are checked
|
||||
* below rather than against the live row count. */
|
||||
if (!op && i == 2) d.shape[0] = 0;
|
||||
if (!op && i == 4) { d.shape[0] = rounds; d.shape[1] = 0; }
|
||||
/* The sampler exposes a flat token plane and its production [M, 1] one. */
|
||||
if (op && i == 4 && a->t[i].rank == 2) { d.rank = 2; d.shape[1] = 1; }
|
||||
if ((rc = span(a->t[i], d, &bytes[i])) != RAD_OK) return rc;
|
||||
if (!op && i == 2 && a->t[i].shape[0] < *M) return RAD_E_SHAPE;
|
||||
if (!op && i == 4 && a->t[i].shape[1] < *M) return RAD_E_SHAPE;
|
||||
const bool wire = op ? (i == 2 || i == 3) : (i == 3 || i == 4);
|
||||
if (wire && ((uintptr_t)a->t[i].data % 8 || a->t[i].stride[0] % 2 ||
|
||||
(a->t[i].rank == 3 && a->t[i].stride[1] % 2)))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* An even ROW stride keeps every shortlist row 8-byte aligned; the innermost stride is 1. */
|
||||
if (!op && a->t[0].stride[0] % 2) return RAD_E_STRIDE;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
for (int j = i + 1; j < 5; ++j) {
|
||||
const uintptr_t x = (uintptr_t)a->t[i].data, y = (uintptr_t)a->t[j].data;
|
||||
if (x < y + bytes[j] && y < x + bytes[i]) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int rad_mtp_couple_propose_args(const RadArgs* a, RadMtpCoupleProposeCall* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
int64_t M, v, nc;
|
||||
const int rc = rad_couple_validate(a, 0, &M, &v, &nc);
|
||||
if (rc != RAD_OK) return rc;
|
||||
RadMtpCoupleProposeCall c{};
|
||||
c.M = M;
|
||||
c.vocab = v;
|
||||
c.round = (int)rad_param_geti(a->p, a->n_p, "round", 0);
|
||||
c.idx = (int32_t*)a->t[0].data;
|
||||
c.val = (const float*)a->t[1].data;
|
||||
c.card = (const int32_t*)a->t[2].data;
|
||||
c.draw = (const uint32_t*)a->t[3].data;
|
||||
c.state = (uint32_t*)a->t[4].data;
|
||||
c.ld_idx = a->t[0].stride[0];
|
||||
c.ld_val = a->t[1].stride[0];
|
||||
c.ld_draw = a->t[3].stride[0];
|
||||
c.st_round = a->t[4].stride[0];
|
||||
c.st_row = a->t[4].stride[1];
|
||||
*out = c;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int rad_mtp_couple_verify_args(const RadArgs* a, RadMtpCoupleVerifyCall* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
int64_t M, v, nc;
|
||||
const int rc = rad_couple_validate(a, 1, &M, &v, &nc);
|
||||
if (rc != RAD_OK) return rc;
|
||||
RadMtpCoupleVerifyCall c{};
|
||||
c.M = M;
|
||||
c.vocab = v;
|
||||
c.n_cand = nc;
|
||||
c.idx = (const int32_t*)a->t[0].data;
|
||||
c.val = (const float*)a->t[1].data;
|
||||
c.params = (const uint32_t*)a->t[2].data;
|
||||
c.state = (const uint32_t*)a->t[3].data;
|
||||
c.token = (int32_t*)a->t[4].data;
|
||||
for (int i = 0; i < 5; ++i) c.ld[i] = a->t[i].stride[0];
|
||||
*out = c;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
RadKernelInfo rad_spechub_row(int i, RadLaunchFn launch) {
|
||||
RadKernelInfo r{};
|
||||
r.name = i ? "spechub_mtp_couple_verify" : "spechub_mtp_couple_propose";
|
||||
r.op = i ? "mtp_couple_verify" : "mtp_couple_propose";
|
||||
r.family = "draft";
|
||||
r.computes = i ? "maximal coupling over the surviving target candidates, FP64 P"
|
||||
: "x~Q over the final top8, FP64 T1 softmax";
|
||||
r.shape = i ? "M,n_cand,n_vocab" : "M,n_vocab,round,max_rounds<=8";
|
||||
r.dtypes = "f32,i32,u32";
|
||||
r.domain = RAD_DOMAIN_DEVICE;
|
||||
r.priority = 100;
|
||||
r.launch = launch;
|
||||
r.opd_shape = i ? rad_mtp_couple_verify_shape : rad_mtp_couple_propose_shape;
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/* plugin/spechub/spechub.h -- the plugin-private contract between its host half and its kernels.
|
||||
*
|
||||
* Plugin-private ON PURPOSE: core/ must never include this, and everything the CORE needs (the wire
|
||||
* row and the coupling arithmetic) already lives in abi/rad_spechub.h. Only the packed call structs
|
||||
* and the argument readers are here, shared by the host reference and the device launch.
|
||||
*/
|
||||
#ifndef RAD_PLUGIN_SPECHUB_H
|
||||
#define RAD_PLUGIN_SPECHUB_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h" /* rad_param_geti/getdim: the pure readers, inline and total */
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_SPECHUB_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_SPECHUB_HD
|
||||
#endif
|
||||
|
||||
/* A draft round's operands, packed once for both the device launch and the host reference. */
|
||||
struct RadMtpCoupleProposeCall {
|
||||
int32_t* idx; /* [M, 8] INOUT: this rank's shortlist; column 0 is the proposal */
|
||||
const float* val; /* [M, 8] the shortlist's scores */
|
||||
const int32_t* card; /* [batch] RadBatch::seq_ids: the slot the advance writes */
|
||||
const uint32_t* draw; /* [M, DRAW_WORDS] RadMtpCoupleDraw */
|
||||
uint32_t* state; /* [rounds, M, STATE_WORDS] RadMtpCoupleState */
|
||||
int64_t M;
|
||||
int64_t vocab;
|
||||
int64_t ld_idx, ld_val, ld_draw, st_round, st_row;
|
||||
int round;
|
||||
};
|
||||
|
||||
/* The verify's operands: the sampler's own candidate plane, its parameter rows, the bound state
|
||||
* rows and the token plane the pick already wrote. */
|
||||
struct RadMtpCoupleVerifyCall {
|
||||
const int32_t* idx; /* [M, n_cand] */
|
||||
const float* val; /* [M, n_cand] */
|
||||
const uint32_t* params; /* [M, 24 words] RadSampleParams */
|
||||
const uint32_t* state; /* [M, STATE_WORDS] RadMtpCoupleState */
|
||||
int32_t* token; /* [M] or [M, 1] */
|
||||
int64_t M, n_cand, vocab, ld[5];
|
||||
};
|
||||
|
||||
int rad_mtp_couple_propose_shape(const RadParam*, int, int, RadOpdDesc*);
|
||||
int rad_mtp_couple_verify_shape(const RadParam*, int, int, RadOpdDesc*);
|
||||
int rad_mtp_couple_propose_args(const RadArgs*, RadMtpCoupleProposeCall*);
|
||||
int rad_mtp_couple_verify_args(const RadArgs*, RadMtpCoupleVerifyCall*);
|
||||
|
||||
/* The geometry/validation the shape hooks and the arg readers share. `op` 0 proposes, 1 verifies. */
|
||||
int rad_couple_validate(const RadArgs*, int op, int64_t* M, int64_t* vocab, int64_t* n_cand);
|
||||
|
||||
/* The op set. Two schemas, two device rows and two host-reference rows. */
|
||||
int rad_spechub_schema_count();
|
||||
const RadOpSchema* rad_spechub_schema_at(int i);
|
||||
RadKernelInfo rad_spechub_row(int i, RadLaunchFn launch);
|
||||
|
||||
/* The launches. */
|
||||
int rad_mine_mtp_couple_propose_launch(const RadArgs*, RadStream);
|
||||
int rad_mine_mtp_couple_verify_launch(const RadArgs*, RadStream);
|
||||
int rad_ref_mtp_couple_propose(const RadArgs*, RadStream);
|
||||
int rad_ref_mtp_couple_verify(const RadArgs*, RadStream);
|
||||
|
||||
/* THE PROPOSE'S HOST ARITHMETIC, host and device. One definition of "x ~ Q over the final eight":
|
||||
* column 0 is what ADV_ROUND/ADV_TAKE take, and it becomes x only for a valid sampled row. */
|
||||
static inline RAD_SPECHUB_HD void rad_mtp_couple_propose_row(const RadMtpCoupleProposeCall& c,
|
||||
int64_t row) {
|
||||
RadMtpCoupleState s{};
|
||||
s.draw = *reinterpret_cast<const RadMtpCoupleDraw*>(c.draw + row * c.ld_draw);
|
||||
int32_t* idx = c.idx + row * c.ld_idx;
|
||||
s.round = c.round;
|
||||
s.x = idx[0];
|
||||
for (int i = 0; i < 8; ++i) s.ids[i] = -1;
|
||||
if (s.draw.mode == 1) {
|
||||
s.status = -1;
|
||||
if (s.draw.card == c.card[row] &&
|
||||
rad_mtp_couple_build_q(idx, c.val + row * c.ld_val, c.vocab, &s)) {
|
||||
const double u = rad_spechub_uniform(s.draw.seed, s.draw.base,
|
||||
RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)c.round);
|
||||
s.x = s.ids[rad_mtp_couple_pick(s, u)];
|
||||
s.status = 1;
|
||||
idx[0] = s.x;
|
||||
} else {
|
||||
s.count = 0;
|
||||
for (int i = 0; i < 8; ++i) { s.ids[i] = -1; s.q[i] = 0; }
|
||||
}
|
||||
}
|
||||
*reinterpret_cast<RadMtpCoupleState*>(c.state + (c.round - 1) * c.st_round + row * c.st_row) = s;
|
||||
}
|
||||
|
||||
/* THE VERIFY'S, after sample_pick. Rows without a valid bound state keep the ordinary token. */
|
||||
static inline RAD_SPECHUB_HD void rad_mtp_couple_verify_row(const RadMtpCoupleVerifyCall& c,
|
||||
int64_t row) {
|
||||
const auto& s = *reinterpret_cast<const RadMtpCoupleState*>(c.state + row * c.ld[3]);
|
||||
if (s.status != 1) return;
|
||||
const auto& p = *reinterpret_cast<const RadSampleParams*>(c.params + row * c.ld[2]);
|
||||
if ((p.flags & RAD_SP_GREEDY) || s.draw.seed != p.seed || s.pos != p.pos ||
|
||||
!rad_mtp_couple_state_valid(s, c.vocab))
|
||||
return;
|
||||
int32_t out = -1;
|
||||
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;
|
||||
}
|
||||
|
||||
#undef RAD_SPECHUB_HD
|
||||
#endif /* RAD_PLUGIN_SPECHUB_H */
|
||||
@@ -0,0 +1,182 @@
|
||||
/* plugin/spechub/spechub.hip -- the device launches for the two coupling ops.
|
||||
*
|
||||
* The kernels are one workgroup per sampled row, and the workgroup is the whole parallel machine
|
||||
* the verify needs: the cuts, the residual mass and the walk are all row-local. The arithmetic
|
||||
* itself is abi/rad_spechub.h (inline, host and device), so this file is a launch and nothing more
|
||||
* -- which is why the host reference and the kernel can be compared on the same bytes.
|
||||
*
|
||||
* STRICT FP64. The coupling sums FP64 masses in ascending candidate order and compares them against
|
||||
* a 53-bit uniform; --fast-math would let the compiler contract those sums and change the answer.
|
||||
* The #error below is the compile-time half of that, and CMakeLists sets -ffp-contract=off.
|
||||
*/
|
||||
#ifdef __FAST_MATH__
|
||||
#error "the MTP coupling requires strict FP64 arithmetic: build without -ffast-math"
|
||||
#endif
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include "spechub.h"
|
||||
#include "../../libr4d/r4d_emit.h"
|
||||
|
||||
namespace {
|
||||
|
||||
/* One thread a row: both ops are row-local and the M is the number of sampled positions. */
|
||||
__global__ void propose(RadMtpCoupleProposeCall c) {
|
||||
const int64_t row = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (row < c.M) rad_mtp_couple_propose_row(c, row);
|
||||
}
|
||||
|
||||
/* ONE WORKGROUP A ROW, 128 threads. The verify's planes are shared: at n_cand 1024 the weights and
|
||||
* the residual masses are 16 KiB of FP64, and the mass walk reads them once per candidate rather
|
||||
* than once per thread. */
|
||||
constexpr int kThreads = 128;
|
||||
constexpr int64_t kMaxCand = 1024;
|
||||
|
||||
__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,
|
||||
int64_t ld4) {
|
||||
RadMtpCoupleVerifyCall c{ idx, values, params, state, token, M, n_cand, vocab,
|
||||
{ ld0, ld1, ld2, ld3, ld4 } };
|
||||
const int64_t row = blockIdx.x;
|
||||
if (row >= M) return;
|
||||
/* ABOVE THE NARROW BAND the general algorithm runs single-threaded: the shared planes are sized
|
||||
* for kMaxCand and a wider row would overrun them. That is the 1025-and-above fallback, and it is
|
||||
* the same FP64 order the cooperative path below keeps. */
|
||||
if (n_cand > kMaxCand) {
|
||||
if (threadIdx.x == 0) rad_mtp_couple_verify_row(c, row);
|
||||
return;
|
||||
}
|
||||
/* THE TWO COOPERATIVE PLANES. `weight` is P's unnormalised FP64 mass per candidate and `mass` is
|
||||
* the residual (P-Q)+ per candidate; both are written by the whole workgroup and read in
|
||||
* ASCENDING candidate order afterwards, which is the order the serial algorithm sums in. */
|
||||
__shared__ double weight[kMaxCand], mass[kMaxCand], pq[8], sum;
|
||||
__shared__ float top;
|
||||
__shared__ int eligible, first[8], ix, dominated;
|
||||
const auto& s = *reinterpret_cast<const RadMtpCoupleState*>(c.state + row * c.ld[3]);
|
||||
const auto& p = *reinterpret_cast<const RadSampleParams*>(c.params + row * c.ld[2]);
|
||||
const int32_t* ids = c.idx + row * c.ld[0];
|
||||
const float* val = c.val + row * c.ld[1];
|
||||
/* The eligibility gate is the DECIDE's own: the same state, seed, position and target check, so
|
||||
* an unbound row writes nothing and keeps the ordinary token. */
|
||||
if (threadIdx.x == 0) {
|
||||
eligible = 0;
|
||||
if (s.status == 1 && !(p.flags & RAD_SP_GREEDY) && s.draw.seed == p.seed &&
|
||||
s.pos == p.pos && rad_mtp_couple_state_valid(s, c.vocab)) {
|
||||
float maximum = -INFINITY;
|
||||
bool valid = true;
|
||||
for (int64_t j = 0; j < c.n_cand; ++j) {
|
||||
if (ids[j] < 0) continue;
|
||||
if (ids[j] >= c.vocab || val[j] != val[j] || val[j] == INFINITY) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
if (val[j] > maximum) maximum = val[j];
|
||||
}
|
||||
if (valid && maximum != -INFINITY) { top = maximum; eligible = 1; }
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (!eligible) return;
|
||||
/* THE FP64 MASS, done COOPERATIVELY: each thread takes a strided slice of the candidates and
|
||||
* writes exp(v - max) into its own slot. No cross-thread reduction happens here -- the sum below
|
||||
* is still walked in ascending order by one thread, which is what keeps the sum bit-identical to
|
||||
* the serial algorithm. */
|
||||
for (int64_t j = threadIdx.x; j < c.n_cand; j += blockDim.x)
|
||||
if (ids[j] >= 0 && val[j] != -INFINITY) weight[j] = ::exp((double)val[j] - top);
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0) {
|
||||
sum = 0;
|
||||
for (int k = 0; k < s.count; ++k) { pq[k] = 0; first[k] = -1; }
|
||||
for (int64_t j = 0; j < c.n_cand; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
const double w = weight[j];
|
||||
sum += w;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (ids[j] == s.ids[k]) {
|
||||
if (first[k] < 0) first[k] = (int)j;
|
||||
pq[k] += w;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) eligible = 0;
|
||||
if (eligible) {
|
||||
ix = -1;
|
||||
dominated = true;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
pq[k] /= sum;
|
||||
dominated = dominated && pq[k] >= s.q[k];
|
||||
if (s.ids[k] == s.x) ix = k;
|
||||
}
|
||||
if (ix < 0) eligible = 0;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (!eligible) return;
|
||||
/* THE RESIDUAL MASS, COOPERATIVELY. A Q token contributes max(0, P-Q) ONCE, at its first
|
||||
* occurrence (`first[k]`), which is the duplicate-first rule; every other candidate contributes
|
||||
* its own P. The plane is written per slot, so the walk below reads it in candidate order. */
|
||||
for (int64_t j = threadIdx.x; j < c.n_cand; j += blockDim.x) {
|
||||
double m = 0;
|
||||
if (ids[j] >= 0 && val[j] != -INFINITY) {
|
||||
bool in_q = false;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (s.ids[k] == ids[j]) {
|
||||
in_q = true;
|
||||
if (first[k] == (int)j) m = rad_spechub_positive(pq[k] - s.q[k]);
|
||||
break;
|
||||
}
|
||||
if (!in_q) m = weight[j] / sum;
|
||||
}
|
||||
mass[j] = m;
|
||||
}
|
||||
__syncthreads();
|
||||
if (threadIdx.x != 0) return;
|
||||
|
||||
/* THE ORDERED WALK. One thread, ascending candidate index, exactly the serial algorithm's
|
||||
* arithmetic: the sums above and this walk are what the coupling's bit-exactness rests on, and
|
||||
* parallelising either would reorder them. */
|
||||
double resid = 0;
|
||||
for (int64_t j = 0; j < c.n_cand; ++j) resid += mass[j];
|
||||
int32_t out = -1;
|
||||
const double u_resid = rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_RESID);
|
||||
if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) {
|
||||
double cdf = u_resid * sum;
|
||||
for (int64_t j = 0; j < c.n_cand; ++j)
|
||||
if (ids[j] >= 0 && val[j] != -INFINITY) {
|
||||
const double w = weight[j];
|
||||
if (w > 0) { out = ids[j]; cdf -= w; if (cdf < 0) break; }
|
||||
}
|
||||
} else if (pq[ix] >= s.q[ix] ||
|
||||
rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_ACCEPT) * s.q[ix] < pq[ix]) {
|
||||
out = s.x;
|
||||
} else {
|
||||
double cdf = u_resid * resid;
|
||||
for (int64_t j = 0; j < c.n_cand; ++j) {
|
||||
if (ids[j] == s.x) continue;
|
||||
const double m = mass[j];
|
||||
if (m > 0) { out = ids[j]; cdf -= m; if (cdf < 0) break; }
|
||||
}
|
||||
}
|
||||
c.token[row * c.ld[4]] = out;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int rad_mine_mtp_couple_propose_launch(const RadArgs* a, RadStream stream) {
|
||||
RadMtpCoupleProposeCall c{};
|
||||
const int rc = rad_mtp_couple_propose_args(a, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return R4D_EMIT(stream, propose, dim3((unsigned)((c.M + 63) / 64)), dim3(64), 0, c);
|
||||
}
|
||||
|
||||
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. */
|
||||
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]);
|
||||
}
|
||||
@@ -240,6 +240,22 @@ if(RAD_HIP_FOUND)
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
# spechub_wiring_test dlopens the built spechub plugin and checks how its rows are classified: the
|
||||
# device rows must be production kernels and the host oracle rows must stay reference. It needs the
|
||||
# library path and the same RAD_SPECHUB_WITH_DEVICE answer the plugin was built with.
|
||||
if(TARGET spechub)
|
||||
target_link_libraries(spechub_wiring_test PRIVATE ${CMAKE_DL_LIBS})
|
||||
target_compile_definitions(spechub_wiring_test PRIVATE
|
||||
RAD_SPECHUB_LIB="${RAD_PLUGIN_OUT}/kernels/spechub.so")
|
||||
if(RAD_HIP_FOUND)
|
||||
target_compile_definitions(spechub_wiring_test PRIVATE RAD_SPECHUB_WITH_DEVICE=1)
|
||||
endif()
|
||||
add_dependencies(spechub_wiring_test spechub)
|
||||
# sample_test's coupling case declares a Sampler with RADIANCE_MTP_COUPLED and needs the verify
|
||||
# op the spechub plugin carries (its host row); it skips when the library is absent.
|
||||
add_dependencies(sample_test spechub)
|
||||
endif()
|
||||
|
||||
# ================================================================== whole models on the CPU
|
||||
#
|
||||
# engine_e2e_test runs the radiance binary on tiny synthetic checkpoints (tests/tiny_model.h) on
|
||||
@@ -498,6 +514,9 @@ endif()
|
||||
# parameters). Cheap, so in the fast tier. libr4d.so is added when built; the script reports
|
||||
# " SKIP " rather than passing when a plugin will not dump.
|
||||
set(RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libref.so)
|
||||
if(TARGET spechub)
|
||||
list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/spechub.so)
|
||||
endif()
|
||||
if(RAD_HIP_FOUND AND TARGET libr4d)
|
||||
list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
|
||||
endif()
|
||||
|
||||
@@ -727,6 +727,74 @@ TEST(a_checkpoint_store_the_host_cannot_hold_is_refused_at_startup) {
|
||||
CHECK(named);
|
||||
}
|
||||
|
||||
/* RADIANCE_MTP_COUPLED is the coupling's only switch, and these are the engine's answers to it
|
||||
* before any request: a value that is not 0/1 refuses the start (never a silent uncoupled run),
|
||||
* and so does a model whose drafter has no per-round draw to couple. Both are checked through the
|
||||
* real binary because both are bringup paths, not helper functions; the drafter shape is the
|
||||
* declaration the engine has in hand, which no environment variable describes. The same model with
|
||||
* the flag off is the control: it starts, which is what makes the two refusals attributable to the
|
||||
* switch and not to the fixture. */
|
||||
TEST(the_coupling_switch_refuses_what_it_cannot_serve_at_startup) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
/* qwen35's tiny checkpoint declares no draft head: no serial chain to couple. The spechub
|
||||
* kernels are loaded beside libref, so the refusal is the drafter's shape and not a missing
|
||||
* coupling kernel. */
|
||||
const Ran on = radiance(w.qwen35, { "--kernels", "libref,spechub" },
|
||||
{ "RADIANCE_MTP_COUPLED=1" }, 120);
|
||||
const std::string want = "RADIANCE_MTP_COUPLED requires the linear serial draft chain "
|
||||
"(RAD_DRAFT_SERIAL with depth > 0)";
|
||||
if (on.status == 0 || on.status == 124 || !has(on.log, want))
|
||||
fprintf(stderr, " RADIANCE_MTP_COUPLED=1 exited %d:\n%s\n", on.status,
|
||||
tail(on.log, 20).c_str());
|
||||
CHECK(on.status != 0);
|
||||
CHECK(on.status != 124);
|
||||
CHECK(has(on.log, want));
|
||||
CHECK(has(on.log, "declares drafter '(none)'"));
|
||||
|
||||
/* THE GATE IS NOT RELAXED EITHER WAY: the same start as a deployment runs it (no
|
||||
* --debug-accept-reference-kernels), with a production library for the model's ops and the
|
||||
* spechub library beside it. On this card-less machine the plugin's device rows are left out
|
||||
* of selection (no card is visible), so the only coupled row left is the host oracle -- and
|
||||
* the gate must still refuse it, naming the coupled op. Marking the library, or the oracle
|
||||
* rows, production would pass this start on a machine that cannot run the coupling at all. */
|
||||
if (::access(RAD_E2E_HOME "/kernels/libavx.so", R_OK) == 0) {
|
||||
std::string gate_log;
|
||||
const int gate = tiny::run(serving_argv(w.qwen35, { "--kernels", "libavx,spechub" }),
|
||||
engine_env({ "RADIANCE_MTP_COUPLED=1" }), &gate_log, 120);
|
||||
const std::string gate_ref = "1 declared op(s) resolve only to a reference implementation "
|
||||
"(spechub)";
|
||||
if (gate == 0 || gate == 124 || !has(gate_log, gate_ref) ||
|
||||
!has(gate_log, "1 distinct op(s): mtp_couple_verify"))
|
||||
fprintf(stderr, " serving start exited %d:\n%s\n", gate,
|
||||
tail(gate_log, 20).c_str());
|
||||
CHECK(gate != 0);
|
||||
CHECK(gate != 124);
|
||||
CHECK(has(gate_log, gate_ref));
|
||||
CHECK(has(gate_log, "distinct op(s): mtp_couple_verify"));
|
||||
}
|
||||
|
||||
/* A typo is refused, not read as off. */
|
||||
const Ran typo = radiance(w.qwen35, {}, { "RADIANCE_MTP_COUPLED=yes" }, 120);
|
||||
const std::string refused = "RADIANCE_MTP_COUPLED accepts 0|1 (or unset)";
|
||||
if (typo.status == 0 || typo.status == 124 || !has(typo.log, refused))
|
||||
fprintf(stderr, " RADIANCE_MTP_COUPLED=yes exited %d:\n%s\n", typo.status,
|
||||
tail(typo.log, 20).c_str());
|
||||
CHECK(typo.status != 0);
|
||||
CHECK(typo.status != 124);
|
||||
CHECK(has(typo.log, refused));
|
||||
|
||||
/* The control on the same checkpoint: flag off starts and declares, so both refusals above are
|
||||
* the switch's answer and not the fixture's. --debug-graph runs declare and plan and exits, so
|
||||
* it is a start, not a serve. */
|
||||
const Ran off = radiance(w.qwen35, { "--debug-graph" }, { "RADIANCE_MTP_COUPLED=0" }, 120);
|
||||
if (off.status != 0)
|
||||
fprintf(stderr, " RADIANCE_MTP_COUPLED=0 exited %d:\n%s\n", off.status,
|
||||
tail(off.log, 20).c_str());
|
||||
CHECK_EQ(off.status, 0);
|
||||
CHECK(!has(off.log, "MTP coupled LIVE"));
|
||||
}
|
||||
|
||||
/* Two ranks split heads, the FFN and the vocabulary, and sum partial products in an all-reduce,
|
||||
* so the rounding differs from one rank's; anything more than rounding is a wrong column or row
|
||||
* (a rank's logits read at another rank's vocabulary offset score near chance). */
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
/* mtp_couple_plan_test.cpp -- the draw the engine stages for a serial drafting row, resolved
|
||||
* against a step plan (core/sched/mtp_couple_plan.h, called by Engine::stage_couple_draws).
|
||||
*
|
||||
* The coupling failed twice before its first draft, and both failures were here rather than in the
|
||||
* ABI:
|
||||
*
|
||||
* - The draw plane was sized from nothing, so every row lookup missed and the first step that
|
||||
* drafted refused with "has no plan entry on its card" -- the engine started and then could
|
||||
* not take one coupled step. The plane is now sized from cfg_.max_seqs, and the rule refuses a
|
||||
* plane that is too small instead of silently missing.
|
||||
* - A row whose card carries another sequence's draw is stale: the plugin refuses the staged
|
||||
* draw, so the row is refused here, named, before any pass reads it.
|
||||
*
|
||||
* The plan is the real StepPlan the scheduler produces; only its entries are built by hand, since
|
||||
* the rule reads nothing else off it.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "sched/mtp_couple_bind.h"
|
||||
#include "sched/mtp_couple_plan.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
namespace {
|
||||
|
||||
/* One plan entry for a sequence on a card, with the pre-commit output size the draw coordinates
|
||||
* on. `greedy` is the request's own choice (top_k 1). */
|
||||
StepEntry entry(Request* r, uint64_t seq, int32_t card, size_t output, bool greedy) {
|
||||
r->sp = SamplingParams{};
|
||||
r->sp.top_k = greedy ? 1 : 0;
|
||||
r->sp.temp = 1.0f;
|
||||
r->output.assign(output, 0);
|
||||
StepEntry e;
|
||||
e.req = r;
|
||||
e.seq = seq;
|
||||
e.card = card;
|
||||
return e;
|
||||
}
|
||||
|
||||
Scheduler::SerialRow row(uint64_t seq, int32_t card) {
|
||||
Scheduler::SerialRow r;
|
||||
r.seq = seq;
|
||||
r.card = card;
|
||||
return r;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* The staged draw names the plan entry on the row's card: sequence, card, the PRE-commit output
|
||||
* size as the coordinate, the request's seed and whether it samples. Cards the plan does not use
|
||||
* stay zero, so a row landing on one of them is refused rather than served a stale draw. */
|
||||
TEST(the_staged_draw_names_the_plan_entry_on_the_rows_card) {
|
||||
Request a, b, c;
|
||||
StepPlan plan;
|
||||
plan.e.push_back(entry(&a, 11, 3, 7, false));
|
||||
plan.e.push_back(entry(&b, 22, 5, 9, true));
|
||||
const Scheduler::SerialRow rows[] = { row(11, 3), row(22, 5) };
|
||||
|
||||
std::vector<RadMtpCoupleDraw> by_card(8);
|
||||
RadMtpCoupleDraw stage[2];
|
||||
std::string why;
|
||||
REQUIRE_EQ(mtp_couple_plan_stage(plan, 8, rows, 2, &by_card, stage, &why), RAD_OK);
|
||||
|
||||
CHECK_EQ(stage[0].seq, (uint64_t)11);
|
||||
CHECK_EQ(stage[0].card, 3);
|
||||
CHECK_EQ(stage[0].base, (uint64_t)7);
|
||||
CHECK_EQ(stage[0].seed, a.sp.seed);
|
||||
CHECK_EQ(stage[0].mode, 1u);
|
||||
/* A greedy request keeps the head's proposal instead of sampling x~Q. */
|
||||
CHECK_EQ(stage[1].seq, (uint64_t)22);
|
||||
CHECK_EQ(stage[1].card, 5);
|
||||
CHECK_EQ(stage[1].mode, 0u);
|
||||
/* Card 0 carried no entry: zeroed, so its seq names nothing a row could match. */
|
||||
CHECK_EQ(by_card[0].seq, (uint64_t)0);
|
||||
CHECK_EQ(by_card[7].seq, (uint64_t)0);
|
||||
(void)c;
|
||||
}
|
||||
|
||||
/* THE FIRST-DRAFT REGRESSION: a plane sized for fewer slots than the step can use would make every
|
||||
* row miss. It is refused by name -- never a silent miss, and never a start that cannot draft. */
|
||||
TEST(a_draw_plane_sized_for_fewer_slots_than_the_step_uses_is_refused) {
|
||||
Request a;
|
||||
StepPlan plan;
|
||||
plan.e.push_back(entry(&a, 11, 30, 7, false));
|
||||
const Scheduler::SerialRow rows[] = { row(11, 30) };
|
||||
|
||||
std::vector<RadMtpCoupleDraw> empty;
|
||||
RadMtpCoupleDraw stage[1];
|
||||
std::string why;
|
||||
const int st = mtp_couple_plan_stage(plan, 32, rows, 1, &empty, stage, &why);
|
||||
if (st == RAD_OK || why.find("holds 0 card slot(s)") == std::string::npos)
|
||||
fprintf(stderr, " status %d, why '%s'\n", st, why.c_str());
|
||||
CHECK_EQ(st, RAD_E_STATE);
|
||||
CHECK(why.find("holds 0 card slot(s), the step can use 32") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A drafting row whose card names another sequence is stale: the staged draw would name a card the
|
||||
* advance writes for someone else, which the plugin refuses. Refused here, naming the row. */
|
||||
TEST(a_row_whose_card_names_another_sequence_is_refused) {
|
||||
Request a;
|
||||
StepPlan plan;
|
||||
plan.e.push_back(entry(&a, 11, 3, 7, false));
|
||||
const Scheduler::SerialRow rows[] = { row(11, 3), row(33, 3) };
|
||||
|
||||
std::vector<RadMtpCoupleDraw> by_card(8);
|
||||
RadMtpCoupleDraw stage[2];
|
||||
std::string why;
|
||||
const int st = mtp_couple_plan_stage(plan, 8, rows, 2, &by_card, stage, &why);
|
||||
if (st == RAD_OK || why.find("drafting row 1 (sequence 33, card 3)") == std::string::npos)
|
||||
fprintf(stderr, " status %d, why '%s'\n", st, why.c_str());
|
||||
CHECK_EQ(st, RAD_E_STATE);
|
||||
CHECK(why.find("drafting row 1 (sequence 33, card 3) has no plan entry on its card") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
/* ================================================== THE VERIFY POSITION CONTRACT
|
||||
*
|
||||
* The sampler stages row k of a request at `n_out + k`, `n_out` being that request's committed
|
||||
* output length when the step is built. Round rd is verified at row k = rd - 1, so the state bound
|
||||
* after the drafting step must carry `n_out + (rd - 1)` for the `n_out` the NEXT step will see.
|
||||
*
|
||||
* These tests walk successive steps through the REAL staging function, the REAL bind rule
|
||||
* (core/sched/mtp_couple_bind.h) and the REAL row check (rad_mtp_couple_binds), with the request's
|
||||
* output growing the way a commit grows it.
|
||||
*
|
||||
* THE ENGINE USED TO REBUILD the coordinate as `pre-commit base + slot n_acc`. For a commit that
|
||||
* emitted exactly what the card accepted -- every commit of a request that is still running -- that
|
||||
* is the same number. It differs only when the commit emits fewer, and such a commit closes the
|
||||
* request (a max_tokens or context cut): the row is then terminal and will never sample again. Work
|
||||
* bound for it is carried terminal work, and a coupled verify there reads as a live round in any
|
||||
* log without being one. So the bind skips a request that is not Running, and the old formula's
|
||||
* one-ahead position for it is checked not to satisfy rad_mtp_couple_binds. */
|
||||
|
||||
namespace {
|
||||
|
||||
/* A sampled state as the propose kernel would leave it for `draw`, at round `rd` and position
|
||||
* `pos`: one Q token, x drawn from it, status 1. */
|
||||
RadMtpCoupleState sampled(const RadMtpCoupleDraw& draw, int rd, uint64_t pos) {
|
||||
RadMtpCoupleState s{};
|
||||
s.draw = draw;
|
||||
s.round = rd;
|
||||
s.status = 1;
|
||||
s.count = 1;
|
||||
s.x = 100 + rd;
|
||||
for (int i = 0; i < 8; ++i) s.ids[i] = -1; /* the proposer's padding */
|
||||
s.ids[0] = s.x;
|
||||
s.q[0] = 1.0;
|
||||
s.pos = pos;
|
||||
return s;
|
||||
}
|
||||
|
||||
/* One step's staging through mtp_couple_plan_stage, for request `r` on `card`. */
|
||||
RadMtpCoupleDraw stage_one(Request* r, uint64_t seq, int32_t card, std::string* why) {
|
||||
StepPlan plan;
|
||||
plan.e.push_back(entry(r, seq, card, r->output.size(), false));
|
||||
const Scheduler::SerialRow rows[] = { row(seq, card) };
|
||||
std::vector<RadMtpCoupleDraw> by_card(8);
|
||||
RadMtpCoupleDraw stage[1];
|
||||
if (mtp_couple_plan_stage(plan, 8, rows, 1, &by_card, stage, why) != RAD_OK) return {};
|
||||
return stage[0];
|
||||
}
|
||||
|
||||
/* The card's slot after a step that accepted `n_acc - 1` drafts: the bind checks each round's
|
||||
* state against the token the card holds for it. */
|
||||
StepSlot slot_for(const int32_t* tok, int rounds, int n_acc) {
|
||||
StepSlot S{};
|
||||
S.acc = n_acc - 1;
|
||||
S.n_acc = n_acc;
|
||||
for (int rd = 1; rd <= rounds; ++rd) S.tok[rd] = tok[rd];
|
||||
return S;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* VARYING n_acc, SEVERAL ROUNDS, A CUT COMMIT. Every round of a live request binds at the length
|
||||
* its commit left, which is the position the next build samples it at. The cut commit closes the
|
||||
* request; its rows bind nothing, and the old formula's position for them is provably not a row the
|
||||
* sampler would stage. */
|
||||
TEST(the_bound_position_is_the_verify_rows_sampling_position) {
|
||||
const int kRounds = 3;
|
||||
/* The card's one-based acceptance (S.n_acc) and what the commit actually appended, per step.
|
||||
* emitted == n_acc while the request runs; the last step is the cut: the card accepted all
|
||||
* three drafts (n_acc 4), the token budget let two through, and the commit closed the request
|
||||
* with "length". A step after it does not exist for this request. */
|
||||
const int n_acc[] = { 1, 4, 3, 4 };
|
||||
const int emitted[] = { 1, 4, 3, 2 };
|
||||
const int steps = (int)(sizeof n_acc / sizeof n_acc[0]);
|
||||
|
||||
Request r;
|
||||
r.id = 7;
|
||||
r.sp = SamplingParams{};
|
||||
r.sp.temp = 1.0f;
|
||||
r.state = ReqState::Running;
|
||||
|
||||
std::vector<RadMtpCoupleState> bound; /* the states bound after the previous step */
|
||||
uint64_t prev_base = 0; /* the previous draw's pre-commit coordinate */
|
||||
int prev_n_acc = 0; /* and the card's one-based acceptance of it */
|
||||
for (int step = 0; step < steps; ++step) {
|
||||
std::string why;
|
||||
const RadMtpCoupleDraw draw = stage_one(&r, r.id, 2, &why);
|
||||
REQUIRE_EQ(why, std::string());
|
||||
/* The draw's base is the PRE-commit length: the draft's own coordinate, not the verify's. */
|
||||
CHECK_EQ(draw.base, (uint64_t)r.output.size());
|
||||
|
||||
/* The build of THIS step runs over the states bound at the previous one, at the length
|
||||
* that commit left. Every round lands on its row. */
|
||||
if (!bound.empty()) {
|
||||
for (int k = 0; k < kRounds; ++k) {
|
||||
const uint64_t n_out = (uint64_t)r.output.size();
|
||||
CHECK(rad_mtp_couple_binds(bound[(size_t)k], r.id, draw.seed, n_out, k,
|
||||
bound[(size_t)k].x, 1 << 20));
|
||||
/* The old formula on the same states: identical while the previous commit emitted
|
||||
* its whole acceptance, one ahead per missing token otherwise. */
|
||||
const uint64_t old_pos = prev_base + (uint64_t)prev_n_acc + (uint64_t)k;
|
||||
CHECK_EQ(old_pos == n_out + (uint64_t)k,
|
||||
emitted[step - 1] == n_acc[step - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* The commit, and the request's state afterwards: a cut closes it. */
|
||||
for (int j = 0; j < emitted[step]; ++j) r.output.push_back(0);
|
||||
const bool live = emitted[step] == n_acc[step];
|
||||
r.state = live ? ReqState::Running : ReqState::Finished;
|
||||
|
||||
/* The bind, after the commit, through the production rule. The point is what the
|
||||
* scheduler's commit snapshot would carry: this fixture owns the request, so it is built
|
||||
* here directly. */
|
||||
MtpCoupleBindPoint bp;
|
||||
bp.found = true;
|
||||
bp.live = r.state == ReqState::Running;
|
||||
bp.n_out = (uint64_t)r.output.size();
|
||||
CHECK_EQ(bp.live, live);
|
||||
|
||||
const int32_t tok[] = { 11, 21, 22, 23 };
|
||||
const StepSlot S = slot_for(tok, kRounds, n_acc[step]);
|
||||
RadMtpCoupleState rb[(size_t)kRounds * 3]{};
|
||||
for (int rd = 1; rd <= kRounds; ++rd) {
|
||||
rb[(size_t)(rd - 1) * 3] = sampled(draw, rd, 0);
|
||||
rb[(size_t)(rd - 1) * 3].x = tok[rd]; /* the card's proposal */
|
||||
rb[(size_t)(rd - 1) * 3].ids[0] = tok[rd];
|
||||
}
|
||||
RadMtpCoupleState out[RAD_MTP_COUPLE_MAX_ROUNDS]{};
|
||||
int n_bound = -1;
|
||||
std::string bwhy;
|
||||
CHECK_EQ(mtp_couple_bind_rounds(bp, draw, rb, 3, kRounds, S, 1 << 20, out, &n_bound,
|
||||
&bwhy), RAD_OK);
|
||||
/* NOT LIVE, NOT BOUND: a terminal row must not read as a coupled verify. */
|
||||
CHECK_EQ(n_bound, live ? kRounds : 0);
|
||||
for (int rd = 1; rd <= (live ? kRounds : 0); ++rd) {
|
||||
const uint64_t want = (uint64_t)r.output.size() + (uint64_t)(rd - 1);
|
||||
CHECK_EQ(out[rd - 1].pos, want);
|
||||
CHECK(rad_mtp_couple_binds(out[rd - 1], r.id, draw.seed,
|
||||
(uint64_t)r.output.size(), rd - 1, tok[rd], 1 << 20));
|
||||
}
|
||||
|
||||
/* THE REGRESSION: where the old formula would have bound this step's rounds, the row
|
||||
* check fails as soon as the commit emitted fewer than the card accepted. */
|
||||
if (!live) {
|
||||
for (int rd = 1; rd <= kRounds; ++rd) {
|
||||
const uint64_t old_pos = draw.base + (uint64_t)n_acc[step] + (uint64_t)(rd - 1);
|
||||
CHECK(old_pos != (uint64_t)r.output.size() + (uint64_t)(rd - 1));
|
||||
CHECK(!rad_mtp_couple_binds(sampled(draw, rd, old_pos), r.id, draw.seed,
|
||||
(uint64_t)r.output.size(), rd - 1, tok[rd], 1 << 20));
|
||||
}
|
||||
}
|
||||
|
||||
prev_base = draw.base;
|
||||
prev_n_acc = n_acc[step];
|
||||
bound.assign(out, out + (live ? kRounds : 0));
|
||||
if (!live) break; /* the request is closed: no further step drafts it */
|
||||
}
|
||||
}
|
||||
|
||||
/* STALE STATES ARE REJECTED. A round from another step, a round whose position is off by one, and
|
||||
* a token the row does not propose all fail the rule -- the coupling never applies a law this step
|
||||
* did not draw. */
|
||||
TEST(a_state_from_another_step_is_refused) {
|
||||
Request r;
|
||||
r.id = 11;
|
||||
r.sp = SamplingParams{};
|
||||
r.sp.temp = 1.0f;
|
||||
std::string why;
|
||||
const RadMtpCoupleDraw d = stage_one(&r, r.id, 3, &why);
|
||||
REQUIRE_EQ(why, std::string());
|
||||
|
||||
const uint64_t n_out = 5;
|
||||
const RadMtpCoupleState good = sampled(d, 1, rad_mtp_couple_verify_pos(n_out, 1));
|
||||
CHECK(rad_mtp_couple_binds(good, r.id, d.seed, n_out, 0, good.x, 1 << 20));
|
||||
|
||||
/* One position ahead: the old arithmetic's answer. */
|
||||
CHECK(!rad_mtp_couple_binds(sampled(d, 1, rad_mtp_couple_verify_pos(n_out, 1) + 1), r.id,
|
||||
d.seed, n_out, 0, good.x, 1 << 20));
|
||||
/* Another step's round. */
|
||||
CHECK(!rad_mtp_couple_binds(sampled(d, 2, rad_mtp_couple_verify_pos(n_out, 2)), r.id,
|
||||
d.seed, n_out, 0, good.x, 1 << 20));
|
||||
/* Another seed, another sequence. */
|
||||
CHECK(!rad_mtp_couple_binds(good, r.id, d.seed + 1, n_out, 0, good.x, 1 << 20));
|
||||
CHECK(!rad_mtp_couple_binds(good, r.id + 1, d.seed, n_out, 0, good.x, 1 << 20));
|
||||
/* The row proposes a token this state did not draw, and a state with no Q at all. */
|
||||
CHECK(!rad_mtp_couple_binds(good, r.id, d.seed, n_out, 0, good.x + 1, 1 << 20));
|
||||
RadMtpCoupleState greedy = good;
|
||||
greedy.status = 0;
|
||||
greedy.draw.mode = 0;
|
||||
CHECK(!rad_mtp_couple_binds(greedy, r.id, d.seed, n_out, 0, good.x, 1 << 20));
|
||||
}
|
||||
|
||||
/* REQUEST AND SLOT REUSE. Two requests take turns on the same card, so each step's staged draw
|
||||
* names the sequence currently on it. The previous request's rounds are not accepted by the new
|
||||
* one's rows, whichever position they carry. */
|
||||
TEST(a_reused_card_serves_the_sequence_that_is_on_it) {
|
||||
Request a, b;
|
||||
a.id = 21;
|
||||
b.id = 22;
|
||||
a.sp = SamplingParams{};
|
||||
b.sp = SamplingParams{};
|
||||
a.output.assign(4, 0);
|
||||
b.output.assign(9, 0);
|
||||
|
||||
std::string why;
|
||||
const RadMtpCoupleDraw da = stage_one(&a, a.id, 5, &why);
|
||||
REQUIRE_EQ(why, std::string());
|
||||
const RadMtpCoupleDraw db = stage_one(&b, b.id, 5, &why);
|
||||
REQUIRE_EQ(why, std::string());
|
||||
CHECK_EQ(da.seq, (uint64_t)21);
|
||||
CHECK_EQ(db.seq, (uint64_t)22);
|
||||
|
||||
/* a's rounds, at a's length, do not bind a row of b -- not even at b's position. */
|
||||
const RadMtpCoupleState sa = sampled(da, 1, rad_mtp_couple_verify_pos((uint64_t)b.output.size(), 1));
|
||||
CHECK(!rad_mtp_couple_binds(sa, b.id, db.seed, (uint64_t)b.output.size(), 0, sa.x, 1 << 20));
|
||||
/* b's own state does. */
|
||||
const RadMtpCoupleState sb = sampled(db, 1, rad_mtp_couple_verify_pos((uint64_t)b.output.size(), 1));
|
||||
CHECK(rad_mtp_couple_binds(sb, b.id, db.seed, (uint64_t)b.output.size(), 0, sb.x, 1 << 20));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+190
-3
@@ -11,6 +11,7 @@
|
||||
#include "gbnf_oracle.h"
|
||||
#include "sample/grammar.h"
|
||||
#include "sample/host_ref.h"
|
||||
#include "sample/mtp_couple_evidence.h"
|
||||
#include "sample/sampler.h"
|
||||
#include "sample/vocab_view.h"
|
||||
#include "text/tokenizer.h"
|
||||
@@ -1496,6 +1497,7 @@ struct HostChain {
|
||||
int64_t nv = 0;
|
||||
bool ok = false;
|
||||
int st = RAD_OK;
|
||||
int64_t step_no = 0; /* the engine step the next step() stages for */
|
||||
|
||||
static inline HostChain* cur = nullptr;
|
||||
static void trampoline(RadCtx* c, const RadBatch*) {
|
||||
@@ -1503,11 +1505,14 @@ struct HostChain {
|
||||
}
|
||||
|
||||
HostChain(int64_t n_vocab, int64_t max_seqs, int max_spec, const VocabView* vocab = nullptr,
|
||||
int64_t max_candidates = 8)
|
||||
int64_t max_candidates = 8, const char* second_plugin = nullptr)
|
||||
: 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. */
|
||||
if (reg.load_plugin(home() + "/kernels/libref.so", 0) < 0) return;
|
||||
/* A second library by name, for an op libref does not carry (the coupling's verify op is
|
||||
* the spechub plugin's, host row included). */
|
||||
if (second_plugin && reg.load_plugin(home() + "/kernels/" + second_plugin, 0) < 0) return;
|
||||
RadModelMeta meta{};
|
||||
meta.arch_id = "sampler_chain";
|
||||
meta.name = "sampler_chain";
|
||||
@@ -1570,7 +1575,7 @@ struct HostChain {
|
||||
const int b = s.begin_request(r->id, r->sp, &err);
|
||||
if (b < 0) return b;
|
||||
}
|
||||
const int bs = s.build_step(reqs);
|
||||
const int bs = s.build_step(reqs, step_no++);
|
||||
if (bs < 0) return bs;
|
||||
int64_t n = 0;
|
||||
s.staged_params(&n);
|
||||
@@ -1610,6 +1615,27 @@ Request make_req(uint64_t id, std::vector<int32_t> prompt, const SamplingParams&
|
||||
return r;
|
||||
}
|
||||
|
||||
/* The per-round states the engine binds after a live commit: `rounds` sampled states of `id`,
|
||||
* each at `first_pos + rd - 1`, proposing the matching draft token. */
|
||||
void couple_states(uint64_t id, uint64_t seed, const int32_t* draft, int rounds,
|
||||
uint64_t first_pos, RadMtpCoupleState* out) {
|
||||
for (int rd = 1; rd <= rounds; ++rd) {
|
||||
RadMtpCoupleState& c = out[rd - 1];
|
||||
c = RadMtpCoupleState{};
|
||||
c.draw.seq = id;
|
||||
c.draw.seed = seed;
|
||||
c.draw.mode = 1;
|
||||
c.round = rd;
|
||||
c.status = 1;
|
||||
c.count = 1;
|
||||
c.x = draft[rd - 1];
|
||||
for (int i = 0; i < 8; ++i) c.ids[i] = -1;
|
||||
c.ids[0] = c.x;
|
||||
c.q[0] = 1.0;
|
||||
c.pos = first_pos + (uint64_t)(rd - 1);
|
||||
}
|
||||
}
|
||||
|
||||
SamplingParams greedy_params() {
|
||||
SamplingParams sp;
|
||||
sp.temp = 0.0f;
|
||||
@@ -3253,4 +3279,165 @@ TEST(a_dry_row_with_breakers_has_its_raw_logprob) {
|
||||
CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
/* ================================================== the coupled verify row */
|
||||
|
||||
/* THE COUPLED STATE AT THE SAMPLER'S OWN BUILD.
|
||||
*
|
||||
* The engine binds a round's state at `n_out + (round - 1)` (core/sched/mtp_couple_bind.h, through
|
||||
* rad_mtp_couple_verify_pos), and build_step stages row k of the request at `n_out + k`, taking the
|
||||
* state only when it names that exact row (rad_mtp_couple_binds). This drives the REAL build_step
|
||||
* with the coupling on: the bound rounds become the draft rows' states, the bonus row stays
|
||||
* unbound, and a state one position ahead -- what the engine's old `base + n_acc` formula produced
|
||||
* once a commit came up short -- is refused. A refused row is deliberately silent in production;
|
||||
* here it is the assertion.
|
||||
*
|
||||
* The verify op is declared by the spechub plugin, whose host row (ref_mtp_couple_verify) is what
|
||||
* makes the declaration succeed here; build_step alone is driven, so the op never runs. */
|
||||
TEST(the_coupled_state_is_staged_only_at_the_row_it_was_bound_for) {
|
||||
setenv("RADIANCE_MTP_COUPLED", "1", 1);
|
||||
HostChain ch(64, 2, 3, nullptr, 8, "spechub.so");
|
||||
unsetenv("RADIANCE_MTP_COUPLED");
|
||||
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));
|
||||
|
||||
/* The states the engine binds after a live commit, at the positions it writes them. */
|
||||
const uint64_t n_out = r.output.size();
|
||||
auto states_at = [&](uint64_t first_pos, RadMtpCoupleState* out) {
|
||||
couple_states(r.id, r.sp.seed, draft, 3, first_pos, out);
|
||||
};
|
||||
RadMtpCoupleState bound[3];
|
||||
states_at(rad_mtp_couple_verify_pos(n_out, 1), bound);
|
||||
CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3));
|
||||
|
||||
std::vector<Request*> reqs = { &r };
|
||||
CHECK_OK(ch.s.build_step(reqs));
|
||||
int64_t n = 0;
|
||||
const DeviceSampleParams* p = ch.s.staged_params(&n);
|
||||
CHECK_EQ(n, 4); /* three draft rows and the bonus row */
|
||||
CHECK(ch.s.staged_any_couple());
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
CHECK_EQ(ch.s.staged_couple(k).round, k + 1);
|
||||
CHECK_EQ(ch.s.staged_couple(k).x, draft[k]);
|
||||
CHECK_EQ(ch.s.staged_couple(k).pos, rad_mtp_couple_verify_pos(n_out, k + 1));
|
||||
/* The row is sampled at the position its state names -- asserted against the row itself,
|
||||
* not through the formula, so a drifted formula cannot move both sides together. */
|
||||
CHECK_EQ(p[k].pos, n_out + (uint64_t)k);
|
||||
CHECK_EQ(ch.s.staged_couple(k).pos, p[k].pos);
|
||||
}
|
||||
CHECK_EQ(ch.s.staged_couple(3).round, 0); /* the bonus row carries no law */
|
||||
|
||||
/* THE OLD FORMULA'S POSITION: one ahead of the row. Every row is refused, so the batch issues
|
||||
* no verify at all -- an inert coupling, which is what the engine's own formula used to
|
||||
* produce. */
|
||||
RadMtpCoupleState ahead[3];
|
||||
states_at(rad_mtp_couple_verify_pos(n_out, 1) + 1, ahead);
|
||||
CHECK_OK(ch.s.set_mtp_couple(r.id, ahead, 3));
|
||||
CHECK_OK(ch.s.build_step(reqs));
|
||||
CHECK(!ch.s.staged_any_couple());
|
||||
for (int k = 0; k < 4; ++k) CHECK_EQ(ch.s.staged_couple(k).round, 0);
|
||||
|
||||
/* REUSE: an ended request's binding is gone, and a new one starts unbound. */
|
||||
ch.s.end_request(r.id);
|
||||
CHECK_EQ(ch.s.set_mtp_couple(r.id, bound, 3), RAD_E_NOTFOUND);
|
||||
Request r2 = make_req(8, { 1, 2, 3 }, sp);
|
||||
r2.draft = draft;
|
||||
r2.n_draft = 3;
|
||||
CHECK_OK(ch.s.begin_request(r2.id, r2.sp, &err));
|
||||
CHECK_OK(ch.s.build_step({ &r2 }));
|
||||
CHECK(!ch.s.staged_any_couple());
|
||||
}
|
||||
|
||||
/* THE SNAPSHOT THE EVIDENCE READS.
|
||||
*
|
||||
* In the coupled serial path build_step stages the bound rows, then the drafter's build_greedy
|
||||
* clears any_couple_ and replaces the staged rows before collect_step's wait returns. An evidence
|
||||
* line gated on staged_any_couple() therefore never fires -- and forced, it would list the greedy
|
||||
* pass's rows. This drives the real chain for two requests: build_step, run() issuing the verify
|
||||
* op, build_greedy (where issue_serial_drafter calls it), then the evidence decision over the
|
||||
* frozen snapshot. The negatives are what the line must not count: a terminal request, another
|
||||
* step's snapshot, and a host row. */
|
||||
TEST(the_coupled_evidence_survives_the_drafters_greedy_build) {
|
||||
setenv("RADIANCE_MTP_COUPLED", "1", 1);
|
||||
HostChain ch(64, 2, 3, nullptr, 8, "spechub.so");
|
||||
unsetenv("RADIANCE_MTP_COUPLED");
|
||||
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 a = make_req(7, { 1, 2, 3 }, sp);
|
||||
Request b = make_req(8, { 4, 5, 6 }, sp);
|
||||
a.draft = b.draft = draft;
|
||||
a.n_draft = b.n_draft = 3;
|
||||
std::string err;
|
||||
for (Request* r : { &a, &b }) {
|
||||
CHECK_OK(ch.s.begin_request(r->id, r->sp, &err));
|
||||
RadMtpCoupleState bound[3];
|
||||
couple_states(r->id, r->sp.seed, draft, 3, rad_mtp_couple_verify_pos(r->output.size(), 1),
|
||||
bound);
|
||||
CHECK_OK(ch.s.set_mtp_couple(r->id, bound, 3));
|
||||
}
|
||||
|
||||
std::vector<float> lg(8 * 64, 0.0f); /* two requests, 3 draft rows + bonus each */
|
||||
for (int row = 0; row < 8; ++row) lg[(size_t)row * 64 + 5] = 5.0f;
|
||||
std::vector<int32_t> tok;
|
||||
CHECK_OK(ch.step({ &a, &b }, lg, &tok));
|
||||
const int64_t step = ch.step_no - 1;
|
||||
|
||||
const Sampler::CoupleBuild& cb = ch.s.couple_build();
|
||||
CHECK_EQ(cb.step, step);
|
||||
CHECK_EQ(cb.rows, (int64_t)6);
|
||||
REQUIRE_EQ(cb.seqs.size(), (size_t)2);
|
||||
CHECK_EQ(cb.seqs[0].first, (uint64_t)7);
|
||||
CHECK_EQ(cb.seqs[0].second, (int64_t)3);
|
||||
CHECK_EQ(cb.seqs[1].first, (uint64_t)8);
|
||||
CHECK_EQ(cb.seqs[1].second, (int64_t)3);
|
||||
/* run() issued the verify op for THIS build, not merely staged rows for it. */
|
||||
CHECK_EQ(ch.s.staged_couple_issued_step(), step);
|
||||
|
||||
/* The drafter's greedy passes, where issue_serial_drafter runs them: after the build, before
|
||||
* the wait. The old gate is false now; the snapshot is not the greedy pass's. */
|
||||
CHECK_OK(ch.s.build_greedy(4));
|
||||
CHECK(!ch.s.staged_any_couple());
|
||||
CHECK_EQ(ch.s.couple_build().step, step);
|
||||
CHECK_EQ(ch.s.couple_build().rows, (int64_t)6);
|
||||
|
||||
auto all_live = [](uint64_t) { return true; };
|
||||
MtpCoupleEvidence ev = mtp_couple_evidence(cb, step, RAD_DOMAIN_DEVICE, all_live);
|
||||
CHECK_EQ(ev.rows, (int64_t)6);
|
||||
CHECK(ev.device);
|
||||
CHECK_EQ(ev.seqs, std::string("7,8"));
|
||||
|
||||
/* A terminal request is not counted: b finished while the step ran. */
|
||||
ev = mtp_couple_evidence(cb, step, RAD_DOMAIN_DEVICE, [](uint64_t s) { return s == 7; });
|
||||
CHECK_EQ(ev.rows, (int64_t)3);
|
||||
CHECK_EQ(ev.seqs, std::string("7"));
|
||||
|
||||
/* Nothing live, or another step's snapshot: no evidence. */
|
||||
CHECK_EQ(mtp_couple_evidence(cb, step, RAD_DOMAIN_DEVICE, [](uint64_t) { return false; }).rows,
|
||||
(int64_t)0);
|
||||
CHECK_EQ(mtp_couple_evidence(cb, step + 1, RAD_DOMAIN_DEVICE, all_live).rows, (int64_t)0);
|
||||
|
||||
/* A host row is reported as host, not read as a device verify. */
|
||||
ev = mtp_couple_evidence(cb, step, RAD_DOMAIN_HOST, all_live);
|
||||
CHECK(!ev.device);
|
||||
CHECK_EQ(ev.rows, (int64_t)6);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "mm/processor.h"
|
||||
#include "sched/mtp_couple_bind.h"
|
||||
#include "sched/scheduler.h"
|
||||
#include "sched/advance_impl.h"
|
||||
#include "sched/derive.h"
|
||||
@@ -1471,6 +1472,204 @@ TEST(rejection_rolls_back_paged_kv_and_moves_the_linear_read_offset) {
|
||||
CHECK_EQ(f.sch.plan().e[0].conv_cursor, (cursor_before + 3) % W);
|
||||
}
|
||||
|
||||
/* THE COUPLED BIND AFTER A REAL COMMIT.
|
||||
*
|
||||
* Engine::finish_serial_drafter binds each round at the request's committed output length, read
|
||||
* from the plan after commit -- the value the next Sampler::build_step stages that row at. This
|
||||
* drives the same rule (sched/mtp_couple_bind.h) against the real Scheduler::commit: a live
|
||||
* commit, a max_tokens cut, and a card reused by a new request afterwards.
|
||||
*
|
||||
* The old engine formula (the draw's pre-commit base + the slot's one-based n_acc) agrees on every
|
||||
* commit of a request that is still running, and drifts by exactly the tokens a cut withheld. A
|
||||
* commit that emits fewer than the card accepted has closed the request; its plan entry is carried
|
||||
* for the bind, but the request will never sample again. Binding it would put a coupled verify on
|
||||
* a terminal row, which reads as a live round in the log without being one. */
|
||||
TEST(the_coupled_bind_skips_a_request_the_commit_closed) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
f.cfg.n_spec = 3;
|
||||
CHECK_OK(f.start());
|
||||
const int64_t vocab = f.prog.meta.n_vocab;
|
||||
|
||||
int32_t draft[3] = { 21, 22, 23 };
|
||||
auto readback = [&](uint64_t seq, uint64_t base, int rounds) {
|
||||
RadMtpCoupleDraw d{};
|
||||
d.seq = seq;
|
||||
d.base = base;
|
||||
d.mode = 1;
|
||||
std::vector<RadMtpCoupleState> rb((size_t)rounds);
|
||||
for (int rd = 1; rd <= rounds; ++rd) {
|
||||
RadMtpCoupleState& s = rb[(size_t)(rd - 1)];
|
||||
s.draw = d;
|
||||
s.round = rd;
|
||||
s.status = 1;
|
||||
s.count = 1;
|
||||
s.x = draft[rd - 1]; /* what the card holds for that round */
|
||||
for (int i = 0; i < 8; ++i) s.ids[i] = -1;
|
||||
s.ids[0] = s.x;
|
||||
s.q[0] = 1.0;
|
||||
}
|
||||
return rb;
|
||||
};
|
||||
auto slot = [&]() {
|
||||
StepSlot S{};
|
||||
S.acc = 3;
|
||||
S.n_acc = 4;
|
||||
for (int rd = 1; rd <= 3; ++rd) S.tok[rd] = draft[rd - 1];
|
||||
return S;
|
||||
};
|
||||
|
||||
/* ---- a live commit: three drafts accepted, the request keeps running. */
|
||||
const uint64_t a = f.submit(160, 64);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain(11);
|
||||
CHECK_OK(f.sch.set_draft(a, draft, 3));
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
const uint64_t a_base = f.sch.find(a)->output.size(); /* the draw's pre-commit coordinate */
|
||||
CHECK_OK(f.commit(9, 0, [](const StepEntry&) { return 3; }));
|
||||
REQUIRE(f.sch.find(a) != nullptr);
|
||||
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running);
|
||||
CHECK_EQ((int)f.sch.find(a)->output.size(), (int)a_base + 4);
|
||||
|
||||
MtpCoupleBindPoint pa;
|
||||
pa.found = f.sch.committed_seq(a, &pa.n_out, &pa.live);
|
||||
CHECK(pa.found);
|
||||
CHECK(pa.live);
|
||||
CHECK_EQ(pa.n_out, (uint64_t)f.sch.find(a)->output.size());
|
||||
|
||||
const std::vector<RadMtpCoupleState> rba = readback(a, a_base, 3);
|
||||
const StepSlot Sa = slot();
|
||||
RadMtpCoupleState bound[RAD_MTP_COUPLE_MAX_ROUNDS]{};
|
||||
int n_bound = -1;
|
||||
std::string why;
|
||||
CHECK_EQ(mtp_couple_bind_rounds(pa, rba[0].draw, rba.data(), 1, 3, Sa, vocab, bound,
|
||||
&n_bound, &why), RAD_OK);
|
||||
CHECK_EQ(n_bound, 3);
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
/* The next build stages row k at n_out + k. */
|
||||
CHECK_EQ(bound[k].pos, pa.n_out + (uint64_t)k);
|
||||
CHECK(rad_mtp_couple_binds(bound[k], a, rba[0].draw.seed, pa.n_out, k, draft[k], vocab));
|
||||
}
|
||||
/* The old formula on the same data: identical, because this commit emitted its whole
|
||||
* acceptance. */
|
||||
for (int k = 0; k < 3; ++k)
|
||||
CHECK_EQ(a_base + 4 + (uint64_t)k, pa.n_out + (uint64_t)k);
|
||||
|
||||
/* ---- a cut commit: the card accepted three drafts, the budget lets two through. */
|
||||
const uint64_t b = f.submit(160, /*max_tokens=*/3);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain(11); /* b's first output token */
|
||||
CHECK_OK(f.sch.set_draft(a, draft, 3));
|
||||
CHECK_OK(f.sch.set_draft(b, draft, 3));
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
const uint64_t b_base = f.sch.find(b)->output.size();
|
||||
CHECK_OK(f.commit(9, 0, [&](const StepEntry& e) { return e.seq == b ? 3 : 0; }));
|
||||
REQUIRE(f.sch.find(b) != nullptr);
|
||||
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Finished);
|
||||
CHECK_EQ((int)f.sch.find(b)->output.size(), 3); /* 1 + 2, not 1 + 4 */
|
||||
|
||||
/* The commit snapshot still names b -- the terminal step is carried into the bind -- but it is
|
||||
* not live: nothing binds, so no coupled verify is staged for a request that is gone. */
|
||||
MtpCoupleBindPoint pb;
|
||||
pb.found = f.sch.committed_seq(b, &pb.n_out, &pb.live);
|
||||
CHECK(pb.found);
|
||||
CHECK(!pb.live);
|
||||
CHECK_EQ(pb.n_out, (uint64_t)f.sch.find(b)->output.size());
|
||||
|
||||
const std::vector<RadMtpCoupleState> rbb = readback(b, b_base, 3);
|
||||
const StepSlot Sb = slot();
|
||||
CHECK_EQ(mtp_couple_bind_rounds(pb, rbb[0].draw, rbb.data(), 1, 3, Sb, vocab, bound,
|
||||
&n_bound, &why), RAD_OK);
|
||||
CHECK_EQ(n_bound, 0);
|
||||
/* THE OLD FORMULA would have bound b's rounds at base + n_acc + k -- two past the length it
|
||||
* actually committed, on a row no build will stage. */
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
const uint64_t old_pos = b_base + 4 + (uint64_t)k;
|
||||
CHECK(old_pos != pb.n_out + (uint64_t)k);
|
||||
RadMtpCoupleState stale = rbb[(size_t)k];
|
||||
stale.pos = old_pos;
|
||||
CHECK(!rad_mtp_couple_binds(stale, b, rbb[0].draw.seed, pb.n_out, k, draft[k], vocab));
|
||||
}
|
||||
|
||||
/* ---- reuse: the next request on a card binds at its own length, and the closed request's
|
||||
* rounds are not accepted by it. */
|
||||
const uint64_t c = f.submit(160, 64);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain(11);
|
||||
CHECK_OK(f.sch.set_draft(c, draft, 3));
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
const uint64_t c_base = f.sch.find(c)->output.size();
|
||||
CHECK_OK(f.commit(9, 0, [](const StepEntry&) { return 3; }));
|
||||
MtpCoupleBindPoint pc;
|
||||
pc.found = f.sch.committed_seq(c, &pc.n_out, &pc.live);
|
||||
CHECK(pc.found);
|
||||
CHECK(pc.live);
|
||||
CHECK_EQ(pc.n_out, (uint64_t)f.sch.find(c)->output.size());
|
||||
CHECK_EQ(pc.n_out, c_base + 4);
|
||||
CHECK(!rad_mtp_couple_binds(rbb[0], c, rbb[0].draw.seed, pc.n_out, 0, draft[0], vocab));
|
||||
RadMtpCoupleState own = readback(c, c_base, 1)[0];
|
||||
own.pos = rad_mtp_couple_verify_pos(pc.n_out, 1);
|
||||
CHECK(rad_mtp_couple_binds(own, c, own.draw.seed, pc.n_out, 0, draft[0], vocab));
|
||||
}
|
||||
|
||||
/* THE BIND POINT OUTLIVES A REAP.
|
||||
*
|
||||
* commit() retires the step, and a request it finished that the next step does not carry is pinned
|
||||
* by nothing any more. The server calls reap() from an HTTP thread as soon as it sees the finish,
|
||||
* and reap() destroys the Request -- while Engine::finish_serial_drafter still has to bind that
|
||||
* row. The bind point is therefore copied by commit under the scheduler lock
|
||||
* (Scheduler::committed_seq), not read off the plan's StepEntry::req, which is dangling by then.
|
||||
* This reaps a non-carried terminal request between commit and bind: the plan-pointer version
|
||||
* could only answer by reading freed memory, and the snapshot answers from the copy.
|
||||
*/
|
||||
TEST(the_committed_bind_point_outlives_a_reap) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
f.cfg.n_spec = 3;
|
||||
CHECK_OK(f.start());
|
||||
const int64_t vocab = f.prog.meta.n_vocab;
|
||||
|
||||
int32_t draft[3] = { 21, 22, 23 };
|
||||
const uint64_t a = f.submit(160, 64); /* live through the commit */
|
||||
const uint64_t b = f.submit(160, /*max_tokens=*/3); /* closed on it by the cut */
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain(11);
|
||||
CHECK_OK(f.sch.set_draft(a, draft, 3));
|
||||
CHECK_OK(f.sch.set_draft(b, draft, 3));
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
CHECK_OK(f.commit(9, 0, [&](const StepEntry& e) { return e.seq == b ? 3 : 0; }));
|
||||
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Finished);
|
||||
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running);
|
||||
|
||||
/* The server's reap lands between commit and bind: b's Request is destroyed here. */
|
||||
CHECK_OK(f.sch.reap(b));
|
||||
CHECK(f.sch.find(b) == nullptr);
|
||||
|
||||
MtpCoupleBindPoint pb;
|
||||
pb.found = f.sch.committed_seq(b, &pb.n_out, &pb.live);
|
||||
CHECK(pb.found);
|
||||
CHECK(!pb.live); /* terminal: nothing binds */
|
||||
CHECK_EQ(pb.n_out, (uint64_t)3);
|
||||
|
||||
MtpCoupleBindPoint pa;
|
||||
pa.found = f.sch.committed_seq(a, &pa.n_out, &pa.live);
|
||||
CHECK(pa.found);
|
||||
CHECK(pa.live);
|
||||
CHECK_EQ(pa.n_out, (uint64_t)f.sch.find(a)->output.size());
|
||||
|
||||
RadMtpCoupleState rb[RAD_MTP_COUPLE_MAX_ROUNDS]{};
|
||||
RadMtpCoupleState out[RAD_MTP_COUPLE_MAX_ROUNDS]{};
|
||||
StepSlot S{};
|
||||
S.acc = 3;
|
||||
S.n_acc = 4;
|
||||
for (int rd = 1; rd <= 3; ++rd) S.tok[rd] = draft[rd - 1];
|
||||
int n_bound = -1;
|
||||
std::string why;
|
||||
CHECK_EQ(mtp_couple_bind_rounds(pb, RadMtpCoupleDraw{}, rb, 1, 3, S, vocab, out, &n_bound,
|
||||
&why), RAD_OK);
|
||||
CHECK_EQ(n_bound, 0);
|
||||
}
|
||||
|
||||
/* A decode benchmark needs the request to last as long as asked, not as long as the model
|
||||
* chooses. EOS still stops an ordinary request, and max_tokens still stops one ignoring EOS. */
|
||||
TEST(ignore_eos_runs_to_max_tokens_and_nothing_else_changes) {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/* tests/spechub_accept_test.cpp -- the coupling's ACCEPTANCE, measured on a real candidate stream.
|
||||
*
|
||||
* spechub_couple_test pins the law. This file measures the number the flag exists for: how many
|
||||
* draft tokens survive verification, compared against the same drafts WITHOUT the coupling's
|
||||
* acceptance rule.
|
||||
*
|
||||
* The comparator is honest about what it is. It does not run a card, a checkpoint or libr4d; it
|
||||
* runs the two decisions over the SAME candidate stream, the same drafts and the same uniforms:
|
||||
*
|
||||
* ORDINARY sample_pick's rule: the draft is a proposal the target checks for equality, so a
|
||||
* draft survives only when it IS the target's own pick. That is the equality
|
||||
* acceptance the plain MTP path applies (core/sample/accept.h).
|
||||
*
|
||||
* COUPLED rad_mtp_couple_decide: accept x with probability min(1, P(x)/Q(x)), and on refusal
|
||||
* emit a draw from the residual (P-Q)+. The COMPOSED law is P (spechub_couple_test
|
||||
* proves it), so the emitted token agrees with the target's own draw more often.
|
||||
*
|
||||
* Both are measured as "the emitted token equals the token the target itself drew" over the same
|
||||
* trials, which is the quantity acceptance length is built from. The report prints the two rates.
|
||||
*
|
||||
* What this is NOT: a serving measurement. The source's own ABI-16 benchmark is the only end-to-end
|
||||
* evidence and it is cited as such in the PR body.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_sample.h"
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
/* Softmax over a shortlist in the verify's own FP64 formula, and the index it picks for a uniform. */
|
||||
int32_t pick_from(const std::vector<float>& v, double u) {
|
||||
float top = -INFINITY;
|
||||
for (float x : v) top = std::max(top, x);
|
||||
double sum = 0, w[16] = {};
|
||||
for (size_t i = 0; i < v.size(); ++i) { w[i] = std::exp((double)v[i] - top); sum += w[i]; }
|
||||
double c = u * sum;
|
||||
for (size_t i = 0; i < v.size(); ++i) { c -= w[i]; if (c < 0) return (int32_t)i; }
|
||||
return (int32_t)v.size() - 1;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* THE ACCEPTANCE COMPARATOR. Over 20000 trials on one shortlist: the target's own draw t, a draft
|
||||
* x drawn from the head's Q, and the two decisions. Prints both rates and requires the coupled
|
||||
* rate to be at least the ordinary one -- never below, which is the whole claim. */
|
||||
TEST(the_coupled_acceptance_beats_equality_on_the_same_stream) {
|
||||
/* The target's candidate plane: 8 live candidates, a plausible decode shape. */
|
||||
const std::vector<float> pval = { 3.10f, 2.95f, 2.40f, 1.80f, 1.10f, 0.40f, -0.60f, -2.00f };
|
||||
/* The head's own shortlist: the same 8, a flatter ranking, which is what a 2-bit head gives. */
|
||||
const std::vector<float> qval = { 2.60f, 2.55f, 2.30f, 2.00f, 1.60f, 1.20f, 0.60f, -0.40f };
|
||||
std::vector<int32_t> ids;
|
||||
for (int i = 0; i < 8; ++i) ids.push_back(i);
|
||||
|
||||
const uint64_t seed = 90210;
|
||||
const int trials = 20000;
|
||||
int64_t ordinary_ok = 0, coupled_ok = 0, drafts = 0;
|
||||
|
||||
for (int k = 0; k < trials; ++k) {
|
||||
const uint64_t pos = (uint64_t)k;
|
||||
/* The target's own draw at this position: what acceptance is measured against. */
|
||||
const int32_t target =
|
||||
pick_from(pval, rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_PICK));
|
||||
|
||||
/* The head's draft, from its own Q, with the coupling's own draw key. */
|
||||
RadMtpCoupleState s{};
|
||||
s.draw.seed = seed;
|
||||
s.draw.base = pos;
|
||||
s.draw.mode = 1;
|
||||
s.round = 1;
|
||||
s.status = 1;
|
||||
int32_t qidx[8];
|
||||
float qv[8];
|
||||
for (int i = 0; i < 8; ++i) { qidx[i] = i; qv[i] = qval[(size_t)i]; }
|
||||
CHECK(rad_mtp_couple_build_q(qidx, qv, 8, &s));
|
||||
s.x = s.ids[rad_mtp_couple_pick(
|
||||
s, rad_spechub_uniform(seed, pos, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
|
||||
++drafts;
|
||||
|
||||
/* ORDINARY: equality, the plain MTP verifier's rule. */
|
||||
if (s.x == target) ++ordinary_ok;
|
||||
|
||||
/* COUPLED: the maximal coupling, then the emitted token against the same target draw. */
|
||||
int32_t out = -1;
|
||||
CHECK(rad_mtp_couple_decide(s, ids.data(), pval.data(), 8, 8,
|
||||
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_ACCEPT),
|
||||
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID), &out));
|
||||
if (out == target) ++coupled_ok;
|
||||
}
|
||||
|
||||
const double ordinary = (double)ordinary_ok / (double)drafts;
|
||||
const double coupled = (double)coupled_ok / (double)drafts;
|
||||
std::fprintf(stderr,
|
||||
" acceptance over %d coupled draws: equality %.6f, coupling %.6f\n",
|
||||
trials, ordinary, coupled);
|
||||
|
||||
/* THE TWO RATES IN CLOSED FORM. The target's draw and the draft are independent, so:
|
||||
* equality acceptance = sum_i P_i Q_i (the draft must equal the target's draw)
|
||||
* the coupling = sum_i P_i^2 (its output is distributed as P, and the target's own
|
||||
* draw is an independent P draw)
|
||||
* Checking against these turns the measurement into an oracle rather than a threshold: a ported
|
||||
* rule that drifted would miss its own closed form, not a number somebody picked. */
|
||||
auto softmax = [](const std::vector<float>& v, double* out) {
|
||||
float top = -INFINITY;
|
||||
for (float x : v) top = std::max(top, x);
|
||||
double sum = 0;
|
||||
for (size_t i = 0; i < v.size(); ++i) { out[i] = std::exp((double)v[i] - top); sum += out[i]; }
|
||||
for (size_t i = 0; i < v.size(); ++i) out[i] /= sum;
|
||||
};
|
||||
const size_t n = pval.size();
|
||||
std::vector<double> P(n), Q(n);
|
||||
softmax(pval, P.data());
|
||||
softmax(qval, Q.data());
|
||||
double want_ordinary = 0.0, want_coupled = 0.0;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
want_ordinary += P[i] * Q[i];
|
||||
want_coupled += P[i] * P[i];
|
||||
}
|
||||
const double sig = std::sqrt(0.25 / (double)drafts); /* a binomial's widest sigma */
|
||||
CHECK_NEAR(ordinary, want_ordinary, 5.0 * sig);
|
||||
CHECK_NEAR(coupled, want_coupled, 5.0 * sig);
|
||||
/* AND THE CLAIM, which follows from the two closed forms: sigma(P^2) >= sigma(P Q) because P is
|
||||
* the draft's own law. Strictly here, since P != Q on this stream. */
|
||||
CHECK(want_coupled > want_ordinary);
|
||||
CHECK(coupled > ordinary);
|
||||
}
|
||||
|
||||
/* AND THE DRAFT ITSELF IS STILL SAMPLED FROM Q. The coupling can only pay if x~Q, so this pins that
|
||||
* the propose row's draw is the FP64 softmax of the shortlist and not the argmax: over many rounds
|
||||
* every candidate with mass appears, and the frequencies match Q. */
|
||||
TEST(the_drafted_token_is_sampled_from_the_heads_own_law) {
|
||||
const std::vector<float> qval = { 1.0f, 0.4f, -0.3f, -1.2f };
|
||||
int32_t qidx[8];
|
||||
float qv[8];
|
||||
for (int i = 0; i < 8; ++i) { qidx[i] = i < 4 ? i : -1; qv[i] = i < 4 ? qval[(size_t)i] : -INFINITY; }
|
||||
|
||||
double sum = 0, Q[4] = {};
|
||||
for (int i = 0; i < 4; ++i) { Q[i] = std::exp((double)qval[(size_t)i] - 1.0); sum += Q[i]; }
|
||||
for (int i = 0; i < 4; ++i) Q[i] /= sum;
|
||||
|
||||
const int trials = 20000;
|
||||
int64_t seen[4] = {};
|
||||
for (int k = 0; k < trials; ++k) {
|
||||
RadMtpCoupleState s{};
|
||||
s.draw.seed = 7;
|
||||
s.draw.base = (uint64_t)k;
|
||||
s.draw.mode = 1;
|
||||
s.round = 1;
|
||||
s.status = 1;
|
||||
CHECK(rad_mtp_couple_build_q(qidx, qv, 8, &s));
|
||||
const int32_t x = s.ids[rad_mtp_couple_pick(
|
||||
s, rad_spechub_uniform(7, (uint64_t)k, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
|
||||
CHECK(x >= 0 && x < 4);
|
||||
++seen[x];
|
||||
}
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const double got = (double)seen[i] / (double)trials;
|
||||
const double sigma = std::sqrt(Q[i] * (1.0 - Q[i]) / (double)trials);
|
||||
CHECK_NEAR(got, Q[i], 5.0 * sigma + 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,282 @@
|
||||
/* tests/spechub_cooperative_test.cpp -- the cooperative verify against the serial one.
|
||||
*
|
||||
* The cooperative kernel writes P's weights and the residual mass across the workgroup and then
|
||||
* walks both planes in ascending candidate order on one thread. That is a REORDERING of the
|
||||
* compute, not of the arithmetic -- and the arithmetic is the ABI here, so the claim has to be
|
||||
* checked rather than argued.
|
||||
*
|
||||
* What this file checks, over the same rows, the same states and the same uniforms:
|
||||
*
|
||||
* PARITY the cooperative decision emits the same token as rad_mtp_couple_decide (the serial
|
||||
* reference the plugin's host row runs) on every row of every width case.
|
||||
*
|
||||
* WIDTHS 129, 1024 and 1025 candidates. 1025 is the case that falls out of the shared-plane
|
||||
* band into the general single-threaded algorithm; it must still agree.
|
||||
*
|
||||
* HOSTILE a row with a hole in the middle, a duplicate id, an -inf candidate, and a row whose
|
||||
* state does not bind -- all of which the planes must treat exactly as the serial walk
|
||||
* does.
|
||||
*
|
||||
* The kernel itself is not launched here: this is the HOST half of the same algorithm, stepped
|
||||
* through the same phase sequence, so a divergence between the two would have to live in the
|
||||
* device code alone. The device launch is covered by the comparator probe the PR body reports.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_sample.h"
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
/* The cooperative algorithm, on the host: the same phases the kernel runs, over the same shared
|
||||
* planes. Deliberately a transcription of the kernel's body, so a change to one that is not made to
|
||||
* the other shows up as a mismatch against rad_mtp_couple_decide. */
|
||||
bool cooperative_decide(const RadMtpCoupleState& s, const std::vector<int32_t>& ids,
|
||||
const std::vector<float>& val, int64_t vocab, double u_accept,
|
||||
double u_resid, int32_t* out) {
|
||||
const int64_t n_cand = (int64_t)ids.size();
|
||||
std::vector<double> weight((size_t)n_cand, 0.0), mass((size_t)n_cand, 0.0);
|
||||
double pq[8] = {};
|
||||
int first[8];
|
||||
double sum = 0;
|
||||
float top = -INFINITY;
|
||||
int ix = -1;
|
||||
bool dominated = true;
|
||||
|
||||
/* PHASE 1: the gate, exactly the kernel's. */
|
||||
bool eligible = false;
|
||||
if (s.status == 1) {
|
||||
float maximum = -INFINITY;
|
||||
bool valid = true;
|
||||
for (int64_t j = 0; j < n_cand; ++j) {
|
||||
if (ids[(size_t)j] < 0) continue;
|
||||
if (ids[(size_t)j] >= vocab || val[(size_t)j] != val[(size_t)j] ||
|
||||
val[(size_t)j] == INFINITY) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
if (val[(size_t)j] > maximum) maximum = val[(size_t)j];
|
||||
}
|
||||
if (valid && maximum != -INFINITY) { top = maximum; eligible = true; }
|
||||
}
|
||||
if (!eligible) return false;
|
||||
|
||||
/* PHASE 2: the weights, per slot. */
|
||||
for (int64_t j = 0; j < n_cand; ++j)
|
||||
if (ids[(size_t)j] >= 0 && val[(size_t)j] != -INFINITY)
|
||||
weight[(size_t)j] = std::exp((double)val[(size_t)j] - top);
|
||||
|
||||
/* PHASE 3: the ordered sum and the Q aggregation. */
|
||||
for (int k = 0; k < s.count; ++k) { pq[k] = 0; first[k] = -1; }
|
||||
for (int64_t j = 0; j < n_cand; ++j) {
|
||||
if (ids[(size_t)j] < 0 || val[(size_t)j] == -INFINITY) continue;
|
||||
const double w = weight[(size_t)j];
|
||||
sum += w;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (ids[(size_t)j] == s.ids[k]) {
|
||||
if (first[k] < 0) first[k] = (int)j;
|
||||
pq[k] += w;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
pq[k] /= sum;
|
||||
dominated = dominated && pq[k] >= s.q[k];
|
||||
if (s.ids[k] == s.x) ix = k;
|
||||
}
|
||||
if (ix < 0) return false;
|
||||
|
||||
/* PHASE 4: the residual mass, per slot. */
|
||||
for (int64_t j = 0; j < n_cand; ++j) {
|
||||
double m = 0;
|
||||
if (ids[(size_t)j] >= 0 && val[(size_t)j] != -INFINITY) {
|
||||
bool in_q = false;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (s.ids[k] == ids[(size_t)j]) {
|
||||
in_q = true;
|
||||
if (first[k] == (int)j) m = rad_spechub_positive(pq[k] - s.q[k]);
|
||||
break;
|
||||
}
|
||||
if (!in_q) m = weight[(size_t)j] / sum;
|
||||
}
|
||||
mass[(size_t)j] = m;
|
||||
}
|
||||
|
||||
/* PHASE 5: the ordered walk. */
|
||||
double resid = 0;
|
||||
for (int64_t j = 0; j < n_cand; ++j) resid += mass[(size_t)j];
|
||||
int32_t result = -1;
|
||||
if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) {
|
||||
double cdf = u_resid * sum;
|
||||
for (int64_t j = 0; j < n_cand; ++j)
|
||||
if (ids[(size_t)j] >= 0 && val[(size_t)j] != -INFINITY) {
|
||||
const double w = weight[(size_t)j];
|
||||
if (w > 0) { result = ids[(size_t)j]; cdf -= w; if (cdf < 0) break; }
|
||||
}
|
||||
} else if (pq[ix] >= s.q[ix] || u_accept * s.q[ix] < pq[ix]) {
|
||||
result = s.x;
|
||||
} else {
|
||||
double cdf = u_resid * resid;
|
||||
for (int64_t j = 0; j < n_cand; ++j) {
|
||||
if (ids[(size_t)j] == s.x) continue;
|
||||
const double m = mass[(size_t)j];
|
||||
if (m > 0) { result = ids[(size_t)j]; cdf -= m; if (cdf < 0) break; }
|
||||
}
|
||||
}
|
||||
*out = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* A bound state over the first `qcount` ids of the plane. */
|
||||
RadMtpCoupleState bound_state(const std::vector<int32_t>& ids, int qcount, uint64_t seed,
|
||||
uint64_t pos) {
|
||||
RadMtpCoupleState s{};
|
||||
s.draw.seed = seed;
|
||||
s.draw.base = pos;
|
||||
s.draw.mode = 1;
|
||||
s.round = 1;
|
||||
s.status = 1;
|
||||
s.pos = pos;
|
||||
int32_t qidx[8];
|
||||
float qv[8];
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
qidx[i] = i < qcount ? ids[(size_t)i] : -1;
|
||||
qv[i] = i < qcount ? -0.3f * (float)i : -INFINITY;
|
||||
}
|
||||
CHECK(rad_mtp_couple_build_q(qidx, qv, (int64_t)ids.size() + 1024, &s));
|
||||
s.x = s.ids[rad_mtp_couple_pick(
|
||||
s, rad_spechub_uniform(seed, pos, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* PARITY AT EVERY WIDTH. 129, 1024 and 1025 candidates, 64 rows each, the same state and uniforms:
|
||||
* the cooperative decision must equal the serial reference on every row. 1025 is the width that
|
||||
* leaves the shared-plane band, so it exercises both paths. */
|
||||
TEST(the_cooperative_decision_equals_the_serial_reference_at_every_width) {
|
||||
for (int64_t n : { 129, 1024, 1025 }) {
|
||||
std::vector<int32_t> ids((size_t)n);
|
||||
std::vector<float> val((size_t)n);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
ids[(size_t)i] = (int32_t)i;
|
||||
/* A long decaying tail: the nucleus is narrow and the residual is a small, spread set,
|
||||
* which is where a mass-plane mistake would show. */
|
||||
val[(size_t)i] = 6.0f - 0.01f * (float)i;
|
||||
}
|
||||
int64_t agree = 0, refusals = 0;
|
||||
for (int k = 0; k < 64; ++k) {
|
||||
const uint64_t pos = (uint64_t)(n + k);
|
||||
const RadMtpCoupleState s = bound_state(ids, 8, 4242, pos);
|
||||
const double ua = rad_spechub_uniform(4242, pos, RAD_SAMPLE_KEY_ACCEPT);
|
||||
const double ur = rad_spechub_uniform(4242, pos, RAD_SAMPLE_KEY_RESID);
|
||||
|
||||
int32_t serial = -7, coop = -7;
|
||||
const bool ok_s = rad_mtp_couple_decide(s, ids.data(), val.data(), n, n, ua, ur,
|
||||
&serial);
|
||||
const bool ok_c = cooperative_decide(s, ids, val, n, ua, ur, &coop);
|
||||
CHECK_EQ(ok_c, ok_s);
|
||||
if (!ok_s) { ++refusals; continue; }
|
||||
if (serial == coop) ++agree;
|
||||
}
|
||||
CHECK_EQ(agree + refusals, (int64_t)64);
|
||||
CHECK_EQ(refusals, (int64_t)0);
|
||||
CHECK_EQ(agree, (int64_t)64);
|
||||
}
|
||||
}
|
||||
|
||||
/* HOSTILE PLANES. A hole in the middle, a duplicate id and an -inf candidate: the cooperative
|
||||
* planes must treat each exactly as the serial walk does, including the duplicate-first rule that
|
||||
* makes a repeated candidate contribute its Q mass once. */
|
||||
TEST(the_cooperative_decision_agrees_on_hostile_candidate_planes) {
|
||||
std::vector<int32_t> ids = { 0, 1, -1, 3, 3, 5, 6, -1, 8, 9 };
|
||||
std::vector<float> val = { 4.0f, 3.0f, -INFINITY, 1.5f, 1.4f, 0.5f, -1.0f, -INFINITY,
|
||||
-2.0f, -INFINITY };
|
||||
int64_t agree = 0, refused = 0;
|
||||
for (int k = 0; k < 256; ++k) {
|
||||
const uint64_t pos = (uint64_t)k;
|
||||
/* Q's shortlist holds each id ONCE -- a duplicate there is a malformed shortlist, which
|
||||
* build_q refuses by design -- while the CANDIDATE plane keeps its duplicate 3, which is the
|
||||
* duplicate-first rule the two decisions must share. */
|
||||
int32_t qidx[8];
|
||||
float qv[8];
|
||||
const int32_t qids[6] = { 0, 1, 3, 5, 6, 8 };
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
qidx[i] = i < 6 ? qids[i] : -1;
|
||||
qv[i] = i < 6 ? -0.3f * (float)i : -INFINITY;
|
||||
}
|
||||
RadMtpCoupleState s{};
|
||||
s.draw.seed = 77;
|
||||
s.draw.base = pos;
|
||||
s.draw.mode = 1;
|
||||
s.round = 1;
|
||||
s.status = 1;
|
||||
s.pos = pos;
|
||||
CHECK(rad_mtp_couple_build_q(qidx, qv, 16, &s));
|
||||
s.x = s.ids[rad_mtp_couple_pick(
|
||||
s, rad_spechub_uniform(77, pos, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
|
||||
const double ua = rad_spechub_uniform(77, pos, RAD_SAMPLE_KEY_ACCEPT);
|
||||
const double ur = rad_spechub_uniform(77, pos, RAD_SAMPLE_KEY_RESID);
|
||||
int32_t serial = -7, coop = -7;
|
||||
const bool ok_s =
|
||||
rad_mtp_couple_decide(s, ids.data(), val.data(), (int64_t)ids.size(), 16, ua, ur,
|
||||
&serial);
|
||||
const bool ok_c = cooperative_decide(s, ids, val, 16, ua, ur, &coop);
|
||||
CHECK_EQ(ok_c, ok_s);
|
||||
if (!ok_s) { ++refused; continue; }
|
||||
CHECK_EQ(coop, serial);
|
||||
++agree;
|
||||
}
|
||||
/* The duplicate id 3 appears twice; the plane is well formed, so no row should refuse. */
|
||||
CHECK_EQ(refused, (int64_t)0);
|
||||
CHECK_EQ(agree, (int64_t)256);
|
||||
}
|
||||
|
||||
/* THE GATE IS `rad_mtp_couple_state_valid`, AND IT IS THE SAME TEST ON BOTH SIDES. `decide` is total
|
||||
* over a candidate plane -- it answers whatever bytes it is given -- so the refusal that keeps an
|
||||
* uncoupled or stale row from overwriting the pick's token lives in the row gate both the kernel and
|
||||
* the sampler apply before calling it. This pins that gate rather than pretending `decide` checks a
|
||||
* state it is never given. */
|
||||
TEST(an_unbound_row_is_refused_by_the_shared_gate) {
|
||||
std::vector<int32_t> ids = { 0, 1, 2, 3 };
|
||||
std::vector<float> val = { 3.0f, 2.5f, 1.0f, -0.5f };
|
||||
RadMtpCoupleState s = bound_state(ids, 4, 9, 100);
|
||||
CHECK(rad_mtp_couple_state_valid(s, 8));
|
||||
|
||||
/* status 0: a greedy row, which has no Q to couple against. */
|
||||
RadMtpCoupleState bad = s;
|
||||
bad.status = 0;
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
|
||||
/* A q[] that no longer sums to 1: the draft's law is gone, so there is nothing to couple to. */
|
||||
bad = s;
|
||||
bad.q[0] += 0.25;
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
|
||||
/* An id outside the vocabulary, and an x outside the support. */
|
||||
bad = s;
|
||||
bad.ids[0] = 99;
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
bad = s;
|
||||
bad.x = 6;
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
|
||||
/* AND THE KERNEL GATES ON THE SAME THING. Its eligibility test is `s.status == 1 &&
|
||||
* !(p.flags & RAD_SP_GREEDY) && s.draw.seed == p.seed && s.pos == p.pos &&
|
||||
* rad_mtp_couple_state_valid(s, vocab)`, so a state that fails the validator above is refused
|
||||
* before any plane is touched. The cooperative host transcription begins with that same gate:
|
||||
* a status-0 state makes it refuse without writing. */
|
||||
RadMtpCoupleState unbound = s;
|
||||
unbound.status = 0;
|
||||
int32_t out = -7;
|
||||
CHECK(!cooperative_decide(unbound, ids, val, 8, 0.5, 0.5, &out));
|
||||
CHECK_EQ(out, (int32_t)-7); /* nothing was written */
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,282 @@
|
||||
/* tests/spechub_couple_test.cpp -- the MTP coupling's arithmetic, checked against its own law.
|
||||
*
|
||||
* What can silently go wrong in a maximal coupling, and what each test pins:
|
||||
*
|
||||
* 1. THE COMPOSED LAW. A coupling is correct when the emitted token is distributed as the
|
||||
* TARGET's P, whatever the draft's Q was. The test builds a (P, Q) pair, draws many tokens
|
||||
* through the coupling, and compares the empirical frequencies against P. This is the one
|
||||
* property that a wrong acceptance rule, a wrong residual or a swapped mass cannot survive.
|
||||
*
|
||||
* 2. THE ACCEPTANCE RULE ITSELF. A draft token is accepted when it equals the token the target
|
||||
* itself drew at that position: with Q = delta_x the coupling must return x on every draw.
|
||||
* With P(x) >= Q(x) it must accept unconditionally, because there is no residual to fall
|
||||
* back on.
|
||||
*
|
||||
* 3. THE UNDERFLOW AND DUPLICATE RULES. r(x) is exactly zero on rejection (distinct doubles never
|
||||
* subtract to 0), so the residual walk can skip x. A candidate that appears twice contributes
|
||||
* its mass once. Both are properties of the shared helpers, checked directly.
|
||||
*
|
||||
* 4. THE Q BUILD. build_q drops entries that underflow, refuses duplicate ids, and stores exactly
|
||||
* the law the draw walks -- so the numbers in state.q[] are the law, not a normalised copy of
|
||||
* it that drifted.
|
||||
*
|
||||
* Nothing here talks to a card or to libr4d: the helpers are abi/rad_spechub.h, which the plugin and
|
||||
* the engine both compile.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_sample.h"
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
/* A state as the propose kernel would leave it: Q over `ids` from `scores`, x drawn from Q. */
|
||||
RadMtpCoupleState make_state(const std::vector<int32_t>& ids, const std::vector<float>& scores,
|
||||
int64_t vocab, uint64_t seed, uint64_t base, int round) {
|
||||
RadMtpCoupleState s{};
|
||||
s.draw.seed = seed;
|
||||
s.draw.base = base;
|
||||
s.draw.seq = 1;
|
||||
s.draw.card = 0;
|
||||
s.draw.mode = 1;
|
||||
s.round = round;
|
||||
s.status = 1;
|
||||
std::vector<int32_t> id8(8, -1);
|
||||
std::vector<float> v8(8, -INFINITY);
|
||||
for (size_t i = 0; i < ids.size() && i < 8; ++i) { id8[i] = ids[i]; v8[i] = scores[i]; }
|
||||
CHECK(rad_mtp_couple_build_q(id8.data(), v8.data(), vocab, &s));
|
||||
const double u = rad_spechub_uniform(seed, base, RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)round);
|
||||
s.x = s.ids[rad_mtp_couple_pick(s, u)];
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The target's candidate plane: ids in [0, n), softmax scores. */
|
||||
void target_plane(int n, std::vector<int32_t>* ids, std::vector<float>* val) {
|
||||
ids->clear();
|
||||
val->clear();
|
||||
for (int i = 0; i < n; ++i) {
|
||||
ids->push_back(i);
|
||||
val->push_back(-0.15f * (float)i); /* a decaying, non-uniform target */
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* THE COMPOSED LAW. Whatever Q is, the coupling's output must be distributed as the target's P.
|
||||
*
|
||||
* The draft must be DRAWN FROM Q ON EVERY TRIAL, which is what a round does. Holding x fixed and
|
||||
* repeating one draw measures the acceptance rate of a single proposal -- P(x)/Q(x) -- not the
|
||||
* composed distribution, and fails against P however correct the rule is.
|
||||
*
|
||||
* The tolerance is five sigma of a binomial at this sample count, so a wrong accept rule (mass on
|
||||
* x alone) or a naive residual (a renormalised P over the non-Q tokens only) cannot pass. */
|
||||
TEST(the_coupled_token_is_distributed_as_the_target) {
|
||||
const uint64_t seed = 424242;
|
||||
const int n = 8;
|
||||
std::vector<int32_t> ids;
|
||||
std::vector<float> val;
|
||||
target_plane(n, &ids, &val);
|
||||
|
||||
/* P from the same FP64 formula the verify uses. */
|
||||
double sum = 0, P[8] = {};
|
||||
float top = -INFINITY;
|
||||
for (float v : val) top = std::max(top, v);
|
||||
for (int i = 0; i < n; ++i) { P[i] = std::exp((double)val[i] - top); sum += P[i]; }
|
||||
for (int i = 0; i < n; ++i) P[i] /= sum;
|
||||
|
||||
/* Q deliberately differs from P: three tokens, in a different order of preference. */
|
||||
const int32_t qids[8] = { 0, 1, 2, -1, -1, -1, -1, -1 };
|
||||
const float qval[8] = { 0.0f, -0.5f, -1.0f, -INFINITY, -INFINITY, -INFINITY, -INFINITY,
|
||||
-INFINITY };
|
||||
|
||||
const int draws = 40000;
|
||||
std::map<int32_t, int64_t> seen;
|
||||
for (int k = 0; k < draws; ++k) {
|
||||
const uint64_t trial = (uint64_t)k;
|
||||
/* A fresh draft from the same shortlist on every trial, at that trial's coordinate. */
|
||||
RadMtpCoupleState s{};
|
||||
s.draw.seed = seed;
|
||||
s.draw.base = trial;
|
||||
s.draw.mode = 1;
|
||||
s.round = 1;
|
||||
s.status = 1;
|
||||
CHECK(rad_mtp_couple_build_q(qids, qval, 8, &s));
|
||||
const double u_draft =
|
||||
rad_spechub_uniform(seed, trial, RAD_MTP_COUPLE_KEY_DRAFT + 1);
|
||||
s.x = s.ids[rad_mtp_couple_pick(s, u_draft)];
|
||||
|
||||
int32_t out = -1;
|
||||
CHECK(rad_mtp_couple_decide(s, ids.data(), val.data(), n, 8,
|
||||
rad_spechub_uniform(seed, trial, RAD_SAMPLE_KEY_ACCEPT),
|
||||
rad_spechub_uniform(seed, trial, RAD_SAMPLE_KEY_RESID), &out));
|
||||
++seen[out];
|
||||
}
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const double want = P[i];
|
||||
const double got = (double)seen[(int32_t)i] / (double)draws;
|
||||
const double sigma = std::sqrt(want * (1.0 - want) / (double)draws);
|
||||
CHECK_NEAR(got, want, 5.0 * sigma + 1e-9);
|
||||
}
|
||||
/* Every survivor can be emitted: a rule that lost a tail token would show as a zero here. */
|
||||
CHECK_EQ((int64_t)seen.size(), (int64_t)n);
|
||||
}
|
||||
|
||||
/* A DRAFT THE TARGET DOMINATES ON EVERY Q TOKEN IS ACCEPTED UNCONDITIONALLY: P(x) >= Q(x), so the
|
||||
* residual is empty and the ratio test has nothing to reject. The state here has ONE Q token, which
|
||||
* is the case a softmax over two tokens cannot give (two equal Q tokens of 0.5 each need P above
|
||||
* 0.5 on both, which a normalised P over three tokens cannot do). */
|
||||
TEST(a_draft_the_target_dominates_is_always_accepted) {
|
||||
RadMtpCoupleState one = make_state({ 2 }, { 0.0f }, 8, 9, 0, 1);
|
||||
CHECK_EQ(one.count, 1);
|
||||
CHECK_EQ(one.x, 2);
|
||||
std::vector<int32_t> ids = { 0, 1, 2 };
|
||||
std::vector<float> peak = { -20.0f, -20.0f, 9.0f }; /* P(2) ~ 1, Q(2) = 1 */
|
||||
for (int k = 0; k < 500; ++k) {
|
||||
int32_t out = -1;
|
||||
CHECK(rad_mtp_couple_decide(one, ids.data(), peak.data(), 3, 8,
|
||||
rad_spechub_uniform(7, (uint64_t)k, RAD_SAMPLE_KEY_ACCEPT),
|
||||
rad_spechub_uniform(7, (uint64_t)k, RAD_SAMPLE_KEY_RESID),
|
||||
&out));
|
||||
CHECK_EQ(out, 2);
|
||||
}
|
||||
|
||||
/* AND WHERE P IS SHORT OF Q THE RATIO RULE APPLIES: the same Q token with a target that barely
|
||||
* admits it is rejected most of the time, and the fallback can never emit x. */
|
||||
std::vector<float> flat = { 4.0f, 4.0f, -4.0f }; /* P(2) is small */
|
||||
int rejected = 0;
|
||||
for (int k = 0; k < 2000; ++k) {
|
||||
int32_t out = -1;
|
||||
CHECK(rad_mtp_couple_decide(one, ids.data(), flat.data(), 3, 8,
|
||||
rad_spechub_uniform(7, (uint64_t)k, RAD_SAMPLE_KEY_ACCEPT),
|
||||
rad_spechub_uniform(7, (uint64_t)k, RAD_SAMPLE_KEY_RESID),
|
||||
&out));
|
||||
if (out != 2) { ++rejected; CHECK(out == 0 || out == 1); }
|
||||
}
|
||||
CHECK(rejected > 0);
|
||||
}
|
||||
|
||||
/* THE RESIDUAL IS (P - Q)+ AND r(x) IS EXACTLY ZERO ON REJECTION. Here Q puts more mass on x than P
|
||||
* does, so x is sometimes rejected and the token must come from the OTHERS. The check that matters
|
||||
* is that y is never x on a rejected draw: r(x) contributes +0 exactly, which is what lets the walk
|
||||
* skip x without changing the total. */
|
||||
TEST(a_rejected_draft_falls_back_to_the_residual_support) {
|
||||
RadMtpCoupleState s = make_state({ 0, 1 }, { 0.0f, 0.0f }, 8, 11, 0, 1); /* Q(0) = Q(1) = 0.5 */
|
||||
CHECK_EQ(s.count, 2);
|
||||
std::vector<int32_t> ids = { 0, 1, 2 };
|
||||
/* P(0) = 0.09, so Q(0) = 0.5 exceeds it and x = 0 is rejected most of the time. */
|
||||
std::vector<float> val = { 0.0f, 2.2f, 1.0f };
|
||||
int accepted = 0, rejected = 0;
|
||||
for (int k = 0; k < 4000; ++k) {
|
||||
int32_t out = -1;
|
||||
CHECK(rad_mtp_couple_decide(s, ids.data(), val.data(), 3, 8,
|
||||
rad_spechub_uniform(3, (uint64_t)k, RAD_SAMPLE_KEY_ACCEPT),
|
||||
rad_spechub_uniform(3, (uint64_t)k, RAD_SAMPLE_KEY_RESID),
|
||||
&out));
|
||||
if (out == s.x) ++accepted;
|
||||
else { ++rejected; CHECK(out != s.x); }
|
||||
}
|
||||
CHECK(accepted > 0);
|
||||
CHECK(rejected > 0);
|
||||
}
|
||||
|
||||
/* build_q STORES THE LAW IT WALKS. A shortlist with a hole, a -inf score and a duplicate id: the
|
||||
* stored q[] sums to 1, the duplicate is refused, and the hole contributes nothing. */
|
||||
TEST(build_q_refuses_malformed_shortlists_and_drops_zero_mass) {
|
||||
RadMtpCoupleState s{};
|
||||
/* A hole at slot 1 and -inf at slot 3: two live candidates. */
|
||||
const int32_t ids[8] = { 4, -1, 7, 9, -1, -1, -1, -1 };
|
||||
const float val[8] = { 0.0f, 0.0f, -1.0f, -INFINITY, 0.0f, 0.0f, 0.0f, 0.0f };
|
||||
CHECK(rad_mtp_couple_build_q(ids, val, 16, &s));
|
||||
CHECK_EQ(s.count, 2);
|
||||
CHECK_EQ(s.ids[0], 4);
|
||||
CHECK_EQ(s.ids[1], 7);
|
||||
CHECK_EQ(s.ids[2], -1);
|
||||
CHECK_NEAR(s.q[0] + s.q[1], 1.0, 1e-15);
|
||||
|
||||
/* A duplicate id is a broken shortlist, not something to aggregate. */
|
||||
const int32_t dup[8] = { 4, 4, -1, -1, -1, -1, -1, -1 };
|
||||
CHECK(!rad_mtp_couple_build_q(dup, val, 16, &s));
|
||||
CHECK_EQ(s.count, 0);
|
||||
|
||||
/* An id outside the vocabulary, and a NaN score, are both refused. */
|
||||
const int32_t wide[8] = { 99, -1, -1, -1, -1, -1, -1, -1 };
|
||||
CHECK(!rad_mtp_couple_build_q(wide, val, 16, &s));
|
||||
const float nan_val[8] = { NAN, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
|
||||
const int32_t one[8] = { 2, -1, -1, -1, -1, -1, -1, -1 };
|
||||
CHECK(!rad_mtp_couple_build_q(one, nan_val, 16, &s));
|
||||
|
||||
/* Every candidate at -inf has no support at all. */
|
||||
float all_inf[8];
|
||||
for (int i = 0; i < 8; ++i) all_inf[i] = -INFINITY;
|
||||
CHECK(!rad_mtp_couple_build_q(one, all_inf, 16, &s));
|
||||
CHECK_EQ(s.count, 0);
|
||||
}
|
||||
|
||||
/* state_valid IS THE ONE RULE BOTH SIDES REFUSE A ROW BY. A status-0 row, a q[] that does not sum to
|
||||
* one, an id outside the vocabulary, x missing from the support, and a round outside the band are
|
||||
* all refused -- because a verifier that accepted any of them would couple against a law that is
|
||||
* not the draft's. */
|
||||
TEST(state_valid_refuses_every_malformed_row) {
|
||||
RadMtpCoupleState s = make_state({ 0, 1 }, { 0.0f, -0.2f }, 8, 5, 0, 2);
|
||||
CHECK(rad_mtp_couple_state_valid(s, 8));
|
||||
|
||||
RadMtpCoupleState bad = s;
|
||||
bad.status = 0;
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
|
||||
bad = s; bad.q[0] += 0.5; /* no longer sums to 1 */
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
|
||||
bad = s; bad.ids[0] = 99; /* outside the vocabulary */
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
|
||||
bad = s; bad.x = 6; /* x is not in the support */
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
|
||||
bad = s; bad.round = 0; /* outside the band */
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
bad = s; bad.round = RAD_MTP_COUPLE_MAX_ROUNDS + 1;
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
|
||||
bad = s; bad.draw.mode = 0; /* a greedy row's state has no Q */
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8));
|
||||
|
||||
bad = s; bad.ids[1] = -1; /* a hole above count must carry no mass */
|
||||
CHECK(!rad_mtp_couple_state_valid(bad, 8) || s.count < 2);
|
||||
}
|
||||
|
||||
/* THE UNIFORM IS THE SPECIFIED DRAW, and it is 53-bit: two seeds that differ in one bit must give
|
||||
* different numbers, and the range must be [0, 1) with no value at 1. This is the number the
|
||||
* acceptance compares P(x) against, so a uniform that repeated would make two draft positions
|
||||
* accept together. */
|
||||
TEST(the_coupling_uniform_is_the_specified_53_bit_draw) {
|
||||
for (uint64_t pos = 0; pos < 32; ++pos) {
|
||||
const double u = rad_spechub_uniform(1234, pos, RAD_SAMPLE_KEY_ACCEPT);
|
||||
CHECK(u >= 0.0 && u < 1.0);
|
||||
/* 53 bits: a multiple of 2^-53, exactly. */
|
||||
CHECK_EQ(u, std::floor(u * 9007199254740992.0) / 9007199254740992.0);
|
||||
}
|
||||
CHECK(rad_spechub_uniform(1, 0, RAD_SAMPLE_KEY_ACCEPT) !=
|
||||
rad_spechub_uniform(2, 0, RAD_SAMPLE_KEY_ACCEPT));
|
||||
CHECK(rad_spechub_uniform(1, 0, RAD_SAMPLE_KEY_ACCEPT) !=
|
||||
rad_spechub_uniform(1, 1, RAD_SAMPLE_KEY_ACCEPT));
|
||||
CHECK(rad_spechub_uniform(1, 0, RAD_SAMPLE_KEY_ACCEPT) !=
|
||||
rad_spechub_uniform(1, 0, RAD_SAMPLE_KEY_RESID));
|
||||
}
|
||||
|
||||
/* THE WIRE ROWS ARE THE SIZE THE PLANES ARE ADDRESSED AT. A field inserted into either struct would
|
||||
* 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(RAD_MTP_COUPLE_DRAW_WORDS, (size_t)8);
|
||||
CHECK_EQ(RAD_MTP_COUPLE_STATE_WORDS, (size_t)38);
|
||||
CHECK_EQ(offsetof(RadMtpCoupleState, q) % 8, (size_t)0);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,122 @@
|
||||
/* spechub_wiring_test.cpp -- what the loader and the reference gate see of the spechub plugin.
|
||||
*
|
||||
* The three spechub_*_test binaries call the abi helpers directly; none of them loads the library
|
||||
* or asks how its rows are classified, so none of them could see the bug this test exists for: a
|
||||
* plugin that declared itself a reference library had EVERY row marked reference, including its
|
||||
* two device rows, and the engine's reference gate then refused to serve `mtp_couple_propose` /
|
||||
* `mtp_couple_verify` at bringup (RAD_E_NOKERNEL) unless --debug-accept-reference-kernels was
|
||||
* passed. The switch alone could not start a coupled run.
|
||||
*
|
||||
* The check is on the real DSO, loaded the way the loader loads it (dlopen, the exported symbols,
|
||||
* nothing else): the classification the gate consumes is exactly `RadKernelInfo::domain` and the
|
||||
* reference answer, so that is what is asserted here. A host build (no RAD_SPECHUB_WITH_DEVICE)
|
||||
* has only the oracle rows and must keep being classified as reference -- that is the half of the
|
||||
* rule that must NOT be relaxed, and it is asserted too.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_abi.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Plugin {
|
||||
void* handle = nullptr;
|
||||
const RadPluginInfo* (*info)() = nullptr;
|
||||
int (*reference)() = nullptr;
|
||||
int (*kern_ref)(int) = nullptr;
|
||||
int (*count)() = nullptr;
|
||||
const RadKernelInfo* (*at)(int) = nullptr;
|
||||
|
||||
bool open(const char* path) {
|
||||
handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
|
||||
if (!handle) return false;
|
||||
info = (const RadPluginInfo* (*)())dlsym(handle, "rad_plugin_info");
|
||||
reference = (int (*)())dlsym(handle, "rad_plugin_reference");
|
||||
kern_ref = (int (*)(int))dlsym(handle, "rad_kernel_reference");
|
||||
count = (int (*)())dlsym(handle, "rad_kernel_count");
|
||||
at = (const RadKernelInfo* (*)(int))dlsym(handle, "rad_kernel_at");
|
||||
return info && reference && count && at;
|
||||
}
|
||||
~Plugin() { if (handle) dlclose(handle); }
|
||||
};
|
||||
|
||||
/* The rule rad_reference_ops applies, over the rows as the loader would classify them: an op is on
|
||||
* the reference when no row for it is a non-reference row. */
|
||||
std::vector<std::string> reference_only_ops(const Plugin& p, const std::vector<int>& is_ref) {
|
||||
std::map<std::string, bool> has_real;
|
||||
for (int i = 0; i < p.count(); ++i) {
|
||||
const RadKernelInfo* k = p.at(i);
|
||||
if (!k) continue;
|
||||
bool& real = has_real[k->op];
|
||||
real = real || !is_ref[(size_t)i];
|
||||
}
|
||||
std::vector<std::string> out;
|
||||
for (const auto& kv : has_real)
|
||||
if (!kv.second) out.push_back(kv.first);
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(spechub_wiring_the_device_rows_are_production_and_the_oracle_rows_are_reference) {
|
||||
Plugin p;
|
||||
REQUIRE(p.open(RAD_SPECHUB_LIB));
|
||||
|
||||
CHECK_EQ(p.info()->kind, (int)RAD_PLUGIN_KERNEL);
|
||||
CHECK_EQ(std::string(p.info()->name), std::string("spechub"));
|
||||
|
||||
/* The per-row answer must exist: without it the loader falls back to the library answer, which
|
||||
* is what mis-classified the device rows. */
|
||||
REQUIRE(p.kern_ref != nullptr);
|
||||
/* And the library as a whole is NOT a reference library -- otherwise the loader sorts it below
|
||||
* the kernel libraries it serves beside and every row inherits the flag. */
|
||||
CHECK_EQ(p.reference(), 0);
|
||||
|
||||
std::vector<int> is_ref;
|
||||
int dev = 0, host = 0;
|
||||
for (int i = 0; i < p.count(); ++i) {
|
||||
const RadKernelInfo* k = p.at(i);
|
||||
REQUIRE(k != nullptr);
|
||||
const int r = p.kern_ref(i);
|
||||
is_ref.push_back(r);
|
||||
if (k->domain == RAD_DOMAIN_DEVICE) {
|
||||
++dev;
|
||||
/* A device row is a kernel, never a reference: this is the line that decides whether a
|
||||
* coupled run may start at all. */
|
||||
CHECK_EQ(r, 0);
|
||||
CHECK(std::string(k->name).rfind("ref_", 0) != 0);
|
||||
} else {
|
||||
++host;
|
||||
CHECK_EQ(k->domain, (int)RAD_DOMAIN_HOST);
|
||||
/* The host oracle beside it keeps its reference status. */
|
||||
CHECK_EQ(r, 1);
|
||||
CHECK(std::string(k->name).rfind("ref_", 0) == 0);
|
||||
}
|
||||
}
|
||||
CHECK_EQ(dev + host, p.count());
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
CHECK_EQ(dev, 2);
|
||||
CHECK_EQ(host, 2);
|
||||
#else
|
||||
CHECK_EQ(dev, 0);
|
||||
CHECK_EQ(host, 2);
|
||||
#endif
|
||||
|
||||
/* Both ops must have at least one production row on a device build. This is the property the
|
||||
* gate reads: with it, the coupling is servable without --debug-accept-reference-kernels. */
|
||||
const std::vector<std::string> refonly = reference_only_ops(p, is_ref);
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
CHECK_EQ(refonly.size(), (size_t)0);
|
||||
#else
|
||||
/* No card: both ops are oracle-only, and the gate must still see them as such. */
|
||||
CHECK_EQ(refonly.size(), (size_t)2);
|
||||
#endif
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,313 @@
|
||||
/* tools/spechub_compare.cpp -- the cooperative verify against the serial one, on a real card.
|
||||
*
|
||||
* THE TARGET'S CONVENTION, NOT THE SOURCE'S: ABI 26 has no RadLaunchDesc, no RadDescribeFn and no
|
||||
* R4D_ENTRY, so this tool drives the two rows through their own `launch` hooks and compares what
|
||||
* they WRITE. That is also the only thing that matters -- the rows' contract is a token plane, and
|
||||
* a geometry description that agreed while the tokens differed would prove nothing.
|
||||
*
|
||||
* Three questions, in the order they can invalidate each other:
|
||||
*
|
||||
* 1. BYTE PARITY. Every case below runs both arms over identical operands and requires the token
|
||||
* planes to be equal, byte for byte, before any timing is believed.
|
||||
*
|
||||
* 2. THE NEGATIVE CONTROL. A case whose two arms disagree if the tool is lying: the fixture's
|
||||
* "poison" row writes a token the other arm cannot produce. A comparator that reports parity
|
||||
* there is broken.
|
||||
*
|
||||
* 3. TIMING. Alternating arms, warmup then timed launches, min/p10/median/p90/max in microseconds.
|
||||
*
|
||||
* WIDTH CASES 129, 1024 AND 1025. The last leaves the shared-plane band and takes the general
|
||||
* single-threaded path in the candidate arm, so it is a parity case and not a speed case.
|
||||
*
|
||||
* Build and run: see the README beside this file. Needs one card; the rows are device rows.
|
||||
*/
|
||||
#include "rad_abi.h"
|
||||
#include "rad_sample.h"
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
void require(bool ok, const char* why) {
|
||||
if (!ok) {
|
||||
std::fprintf(stderr, "spechub_compare: %s\n", why);
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/* A DEVICE OR HOST row loaded from the plugin, by name, and checked to be the one the file exports.
|
||||
* `want` is the domain the caller means -- the device row under test, or the host reference beside
|
||||
* it -- because both declare `mtp_couple_verify` and only the domain tells them apart. */
|
||||
struct Row {
|
||||
const RadKernelInfo* info = nullptr;
|
||||
explicit Row(const char* path, const char* name, int want) {
|
||||
void* h = dlopen(path, RTLD_NOW | RTLD_LOCAL);
|
||||
require(h != nullptr, "dlopen of the plugin failed");
|
||||
auto abi = (uint32_t (*)())dlsym(h, "rad_plugin_abi_version");
|
||||
auto count = (int (*)())dlsym(h, "rad_kernel_count");
|
||||
auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at");
|
||||
require(abi && count && at && abi() == RAD_ABI_VERSION, "plugin ABI or exports mismatch");
|
||||
for (int i = 0; i < count(); ++i) {
|
||||
const RadKernelInfo* r = at(i);
|
||||
if (r && r->name && !std::strcmp(r->name, name)) { info = r; break; }
|
||||
}
|
||||
require(info && info->launch && info->op && !std::strcmp(info->op, "mtp_couple_verify") &&
|
||||
info->domain == want,
|
||||
"the requested mtp_couple_verify row is not in the plugin at that domain");
|
||||
}
|
||||
};
|
||||
|
||||
/* One case's operands, in host memory, sized for `rows` sampled positions of `n` candidates. */
|
||||
struct Case {
|
||||
int rows = 1, n = 8;
|
||||
std::vector<int32_t> idx, token;
|
||||
std::vector<float> val;
|
||||
std::vector<uint32_t> params, state;
|
||||
std::vector<int32_t> want; /* the arm A result, for parity */
|
||||
};
|
||||
|
||||
/* Fill a case: P over `n` candidates, Q over the first eight, a state bound to row 0's parameters.
|
||||
* `mix` selects a draft that is usually accepted or usually rejected, which is the two halves of a
|
||||
* coupled row's life. */
|
||||
void build(Case* c, int rows, int n, bool accept_first) {
|
||||
c->rows = rows;
|
||||
c->n = n;
|
||||
const int64_t nc = n;
|
||||
const int64_t w = 24; /* RadSampleParams words */
|
||||
const int64_t sw = RAD_MTP_COUPLE_STATE_WORDS;
|
||||
c->idx.assign((size_t)(rows * nc), -1);
|
||||
c->val.assign((size_t)(rows * nc), -INFINITY);
|
||||
c->params.assign((size_t)(rows * w), 0);
|
||||
c->state.assign((size_t)(rows * sw), 0);
|
||||
c->token.assign((size_t)rows, -7);
|
||||
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
/* P: a descending plane, so the nucleus is narrow and the residual is a spread tail. */
|
||||
for (int64_t j = 0; j < nc; ++j) {
|
||||
c->idx[(size_t)(r * nc + j)] = (int32_t)j;
|
||||
c->val[(size_t)(r * nc + j)] = 6.0f - 0.004f * (float)j;
|
||||
}
|
||||
RadSampleParams* p = reinterpret_cast<RadSampleParams*>(&c->params[(size_t)(r * w)]);
|
||||
p->seed = 2024;
|
||||
p->pos = (uint64_t)(100 + r);
|
||||
p->temp = 1.0f;
|
||||
p->top_k = 0;
|
||||
p->mask_row = -1;
|
||||
|
||||
RadMtpCoupleState* s = reinterpret_cast<RadMtpCoupleState*>(&c->state[(size_t)(r * sw)]);
|
||||
s->draw.seed = p->seed;
|
||||
s->draw.base = p->pos;
|
||||
s->draw.seq = (uint64_t)(r + 1);
|
||||
s->draw.card = r;
|
||||
s->draw.mode = 1;
|
||||
s->pos = p->pos;
|
||||
s->round = 1;
|
||||
s->status = 1;
|
||||
/* Q over the first eight: the head's own shortlist. `accept_first` ranks the target's
|
||||
* favourite first, so most drafts are accepted; otherwise it favours a token the target
|
||||
* discounts, so most are rejected and the residual carries the row. */
|
||||
int32_t qi[8];
|
||||
float qv[8];
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
qi[i] = accept_first ? i : (int32_t)(nc - 1 - i);
|
||||
qv[i] = -0.05f * (float)i;
|
||||
}
|
||||
require(rad_mtp_couple_build_q(qi, qv, nc, s), "build_q refused the fixture's shortlist");
|
||||
s->x = s->ids[rad_mtp_couple_pick(
|
||||
*s, rad_spechub_uniform(s->draw.seed, s->draw.base, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
|
||||
}
|
||||
}
|
||||
|
||||
/* One launch of one row against a device copy of the case. */
|
||||
struct Device {
|
||||
void* idx = nullptr; void* val = nullptr; void* params = nullptr; void* state = nullptr;
|
||||
void* token = nullptr;
|
||||
hipStream_t stream = nullptr;
|
||||
|
||||
void upload(const Case& c) {
|
||||
const size_t n_idx = c.idx.size() * 4, n_val = c.val.size() * 4;
|
||||
const size_t n_p = c.params.size() * 4, n_s = c.state.size() * 4, n_t = c.token.size() * 4;
|
||||
require(hipMalloc(&idx, n_idx) == hipSuccess && hipMalloc(&val, n_val) == hipSuccess &&
|
||||
hipMalloc(¶ms, n_p) == hipSuccess && hipMalloc(&state, n_s) == hipSuccess &&
|
||||
hipMalloc(&token, n_t) == hipSuccess, "device allocation failed");
|
||||
require(hipMemcpy(idx, c.idx.data(), n_idx, hipMemcpyHostToDevice) == hipSuccess &&
|
||||
hipMemcpy(val, c.val.data(), n_val, hipMemcpyHostToDevice) == hipSuccess &&
|
||||
hipMemcpy(params, c.params.data(), n_p, hipMemcpyHostToDevice) == hipSuccess &&
|
||||
hipMemcpy(state, c.state.data(), n_s, hipMemcpyHostToDevice) == hipSuccess,
|
||||
"upload failed");
|
||||
}
|
||||
void reset_token(const std::vector<int32_t>& t) {
|
||||
require(hipMemcpy(token, t.data(), t.size() * 4, hipMemcpyHostToDevice) == hipSuccess,
|
||||
"token reset failed");
|
||||
}
|
||||
void read(std::vector<int32_t>* out, size_t count) {
|
||||
out->resize(count);
|
||||
require(hipMemcpy(out->data(), token, count * 4, hipMemcpyDeviceToHost) == hipSuccess,
|
||||
"readback failed");
|
||||
}
|
||||
~Device() {
|
||||
for (void* p : { idx, val, params, state, token })
|
||||
if (p) (void)hipFree(p);
|
||||
}
|
||||
};
|
||||
|
||||
/* The operands the row's launch hook reads, in the schema's order. */
|
||||
struct Args {
|
||||
RadTensor t[5]{};
|
||||
std::vector<RadParam> p;
|
||||
RadArgs a{};
|
||||
};
|
||||
|
||||
void make_args(Args* out, const Case& c, const Device& d) {
|
||||
auto row2 = [&](RadTensor* t, void* data, uint32_t dt, int64_t r, int64_t cols, int64_t stride) {
|
||||
t->data = data;
|
||||
t->dtype = dt;
|
||||
t->rank = 2;
|
||||
t->shape[0] = r;
|
||||
t->shape[1] = cols;
|
||||
t->stride[0] = stride;
|
||||
t->stride[1] = 1;
|
||||
};
|
||||
row2(&out->t[0], d.idx, RAD_I32, c.rows, c.n, c.n);
|
||||
row2(&out->t[1], d.val, RAD_F32, c.rows, c.n, c.n);
|
||||
row2(&out->t[2], d.params, RAD_U32, c.rows, 24, 24);
|
||||
row2(&out->t[3], d.state, RAD_U32, c.rows, RAD_MTP_COUPLE_STATE_WORDS,
|
||||
RAD_MTP_COUPLE_STATE_WORDS);
|
||||
row2(&out->t[4], d.token, RAD_I32, c.rows, 1, 1);
|
||||
|
||||
out->p.clear();
|
||||
out->p.push_back(RadParam{ "M", RAD_P_INT, c.rows, 0, nullptr });
|
||||
out->p.push_back(RadParam{ "n_cand", RAD_P_INT, c.n, 0, nullptr });
|
||||
out->p.push_back(RadParam{ "n_vocab", RAD_P_INT, 200000, 0, nullptr });
|
||||
|
||||
out->a = RadArgs{};
|
||||
out->a.t = out->t;
|
||||
out->a.n_t = 5;
|
||||
out->a.p = out->p.data();
|
||||
out->a.n_p = (int)out->p.size();
|
||||
out->a.rank = 0;
|
||||
out->a.world_size = 1;
|
||||
}
|
||||
|
||||
double median_of(std::vector<double> v) {
|
||||
std::sort(v.begin(), v.end());
|
||||
return v[v.size() / 2];
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const char* plugin = argc > 1 ? argv[1] : "build/radiance_home/kernels/spechub.so";
|
||||
int card = argc > 2 ? std::atoi(argv[2]) : 0;
|
||||
|
||||
require(hipSetDevice(card) == hipSuccess, "hipSetDevice failed");
|
||||
hipDeviceProp_t prop{};
|
||||
require(hipGetDeviceProperties(&prop, card) == hipSuccess, "hipGetDeviceProperties failed");
|
||||
std::printf("card=%d %s\n", card, prop.name);
|
||||
|
||||
/* THE TWO ARMS ARE THE SAME ROW IN TWO PLUGINS: the candidate is this tree's cooperative row,
|
||||
* the frozen arm is the serial reference row the same library exports. Comparing against a
|
||||
* reimplementation would prove nothing about what serves. */
|
||||
const Row candidate(plugin, "spechub_mtp_couple_verify", RAD_DOMAIN_DEVICE);
|
||||
const Row frozen(plugin, "ref_mtp_couple_verify", RAD_DOMAIN_HOST);
|
||||
require(candidate.info->domain == RAD_DOMAIN_DEVICE && frozen.info->domain == RAD_DOMAIN_HOST,
|
||||
"the two arms are not the device row and its reference");
|
||||
|
||||
struct Spec { const char* label; int rows; int n; bool accept_first; };
|
||||
const Spec specs[] = {
|
||||
{ "accept-first", 4, 1024, true },
|
||||
{ "reject-first", 4, 1024, false },
|
||||
{ "narrow-129", 3, 129, true },
|
||||
{ "wide-1025", 2, 1025, true },
|
||||
};
|
||||
|
||||
for (const Spec& sp : specs) {
|
||||
Case c;
|
||||
build(&c, sp.rows, sp.n, sp.accept_first);
|
||||
Device da, db;
|
||||
da.upload(c);
|
||||
db.upload(c);
|
||||
require(hipStreamCreate(&da.stream) == hipSuccess && hipStreamCreate(&db.stream) == hipSuccess,
|
||||
"stream creation failed");
|
||||
|
||||
Args aa, ab;
|
||||
make_args(&aa, c, da);
|
||||
make_args(&ab, c, db);
|
||||
|
||||
/* PARITY FIRST: both arms over identical operands, then a byte comparison of the tokens. */
|
||||
const int ra = candidate.info->launch(&aa.a, reinterpret_cast<RadStream>(da.stream));
|
||||
const int rb = frozen.info->launch(&ab.a, reinterpret_cast<RadStream>(db.stream));
|
||||
require(ra == RAD_OK && rb == RAD_OK, "a verify arm refused the case");
|
||||
require(hipStreamSynchronize(da.stream) == hipSuccess &&
|
||||
hipStreamSynchronize(db.stream) == hipSuccess, "a verify arm's stream failed");
|
||||
std::vector<int32_t> ta, tb;
|
||||
da.read(&ta, (size_t)c.rows);
|
||||
db.read(&tb, (size_t)c.rows);
|
||||
const bool same = std::memcmp(ta.data(), tb.data(), (size_t)c.rows * 4) == 0;
|
||||
std::printf("case=%s rows=%d n=%d tokens=%d,%d parity=%s\n", sp.label, sp.rows, sp.n,
|
||||
ta.empty() ? -1 : ta[0], tb.empty() ? -1 : tb[0], same ? "byte_exact" : "DIFFER");
|
||||
require(same, "the cooperative arm and the serial arm disagree");
|
||||
|
||||
/* THE NEGATIVE CONTROL: poison the token plane and require the arms NOT to agree with the
|
||||
* poison. A comparator that reports parity here is not reading what it launches. */
|
||||
{
|
||||
std::vector<int32_t> poison((size_t)c.rows, 1234567);
|
||||
da.reset_token(poison);
|
||||
const int rc = candidate.info->launch(&aa.a, reinterpret_cast<RadStream>(da.stream));
|
||||
require(rc == RAD_OK && hipStreamSynchronize(da.stream) == hipSuccess,
|
||||
"the poisoned launch failed");
|
||||
std::vector<int32_t> out;
|
||||
da.read(&out, (size_t)c.rows);
|
||||
const bool poisoned = std::memcmp(out.data(), poison.data(), (size_t)c.rows * 4) == 0;
|
||||
std::printf("case=%s negative-control=%s\n", sp.label, poisoned ? "BROKEN" : "ok");
|
||||
require(!poisoned, "the negative control passed: the comparator reads nothing");
|
||||
require(std::memcmp(out.data(), tb.data(), (size_t)c.rows * 4) == 0,
|
||||
"the replayed launch does not reproduce the reference");
|
||||
}
|
||||
|
||||
/* TIMING: alternating arms so a clock drift hits both, warmup then timed launches. */
|
||||
if (sp.n <= 1024) {
|
||||
const int warmup = 50, timed = 400;
|
||||
const std::vector<int32_t> init((size_t)c.rows, -7);
|
||||
for (int i = 0; i < warmup; ++i) {
|
||||
da.reset_token(init);
|
||||
(void)candidate.info->launch(&aa.a, reinterpret_cast<RadStream>(da.stream));
|
||||
(void)frozen.info->launch(&ab.a, reinterpret_cast<RadStream>(db.stream));
|
||||
}
|
||||
require(hipStreamSynchronize(da.stream) == hipSuccess &&
|
||||
hipStreamSynchronize(db.stream) == hipSuccess, "warmup failed");
|
||||
std::vector<double> us_a, us_b;
|
||||
for (int i = 0; i < timed; ++i) {
|
||||
/* A launch alone would measure only submission; the synchronise is the row's cost. */
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
(void)candidate.info->launch(&aa.a, reinterpret_cast<RadStream>(da.stream));
|
||||
require(hipStreamSynchronize(da.stream) == hipSuccess, "timed launch failed");
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
(void)frozen.info->launch(&ab.a, reinterpret_cast<RadStream>(db.stream));
|
||||
require(hipStreamSynchronize(db.stream) == hipSuccess, "timed launch failed");
|
||||
const auto t2 = std::chrono::steady_clock::now();
|
||||
using us = std::chrono::duration<double, std::micro>;
|
||||
us_a.push_back(us(t1 - t0).count());
|
||||
us_b.push_back(us(t2 - t1).count());
|
||||
}
|
||||
std::printf("timing case=%s candidate median_us=%.3f serial median_us=%.3f ratio=%.3f\n",
|
||||
sp.label, median_of(us_a), median_of(us_b),
|
||||
median_of(us_a) / median_of(us_b));
|
||||
}
|
||||
(void)hipStreamDestroy(da.stream);
|
||||
(void)hipStreamDestroy(db.stream);
|
||||
}
|
||||
std::printf("done\n");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user