merge 1.12.0: gemma4 E2B/E4B and Nemotron Bolt E4B arrive; the ref2va audio, rows and ABI work carried across

conv1d keeps both stride forms: upstream's causal codec downsample with cu_div (Fish Audio) and the port's explicit-pad non-causal one (the H3 audio encoder's), in libref, libavx and libr4d alike; the ABI takes upstream's 27 on top of the port's RadVideoGenBatch growth.
This commit is contained in:
gearwave00001 committed 2026-10-24 19:03:26 -05:00
commit 7c3b5ab7d5
285 files changed
+30500 -2898

No files matched your search

+16 -3
View File
@@ -13,11 +13,12 @@ extern "C" {
#endif
/* Bumped whenever anything a plugin compiles against changes shape: this header, rad_types.h,
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h or rad_sample.h. Every
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h, rad_sample.h or
* rad_spechub.h. Every
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
* change of shape: a plugin without it gets the default. */
#define RAD_ABI_VERSION 26u
#define RAD_ABI_VERSION 27u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
@@ -549,9 +550,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
+156 -17
View File
@@ -80,6 +80,13 @@ enum {
RAD_KVQ_K6V4 = 2
};
/* 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. */
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 */
};
typedef struct RadBuildCtx {
int rank; /* declare runs once per rank; the plugin declares dimensions */
int world_size; /* already divided -- the core inserts no collectives (spec §9) */
@@ -174,6 +181,17 @@ typedef struct RadBuildCtx {
* 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 and a plugin built
* against the older struct is unchanged. */
int attn_prefill_fp8;
/* ---- appended in ABI 26 (control vectors) */
/* A control vector loaded from a GGUF `controlvector` file found for this model, or null.
*
@@ -190,6 +208,38 @@ typedef struct RadBuildCtx {
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
const struct RadControlVector* cvec;
/* ---- appended in ABI 27 (row-split prefill attention) */
/* 1 from --tp-attn-split rows: from the plugin's split threshold, a prefill-sized step under
* tensor parallelism runs attention by rows, each rank all heads of its run of the step's
* rows and an all_gather of the runs, instead of by heads. It is faster where the attention
* dominates, costs the full-width projections on every rank, and is not bit-identical to the
* head split. 0 (the zero-initialised default) is the head split. The engine sets it only
* above one rank and only for a plugin whose probe sets RadArchProbe::tp_attn_rows_ok, and
* refuses the flag otherwise.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int tp_attn_rows;
/* ---- appended in ABI 27 (recurrent state at f16) */
/* RAD_F16 from --state-cache-dtype f16: the recurrent state caches (RAD_KV_LINEAR groups) are
* stored at f16 instead of the plugin's f32, which halves the state pool, its checkpoints and
* its traffic and changes the generated text. 0 (the zero-initialised default) is the
* plugin's own width. The engine sets it only for a plugin whose probe has
* RadArchProbe::state_f16_ok and refuses the flag otherwise.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
uint32_t state_dtype;
/* ---- appended in ABI 27 (draft coupling) */
/* Nonzero from --draft-coupling on: a linear serial drafter samples each round's proposal from
* its own shortlist law and declares the planes and ops the coupled verify reads
* (abi/rad_spechub.h, docs/OPS.md `mtp_couple_propose`). 0, the zero-initialised default,
* declares the greedy drafter. A plugin that cannot couple returns RAD_E_UNSUPPORTED from
* declare when it is set; the engine refuses a model whose program carries no coupled planes.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int draft_coupling;
} RadBuildCtx;
/* ================================================================== control vectors */
@@ -351,13 +401,20 @@ enum {
RAD_KV_FULL = 0, /* paged, per-token, growing -- full attention */
RAD_KV_WINDOW = 1, /* paged, per-token, bounded by the window */
RAD_KV_LINEAR = 2, /* per-sequence, fixed size -- GDN recurrent state */
RAD_KV_CONV = 3 /* per-sequence, a rolling window of width-1 + num_spec entries */
RAD_KV_CONV = 3, /* per-sequence, a rolling window of width-1 + num_spec entries */
/* Paged exactly like RAD_KV_WINDOW, but the window's floor is per sequence and set at
* runtime (R-SWA, spec §7.2): `window` is the ring's W, and a sequence keeps everything from
* position 0 up to its own prompt (prefill and image rows) plus a ring of W slots after it,
* rewritten in place. So the group is sized for the whole context plus one ring a sequence,
* never checkpointed, and never reused from the prefix cache. A model that serves a fixed
* sliding window declares RAD_KV_WINDOW instead. */
RAD_KV_RING = 4
};
typedef struct RadKVGroupDecl {
int kind; /* RAD_KV_* */
uint32_t dtype;
int64_t window; /* RAD_KV_WINDOW: the window; 0 otherwise */
int64_t window; /* RAD_KV_WINDOW: the window; RAD_KV_RING: the ring's W; 0 otherwise */
int64_t n_head_kv;
int64_t head_dim;
int64_t state_dim[2]; /* RAD_KV_LINEAR: the per-head state geometry, e.g. {128,128} */
@@ -421,6 +478,17 @@ int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
* A no-op for a PERSIST or DERIVED buffer, which is live everywhere already. */
int rad_buf_concurrent(RadBuilder* b, rad_buf buf);
/* ---- appended in ABI 27 (the second lane's window) */
/* The second lane's window: every op the architecture issues on lane 1 is declared between
* rad_lane1_window_begin and rad_lane1_window_end. With a window a rad_buf_concurrent buffer is live
* over the window and its own declared uses instead of the whole program, so buffers used only
* outside the window (a drafter's, the heads') can share its bytes. The runtime holds the
* architecture to it: an op issued on lane 1 outside the window fails the step by name, and an op
* issued on lane 0 outside the window joins lane 1 first when lane 1 has work pending. Optional, one
* window a program; call both at declare, in order. */
int rad_lane1_window_begin(RadBuilder* b);
int rad_lane1_window_end(RadBuilder* b);
/* An uneven shard: this rank's slice of a RAD_SHARD_ROW or RAD_SHARD_COL weight's split dimension
* is [lo, hi) rather than an even 1/tp. Rows of each stacked row part for ROW, columns for COL, in
* the container's unsharded units. The declared extent must already be `hi - lo` (per row part,
@@ -601,7 +669,8 @@ typedef struct RadDrafterDecl {
/* Where a pass leaves its proposal. 0 = the sampler's token buffer. */
rad_buf proposal;
int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1 */
int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1, and for a BLOCK
* drafter `depth` (less is refused) */
/* BLOCK only. `mask_token` is the id every unfilled block position embeds; a block drafter
* without one cannot run. `window` is the drafter's own sliding window over its own cache, 0
@@ -654,14 +723,24 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
/* 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 -- by default where the model's
* plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter
* decodes speculatively, or as RADIANCE_CHAIN says. A plugin that places work by whether a kernel
* waits in its prologue behind the one before it -- a weight read issued on lane 0 right after its
* GEMM -- asks this instead of reading the environment, so it follows that decision. Additive
* export; RAD_ABI_VERSION does not move. */
* 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
* speculatively. A plugin that places work by whether a kernel waits in its prologue behind the
* one before it -- a weight read issued on lane 0 right after its GEMM -- asks this, so it follows
* that decision. Additive export; RAD_ABI_VERSION does not move. */
int rad_chain_on(void);
/* A block drafter that also serves a shorter block: the plugin declared its query pass at `block`
* rows a sequence as well as at RadDrafterDecl::block, with the same anchor convention, so the
* core may stage a step's block at either. The short block proposes
* `block - (RadDrafterDecl::block - depth)` tokens. Called once, after rad_declare_drafter.
*
* The block is proposed whole, so its length is paid for by every drafting sequence whatever each
* verifies: at one sequence a long block's extra drafts pay, at many its rows and its weaker first
* positions cost more than they bring. The core picks per step (--draft-short-from). */
/* ---- appended in ABI 27 (a block drafter's short block) */
int rad_drafter_short_block(RadBuilder* b, int64_t block);
/* ================================================================== the encoder */
/* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and
* reads its result, so the plugin declares it. A plugin that declares none serves text only, and
@@ -692,6 +771,12 @@ typedef struct RadEncoderDecl {
* the pass and before any other pass runs, so the planner may share its bytes with buffers
* no encoder pass touches. */
rad_buf out;
/* ---- appended in ABI 26 (one grid a pass) */
/* 1: every segment of a pass has one grid (Item segment height), for an encoder whose
* position tables or kernels are per geometry; the core ends a pass where the grid changes.
* 0 packs segments of any grid into a pass. */
int32_t one_grid;
} RadEncoderDecl;
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
@@ -866,6 +951,11 @@ typedef struct RadGeneratorDecl {
* `cond_rows` a whole number of windows. */
int32_t chunk_tokens;
int32_t chunk_bos, chunk_eos;
/* ---- appended in ABI 26 (Krea 2's rebalance) */
/* The RAD_GEN_COND_* options (rad_runtime.h) the plugin's COND pass serves, as a mask; a
* request asking for another is refused. 0: none. */
uint32_t cond_opts;
} RadGeneratorDecl;
/* RadGeneratorDecl::beta_schedule: betas linear in sqrt(beta) (Stable Diffusion's
@@ -962,7 +1052,8 @@ typedef struct RadAudioGenDecl {
/* The prompt, as text the core tokenises: `{instructions}` is replaced by the request's
* instructions (a piece's description, a voice's) and `{input}` by its input text (lyrics, the
* words to speak), each first rewritten by the plugin's rad_arch_text_prepare when it exports
* one. Special tokens are spelled as text. */
* one. Special tokens are spelled as text. NULL for a model that takes no instructions, which
* then declares `tmpl_plain` and has a request's instructions refused. */
const char* tmpl;
/* The unconditional branch is the conditional prompt with every token but the first
* `neg_keep_head` and the last `neg_keep_tail` replaced by `neg_token`, so the two branches
@@ -1023,6 +1114,36 @@ typedef struct RadAudioGenDecl {
* latent: `lat_num` = `lat_den` = 1, `samples_per_latent` samples a frame. */
int64_t voc_chunk;
int64_t voc_context;
/* ---- appended in ABI 27 (one-branch speech over a hybrid model, references) */
/* Sequences a request runs: 0 or 2, the conditional and unconditional branches above; 1, the
* conditional one alone, for a model without guidance (no unconditional prompt is rendered,
* a request's guidance must be 1, and every per-entry array of a PROMPT or FRAME pass has one
* entry a lane, its `slot` the lane itself). The KV, the prompt's rows and a frame's rows then
* cost half. */
int32_t branches;
/* Nonzero: the `{input}` slot is tokenised with its special tokens, which the template's own
* text always is, so a caller can write the model's speaker tags. The plugin's
* rad_arch_text_prepare then refuses the control tokens a caller must not write. */
int32_t input_special;
/* References (voice cloning): with `tmpl_ref`, a request may carry up to `ref_max` of them,
* each a transcript and a clip of the voice saying it, which the plugin encodes into frames
* in the request's PROMPT pass (whole prompts only: `prompt_whole`). `tmpl_ref` is the prompt
* of a request with references, `{references}` each of them rendered from `ref_item` in turn
* and `{input}` as in `tmpl_plain`. `ref_item` is one reference: `{index}` its number from 1,
* `{text}` its transcript (rewritten by rad_arch_text_prepare as RAD_TEXT_REFERENCE) and
* `{audio}` its frames, one prompt row each (RadAudioGenBatch::ref_frame); the text before
* `{audio}` is tokenised as one segment with its special tokens (the transcript's own, which
* 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. */
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;
} RadAudioGenDecl;
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
@@ -1477,12 +1598,28 @@ typedef struct RadArchProbe {
* 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;
/* ---- 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 by default; RADIANCE_CHAIN overrides either way. Zero keeps them off: plain
* decode measured slower chained, and a plugin that never measured them asks for nothing. */
* then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin
* that never measured them asks for nothing. */
int32_t chain_pays;
/* Nonzero when the plugin applies RadBuildCtx::cvec for this model. --control-vector is
* refused at startup with the plugin named when this is 0. */
int32_t control_vector_ok;
/* ---- appended in ABI 27 (row-split prefill attention) */
/* Nonzero when the plugin serves RadBuildCtx::tp_attn_rows for this model. --tp-attn-split
* rows is refused at startup with the plugin named when this is 0. */
int32_t tp_attn_rows_ok;
/* ---- appended in ABI 27 (recurrent state at f16) */
/* Nonzero when the plugin declares its recurrent state at f16 under RadBuildCtx::state_dtype
* and its kernels read that width. --state-cache-dtype f16 is refused at startup with the
* plugin named when this is 0. */
int32_t state_f16_ok;
} RadArchProbe;
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
@@ -1661,11 +1798,13 @@ const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta);
* as given. Training data has conventions a client does not know -- section tags on lines of
* their own and lower case, no markdown in a description -- and only the plugin knows them.
*
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8. Writes at most `cap` bytes, the NUL included,
* and returns the length the whole result needs without its NUL (call again with more room when
* it is >= cap), or a negative status for text the model cannot take. Called on HTTP threads, so
* it keeps no state. */
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2 };
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8: the instructions, the input, or a
* reference's transcript (RadAudioGenDecl::ref_item's `{text}`). Writes at most `cap` bytes, the
* NUL included, and returns the length the whole result needs without its NUL (call again with
* more room when it is >= cap), or a negative status for text the model cannot take, with the
* reason in `out` (NUL-terminated within `cap`) when it has one to give the caller. Called on
* HTTP threads, so it keeps no state. */
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2, RAD_TEXT_REFERENCE = 3 };
int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap);
/* The layout of a video generator's passes (rad_declare_video_generator), which only the model
+43 -3
View File
@@ -243,6 +243,19 @@ typedef struct RadBatch {
/* A video generator's pass (rad_declare_video_generator; `gen` is one of its
* RAD_GEN_PASS_*): its payload. Null on every other step. */
const struct RadVideoGenBatch* vgen_b;
/* ---- appended in ABI 26 (control vectors) */
/* Host-side: nonzero when some row of this pass takes the loaded control vector (its
* `projection_on_rows` entry is 1). A projection skips a zero row anyway, so a block issues
* no projection op when this is 0 and the pass is the one a deployment without a vector runs. */
int32_t control_vector;
/* ---- appended in ABI 26 (per-segment encoder grids) */
/* host: [enc_n_seg] each segment's grid in patches, the same values enc_coord planes 2 and 3
* carry. A plugin that has to pick a geometry before it issues ops (a tower with one set of
* position tables per grid) reads them here; they live as long as the pass. */
const int32_t* enc_seg_h;
const int32_t* enc_seg_w;
} RadBatch;
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
@@ -379,13 +392,15 @@ typedef struct RadGenBatch {
* where a window's end-of-text marker sits. */
const int32_t* tokens_h;
/* ---- appended in ABI 26 (Krea 2's rebalance) */
/* COND: the request's RAD_GEN_COND_* options, 0 for none. */
/* COND: the request's RAD_GEN_COND_* options, 0 for none and on every other pass. Only
* options the plugin declares (RadGeneratorDecl::cond_opts) are set. */
int32_t cond_opts;
} RadGenBatch;
/* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */
enum {
RAD_GEN_COND_REBALANCE = 1 /* Krea 2: the text taps at the plugin's fixed rebalance gains */
RAD_GEN_COND_REBALANCE = 1 /* the conditioning at the plugin's fixed rebalance gains (the
* request field `rebalance`; Krea 2: its text taps) */
};
/* An entry's flags on a DENOISE pass. */
@@ -474,6 +489,30 @@ typedef struct RadAudioGenBatch {
/* VOCODE with RadAudioGenDecl::voc_chunk: the lane's first frame the pass reads, counted
* from the first kept frame. 64 bits so that it starts past the struct's ABI 18 end. */
int64_t voc_frame0;
/* ---- appended in ABI 27 (a frame head at the previous row, references) */
/* FRAME, one value per entry ([n_seq]): the row before the frame's own row -- the one whose
* hidden state the frame is sampled from -- as its KV slot, its position, and the context
* through it (position + 1). A model whose frame head attends at that row (Fish Audio
* drama-3's codebook tower, layers bound to the language model's full-attention group) issues
* those layers there, before the language model runs at the frame's own row. */
const int32_t* prev_slot;
const int32_t* prev_pos;
const int32_t* prev_used;
/* PROMPT of a request with references (RadAudioGenDecl::tmpl_ref; n_ref 0 without): its
* clips' samples end to end (`ref_samples` f32 on the device), the clips' bounds in samples
* ([n_ref + 1], each a whole number of RadAudioGenDecl::ref_hop), and for every row of the
* pass the frame of the clips it is or -1 for a token row ([n_tok]), frames counted over the
* clips in order, frame f the samples [f ref_hop, (f + 1) ref_hop). A frame's row stages
* token 0; the plugin embeds the frame there instead. */
int64_t n_ref;
int64_t ref_samples;
const float* ref_audio;
const int32_t* ref_cu;
const int32_t* ref_cu_h;
const int32_t* ref_frame;
const int32_t* ref_frame_h;
} RadAudioGenBatch;
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
@@ -738,7 +777,8 @@ int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n)
* the all-reduce numbers its scratch slots per launch and the ranks must agree; a kernel with a
* device-wide arrival counter must key it on the stream (libr4d's split-K GEMM does), or it may
* not run here; and every buffer the second lane touches must be named to rad_buf_concurrent,
* because the planner packs transients from one linear order. */
* because the planner packs transients from one linear order (live for the whole program, or across
* the second lane's window where the architecture declares one, abi/rad_builder.h). */
int rad_lane(RadCtx* c, int lane);
int rad_lane_join(RadCtx* c, int from, int to);
+267
View File
@@ -0,0 +1,267 @@
/* rad_spechub.h -- the linear-MTP coupling: wire rows and the shared arithmetic.
*
* The core writes these rows and a kernel plugin reads them, so their layout is ABI. The helpers
* are header-only and stateless, so the host reference, the device kernel and the sampler share
* one definition of the wire and of the arithmetic that turns it into a token.
*
* A row lives in a U32 plane whose base and row stride are eight-byte aligned, so a state can be
* loaded 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 RadSampleParams row. */
#include "rad_sample.h"
/* Linear MTP coupling (--draft-coupling on). 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
*
* Q is the FP64 softmax of an FP32 shortlist at temperature 1; P is the FP64 softmax of the
* sampler's FP32 candidate logits; uniforms are 53-bit. A coupled row therefore realises the
* filtered target law to FP64 rounding rather than sample_pick's FP32/24-bit law, and is not
* seed-identical to the ordinary pick.
*/
#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;
}
/* A 53-bit uniform in [0, 1): splitmix64 over (seed ^ key, pos), top 53 bits scaled by 2^-53. */
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 coupled round r (1-based): the 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 the
* request's committed output length when the step is built; round r is verified at row r - 1. The
* acceptance and residual uniforms are drawn at this position.
*
* `n_out` is read from the request after the drafting step's commit. It is not rebuilt from the
* draft's pre-commit `base` plus the accepted count: the two differ when the commit emits fewer
* tokens than the card accepted (a max_tokens or context cut) or a step is carried. */
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 of the target's law P (over the surviving candidates) with the draft's Q.
* Writes the emitted token to *out and returns true, or returns false for an invalid or empty
* target. u_accept and u_resid are independent uniforms in [0, 1).
*
* The draft x is kept when P dominates Q on every Q token or when u_accept * Q(x) < P(x); otherwise
* the token is drawn from the residual (P - Q)+. The emitted token is distributed as P, and it
* equals x with probability sum min(P, Q).
*
* If FP64 cancellation leaves the residual total R at 0 while some Q token has P < Q, P is sampled
* directly in FP64 with u_resid. That branch depends on (P, Q) only, never on x or a uniform.
*
* R sums r over every candidate including x. The residual walk runs only when P(x) < Q(x), where
* r(x) is exactly +0, so skipping x in the walk leaves its total equal to 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 */