Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port

102 upstream commits. Nine conflicts resolved. Fork side of the merge:
- libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it
  from libavx and libref; the device libraries now each carry it).
- plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table
  regenerated, kTableAbi = 42.

Known before the PR: arch_test (MTP lint and pinned graph hashes for
qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
aneinanderandClaude Opus 5.5 committed 2026-11-18 15:06:17 +01:00
commit 4b70a96378
850 files changed
+157819 -58519

No files matched your search

+25 -5
View File
@@ -21,7 +21,7 @@ extern "C" {
* (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default.
* rad_sycl.h is versioned on its own (RAD_SYCL_STREAM_VERSION), since only SYCL kernel libraries
* read it. */
#define RAD_ABI_VERSION 37u
#define RAD_ABI_VERSION 42u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
@@ -64,8 +64,8 @@ typedef struct RadArgs {
int world_size;
/* ABI 35: host-side maximum KV length represented by this exact launch operand (a seqused
* span or a supported one-sequence prefill boundary), or -1 when it cannot be proven. In a
* decode, verify or draft pass of an architecture with no rad_arch_pass_key it is instead the
* step's context bound plus its longest query, which the recorded pass's key holds. Plugins
* decode, verify or draft pass it is instead the step's context bound plus its longest query,
* which the recorded pass's key holds. Plugins
* must not infer it from a device pointer or synchronously read device memory to get it. */
int32_t kv_used_max_h;
/* The current rank's WGP count (HIP multiProcessorCount on RDNA); lets split launchers use
@@ -164,7 +164,8 @@ typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEnc
/* Write the stored form `layout` described into `dst`, `dst_bytes` long, from the planes, which
* now carry their bytes. Pure host code, run by the loader on a pool behind the container read,
* so it has to keep pace with the disk. */
* so it has to keep pace with the disk. The planes are read only: the loader may hand them
* straight out of its read buffer, which the copies for other ranks read at the same time. */
typedef int (*RadRelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes, void* dst,
int64_t dst_bytes);
@@ -517,6 +518,15 @@ const RadKernelInfo* rad_kernel_at(int i);
typedef int (*RadPluginOpenFn) (void);
typedef void (*RadPluginCloseFn)(void);
/* Optional, symbol `rad_plugin_freed`. The core has freed the device memory [base, base + bytes)
* and nothing launched against it runs any more. A kernel library that keeps state keyed by an
* operand's address (a counter block per output buffer, made at the first launch and replayed by
* recorded passes) drops what it keeps for addresses inside the range. A process serving several
* models frees an engine's memory when it unloads the model, so state kept past that would pile
* up with every load. Called from the freeing thread, any number of times, possibly for ranges the
* plugin never saw. */
typedef void (*RadPluginFreedFn)(const void* base, int64_t bytes);
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means every launch reads and writes
* only its operands and the scratch it was handed (no allocation it keeps, no counter kept between
* launches), so two launches may run at once on one device when their operands and scratch do not
@@ -536,7 +546,17 @@ typedef int (*RadKernelConcurrentFn)(int i);
* do, adds exactly once. The record is RAD_CHAIN_REC_BYTES at byte RAD_CHAIN_KARG_OFF of the
* kernel's argument segment: { magic, target, ctr, check }, with check = magic ^ target ^ ctr ^
* RAD_CHAIN_CHECK. A record whose magic or check does not match means: run without waiting and do
* not add. Without the symbol, or with 0, the engine never asks. Symbol name: `rad_kernel_chain`. */
* not add. Without the symbol, or with 0, the engine never asks.
*
* 2 instead of 1 adds a second promise: the chained form's own acquire covers everything it reads
* behind the wait, scalar loads included. A compiler's agent-scope fence invalidates the vector
* caches only; a load every lane shares may be a scalar one, served from the scalar data cache,
* which still holds what was there before the launch in front wrote. A form that invalidates that
* cache behind its acquire (`s_dcache_inv`), or reads no operand through it, may say 2. Where
* every chainable row an engine loads says 2, the engine issues a chained launch that has lost
* its barrier bit without the packet processor's acquire as well: on an R9700 that acquire holds
* the processor ~0.9 us a launch, and it comes too early to serve a kernel that then waits for
* the launch in front. With 1 the packets keep it. Symbol name: `rad_kernel_chain`. */
typedef int (*RadKernelChainFn)(int i);
#define RAD_CHAIN_KARG_OFF 992
#define RAD_CHAIN_REC_BYTES 32
+10 -3
View File
@@ -17,7 +17,7 @@ ABI_FIELD(RadArchProbe, gen_patches)
ABI_FIELD(RadArchProbe, gen_audio)
ABI_FIELD(RadArchProbe, gen_ctx)
ABI_FIELD(RadArchProbe, gen_video)
ABI_FIELD(RadArchProbe, kv_quant_ok)
ABI_FIELD(RadArchProbe, kv_fp8_ok)
ABI_FIELD(RadArchProbe, chain_pays)
ABI_FIELD(RadArchProbe, kv_stream_ok)
ABI_FIELD(RadArchProbe, control_vector_ok)
@@ -130,8 +130,6 @@ ABI_FIELD(RadBuildCtx, max_enc_patches)
ABI_FIELD(RadBuildCtx, max_out_rows)
ABI_FIELD(RadBuildCtx, max_audio_frames)
ABI_FIELD(RadBuildCtx, max_mixed_tok)
ABI_FIELD(RadBuildCtx, kv_quant)
ABI_FIELD(RadBuildCtx, attn_prefill_fp8)
ABI_FIELD(RadBuildCtx, kv_resident_blocks)
ABI_FIELD(RadBuildCtx, kv_stream_ok)
ABI_FIELD(RadBuildCtx, cvec)
@@ -147,6 +145,7 @@ ABI_FIELD(RadBuildCtx, calib_tokens)
ABI_FIELD(RadBuildCtx, gen_max_pixels)
ABI_FIELD(RadBuildCtx, gen_max_refs)
ABI_FIELD(RadBuildCtx, expert_file_tier)
ABI_FIELD(RadBuildCtx, slot_base)
ABI_FIELD(RadBuildCtx, plain_norm)
ABI_STRUCT(RadAudioGenBatch)
ABI_FIELD(RadAudioGenBatch, n_lane)
@@ -194,6 +193,7 @@ ABI_FIELD(RadAudioGenBatch, ref_cu)
ABI_FIELD(RadAudioGenBatch, ref_cu_h)
ABI_FIELD(RadAudioGenBatch, ref_frame)
ABI_FIELD(RadAudioGenBatch, ref_frame_h)
ABI_FIELD(RadAudioGenBatch, prompt_cu_h)
ABI_STRUCT(RadAudioGenDecl)
ABI_FIELD(RadAudioGenDecl, name)
ABI_FIELD(RadAudioGenDecl, tmpl)
@@ -234,6 +234,8 @@ ABI_FIELD(RadAudioGenDecl, ref_rate)
ABI_FIELD(RadAudioGenDecl, ref_hop)
ABI_FIELD(RadAudioGenDecl, ref_max_samples)
ABI_FIELD(RadAudioGenDecl, ref_max)
ABI_FIELD(RadAudioGenDecl, tmpl_ref_instruct)
ABI_FIELD(RadAudioGenDecl, neg_tmpl_ref)
ABI_STRUCT(RadControlVector)
ABI_FIELD(RadControlVector, dir)
ABI_FIELD(RadControlVector, scales)
@@ -280,6 +282,7 @@ ABI_FIELD(RadChatFormat, object_string_close)
ABI_FIELD(RadChatFormat, object_bare_keys)
ABI_FIELD(RadChatFormat, reasoning_anywhere)
ABI_FIELD(RadChatFormat, arg_json_value_prefix)
ABI_FIELD(RadChatFormat, content_open)
ABI_STRUCT(RadConstraint)
ABI_FIELD(RadConstraint, key)
ABI_FIELD(RadConstraint, op)
@@ -953,3 +956,7 @@ ABI_FIELD(RadMtpCoupleState, x)
ABI_FIELD(RadMtpCoupleState, count)
ABI_FIELD(RadMtpCoupleState, ids)
ABI_FIELD(RadMtpCoupleState, q)
ABI_FIELD(RadMtpCoupleState, nkids)
ABI_FIELD(RadMtpCoupleState, scheme)
ABI_FIELD(RadMtpCoupleState, blk)
ABI_FIELD(RadMtpCoupleState, pad_)
+96 -68
View File
@@ -56,35 +56,27 @@ double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt);
const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt);
/* ================================================================== build context */
/* RadBuildCtx::kv_quant. A layout groups each head's dims by 32 with an f16 scale per group, the
* group's absmax over the largest code. A token's row in a head, at head_dim HD (a multiple of 32):
/* A paged cache group's dtype says how a token's row in a head is laid out, at head_dim HD:
*
* RAD_KVQ_V4 (fp8_v4), 25 * HD / 16 bytes:
* [0, HD) K, E4M3 as the fp8 cache stores it
* [HD, 3HD/2) V's int4 codes, dim d in the nibble at bit 4 * (d % 2) of byte d / 2
* [3HD/2, 25HD/16) V's scales (absmax / 7)
* RAD_KVQ_K6V4 (k6_v4), 22 * HD / 16 bytes:
* [0, HD/2) K's low four bits, as V's codes above
* [HD/2, 3HD/4) K's high two bits, a 4-byte word per 16 dims whose byte j holds dims 2j
* and 2j+1 in bits 0-3 and dims 8+2j and 9+2j in bits 4-7
* [3HD/4, 5HD/4) V's int4 codes
* [5HD/4, 21HD/16) K's scales (absmax / 31)
* [21HD/16, 22HD/16) V's scales (absmax / 7)
*
* Codes are two's complement (int4 -7..7, int6 -31..31). The group is declared at RAD_F8E4M3 with
* head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read
* it. */
enum {
RAD_KVQ_NONE = 0,
RAD_KVQ_V4 = 1,
RAD_KVQ_K6V4 = 2
};
* RAD_BF16, 4 * HD bytes: K then V, as the model computes them.
* RAD_I8, 2 * HD + 4 bytes: K and V as int8 codes with one f16 scale each per (token, head):
* [0, HD) K's int8 codes (two's complement, -127..127)
* [HD, 2HD) V's int8 codes
* [2HD, 2HD + 2) K's scale (the head's absmax / 127)
* [2HD + 2, 2HD + 4) V's scale (absmax / 127)
* The plugin declares HD; the core adds the scales' bytes (rad_kv_row_elems). */
/* The products of the prefill attention a deployment accepts in e4m3 (RadBuildCtx::
* attn_prefill_fp8, `attn_paged`'s `prefill_fp8`): bits, so both is 3. */
/* Elements of a token's row in one head of a paged group declared at `dtype` and `head_dim`: K
* then V, and under the int8 cache the two f16 scales after them. */
static inline int64_t rad_kv_row_elems(uint32_t dtype, int64_t head_dim) {
return 2 * head_dim + (dtype == RAD_I8 ? 4 : 0);
}
/* RadArchProbe::chain_pays. */
enum {
RAD_ATTN_FP8_QK = 1, /* Q.K^T, the query rounded to e4m3 after the softmax scale */
RAD_ATTN_FP8_PV = 2 /* P.V, the probabilities rounded to e4m3 */
RAD_CHAIN_NONE = 0,
RAD_CHAIN_SPEC = 1, /* with a drafter decoding speculatively */
RAD_CHAIN_ALWAYS = 2 /* with or without one */
};
typedef struct RadBuildCtx {
@@ -111,17 +103,16 @@ typedef struct RadBuildCtx {
int64_t tp_wire_min_bytes;
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint: fp8
* weights may want a bf16 cache and vice versa.
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint.
*
* RAD_DT_INVALID (the zero-initialised default) means the plugin's default, bf16 for every
* architecture in this tree. RAD_F8E4M3 is the only other implemented value: the fp8kv
* attention family is band-gated on it, and the store side writes E4M3 with per-(sequence,
* head) descales. `kv_quant` below narrows the trunk's attention cache further.
* architecture in this tree. RAD_I8 is the other value every paged attention serves, the
* int8 cache above: the attention kernels band on it and the store writes each token's codes
* and scales. RAD_F8E4M3 reaches only a plugin whose probe sets RadArchProbe::kv_fp8_ok.
*
* An ABI field rather than an environment variable because it changes what the model
* computes, so it must have one visible answer: --kv-cache-dtype. */
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); or RAD_F8E4M3 */
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); RAD_I8; RAD_F8E4M3 */
int is_draft; /* this builder scope is a drafter (spec §10) */
const char* scope; /* "", "draft", "vision", "audio" -- prefixes declared names */
@@ -172,25 +163,6 @@ typedef struct RadBuildCtx {
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int64_t max_mixed_tok;
/* A narrower layout of the trunk's attention cache under kv_dtype RAD_F8E4M3, from
* --kv-cache-dtype fp8_v4 or k6_v4: a RAD_KVQ_* (below). The engine sets it only for a plugin
* whose probe has the layout's bit in RadArchProbe::kv_quant_ok and refuses the flag
* otherwise, so no plugin sees it that would store plain E4M3 instead. A drafter's cache stays
* E4M3.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int kv_quant;
/* ---- appended in ABI 26 (fp8 prefill attention) */
/* RAD_ATTN_FP8_* bits from --attn-prefill-fp8: the attention products the deployment accepts
* in e4m3 rather than exactly. 0 (the zero-initialised default) is exact. A plugin passes a
* nonzero value on as `attn_paged`'s `prefill_fp8` (docs/OPS.md) and omits the parameter at
* 0, so an exact declare is unchanged. The engine refuses to start when no resolved kernel
* takes it, so a plugin that ignores the field is refused rather than silently exact.
*
* Zero-defaulted and in the padding after kv_quant, so no other field moves. */
int attn_prefill_fp8;
/* ---- appended in ABI 30 (KV streaming) */
/* --kv-resident in tokens, 0 when nothing streams: the ring a streamed group carves is this in
* whole blocks, raised to the engine's floors and clamped to the context. A plugin states it as
@@ -302,19 +274,32 @@ typedef struct RadBuildCtx {
* keeps them whole for this; 0 leaves it free to split them across the ranks by width. */
int expert_file_tier;
/* ---- appended in the SYCL fork (the plain block norm) */
/* ---- appended in ABI 38 (several engines in one process) */
/* The first of this engine's slots. Each engine in the process holds a contiguous block of
* slots, one per rank, so an instance's slot, `slot_base + rank` (rad_build_slot), is unique
* among the ranks of every engine alive, where `rank` is unique only within one engine. A
* plugin keeps per-instance state (handles, geometry, its step's view of the model) indexed by
* the slot, and reads it back in step() with rad_slot(). Zero, the default, makes the slot the
* rank: one engine in a process, or a test driving a plugin alone. Two engines may serve the
* same plugin at once only when it says so (rad_arch_multi_instance). */
int slot_base;
/* ---- appended in ABI 42 (the plain block norm) */
/* Nonzero: where no reader of a block norm's output takes its E4M3 code pair (every reader a
* 4-bit or plain bf16 projection, which reads the bf16 plane), the plugin may run the norm as
* `add` (the residual stored first, as `rmsnorm_quant_fp8` stores it) then `rmsnorm`: the same
* bf16 values, without codes nobody reads. The engine sets it on the SYCL backend, whose
* quantising norm is bound by libref's ordered sum of squares while its `rmsnorm` is a fast
* row (docs/SYCL_PROGRESS.md); 0 elsewhere, so other backends declare what they did.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. 64-bit
* so it starts past the end of ABI 37's struct, not in the padding after expert_file_tier. */
int64_t plain_norm;
* row (docs/SYCL_PROGRESS.md); 0 elsewhere, so other backends declare what they did. */
int plain_norm;
} RadBuildCtx;
/* The most instances (engine ranks) one process holds at once; every slot is below it. */
#define RAD_MAX_SLOTS 32
/* The declaring instance's slot (see RadBuildCtx::slot_base). */
static inline int rad_build_slot(const RadBuildCtx* c) { return c->slot_base + c->rank; }
/* ================================================================== control vectors */
/* A direction per layer, in the shape llama.cpp's `--cvec-mode project` applies it:
*
@@ -846,6 +831,23 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
* the drafter's passes (the KL mode drafts nothing, so trees do not apply there). */
int rad_drafter_tree(RadBuilder* b, rad_buf parents);
/* The model's routing counts live in `table`: an i32 RAD_BUF_PERSIST device buffer of at least
* [layers, n_expert], one row per layer that reports (rad_route_report's `layer`, so a head past
* the trunk counts) and n_expert the model's expert count. Each layer's router writes its counts
* into its own row and the report names that row as RadRouting::expert_count; the core takes it
* in place and copies the pass's rows to the host once, at the end of the pass. Without a table
* the core keeps the rows itself and a report costs one copy dispatch per routed layer on the
* compute stream, since a plugin cannot bind the core's rows as operands of a recorded pass. A
* report naming any other buffer is still copied, into the layer's row of the table.
*
* A row per layer also means a consumer that reads a layer's counts later in stream order (the
* file stager, at the layer's first expert op) reads that layer's, which one buffer shared by
* every layer does not guarantee once a later layer's router has run.
*
* Called at most once. The row count is checked when a context binds, where the reporting layers
* are known. Additive export; RAD_ABI_VERSION does not move. */
int rad_route_table(RadBuilder* b, rad_buf table);
/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on
* the AQL backend only, which keeps a completion counter per queue, where the model's plugin
* measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
@@ -1271,13 +1273,22 @@ typedef struct RadAudioGenDecl {
* prepare() has limited to those a caller may write), and so is the text after it. A clip is
* mono f32 in [-1, 1] at `ref_rate`, right-padded with zeros to a whole number of `ref_hop`
* samples, each `ref_hop` samples one frame; a request's clips hold at most `ref_max_samples`
* samples together. NULL `tmpl_ref`: references are refused. */
* samples together. With two branches, references require default_cfg 1 and a plain
* neg_tmpl: guidance 1 repeats the conditional prompt and frame map in both branches.
* Reference direction is opt-in through the templates appended below. NULL `tmpl_ref`:
* references are refused. */
const char* tmpl_ref;
const char* ref_item;
int64_t ref_rate;
int64_t ref_hop;
int64_t ref_max_samples;
int32_t ref_max;
/* ABI 40: reference-plus-instructions uses tmpl_ref_instruct ({references},
* {instructions}, {input} once each). Its guidance baseline is neg_tmpl_ref
* ({references}, {input}, no instructions). Both branches retain the same clips;
* their text lengths and reference-frame maps may differ. NULL: direction refused. */
const char* tmpl_ref_instruct;
const char* neg_tmpl_ref;
} RadAudioGenDecl;
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
@@ -1605,6 +1616,13 @@ const char* rad_arch_quant(void);
* move. */
int rad_arch_serves_imports(void);
/* Nonzero when every piece of per-instance state the plugin keeps is indexed by
* rad_build_slot() / rad_slot(), so several engines in one process may run it at once
* (docs/MULTIMODEL.md §3.3). Optional: absent or zero, the core runs the plugin for one engine at
* a time and refuses a second engine on it by name. arch/common/rad_arch.h writes it with
* RAD_ARCH_MULTI_INSTANCE(). */
int rad_arch_multi_instance(void);
/* What the plugin can say before it declares anything. Optional: a plugin that does not export
* it answers zero to everything, each field's default.
*
@@ -1664,17 +1682,18 @@ typedef struct RadArchProbe {
* `gen_rows` (its largest pass: a step's packed sequence at the largest size and length). It
* keeps no KV. */
int32_t gen_video;
/* The RadBuildCtx::kv_quant layouts the plugin serves for this model, bit 1 << RAD_KVQ_*:
* libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at
* startup with the plugin named. */
int32_t kv_quant_ok;
/* Nonzero when the plugin serves an E4M3 cache for this model (--kv-cache-dtype fp8,
* RadBuildCtx::kv_dtype RAD_F8E4M3): GLM-5.3's latent attention. The engine refuses the flag
* for a plugin that leaves it zero, naming the int8 cache every paged attention serves. */
int32_t kv_fp8_ok;
/* ---- appended in ABI 26 (chained launches, control vectors) */
/* Nonzero when this plugin measured its speculative step faster with chained launches
* (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the
* queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core
* then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin
* that never measured them asks for nothing. */
/* How this plugin measured chained launches (RadKernelChainFn: a dependent kernel waits in its
* own prologue rather than behind the queue's barrier bit), a RAD_CHAIN_*. SPEC: its
* speculative step is faster with them, and the core takes them on the AQL backend while a
* drafter decodes speculatively. ALWAYS: its plain decode is faster too, and the core takes
* them with or without a drafter. Zero keeps them off: some models' plain decode measured
* slower chained, and a plugin that never measured them asks for nothing. */
int32_t chain_pays;
/* ---- appended in ABI 30 (KV streaming) */
/* Nonzero when the architecture can stream a KV group between host memory and a VRAM ring: its
@@ -1846,6 +1865,13 @@ typedef struct RadChatFormat {
* decides how its value is read, whatever the schema says; the grammar writes the one the
* schema calls for. NULL: the schema alone types a value. */
const char* arg_json_value_prefix;
/* A header the model writes first when it answers without reasoning, in place of
* reasoning_open: the reply then starts with this literal, which is dropped, and the rest is
* content. A reply that starts with anything else, or with only part of it, is read as
* written. When the model does reason, its header after the block is reasoning_close's.
* NULL or "": the reply starts with its content. */
const char* content_open;
} RadChatFormat;
/* Return the format, or NULL for "derive it from the chat template". Called once at startup. */
@@ -1961,7 +1987,9 @@ void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
/* Optional. Return a stable fingerprint of actual dispatch geometry whose grid depends on live
* per-group seqused values. `kv_used_max_h[g]` is the host maximum for batch->kv[g], and
* rad_ctx_wgp_count(c) supplies the device's WGP count. Return 0 when exact geometry is unknown;
* that pass runs live and is not recorded. */
* that pass runs live and is not recorded. Only prefill and mixed launches read the live maximum:
* in a decode, verify or draft pass every launch reads the step's keyed context bound
* (RadArgs::kv_used_max_h), so such a pass needs no geometry here and returns nonzero. */
uint64_t rad_arch_pass_key(struct RadCtx* c, const struct RadBatch* batch,
const int32_t* kv_used_max_h);
+323
View File
@@ -0,0 +1,323 @@
/* rad_mtp_block.h -- BLOCK VERIFICATION of a linear MTP draft chain (--draft-verify block).
*
* Sun, Mendlovic, Leviathan, Aharoni, Beirami, Ro, Suresh, "Block Verification Accelerates
* Speculative Decoding" (arXiv 2403.10444): the chain's draft tokens X_1 .. X_g are accepted or
* rejected JOINTLY. Token-wise speculative sampling (what --draft-coupling does at each row) is
* optimal per token; block verification is optimal for the whole block: the expected number of
* accepted tokens is never lower and the output law is the target's, exactly.
*
* With P_i = the target's law after X^i (the sampler's filtered candidate softmax at verify row i,
* i = 0 .. g-1) and Q_{i+1} = the head's law the draft X_{i+1} was sampled from (the coupled state
* of round i + 1, the FP64 softmax of the reranked top 8):
*
* p_0 = 1, p_i = min(1, p_{i-1} P_{i-1}(X_i) / Q_i(X_i)) i = 1 .. g
* S_i = sum_x max(p_i P_i(x) - Q_{i+1}(x), 0) i = 0 .. g-1
* h_i = S_i / (S_i + 1 - p_i) (i < g), h_g = p_g
*
* for i = g, g-1, ..., 0: accept the block's first i tokens with probability h_i; the first
* success is tau. (h_0 = 1: it always stops.)
* tau = g: X_1 .. X_g are emitted and the next token is the ordinary draw from P_g.
* tau < g: X_1 .. X_tau are emitted, then Y ~ max(p_tau P_tau - Q_{tau+1}, 0) normalised.
*
* Exactness is checked in tests/mtp_block_test.cpp by exact enumeration of the draft tree of a toy
* model (the law of the emitted tokens computed in closed form, to 1e-12) and by a chi-square of the
* real device-shared code, with a negative control (the same rule with a wrong residual).
*
* Y may equal X_{tau+1}; the core then takes that draft as accepted (ADV_ACCEPT: "the draft is the
* sampler's token at this row") and reads the next row, which keeps its ordinary pick: a draw from
* the target's law given exactly the tokens emitted so far, so the extra tokens continue the same
* autoregressive sample. The verify op therefore writes only rows 0 .. tau of the block and leaves
* every later row alone.
*
* Relation to --draft-coupling: the DRAFT half is shared (x ~ Q at temperature 1 from the head's
* top 8, coupled states with their FP64 Q); only the verify half differs. Maximal coupling decides
* row k from P_k and Q_{k+1} alone, so it is a per-row rule the core's token comparison walks
* unchanged. Block verification decides row k from the rows after it (h_i for i > k), so the two
* rules cannot be applied to the same row; `--draft-verify block` replaces the coupling's verify
* and requires the coupled drafting (it switches it on), and it is for a LINEAR chain; Traversal
* Verification (abi/rad_mtp_traversal.h, 2505.12398) is the walk that also covers a node with
* several children.
*/
#ifndef RAD_MTP_BLOCK_H
#define RAD_MTP_BLOCK_H
#include "rad_spechub.h"
#ifdef __cplusplus
#ifdef __HIPCC__
#define RAD_BLK_HD __host__ __device__
#else
#define RAD_BLK_HD
#endif
#define RAD_MTP_BLOCK_MAX RAD_MTP_COUPLE_MAX_ROUNDS /* g: the chain's longest block */
#define RAD_MTP_BLOCK_KEY_STOP 0x424c4b53544f5000ull /* the h_i uniforms, per block */
/* Summation structure. The device decides a block with one workgroup of RAD_MTP_BLOCK_LANES
* threads, so every FP64 sum over a row's candidate plane is DEFINED as this fixed tree, which the
* host reference mirrors operation for operation (FP64 addition is not associative: the tree is
* the definition, not an approximation):
* - plane slot j belongs to lane j % LANES; a lane adds its live slots in ascending j;
* - the lanes are reduced inside each group of RAD_MTP_BLOCK_WAVE by the butterfly
* a[l] = a[l] + a[l ^ d], d = 16, 8, 4, 2, 1 (every lane of a group ends with the same bits),
* and the LANES / WAVE group sums are added as ((g0 + g1) + (g2 + g3)).
* The exp() of a slot is the same libm / device function on both sides, as before. */
#define RAD_MTP_BLOCK_LANES 128
#define RAD_MTP_BLOCK_WAVE 32
/* One verify row's candidate plane, dense (n slots, holes id < 0 and -inf scores skipped), with
* `valid` and `top` the scan of the whole plane (rad_mtp_block_scan makes it on the host; the
* device reduces the same two values across its workgroup: a max and an OR are order free). */
struct RadBlockRow {
const int32_t* ids;
const float* val;
int64_t n;
int valid;
float top;
};
/* The dense row's validity and maximum, as rad_mtp_couple_decide scans them. */
static inline RAD_BLK_HD void rad_mtp_block_scan(RadBlockRow* r, int64_t vocab) {
float top = -INFINITY;
int valid = 1;
for (int64_t j = 0; j < r->n; ++j) {
if (r->ids[j] < 0) continue;
if (r->ids[j] >= vocab || r->val[j] != r->val[j] || r->val[j] == INFINITY) valid = 0;
else if (r->val[j] > top) top = r->val[j];
}
r->valid = valid;
r->top = top;
}
static inline RAD_BLK_HD bool rad_mtp_block_live(int32_t id, float v) { return id >= 0 && v != -INFINITY; }
/* A lane's partial sums of one row: v[0..7] the mass on Q's ids (by their place in the state),
* v[8] the mass off Q's support, v[9] the total. */
struct RadBlockAcc { double v[10]; };
static inline RAD_BLK_HD int rad_mtp_block_find(const RadMtpCoupleState& s, int32_t id) {
int k = 0;
while (k < s.count && id != s.ids[k]) ++k;
return k;
}
/* Adds the live slot (id, v) to a lane's partial. */
static inline RAD_BLK_HD void rad_mtp_block_acc_add(RadBlockAcc* a, const RadMtpCoupleState& s,
int32_t id, float v, float top) {
const double w = ::exp((double)v - top);
const int k = rad_mtp_block_find(s, id);
for (int kk = 0; kk < 8; ++kk) a->v[kk] += kk == k ? w : 0.0;
a->v[8] += k >= s.count ? w : 0.0;
a->v[9] += w;
}
/* The lanes' partials reduced by the tree above (the host form; the device does the butterfly with
* shuffles and adds the four group sums the same way). */
static inline RAD_BLK_HD RadBlockAcc rad_mtp_block_tree(const RadBlockAcc* lane) {
RadBlockAcc grp[RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE];
for (int w = 0; w < RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE; ++w) {
RadBlockAcc a[RAD_MTP_BLOCK_WAVE], t[RAD_MTP_BLOCK_WAVE];
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) a[l] = lane[w * RAD_MTP_BLOCK_WAVE + l];
for (int d = RAD_MTP_BLOCK_WAVE / 2; d > 0; d >>= 1) {
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) t[l] = a[l];
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l)
for (int c = 0; c < 10; ++c) a[l].v[c] = t[l].v[c] + t[l ^ d].v[c];
}
grp[w] = a[0];
}
RadBlockAcc o;
for (int c = 0; c < 10; ++c) o.v[c] = (grp[0].v[c] + grp[1].v[c]) + (grp[2].v[c] + grp[3].v[c]);
return o;
}
/* P_i over Q_{i+1}'s support (pq, normalised, duplicate candidates aggregated), the mass off that
* support (pout), the normaliser `sum` and the index `ix` of the draft token in the state's ids. */
struct RadBlockStat {
double pq[8];
double pout, sum;
int ix;
};
/* The stat from the reduced partials `t` (what the device builds from its workgroup's tree). */
static inline RAD_BLK_HD bool rad_mtp_block_stat_from(const RadBlockAcc& t, int valid, float top,
const RadMtpCoupleState& s, RadBlockStat* o) {
if (!valid || top == -INFINITY) return false;
const double sum = t.v[9];
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
o->ix = -1;
for (int k = 0; k < 8; ++k) o->pq[k] = k < s.count ? t.v[k] : 0.0;
for (int k = 0; k < s.count; ++k) {
o->pq[k] /= sum;
if (s.ids[k] == s.x) o->ix = k;
}
o->pout = t.v[8] / sum;
o->sum = sum;
return o->ix >= 0;
}
static inline RAD_BLK_HD bool rad_mtp_block_stat(const RadBlockRow& r, const RadMtpCoupleState& s,
RadBlockStat* o) {
if (!r.valid || r.top == -INFINITY) return false;
RadBlockAcc lane[RAD_MTP_BLOCK_LANES];
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l)
for (int c = 0; c < 10; ++c) lane[l].v[c] = 0;
for (int64_t j = 0; j < r.n; ++j)
if (rad_mtp_block_live(r.ids[j], r.val[j]))
rad_mtp_block_acc_add(&lane[j % RAD_MTP_BLOCK_LANES], s, r.ids[j], r.val[j], r.top);
return rad_mtp_block_stat_from(rad_mtp_block_tree(lane), r.valid, r.top, s, o);
}
/* The block's weights. p[i] (i = 0 .. g), h[i] (i = 0 .. g). */
struct RadBlockPlan {
int g;
double p[RAD_MTP_BLOCK_MAX + 1];
double h[RAD_MTP_BLOCK_MAX + 1];
double s[RAD_MTP_BLOCK_MAX + 1]; /* S_i, the residual's mass (s[g] unused) */
};
/* The residual mass of one token of row i at weight p: max(p P(x) - Q(x), 0) on Q's support,
* p P(x) off it. */
static inline RAD_BLK_HD double rad_mtp_block_resid_sum(const RadMtpCoupleState& s,
const RadBlockStat& t, double p) {
double r = p * t.pout;
for (int k = 0; k < s.count; ++k) r += rad_spechub_positive(p * t.pq[k] - s.q[k]);
return r;
}
/* st[i] / stat[i] for i = 0 .. g-1. */
static inline RAD_BLK_HD void rad_mtp_block_plan(const RadMtpCoupleState* st,
const RadBlockStat* stat, int g,
RadBlockPlan* o) {
o->g = g;
o->p[0] = 1.0;
for (int i = 0; i < g; ++i) {
const double ratio = stat[i].pq[stat[i].ix] / st[i].q[stat[i].ix];
const double v = o->p[i] * ratio;
o->p[i + 1] = v < 1.0 ? v : 1.0;
}
for (int i = 0; i < g; ++i) {
const double S = rad_mtp_block_resid_sum(st[i], stat[i], o->p[i]);
o->s[i] = S;
const double den = S + (1.0 - o->p[i]);
o->h[i] = (den > 0 && rad_spechub_finite(den)) ? S / den : 1.0;
}
o->s[g] = 0;
o->h[g] = o->p[g];
}
/* tau: the first i, counting down from g, whose uniform falls below h_i. The uniforms are keyed by
* the block's first output position, so no row's own draws are reused. */
static inline RAD_BLK_HD int rad_mtp_block_tau(const RadBlockPlan& pl, uint64_t seed, uint64_t pos0) {
for (int i = pl.g; i > 0; --i)
if (rad_spechub_uniform(seed, pos0, RAD_MTP_BLOCK_KEY_STOP + (uint64_t)i) < pl.h[i]) return i;
return 0;
}
/* One lane's partials of the residual draw: `off` the off-support masses p * (w / sum) (slots whose
* id is not among Q's), `all` the plain weights (the fallback draw from P itself), and the last
* positive id of each, in the lane's slot order. */
struct RadBlockLane { double off, all; int32_t last_off, last_all; };
static inline RAD_BLK_HD void rad_mtp_block_lane_add(RadBlockLane* a, const RadMtpCoupleState& s,
const RadBlockStat& t, double p, int32_t id,
float v, float top) {
const double w = ::exp((double)v - top);
a->all += w;
if (w > 0) a->last_all = id;
if (rad_mtp_block_find(s, id) >= s.count) {
const double m = p * (w / t.sum);
a->off += m;
if (m > 0) a->last_off = id;
}
}
/* Y ~ max(p P - Q, 0) normalised (state s, row r, stat t) with the uniform u in [0, 1). The mass
* is walked in a fixed order: the ids of Q (place k = 0 .. count-1, mass max(p pq[k] - q[k], 0)),
* then the other live slots lane by lane (the lanes of the tree above, each lane's slots in
* ascending order; the lane totals are added in lane order). The walk subtracts the masses from
* c = u * total and stops at the first negative; inside the lane it stops in, the walk restarts
* from the c at the lane's start, so the structure is exactly what the workgroup computes. When
* the total underflows to zero (FP64 cancellation with p = 1: P == Q) Y is drawn from P itself
* over all live slots in the same lane order, a branch that depends on (P, Q) only. False: no live
* candidate. */
static inline RAD_BLK_HD bool rad_mtp_block_resid_walk(const RadBlockRow& r,
const RadMtpCoupleState& s,
const RadBlockStat& t, double p, double u,
const RadBlockLane* lane, int32_t* out) {
double on[8];
double total = 0;
for (int k = 0; k < s.count; ++k) { on[k] = rad_spechub_positive(p * t.pq[k] - s.q[k]); total += on[k]; }
double offt = 0;
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) offt += lane[l].off;
total += offt;
const bool resid = total > 0 && rad_spechub_finite(total);
double c = resid ? u * total : u * t.sum;
int32_t last = -1;
if (resid) {
for (int k = 0; k < s.count; ++k)
if (on[k] > 0) { last = s.ids[k]; c -= on[k]; if (c < 0) { *out = last; return true; } }
}
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) {
const double T = resid ? lane[l].off : lane[l].all;
const int32_t ll = resid ? lane[l].last_off : lane[l].last_all;
if (!(T > 0)) continue;
if (ll >= 0) last = ll;
if (c - T < 0) {
double cl = c;
int32_t lastl = -1;
for (int64_t j = l; j < r.n; j += RAD_MTP_BLOCK_LANES) {
if (!rad_mtp_block_live(r.ids[j], r.val[j])) continue;
const double w = ::exp((double)r.val[j] - r.top);
double m;
if (resid) {
if (rad_mtp_block_find(s, r.ids[j]) < s.count) continue;
m = p * (w / t.sum);
} else {
m = w;
}
if (m > 0) { lastl = r.ids[j]; cl -= m; if (cl < 0) { *out = lastl; return true; } }
}
*out = lastl >= 0 ? lastl : ll;
return *out >= 0;
}
c -= T;
}
*out = last;
return last >= 0;
}
static inline RAD_BLK_HD bool rad_mtp_block_resid_draw(const RadBlockRow& r,
const RadMtpCoupleState& s,
const RadBlockStat& t, double p, double u,
int32_t* out) {
RadBlockLane lane[RAD_MTP_BLOCK_LANES];
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) lane[l] = RadBlockLane{ 0, 0, -1, -1 };
for (int64_t j = 0; j < r.n; ++j)
if (rad_mtp_block_live(r.ids[j], r.val[j]))
rad_mtp_block_lane_add(&lane[j % RAD_MTP_BLOCK_LANES], s, t, p, r.ids[j], r.val[j], r.top);
return rad_mtp_block_resid_walk(r, s, t, p, u, lane, out);
}
/* The whole decision on the host: rows[0 .. g-1] / st[0 .. g-1] are the block's verify rows and
* their coupled states (round i + 1 at row i), pos0 the first row's output position. Writes tau and
* *y; *y = -1 when tau == g (the g-th row's ordinary draw stands). False for an invalid target. */
static inline RAD_BLK_HD bool rad_mtp_block_decide(const RadMtpCoupleState* st,
const RadBlockRow* rows, int g, uint64_t seed,
uint64_t pos0, int* tau, int32_t* y) {
RadBlockStat stat[RAD_MTP_BLOCK_MAX];
RadBlockPlan pl;
if (g < 1 || g > RAD_MTP_BLOCK_MAX) return false;
for (int i = 0; i < g; ++i)
if (!rad_mtp_block_stat(rows[i], st[i], &stat[i])) return false;
rad_mtp_block_plan(st, stat, g, &pl);
const int t = rad_mtp_block_tau(pl, seed, pos0);
*tau = t;
*y = -1;
if (t >= g) return true;
return rad_mtp_block_resid_draw(rows[t], st[t], stat[t], pl.p[t],
rad_spechub_uniform(seed, pos0 + (uint64_t)t, RAD_SAMPLE_KEY_RESID), y);
}
#endif /* __cplusplus */
#endif /* RAD_MTP_BLOCK_H */
+426
View File
@@ -0,0 +1,426 @@
/* rad_mtp_rrs.h -- recursive rejection sampling over a node's SIBLING drafts under
* --draft-coupling on: the draft side (children sampled without replacement from Q) and the
* verify side (the walk over a node's children against the target's P), as plain code the host
* oracle, the device kernels and the tests share, so they cannot drift. Traversal verification
* (abi/rad_mtp_traversal.h) walks nodes that drafted several children; the serial head of this
* engine drafts one (nkids <= 1, the chain), so nothing in the engine draws siblings yet: the
* header is the verify side's definition and its tests (tests/mtp_rrs_test.cpp). The short proof:
*
* Draft. A node whose head pass left the law Q (the FP64 T1 softmax of the reranked top 8,
* rad_mtp_couple_build_q) drafts its children x_1, x_2, ... by Gumbel-top-k over log Q: add an
* independent Gumbel to every log q_i and take the entries in descending order. That is sampling
* without replacement (Plackett-Luce): x_1 ~ Q, x_2 ~ Q(. | not x_1), ... The first m of them are
* the node's children, m chosen by anything that does not read the values x_j it applies to
* (a fixed count, or a rule over the slot priorities, the j-th largest q of Q, never the drawn
* token).
*
* Verify (Sequoia, Chen et al. 2024, Alg. 1; SpecInfer's multi-step verification with the draft
* law renormalised after each removal). P_1 = the target's law, q_1 = Q. For i = 1..m:
* accept x_i with probability min(1, P_i(x_i) / q_i(x_i));
* on rejection P_{i+1} = norm(max(P_i - q_i, 0)), q_{i+1} = q_i with x_i removed, renormalised.
* All rejected: the token is a draw from P_{m+1}. Exactness (induction on m): after a rejection of
* the first draft the continuation depends on x_1 only through q_2, and P_2 = norm(max(P - q, 0))
* does not depend on x_1 at all, so by the hypothesis it emits ~ P_2 whatever x_1 was; then
* P(emit y) = sum_x q(x) min(1, P(x)/q(x)) [x = y] + P(reject) P_2(y) = min(P, q)(y) +
* max(P - q, 0)(y) = P(y). The emitted token is the accepted child's token, or a residual draw that
* has no mass on any rejected child (P_{i+1}(x_i) = 0 after a rejection), so the core's rule "follow
* the first child whose token is the sampler's token at the row" (ADV_ACCEPT) walks exactly the
* decision made here and needs no change.
*
* Wire: the node's RadMtpCoupleState holds Q (ids, q), the children in draft order in ids[0 ..
* nkids), x = ids[0]. A state with nkids <= 1 is the chain's (rad_mtp_couple_decide, bit for bit).
*/
#ifndef RAD_MTP_RRS_H
#define RAD_MTP_RRS_H
#include "rad_spechub.h"
#ifdef __cplusplus
#ifdef __HIPCC__
#define RAD_RRS_HD __host__ __device__
#else
#define RAD_RRS_HD
#endif
#define RAD_MTP_RRS_KEY_TREE 0x4d54524545474d42ull /* the draft's Gumbel stream */
#define RAD_MTP_RRS_KEY_ACCEPT 0x41435054ull
static inline RAD_RRS_HD uint64_t rad_mtp_rrs_mix(uint64_t z) {
z += 0x9e3779b97f4a7c15ull;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
return z ^ (z >> 31);
}
/* The open-interval uniform of candidate `c` of draft node `node`: (seed, base) name the draft
* stream (the request's seed and its pre-commit output length, which no later step reuses). */
static inline RAD_RRS_HD double rad_mtp_rrs_gumbel_u(uint64_t seed, uint64_t base,
uint64_t node, int c) {
uint64_t z = rad_mtp_rrs_mix(seed ^ RAD_MTP_RRS_KEY_TREE);
z = rad_mtp_rrs_mix(z ^ base);
z = rad_mtp_rrs_mix(z + node * 16u + (uint64_t)c);
return ((double)(z >> 11) + 0.5) * 0x1p-53;
}
/* Gumbel-top-k order of Q's support: order[0 .. s.count) are indices into s.ids, the draft order
* (descending of log q + Gumbel, ties to the lower index). Draws one uniform per support entry from
* the state's own draw, node `node`. */
static inline RAD_RRS_HD void rad_mtp_rrs_order(const RadMtpCoupleState& s, uint64_t node,
int* order) {
double key[8];
for (int i = 0; i < s.count; ++i) {
const double u = rad_mtp_rrs_gumbel_u(s.draw.seed, s.draw.base, node, i);
key[i] = ::log(s.q[i]) - ::log(-::log(u));
order[i] = i;
}
for (int i = 1; i < s.count; ++i) { /* insertion sort, stable */
const int o = order[i];
int j = i;
while (j > 0 && key[order[j - 1]] < key[o]) { order[j] = order[j - 1]; --j; }
order[j] = o;
}
}
/* Draw the node's children: reorder Q's support into the draft order (ids and q together), set
* x = ids[0] and nkids = `nkids`. */
static inline RAD_RRS_HD void rad_mtp_rrs_draw(RadMtpCoupleState* s, uint64_t node, int nkids) {
int order[8];
rad_mtp_rrs_order(*s, node, order);
int32_t ids[8];
double q[8];
for (int i = 0; i < s->count; ++i) { ids[i] = s->ids[order[i]]; q[i] = s->q[order[i]]; }
for (int i = 0; i < s->count; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
s->x = s->ids[0];
s->nkids = nkids < s->count ? nkids : s->count;
}
/* The SLOT priorities of a node's law: slot j carries the log of the j-th LARGEST q of Q
* (descending, ties by position), -inf past the support. They are a function of Q alone, never of
* which token was drawn into which slot, so a rule that reads only them admits children by a
* quantity independent of the values the children take. `s` is read before the draw reorders it
* or after (the multiset of q is the same). */
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq(const RadMtpCoupleState& s, float* ov) {
double qs[8];
const int n = s.count < 8 ? s.count : 8;
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
for (int i = 1; i < n; ++i) {
const double v = qs[i];
int j = i;
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
qs[j] = v;
}
for (int c = 0; c < 8; ++c) ov[c] = c < n ? (float)::log(qs[c]) : -INFINITY;
}
/* The longest prefix of the state's children that are the first `n` of `kid[]` (the tree's
* children of this row, in node order, repeats dropped): what a verify may keep when a window cut
* the tree short. 0 when even the first differs. */
static inline RAD_RRS_HD int rad_mtp_rrs_prefix(const RadMtpCoupleState& s, const int32_t* kid,
int n) {
const int have = s.nkids >= 1 ? s.nkids : 1;
int m = 0;
while (m < have && m < n && m < s.count && s.ids[m] == kid[m]) ++m;
return s.nkids >= 2 ? m : (n >= 1 && s.x == kid[0] ? 1 : 0);
}
/* The acceptance uniform of the i-th child at output position `pos`: the first is the chain's. */
static inline RAD_RRS_HD double rad_mtp_rrs_uaccept(uint64_t seed, uint64_t pos, int i) {
return rad_spechub_uniform(seed, pos, i == 0 ? (uint64_t)RAD_SAMPLE_KEY_ACCEPT
: RAD_MTP_RRS_KEY_ACCEPT ^ rad_mtp_rrs_mix((uint64_t)i));
}
/* The verify of a node with nkids >= 2 children: the recursion above over the sampler's surviving
* candidates (ids/val, n of them, FP64 P = softmax of val). Writes the emitted token to *out and
* returns true, or false for an invalid target (the row keeps the ordinary token).
*
* The decision reads the live candidates (id >= 0, value not -inf) in ascending order through a view
* `C::each(f)`, f(id, w, k) -> bool (false stops): w = exp(val - top) in FP64, k the id's slot in the
* state's support (the first match) or s.count when it is outside. The host view (RadRrsHostCands)
* computes them on the fly; the device verify (plugin/spechub/spechub.hip) compacts the live
* candidates and computes every w and k with the whole workgroup, then runs this same function on one
* lane over the stored values, so the ordered sums, and with them the token, are the host's. `pq_out`
* and `sum_out` (optional) hand back P's masses on the support and their normaliser (the export). */
template <class C>
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_over(const RadMtpCoupleState& s, const C& cs,
uint64_t seed, uint64_t pos, int32_t* out,
double* pq_out = nullptr,
double* sum_out = nullptr) {
double sum = 0, pq[8] = {}, wout = 0;
cs.each([&](int32_t, double w, int k) {
sum += w;
if (k < s.count) pq[k] += w; else wout += w;
return true;
});
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
if (pq_out) for (int k = 0; k < 8; ++k) pq_out[k] = pq[k];
if (sum_out) *sum_out = sum;
/* P over Q's support (normalised), and the off-support mass's scale `so` (P_i(y) = so * w / sum
* there). qr: the draft law with the drawn children removed. */
double r[8], qr[8], so = 1.0;
for (int k = 0; k < s.count; ++k) { r[k] = pq[k] / sum; qr[k] = s.q[k]; }
const double pout = wout / sum;
bool direct = false;
for (int i = 0; i < s.nkids && !direct; ++i) {
double sq = 0;
for (int k = 0; k < s.count; ++k) sq += qr[k];
if (!(sq > 0)) break;
const double qx = qr[i] / sq;
if (r[i] >= qx || rad_mtp_rrs_uaccept(seed, pos, i) * qx < r[i]) { *out = s.ids[i]; return true; }
double z = so * pout;
for (int k = 0; k < s.count; ++k) {
const double d = r[k] - qr[k] / sq;
r[k] = d > 0 ? d : 0;
z += r[k];
}
if (!(z > 0) || !rad_spechub_finite(z)) { direct = true; break; }
for (int k = 0; k < s.count; ++k) r[k] /= z;
so /= z;
qr[i] = 0;
}
const double u = rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID);
double c;
int32_t last = -1;
if (direct) {
c = u * sum;
bool hit = false;
cs.each([&](int32_t id, double w, int) {
if (w > 0) { last = id; c -= w; if (c < 0) { hit = true; return false; } }
return true;
});
*out = last;
(void)hit;
return true;
}
double total = 0;
for (int k = 0; k < s.count; ++k) total += r[k];
total += so * pout;
c = u * total;
unsigned seen = 0;
bool hit = false;
cs.each([&](int32_t id, double w, int k) {
double m;
if (k < s.count) {
if (seen & (1u << k)) return true;
seen |= 1u << k;
m = r[k];
} else {
m = so * (w / sum);
}
if (m > 0) { last = id; c -= m; if (c < 0) { hit = true; return false; } }
return true;
});
*out = last;
(void)hit;
return last >= 0;
}
/* The host view: the candidates as the sampler wrote them, weights computed as they are read. */
struct RadRrsHostCands {
const RadMtpCoupleState& s;
const int32_t* ids; const float* val; int64_t n; float top;
template <class F> RAD_RRS_HD void each(F&& f) const {
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
int k = 0;
while (k < s.count && ids[j] != s.ids[k]) ++k;
if (!f(ids[j], ::exp((double)val[j] - top), k)) return;
}
}
};
static inline RAD_RRS_HD bool rad_mtp_rrs_decide(const RadMtpCoupleState& s, const int32_t* ids,
const float* val, int64_t n, int64_t vocab,
uint64_t seed, uint64_t pos, int32_t* out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
if (top == -INFINITY) return false;
return rad_mtp_rrs_decide_over(s, RadRrsHostCands{ s, ids, val, n, top }, seed, pos, out);
}
/* ================================================================== RheoSampling siblings
*
* --draft-siblings rheo (--draft-rheo-m m). Hu et al. 2025 (arXiv 2502.18779, Thm 8, the greedy
* multi-draft verifier) and RheoSampling (arXiv 2609.21827): instead of Gumbel-top-k siblings, a node's
* children are
* T = the m tokens of largest Q, in descending q order (deterministic, rank slots 0 .. m-1), and
* u ~ Qt, ONE token sampled from the tail law Qt(x) = Q(x) / z over the support outside T,
* z = Q(outside T), in slot m;
* the draft order stored in the state is ids = [T..., u, the rest of the support in descending q],
* scheme = m + 1. A node whose support has no more than m tokens has no tail child (all of it is T).
*
* Verify (derived here, not quoted; the law is checked by tests/mtp_rrs_test.cpp by exhaustive
* enumeration). P = the target's law, children present = the first nkids of the draft order.
* tail child present (nkids > |T|, which with a prefix draft order means every T token is a child):
* accept u with probability min(1, P(u) / Qt(u)) -> emit u
* else emit y ~ R / |R|, R(y) = P(y) y in T or off Q's support,
* R(y) = max(P(y) - Qt(y), 0) y in the tail support (R(u) = 0 here)
* otherwise (the tail slot was pruned or cut by a window, or Q has no tail): emit y ~ P directly.
* Exactness: P(emit y) = min(P, Qt)(y) [y in tail] + (1 - A) R(y) / |R| with |R| = 1 - A,
* A = sum_tail min(P, Qt), and min(P, Qt) + R = P on the tail, R = P elsewhere: P(emit y) = P(y).
* It needs only that u ~ Qt independently of the verifier's uniforms (a separate draft stream), and
* that WHICH slots exist depends on Q and the tree's budget alone (never on the value of u): both
* hold, the slot priorities are rad_mtp_rrs_slot_logq_rheo. The emitted token is a child with
* probability P(T) + A = sum_T P + sum_tail min(P, Qt), Thm 8's value, and a residual draw never
* lands on u (R(u) = 0 when u was rejected), so the core's "follow the first child whose token is
* the sampler's" walks the decision made here.
* m = 0 is the single-draft maximal coupling of the chain (rad_mtp_couple_decide) with the sampled
* child in slot 0.
*/
#define RAD_MTP_RRS_KEY_TAIL_C 8 /* candidate index of the tail draw in the draft stream (0..7 are Gumbel's) */
/* Slot priorities of a rheo node (functions of Q alone, non-increasing): slots 0 .. m-1 carry the
* log of the j-th largest q, slot m RheoSampling's proxy log min{q_(m-1), z} (z = the tail mass; with
* m = 0, z = 1), -inf for the other slots and for slots past the support. */
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq_rheo(const RadMtpCoupleState& s, int m, float* ov) {
double qs[8];
const int n = s.count < 8 ? s.count : 8;
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
for (int i = 1; i < n; ++i) {
const double v = qs[i];
int j = i;
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
qs[j] = v;
}
const int nt = m < n ? m : n;
for (int c = 0; c < 8; ++c) ov[c] = c < nt ? (float)::log(qs[c]) : -INFINITY;
if (n > nt) {
double z = 0;
for (int i = nt; i < n; ++i) z += qs[i];
if (z > 1) z = 1;
const double ref = nt > 0 ? qs[nt - 1] : 1.0;
ov[nt] = (float)::log(z < ref ? z : ref);
}
}
/* Draw a rheo node's children: reorder Q's support into [top-m by q desc, the sampled tail child,
* the rest by q desc], set x = ids[0], scheme = m + 1 and nkids = min(nkids, children possible). The
* tail child is the inverse-CDF draw of Qt with the draft stream's uniform of (seed, base, node). */
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo_u(RadMtpCoupleState* s, double ut, int nkids, int m) {
int ord[8];
const int n = s->count;
for (int i = 0; i < n; ++i) ord[i] = i;
for (int i = 1; i < n; ++i) { /* descending q, stable */
const int o = ord[i];
int j = i;
while (j > 0 && s->q[ord[j - 1]] < s->q[o]) { ord[j] = ord[j - 1]; --j; }
ord[j] = o;
}
const int nt = m < n ? m : n;
if (n > nt) {
double z = 0;
for (int i = nt; i < n; ++i) z += s->q[ord[i]];
double c = ut * z;
int pick = n - 1;
for (int i = nt; i < n; ++i) { c -= s->q[ord[i]]; if (c < 0) { pick = i; break; } }
const int o = ord[pick];
for (int i = pick; i > nt; --i) ord[i] = ord[i - 1];
ord[nt] = o;
}
int32_t ids[8];
double q[8];
for (int i = 0; i < n; ++i) { ids[i] = s->ids[ord[i]]; q[i] = s->q[ord[i]]; }
for (int i = 0; i < n; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
const int cap = nt + (n > nt ? 1 : 0);
s->x = s->ids[0];
s->scheme = m + 1;
s->nkids = nkids < cap ? nkids : cap;
}
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo(RadMtpCoupleState* s, uint64_t node, int nkids, int m) {
rad_mtp_rrs_draw_rheo_u(s, rad_mtp_rrs_gumbel_u(s->draw.seed, s->draw.base, node, RAD_MTP_RRS_KEY_TAIL_C),
nkids, m);
}
/* The verify of a rheo node (any nkids >= 0): the rule above. Same contract as rad_mtp_rrs_decide. */
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo_u(const RadMtpCoupleState& s, const int32_t* ids,
const float* val, int64_t n, int64_t vocab,
double u_accept, double u_resid, int32_t* out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
if (top == -INFINITY) return false;
double sum = 0, pq[8] = {};
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
const double w = ::exp((double)val[j] - top);
sum += w;
for (int k = 0; k < s.count; ++k)
if (ids[j] == s.ids[k]) { pq[k] += w; break; }
}
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
const int m = s.scheme - 1;
const int nt = m < s.count ? m : s.count;
const bool tail = m >= 0 && s.count > nt && s.nkids > nt;
double qt[8] = {}, r[8] = {};
bool dominated = true;
for (int k = 0; k < s.count; ++k) pq[k] /= sum;
if (tail) {
double z = 0;
for (int k = nt; k < s.count; ++k) z += s.q[k];
for (int k = nt; k < s.count; ++k) {
const double v = nt == 0 ? s.q[k] : s.q[k] / z;
qt[k] = v > 1 ? 1 : v; /* clamp: rounding must not push a one-token tail past 1 */
dominated = dominated && pq[k] >= qt[k];
}
for (int k = 0; k < s.count; ++k) r[k] = k < nt ? pq[k] : rad_spechub_positive(pq[k] - qt[k]);
}
/* mass of candidate j in R (the tail case) or in P (otherwise); Q tokens count once. */
unsigned seen = 0;
auto mass = [&](int64_t j) -> double {
if (ids[j] < 0 || val[j] == -INFINITY) return 0;
for (int k = 0; k < s.count; ++k)
if (s.ids[k] == ids[j]) {
if (seen & (1u << k)) return 0;
seen |= 1u << k;
return tail ? r[k] : pq[k];
}
return ::exp((double)val[j] - top) / sum;
};
double resid = 0;
if (tail) {
for (int64_t j = 0; j < n; ++j) resid += mass(j);
seen = 0;
}
if (!tail || (!dominated && !(resid > 0 && rad_spechub_finite(resid)))) {
double c = u_resid * sum; /* P itself, in the sampler's candidate order */
int32_t last = -1;
for (int64_t j = 0; j < n; ++j)
if (ids[j] >= 0 && val[j] != -INFINITY) {
const double w = ::exp((double)val[j] - top);
if (w > 0) { last = ids[j]; c -= w; if (c < 0) { *out = last; return true; } }
}
*out = last;
return last >= 0;
}
const int iu = nt;
if (pq[iu] >= qt[iu] || u_accept * qt[iu] < pq[iu]) {
*out = s.ids[iu];
return true;
}
double c = u_resid * resid;
int32_t last = -1;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] == s.ids[iu]) continue;
const double mm = mass(j);
if (mm > 0) { last = ids[j]; c -= mm; if (c < 0) { *out = last; return true; } }
}
*out = last;
return last >= 0;
}
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo(const RadMtpCoupleState& s, const int32_t* ids,
const float* val, int64_t n, int64_t vocab,
uint64_t seed, uint64_t pos, int32_t* out) {
return rad_mtp_rrs_decide_rheo_u(s, ids, val, n, vocab,
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID), out);
}
#endif /* __cplusplus */
#endif /* RAD_MTP_RRS_H */
+549
View File
@@ -0,0 +1,549 @@
/* rad_mtp_traversal.h -- Traversal Verification (Weng et al., arXiv 2505.12398) of a draft under
* sampling (--draft-verify traversal, needs --draft-coupling on). The walk is defined on a tree; the
* serial head of this engine drafts a chain, a tree of one child a node, which the sampler stages
* (core/sample/sampler.cpp). Plain code shared by the host oracle, the device kernel and the tests;
* the short form of the argument:
*
* Row-wise verification (rad_mtp_rrs_decide) decides each node on its own. Traversal verification
* decides a whole ROOT-TO-LEAF PATH at once, bottom-up, and so can accept a longer prefix from the
* same tree (for a chain it is Block Verification, never worse than token-level rejection sampling).
*
* State of a node v during the walk: p_v (its acceptance rate, a sequence-level ratio), the target
* law M_b(.|v) restricted to what has not been rejected below it (r), and the law the NEXT child of
* v was drawn from.
* - A child c of v enters with p_c = min(1, p_v * r(c)/qn(c)), qn the law c was drawn from GIVEN
* the children tried before it.
* - The walk descends to the first leaf and tests eta < p_leaf. Accept: the path is accepted and
* the final token is drawn from that node's current residual law r (the plain target if none of
* its children was rejected). Reject: the leaf is deleted and its parent v is updated:
* S = sum_x [ p_v r(x) - qn(x) ]+
* p_v' = S / (S + 1 - p_v)
* r' = [ p_v r - qn ]+ / S
* and the walk continues with v's next child, or tests v itself once it has none.
* The walk keeps the PRODUCT m(x) = p_v r(x) (on the draft support per slot, and one number for
* everything off it, where qn is zero), which is all the rules read: p_c = min(1, m(c)/qn(c)), and
* the update is one division, m' = [m - qn]+ / (S + 1 - p_v), p_v' = S / (S + 1 - p_v), the
* off-support mass scaled alike; the final token is drawn in proportion to m. A node entered with
* rate p keeps its target law unscaled and the factor p beside it (sc) until its first child is
* rejected, so entering a node costs one division (the child's rate) and no pass over its law.
* Exactness (Theorem 3.3 of the paper, Lemma A.2 by induction over a node's descendants): the
* subtree of v is accepted with probability p_v and, given that, the token after v follows r. One
* step of the induction, for a child drawn from ANY law qn that may depend on the children before
* it: P(accepted through a child x) = qn(x) min(1, p_v r(x)/qn(x)) = min(qn(x), p_v r(x));
* P(the child's subtree is rejected) = 1 - p_v + S; the rest then accepts with p_v' and r', which
* adds (1 - p_v + S) p_v' r'(x) = [p_v r(x) - qn(x)]+, and the two sum to p_v r(x). It needs the
* tree's shape to be independent of the drawn tokens (a chain's is), and each child's own law:
* - Gumbel-top-k siblings (the default, Plackett-Luce without replacement): qn is the node's Q
* with the children already tried removed, renormalised;
* - RheoSampling siblings (state.scheme = m + 1, abi/rad_mtp_rrs.h): the
* sampled tail child is tried FIRST with qn = Qt, the tail law, then the deterministic top-q
* children in their order, each with qn = a point mass on its token. A point mass accepts with
* p_v r(c) and leaves r without c; tried in this order the node's children take
* sum_tail min(P, Qt) + P(T) of the target, the greedy multi-draft verifier's value (Hu et al.
* 2025, Thm 8).
* tests/mtp_rrs_test.cpp checks the walk by exact enumeration and by chi-square, and shows that
* plausible mistakes (token-level ratios, no (1 - p) term, with-replacement update for
* without-replacement drafts, a rheo node walked as a Gumbel one) fail the same statistic.
*
* THE TARGET LAW IN FIXED POINT. The walk reads a row's target law only through its mass on the
* node's draft support (eight ids), the mass off it and the total; the final token needs the
* off-support candidates in order. Each live candidate's weight is an INTEGER:
*
* m_j = floor(2^40 * e(val_j - top)), e(x) = rad_mtp_trav_mass's FP32 exponential
*
* (top the row's largest value; the scale drops a bit per doubling of the plane past 4096 slots so
* a row's total stays below 2^53). Integer addition is associative, so the sums are the same bits
* whatever order a workgroup adds them in: the device kernel (plugin/spechub/spechub.hip) splits a
* row over its threads any way it likes and still equals this header's serial loops, with no
* reduction tree to mirror. e() is basic FP32 arithmetic and integer shifts, identical on host and
* device (no libm call, no contraction: -ffp-contract=off, and the attribute below for a host
* build that enables FMA).
* Why FP32 suffices: the algorithm is exact for whatever positive weights define the law, as long as
* every decision reads the same ones, which the integers guarantee. The law it realises is
* P~(y) = m_y / sum m, within 2^-22 relative per candidate (e's error, tests/mtp_rrs_test.cpp checks
* it) plus 2^-40 absolute of the softmax of the sampler's FP32 candidates: the accuracy class of the
* uncoupled sample_pick (FP32 expf, FP32 running sum, a 24-bit uniform), which is the law a request
* gets without speculation. The 8-wide FP64 sums of the walk are a fixed tree (rad_mtp_trav_sum8),
* so a device may run them on one lane or across eight.
*
* Wire: no new state. The walk reads the same RadMtpCoupleState rows as the row-wise verify and
* writes the SAME plane the core already walks (ADV_ACCEPT: the first child whose token is the
* sampler's token at the row): on the accepted path every row's token is its path child's token and
* the last row's token is the final one; the other rows are not on the walk and keep the pick.
*/
#ifndef RAD_MTP_TRAVERSAL_H
#define RAD_MTP_TRAVERSAL_H
#include "rad_spechub.h"
#include "rad_mtp_rrs.h"
#ifdef __cplusplus
#define RAD_MTP_TRAV_MAX_DEPTH 16
#define RAD_MTP_TRAV_MAX_ROWS 64 /* rows of one request the walk reads (its first ones) */
#define RAD_MTP_TRAV_KEY 0x54524156ull /* "TRAV": the walk's acceptance uniforms */
#define RAD_MTP_TRAV_QBITS 40 /* the unit of a candidate's mass: 2^-40 of the top's */
/* A host build with FMA enabled must not contract the exponential's products into its sums: the
* device does not (-ffp-contract=off), and the masses have to be the same bits. */
#if defined(__GNUC__) && !defined(__clang__)
#define RAD_TRAV_STRICT __attribute__((optimize("fp-contract=off")))
#else
#define RAD_TRAV_STRICT
#endif
/* Test-only switches; the engine passes the zero value. */
struct RadMtpTravOpt {
int ctl = 0; /* negative controls: 1 token-level ratios, 2 no (1 - p) term, 3 q never
renormalised (the with-replacement update on without-replacement drafts),
4 a RheoSampling node walked as a Gumbel one */
/* Enumeration (tests): >= 0 replaces the uniforms -- test number `accept_at` (1-based) accepts
* and every earlier one rejects; `p_test[i]` receives the acceptance rate of test i + 1 and
* `*n_tests` their count. */
int accept_at = -1;
double* p_test = nullptr;
int* n_tests = nullptr;
int max_tests = 0;
double u_final = -1.0; /* >= 0: the final token's uniform (rad_mtp_trav_walk) */
};
struct RadMtpTravOut {
int n = 0; /* nodes on the path, root first */
int node[RAD_MTP_TRAV_MAX_DEPTH + 2] = {};
int32_t y = -1; /* the final token ... */
bool has_y = false; /* ... when the last node carries a valid state */
};
/* ---------------------------------------------------------------- the target law in fixed point */
/* The mass unit of a plane of n candidates: 2^-qbits of the top candidate's weight, so that a
* row's total stays below 2^53 (exact in FP64). */
static inline RAD_RRS_HD int rad_mtp_trav_qbits(int64_t n) {
int q = RAD_MTP_TRAV_QBITS;
for (int64_t c = 4096; c < n && q > 20; c <<= 1) --q;
return q;
}
/* floor(2^qbits * e^(v - top)) for a live candidate (v <= top, both finite): the FP32 exponential
* of Cephes' expf (argument reduction by n ln 2 in two parts, a degree-5 polynomial in the reduced
* argument), taken as a 24-bit mantissa and shifted. Zero below 2^-41 of the top. Basic IEEE FP32
* operations and integer shifts only. */
RAD_TRAV_STRICT static inline RAD_RRS_HD uint64_t rad_mtp_trav_mass(float v, float top, int qbits) {
#if defined(__clang__)
#pragma clang fp contract(off)
#endif
const float x = v - top;
if (!(x > -28.5f)) return 0;
const int n = (int)(x * 1.44269504088896341f - 0.5f); /* round(x / ln 2), x <= 0 */
const float fn = (float)n;
float r = x - fn * 0.693359375f;
r = r - fn * -2.12194440e-4f;
const float z = r * r;
float y = 1.9875691500e-4f;
y = y * r + 1.3981999507e-3f;
y = y * r + 8.3334519073e-3f;
y = y * r + 4.1665795894e-2f;
y = y * r + 1.6666665459e-1f;
y = y * r + 5.0000001201e-1f;
y = y * z + r;
y = y + 1.0f; /* e^r, in [0.70, 1.42] */
const uint32_t mant = (uint32_t)(y * 8388608.0f); /* y * 2^23, below 2^24 */
const int sh = qbits + n - 23;
if (sh >= 0) return (uint64_t)mant << sh;
return sh > -32 ? (uint64_t)(mant >> -sh) : 0;
}
/* An integer below 2^53 as a double, exactly, the same way on host and device. */
static inline RAD_RRS_HD double rad_mtp_trav_u2d(uint64_t x) {
return (double)(uint32_t)(x >> 32) * 4294967296.0 + (double)(uint32_t)x;
}
/* The integer part of a double in [0, 2^53). */
static inline RAD_RRS_HD uint64_t rad_mtp_trav_d2u(double d) {
const uint32_t hi = (uint32_t)(d * (1.0 / 4294967296.0));
const double lo = d - (double)hi * 4294967296.0;
return ((uint64_t)hi << 32) + (uint64_t)(uint32_t)lo;
}
/* Candidate id's slot in a node's support (the first match), or cnt when it is outside. */
static inline RAD_RRS_HD int rad_mtp_trav_slot(const int32_t* sid, int cnt, int32_t id) {
int k = 0;
while (k < cnt && id != sid[k]) ++k;
return k;
}
/* A row's validity and largest value, as rad_mtp_couple_decide scans them: false for an id past the
* vocabulary, a NaN or +inf among the ids >= 0, or no finite value at all. */
static inline RAD_RRS_HD bool rad_mtp_trav_row_top(const int32_t* ids, const float* val, int64_t n,
int64_t vocab, float* top_out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
*top_out = top;
return top != -INFINITY;
}
/* One row's target law over a node's support `sid[0 .. cnt)`: the masses on the support slots
* (duplicate candidates aggregated at the first matching slot), off it, and the total. The serial
* definition; a workgroup adds the same integers in its own order. */
struct RadTravLaw {
uint64_t pq[8];
uint64_t off, sum;
};
static inline RAD_RRS_HD void rad_mtp_trav_row_law(const int32_t* ids, const float* val, int64_t n,
float top, const int32_t* sid, int cnt,
RadTravLaw* o) {
const int qb = rad_mtp_trav_qbits(n);
for (int k = 0; k < 8; ++k) o->pq[k] = 0;
o->off = 0; o->sum = 0;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
o->sum += m;
const int k = rad_mtp_trav_slot(sid, cnt, ids[j]);
if (k < cnt) o->pq[k] += m; else o->off += m;
}
}
/* The off-support candidate that holds unit `t` of the off-support mass, candidates in ascending
* slot order (t < the row's off-support mass). -1 when there is none. */
static inline RAD_RRS_HD int32_t rad_mtp_trav_off_token(const int32_t* ids, const float* val,
int64_t n, float top, const int32_t* sid,
int cnt, uint64_t t) {
const int qb = rad_mtp_trav_qbits(n);
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
if (rad_mtp_trav_slot(sid, cnt, ids[j]) < cnt) continue;
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
if (t < m) return ids[j];
t -= m;
}
return -1;
}
/* ---------------------------------------------------------------- the prepared tree */
/* The eight-wide FP64 sums of the walk, as one fixed tree: the xor-4, xor-2, xor-1 butterfly of
* eight lanes (IEEE addition is commutative, so every lane of the butterfly ends with these bits). */
static inline RAD_RRS_HD double rad_mtp_trav_sum8(const double* v) {
return ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7]));
}
/* A node's draft side in the walk's canonical order: the children first, in draft order (a chain's
* one child is x). `nk` the children the walk may try, `nt` -1 for Gumbel-top-k siblings, else the
* number of deterministic top-q children of a RheoSampling node (its tail child is slot nt, `tail`
* whether the node carries it), `swap` the stored slot that changed places with slot 0 (a chain row
* whose x was not first; else 0).
* False when the state names no child (unreachable for a rad_mtp_couple_state_valid state). */
static inline RAD_RRS_HD bool rad_mtp_trav_canon(const RadMtpCoupleState& s, int ctl, int32_t* ids,
double* q, int* nk, int* nt, int* tail, int* swap) {
/* Every index below is a constant: a device lane keeps the state and the result in registers. */
*swap = 0;
*tail = 0;
if (s.scheme > 0 && ctl != 4) {
for (int k = 0; k < 8; ++k) {
ids[k] = k < s.count ? s.ids[k] : -1;
q[k] = k < s.count ? s.q[k] : 0.0;
}
const int m = s.scheme - 1;
const int t = m < s.count ? m : s.count;
const int cap = t + (s.count > t ? 1 : 0);
*nt = t;
*nk = s.nkids < cap ? (s.nkids > 0 ? s.nkids : 0) : cap;
*tail = *nk > t;
return true;
}
*nt = -1;
*nk = s.nkids >= 2 ? (s.nkids < s.count ? s.nkids : s.count) : 1;
/* a chain row: x to the front (the first slot that holds it changes places with slot 0) */
int kx = 0;
if (s.nkids < 2) {
kx = 8;
for (int k = 7; k >= 0; --k)
if (k < s.count && s.ids[k] == s.x) kx = k;
}
const bool found = kx < 8;
int32_t idx = -1;
double qx = 0.0;
for (int k = 0; k < 8; ++k) {
idx = k == kx ? s.ids[k] : idx;
qx = k == kx ? s.q[k] : qx;
}
for (int k = 0; k < 8; ++k) {
const bool in = found && k < s.count;
const int32_t idk = k == 0 ? idx : (k == kx ? s.ids[0] : s.ids[k]);
const double qk = k == 0 ? qx : (k == kx ? s.q[0] : s.q[k]);
ids[k] = in ? idk : -1;
q[k] = in ? qk : 0.0;
}
*swap = found ? kx : 0;
return found;
}
/* One request's tree as the walk reads it, node-indexed (node 0 the root, parents before
* children). Plain data: the device keeps it in LDS and fills it with a workgroup. */
struct RadTravTree {
int n; /* nodes */
int ok[RAD_MTP_TRAV_MAX_ROWS]; /* an eligible state with a valid target law */
int nk[RAD_MTP_TRAV_MAX_ROWS]; /* children the walk tries */
int nt[RAD_MTP_TRAV_MAX_ROWS]; /* -1 Gumbel; else a rheo node's deterministic children */
int tail[RAD_MTP_TRAV_MAX_ROWS]; /* a rheo node that carries its sampled tail child */
int ci[RAD_MTP_TRAV_MAX_ROWS]; /* children tried so far */
int child[RAD_MTP_TRAV_MAX_ROWS][8]; /* slot k's child node, or -1 */
int32_t ids[RAD_MTP_TRAV_MAX_ROWS][8]; /* the support, canonical order, -1 past it */
double qr[RAD_MTP_TRAV_MAX_ROWS][8]; /* the draft law (Gumbel: tried children zeroed) */
double m[RAD_MTP_TRAV_MAX_ROWS][8]; /* rate * residual on the support slots (the target's
law itself until the node is entered) */
double moff[RAD_MTP_TRAV_MAX_ROWS]; /* the same off the support, in all */
double sc[RAD_MTP_TRAV_MAX_ROWS]; /* the factor m and moff still owe: the node's rate from
its entry to its first rejected child, then 1 */
double p[RAD_MTP_TRAV_MAX_ROWS]; /* the node's acceptance rate */
uint64_t off[RAD_MTP_TRAV_MAX_ROWS]; /* the off-support mass in units (the final draw) */
float top[RAD_MTP_TRAV_MAX_ROWS]; /* the row's largest value */
int stack[RAD_MTP_TRAV_MAX_DEPTH + 1];
};
/* Node v's laws from its canonical draft side and its row's integer law (`valid`: the row scanned
* clean and its total is positive). */
static inline RAD_RRS_HD void rad_mtp_trav_set_law(RadTravTree* t, int v, bool valid, float top,
const RadTravLaw& w) {
const bool ok = valid && w.sum > 0;
const double sum = ok ? rad_mtp_trav_u2d(w.sum) : 1.0;
for (int k = 0; k < 8; ++k) t->m[v][k] = ok ? rad_mtp_trav_u2d(w.pq[k]) / sum : 0.0;
t->moff[v] = ok ? rad_mtp_trav_u2d(w.off) / sum : 0.0;
t->off[v] = ok ? w.off : 0;
t->top[v] = top;
t->ci[v] = 0;
t->ok[v] = ok;
}
/* The slot of node v's j-th tried child. Gumbel: the draft order. Rheo: the sampled tail child
* first (when the node carries it), then the deterministic ones. */
static inline RAD_RRS_HD int rad_mtp_trav_try_slot(const RadTravTree& t, int v, int j) {
const int nt = t.nt[v];
if (nt < 0) return j;
return t.tail[v] ? (j == 0 ? nt : j - 1) : j;
}
/* The law node v's j-th tried child was drawn from, at support slot k. `isq` is the reciprocal of
* rad_mtp_trav_try_norm: the sum of the node's remaining draft law (Gumbel) or of its tail's (rheo). */
static inline RAD_RRS_HD double rad_mtp_trav_try_norm(const RadTravTree& t, int v) {
const int nt = t.nt[v];
if (nt < 0) return rad_mtp_trav_sum8(t.qr[v]);
double tail[8];
for (int k = 0; k < 8; ++k) tail[k] = k >= nt ? t.qr[v][k] : 0.0;
return rad_mtp_trav_sum8(tail);
}
static inline RAD_RRS_HD double rad_mtp_trav_try_q(const RadTravTree& t, int v, int j, double isq,
int k) {
const int nt = t.nt[v];
if (nt < 0) return t.qr[v][k] * isq;
const int slot = rad_mtp_trav_try_slot(t, v, j);
if (slot != nt) return k == slot ? 1.0 : 0.0; /* a deterministic child: a point mass */
if (k < nt) return 0.0;
const double q = nt == 0 ? t.qr[v][k] : t.qr[v][k] * isq;
return q > 1.0 ? 1.0 : q; /* clamp: rounding must not push a one-token tail past 1 */
}
/* m / q for node v's j-th tried child at its own slot i, m the child's mass in the node's law: the
* child's rate before the cap, in one division (m * sq / qr rather than m / (qr / sq)). Negative
* when the law has no mass there (the child is not tried). */
static inline RAD_RRS_HD double rad_mtp_trav_try_ratio(const RadTravTree& t, int v, int j, int i,
double m) {
const int nt = t.nt[v];
const double q = t.qr[v][i];
if (nt >= 0 && i != nt) return m; /* a point mass */
if (!(q > 0)) return -1.0;
if (nt == 0) return q < 1.0 ? m / q : m;
const double sq = rad_mtp_trav_try_norm(t, v);
return q < sq ? m * sq / q : m; /* the law's value is at most 1 */
}
/* The walk over a prepared tree: the accepted path into path[0 .. *n_path). Returns false when
* nothing was decided (an invalid root state: every row keeps the pick). `pos0` is the root row's
* output position, the coordinate of the acceptance uniforms. Updates the tree in place: the last
* node's m / moff are its residual law (up to the node's factor sc), which
* rad_mtp_trav_final_pick reads. */
static inline RAD_RRS_HD bool rad_mtp_trav_walk_tree(RadTravTree& t, uint64_t seed, uint64_t pos0,
int* path, int* n_path,
const RadMtpTravOpt& opt = RadMtpTravOpt{}) {
int top = 0, tests = 0;
t.stack[0] = 0;
t.p[0] = 1.0;
t.sc[0] = 1.0; /* the root's m is the target's law itself */
*n_path = 0;
if (!t.ok[0]) return false;
for (;;) {
const int v = t.stack[top];
if (t.ok[v] && t.ci[v] < t.nk[v]) {
const int j = t.ci[v];
const int i = rad_mtp_trav_try_slot(t, v, j);
/* p_c = min(1, p_v r(c) / qn(c)); control 1 drops p_v (token-level ratios) */
const double f = opt.ctl == 1 ? (t.p[v] > 0 ? t.sc[v] / t.p[v] : 0.0) : t.sc[v];
const double ratio = rad_mtp_trav_try_ratio(t, v, j, i, f * t.m[v][i]);
const int c = top < RAD_MTP_TRAV_MAX_DEPTH && ratio >= 0 ? t.child[v][i] : -1;
if (c < 0) { t.nk[v] = j; continue; } /* a child the verify no longer carries: cut here */
const double pc = ratio < 1.0 ? ratio : 1.0;
t.p[c] = pc;
t.sc[c] = pc; /* the child's law becomes rate * law, when it is first needed */
t.stack[++top] = c;
continue;
}
/* a leaf: the sequence-level test */
++tests;
bool accept;
if (opt.accept_at >= 0) {
if (opt.p_test && tests <= opt.max_tests) opt.p_test[tests - 1] = t.p[v];
if (opt.n_tests) *opt.n_tests = tests;
accept = tests == opt.accept_at;
} else {
const double u = rad_spechub_uniform(
seed, pos0, RAD_MTP_TRAV_KEY ^ rad_mtp_rrs_mix((uint64_t)tests));
accept = u < t.p[v];
}
if (accept) {
*n_path = top + 1;
for (int i = 0; i <= top; ++i) path[i] = t.stack[i];
return true;
}
if (top == 0) return false; /* the root always accepts (p = 1); only roundoff gets here */
--top;
const int g = t.stack[top];
const int j = t.ci[g];
const double isq = 1.0 / rad_mtp_trav_try_norm(t, g);
const double pold = t.p[g], sc = t.sc[g];
double d[8];
for (int k = 0; k < 8; ++k) {
const double x = sc * t.m[g][k] - rad_mtp_trav_try_q(t, g, j, isq, k);
d[k] = x > 0 ? x : 0;
}
const double moff = sc * t.moff[g];
const double S = moff + rad_mtp_trav_sum8(d);
if (!(S > 0) || !rad_spechub_finite(S)) {
/* nothing of the target is left above the draft: this node cannot accept, nor a child of it */
t.p[g] = 0;
t.sc[g] = 0;
} else {
const double den = opt.ctl == 2 ? S : S + 1.0 - pold;
const double inv = 1.0 / den;
const double pn = S * inv;
t.p[g] = pn < 1.0 ? pn : 1.0; /* a rate is at most 1: rounding may not push it past */
for (int k = 0; k < 8; ++k) t.m[g][k] = d[k] * inv;
t.moff[g] = moff * inv;
t.sc[g] = 1.0;
}
/* Gumbel siblings are drawn WITHOUT replacement: the remaining Q renormalises */
if (t.nt[g] < 0 && opt.ctl != 3) t.qr[g][j] = 0;
++t.ci[g];
}
}
/* The final token of node v's residual law (in proportion to m on the support slots and moff off it:
* the node's factor sc is common to both and cancels), by the uniform
* u: the support slots first, in the canonical order, then the off-support candidates in slot
* order. kind 0: no token (the row keeps the pick); 1: the token of support slot `slot`; 2: the
* off-support candidate holding unit `t` of the row's off-support mass (rad_mtp_trav_off_token). */
struct RadTravPick {
int kind, slot;
uint64_t t;
};
static inline RAD_RRS_HD RadTravPick rad_mtp_trav_final_pick(const RadTravTree& t, int v, double u) {
RadTravPick o;
o.kind = 0; o.slot = -1; o.t = 0;
const double woff = t.moff[v];
const double total = rad_mtp_trav_sum8(t.m[v]) + woff;
if (!(total > 0) || !rad_spechub_finite(total)) return o;
double c = u * total;
int last = -1;
for (int k = 0; k < 8; ++k) {
const double m = t.m[v][k];
if (m > 0) {
last = k;
c -= m;
if (c < 0) { o.kind = 1; o.slot = k; return o; }
}
}
const uint64_t off = t.off[v];
if (woff > 0 && off > 0) {
const double frac = c / woff;
uint64_t tt = frac < 1.0 ? rad_mtp_trav_d2u(frac * rad_mtp_trav_u2d(off)) : off - 1;
if (tt >= off) tt = off - 1;
o.kind = 2; o.t = tt;
return o;
}
if (last >= 0) { o.kind = 1; o.slot = last; }
return o;
}
/* ---------------------------------------------------------------- a tree behind an interface
*
* The tree the walk reads (a Tree type provides):
* const RadMtpCoupleState* state(int v) the node's bound state, or null (node is a leaf)
* bool cand(int v, const int32_t** ids, const float** val, int64_t* n) target candidates
* int child(int v, int32_t token) the node's first child row with that token, or -1
* int64_t vocab()
* rad_mtp_trav_walk prepares the nodes the walk can reach (in discovery order, at most
* RAD_MTP_TRAV_MAX_ROWS), walks and draws the final token: the host reference and the tests. */
template <class Tree>
static inline bool rad_mtp_trav_walk(const Tree& T, int root, uint64_t seed, uint64_t pos0,
RadMtpTravOut* out, RadMtpTravOpt opt = RadMtpTravOpt{},
RadTravTree* keep = nullptr, int* ids_out = nullptr) {
RadTravTree local;
RadTravTree& t = keep ? *keep : local;
int id[RAD_MTP_TRAV_MAX_ROWS]; /* node -> the tree's own id */
struct Row { const int32_t* ids; const float* val; int64_t n; };
Row rows[RAD_MTP_TRAV_MAX_ROWS];
t.n = 1;
id[0] = root;
for (int a = 0; a < t.n; ++a) {
const int v = id[a];
t.ok[a] = 0; t.nk[a] = 0; t.nt[a] = -1; t.tail[a] = 0; t.ci[a] = 0;
t.moff[a] = 0; t.sc[a] = 1.0; t.p[a] = 0; t.off[a] = 0; t.top[a] = -INFINITY;
for (int k = 0; k < 8; ++k) { t.child[a][k] = -1; t.ids[a][k] = -1; t.qr[a][k] = 0; t.m[a][k] = 0; }
rows[a] = Row{ nullptr, nullptr, 0 };
const RadMtpCoupleState* sp = T.state(v);
if (!sp) continue;
int swap = 0;
if (!rad_mtp_trav_canon(*sp, opt.ctl, t.ids[a], t.qr[a], &t.nk[a], &t.nt[a], &t.tail[a], &swap)) continue;
const int32_t* ids = nullptr; const float* val = nullptr;
int64_t n = 0;
if (!T.cand(v, &ids, &val, &n)) continue;
rows[a] = Row{ ids, val, n };
float top = -INFINITY;
RadTravLaw w{};
const bool valid = rad_mtp_trav_row_top(ids, val, n, T.vocab(), &top);
if (valid) rad_mtp_trav_row_law(ids, val, n, top, t.ids[a], sp->count, &w);
rad_mtp_trav_set_law(&t, a, valid, top, w);
if (!t.ok[a]) continue;
for (int k = 0; k < t.nk[a]; ++k) {
const int c = T.child(v, t.ids[a][k]);
if (c < 0 || t.n >= RAD_MTP_TRAV_MAX_ROWS) continue;
t.child[a][k] = t.n;
id[t.n++] = c;
}
}
int path[RAD_MTP_TRAV_MAX_DEPTH + 1], np = 0;
if (ids_out) for (int a = 0; a < t.n; ++a) ids_out[a] = id[a];
if (!rad_mtp_trav_walk_tree(t, seed, pos0, path, &np, opt)) return false;
out->n = np;
for (int i = 0; i < np; ++i) out->node[i] = id[path[i]];
out->has_y = false;
const int f = path[np - 1];
if (t.ok[f]) {
const double ur = opt.u_final >= 0 ? opt.u_final
: rad_spechub_uniform(seed, pos0 + (uint64_t)(np - 1), RAD_SAMPLE_KEY_RESID);
const RadTravPick pk = rad_mtp_trav_final_pick(t, f, ur);
if (pk.kind == 1) { out->y = t.ids[f][pk.slot]; out->has_y = true; }
if (pk.kind == 2) {
int cnt = 0;
while (cnt < 8 && t.ids[f][cnt] >= 0) ++cnt;
out->y = rad_mtp_trav_off_token(rows[f].ids, rows[f].val, rows[f].n, t.top[f], t.ids[f], cnt, pk.t);
out->has_y = out->y >= 0;
}
}
return true;
}
#endif /* __cplusplus */
#endif /* RAD_MTP_TRAVERSAL_H */
+8 -1
View File
@@ -625,6 +625,9 @@ typedef struct RadAudioGenBatch {
const int32_t* ref_cu_h;
const int32_t* ref_frame;
const int32_t* ref_frame_h;
/* ABI 40: PROMPT branch boundaries on the host, [n_seq + 1], including unequal
* reference-direction branches. Same rows as RadBatch::cu_seqlens on device. */
const int32_t* prompt_cu_h;
} RadAudioGenBatch;
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
@@ -726,7 +729,8 @@ typedef struct RadVideoGenBatch {
/* VENCODE: f32 [enc_frames, enc_height, enc_width, 3] RGB in 0..255, the frames padded to
* whole clips by repeating the last (rad_arch_encode_geom's entry 23). AENCODE: f32
* [enc_channels, enc_n_samples], each channel padded with zeros to the hop (entry 0). Both:
* the pass's geometry as rad_arch_encode_geom gave it, i32 on the device, and the media's
* the pass's geometry as rad_arch_encode_geom gave it, i32 in pinned host memory also readable
* by device kernels (mixed-site encoders share it), and the media's
* kind (RAD_ENC_*, below) and its number within the kind from 1. */
const float* enc_pixels;
int32_t enc_frames, enc_height, enc_width;
@@ -936,6 +940,9 @@ int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGrou
int layer);
int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer);
int rad_rank(RadCtx* c);
/* The instance's slot, rad_build_slot() of the declare that built it: what a plugin indexes its
* per-instance state by. */
int rad_slot(RadCtx* c);
int rad_world_size(RadCtx* c);
/* Workgroups the current rank's card can run concurrently (HIP multiProcessorCount on RDNA;
* 32 on the host backend or when the backend has no positive count). */
+22 -1
View File
@@ -37,7 +37,23 @@ typedef struct RadMtpCoupleState {
int32_t status, round, x, count;
int32_t ids[8];
double q[8];
/* The node drafted `nkids` children, sampled without replacement from q, and ids[0 .. nkids) are
* them in draft order (x == ids[0]; ids[nkids .. count) the rest of the support). nkids <= 1 is
* the linear chain's single draw, whose ids keep the shortlist's order, and what the serial
* MTP head writes (abi/rad_mtp_rrs.h states the siblings' law; the traversal walk of
* abi/rad_mtp_traversal.h reads it). Zero from every writer that is not a sibling draw. */
int32_t nkids;
/* The sibling scheme of those children: 0 = Gumbel-top-k without replacement (the only one a
* writer in this engine produces), m + 1 = RheoSampling's m deterministic top-q children plus one
* sampled from the tail law (abi/rad_mtp_rrs.h). Zero from every other writer. */
int32_t scheme;
/* --draft-verify block (abi/rad_mtp_block.h): the length g of the block this row's chain is
* verified as one (the rows 0 .. g-1 bound to rounds 1 .. g, staged on every row of it); 0 for
* token-by-token verification. Written by the sampler's staging only; zero from the device. */
int32_t blk;
int32_t pad_;
} RadMtpCoupleState;
#define RAD_MTP_COUPLE_MAX_RHEO_M 7
#define RAD_MTP_COUPLE_DRAW_WORDS (sizeof(RadMtpCoupleDraw) / 4)
#define RAD_MTP_COUPLE_STATE_WORDS (sizeof(RadMtpCoupleState) / 4)
#define RAD_MTP_COUPLE_MAX_ROUNDS 8
@@ -46,7 +62,7 @@ typedef struct RadMtpCoupleState {
#define RAD_MTP_COUPLE_KEY_DRAFT 0x4d5450434f55504cull
#ifdef __cplusplus
static_assert(sizeof(RadMtpCoupleDraw) == 32, "MTP coupling draw wire");
static_assert(sizeof(RadMtpCoupleState) == 152, "MTP coupling state wire");
static_assert(sizeof(RadMtpCoupleState) == 168, "MTP coupling state wire");
static_assert(offsetof(RadMtpCoupleState, q) % 8 == 0, "MTP coupling q alignment");
#endif
@@ -101,6 +117,9 @@ static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleS
sum += s.q[i];
has_x |= s.ids[i] == s.x;
}
if (s.nkids < 0 || s.nkids > s.count || (s.nkids >= 2 && s.ids[0] != s.x)) return false;
if (s.scheme < 0 || s.scheme > RAD_MTP_COUPLE_MAX_RHEO_M + 1 || (s.scheme && s.nkids >= 1 && s.ids[0] != s.x))
return false;
return has_x && (sum - 1) <= 1e-12 && (1 - sum) <= 1e-12;
}
@@ -327,6 +346,8 @@ static inline RAD_SPECHUB_HD int32_t rad_dflash_couple_step(const float* sc, con
s->pos = 0;
s->round = round;
s->count = 0;
s->nkids = 0; /* a walk's position is one draw: the chain's wire */
s->scheme = 0;
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
if (d.mode != 1) {
s->status = 0;