radiance 1.12.0

New models:
- Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference
  clips (the `references` field of /v1/audio/speech and the streaming session), two cards
- Gemma 4 E2B/E4B (KV-shared layers, per-layer embeddings, clipped vision linears), with
  NVIDIA-Nemotron-3.5-Bolt-E4B in bf16 with DFlash and vision on one card, and E4B recipes

Speed:
- MXFP4 GEMMs for one to 64 rows and a tiled prefill GEMM at TN=4 from 1024 rows: the 27B MXFP4
  with DFlash2 decodes about 1% faster at c1, 5% at c4 and 14% at c16
- The fp8 and int8 LM heads read their weight once for 65 to 128 rows
- A prefill step of one sequence runs in two pieces on a second lane at two ranks (qwen35_fp8,
  gemma3): a 45K-token prompt on the 27B fp8 in 15.1 s instead of 16.2 s
- Gemma 3's fused all-reduce junctions also under a lossy wire
- --draft-short-from N: a block drafter runs its shorter block from N decoding sequences on
  (off by default; with 8 on the 27B MXFP4: c8 +12%, c16 +18%, c64 +32%, c1 unchanged)
- --tp-attn-split rows: GLM-5.3-Flash's MLA attention split by rows over the ranks, 18 to 21%
  faster prefill; lossy, `heads` stays the default
- --draft-coupling on: Qwen3.8-Flash-Next's MTP drafter samples its proposals from its reranked
  top-8 and the target's draw is coupled to it; pays at high temperatures (c1 at T 1.0: 155 ->
  178 tok/s), costs at low ones; off by default

Features:
- Edited prompts on windowed models (Gemma 4) reuse their prefix: periodic window snapshots, and
  snapshot-backed prefix KV kept across recomputes (an edited tail on Gemma 4 31B: 96 s -> 2.6 s)
- DELETE /sessions/<label> and DELETE /sessions?id=<id> forget one stored conversation
- --state-cache-dtype f16: the delta-net state cache at half the memory (qwen35 plugins; lossy)

Fixes:
- A browser's CORS preflight allows DELETE

Changes: Plugin ABI 27: out-of-tree plugins must be rebuilt. The environment switches the PRs
added are flags now (--tp-attn-split, --draft-coupling, --state-cache-dtype).
This commit is contained in:
137 files changed
+12959 -1126

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
# spechub -- the linear-MTP coupling kernels.
#
# Two ops, `mtp_couple_propose` and `mtp_couple_verify`, each with a device row and a host reference
# row. The arithmetic is abi/rad_spechub.h's, shared with the engine. The device launches include
# libr4d/r4d_emit.h by its path in this tree, so the device form builds from this tree's sources
# (in the tree's build or standalone against an install); a host-only build needs abi/ alone.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(spechub LANGUAGES CXX)
find_package(radiance REQUIRED)
# The device rows are built where the installed radiance has a device build; HIP is enabled
# after project(), from the package's record of that build.
if(RAD_HIP_FOUND)
enable_language(HIP)
endif()
rad_plugin_defaults()
endif()
set(SPECHUB_COMMON
${CMAKE_CURRENT_SOURCE_DIR}/spechub.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ref_spechub.cpp
${CMAKE_CURRENT_SOURCE_DIR}/exports.cpp)
if(NOT RAD_HIP_FOUND)
message(STATUS "spechub: this radiance has no device build -- only the host reference is built")
rad_add_plugin(spechub kernels SOURCES ${SPECHUB_COMMON})
else()
# The owning project must enable HIP itself; enable_language() is project scope. The top-level tree
# does it with -DRAD_WITH_HIP=ON, and a standalone build must do the same after project().
get_property(spechub_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
if(NOT "HIP" IN_LIST spechub_langs)
message(FATAL_ERROR "spechub: HIP_SOURCES need `enable_language(HIP)` in this project (set "
"-DRAD_WITH_HIP=ON, or enable it after project()).")
endif()
rad_add_plugin(spechub kernels SOURCES ${SPECHUB_COMMON}
HIP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/spechub.hip)
target_compile_definitions(spechub PRIVATE RAD_SPECHUB_WITH_DEVICE=1)
endif()
# -ffp-contract=off for correctness: an FMA fused into the ordered FP64 mass sums would move the
# token off the host reference.
target_compile_options(spechub PRIVATE -ffp-contract=off)
+97
View File
@@ -0,0 +1,97 @@
/* plugin/spechub/exports.cpp -- the plugin's export block.
*
* The whole kernel-plugin set (schema count/at, kernel count/at, ABI version, info) and nothing else.
* The rows themselves, their schemas and their argument readers are in spechub.cpp; the launches are
* spechub.hip (device) and ref_spechub.cpp (host).
*
* Reference status is per row: the library carries device rows and their host oracle, so
* `rad_kernel_reference` marks the device rows 0 and the host rows 1, and `rad_plugin_reference`
* stays 0. Marking the whole library would make the reference gate refuse the device rows. On a
* machine with no card only the reference rows exist, and the gate refuses the coupling there.
*
* The ops are declared only under --draft-coupling on; the plugin never reads the flag.
*/
#include "spechub.h"
#ifdef RAD_SPECHUB_WITH_DEVICE
#include "../../libr4d/r4d_emit.h" /* only for the three globals it declares */
/* r4d_emit.h's dispatch recorder, defined here because plugins load RTLD_LOCAL and cannot
* resolve libr4d's copy. Nothing in this plugin sets the log, so the recorder stays inert. */
const void** r4d_dispatch_log = nullptr;
int r4d_dispatch_cap = 0;
int r4d_dispatch_n = 0;
#endif
namespace {
const RadPluginInfo kInfo = {
RAD_PLUGIN_KERNEL, "spechub", "0.1.0",
"Linear-MTP maximal coupling: a Q draw per round and the coupled target verify", "gfx1201",
};
} /* namespace */
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
/* Mixed library: 0, and the per-row answer below does the classifying. */
extern "C" int rad_plugin_reference(void) { return 0; }
/* Row layout is [device 0, device 1, ref 0, ref 1] with a card, [ref 0, ref 1] without. The
* device rows are the production kernels; the host rows are the oracle rad-kbench checks them
* against and the only thing a card-less machine can run. */
extern "C" int rad_kernel_reference(int i) {
#ifdef RAD_SPECHUB_WITH_DEVICE
return (i == 0 || i == 1) ? 0 : 1;
#else
(void)i;
return 1;
#endif
}
extern "C" int rad_kernel_schema_count(void) { return rad_spechub_schema_count(); }
extern "C" const RadOpSchema* rad_kernel_schema_at(int i) { return rad_spechub_schema_at(i); }
/* Two device rows and the two host references beside them, in that order. A card-less machine loads
* the same library and resolves only the reference rows. */
extern "C" int rad_kernel_count(void) {
#ifdef RAD_SPECHUB_WITH_DEVICE
return 4;
#else
return 2;
#endif
}
extern "C" const RadKernelInfo* rad_kernel_at(int i) {
const int op = i & 1;
#ifdef RAD_SPECHUB_WITH_DEVICE
if (i == 0 || i == 1) {
static const RadKernelInfo r[2] = {
rad_spechub_row(0, rad_mine_mtp_couple_propose_launch),
rad_spechub_row(1, rad_mine_mtp_couple_verify_launch),
};
return &r[i];
}
#endif
static const RadKernelInfo ref[2] = {
[] {
RadKernelInfo x = rad_spechub_row(0, rad_ref_mtp_couple_propose);
x.name = "ref_mtp_couple_propose";
x.domain = RAD_DOMAIN_HOST;
x.priority = 0;
return x;
}(),
[] {
RadKernelInfo x = rad_spechub_row(1, rad_ref_mtp_couple_verify);
x.name = "ref_mtp_couple_verify";
x.domain = RAD_DOMAIN_HOST;
x.priority = 0;
return x;
}(),
};
#ifdef RAD_SPECHUB_WITH_DEVICE
if (i < 2 || i > 3) return nullptr;
return &ref[op];
#else
if (i < 0 || i > 1) return nullptr;
return &ref[i];
#endif
}
+22
View File
@@ -0,0 +1,22 @@
/* plugin/spechub/ref_spechub.cpp -- the two coupling ops on the host.
*
* One row at a time through the abi/rad_spechub.h helpers. These are the rows the device kernels
* are checked against, and the only implementation a machine with no card can run.
*/
#include "spechub.h"
int rad_ref_mtp_couple_propose(const RadArgs* a, RadStream) {
RadMtpCoupleProposeCall c{};
const int rc = rad_mtp_couple_propose_args(a, &c);
if (rc != RAD_OK) return rc;
for (int64_t row = 0; row < c.M; ++row) rad_mtp_couple_propose_row(c, row);
return RAD_OK;
}
int rad_ref_mtp_couple_verify(const RadArgs* a, RadStream) {
RadMtpCoupleVerifyCall c{};
const int rc = rad_mtp_couple_verify_args(a, &c);
if (rc != RAD_OK) return rc;
for (int64_t row = 0; row < c.M; ++row) rad_mtp_couple_verify_row(c, row);
return RAD_OK;
}
+255
View File
@@ -0,0 +1,255 @@
/* plugin/spechub/spechub.cpp -- the two coupling ops' schemas, shapes and argument validation.
*
* Shape hooks and geometry only: the arithmetic is in abi/rad_spechub.h (inline, host and device) and
* the launches are in spechub.hip and ref_spechub.cpp. This file is host C++ and compiles with no
* card, which is what lets a card-less machine check the plugin's schema and shapes.
*/
#include "spechub.h"
#include <climits>
#include <cstddef>
namespace {
#define PI(k) { k, RAD_P_INT, RAD_REQUIRED, 0 }
const RadParamSpec kProposeParams[] = {
PI("M"), PI("n_vocab"), PI("round"), PI("max_rounds"),
};
const RadParamSpec kVerifyParams[] = { PI("M"), PI("n_cand"), PI("n_vocab") };
#undef PI
/* `idx` is INOUT: the round's proposal IS the head's column 0, and a sampled row overwrites it. */
const RadOperandSpec kProposeOperands[] = {
{ "idx", RAD_OPD_INOUT, 0 },
{ "val", RAD_OPD_IN, 0 },
{ "seq_ids", RAD_OPD_IN, 0 },
{ "draw", RAD_OPD_IN, 0 },
{ "state", RAD_OPD_INOUT, 0 },
};
/* The verify runs after the ordinary pick over the SAME final candidate plane, so its operands are
* the sampler's own: candidates, parameter rows, coupled state rows, and the token plane the pick
* already wrote. */
const RadOperandSpec kVerifyOperands[] = {
{ "cand_idx", RAD_OPD_IN, 0 },
{ "cand_val", RAD_OPD_IN, 0 },
{ "params", RAD_OPD_IN, 0 },
{ "state", RAD_OPD_IN, 0 },
{ "token", RAD_OPD_INOUT, 0 },
};
const RadOpSchema kSchemas[] = {
{ "mtp_couple_propose", kProposeParams, 4, kProposeOperands, 5,
"Linear MTP round `round`: x~Q, Q = FP64 T1 softmax of the final top8 scores; x into idx "
"column 0 and the state into state[round-1][row]. mode0 rows keep column 0 (status 0); bad "
"ids/scores or seq_ids != draw.card keep it too (status -1)." },
{ "mtp_couple_verify", kVerifyParams, 3, kVerifyOperands, 5,
"Maximal coupling of a bound mtp_couple state after sample_pick over all surviving target "
"candidates, FP64 P and 53-bit ACCEPT/RESID uniforms at params.pos; residual (P-Q)+ with "
"r(x)=0. Rows whose state is not status 1, not bound to params seed/pos, malformed, or whose "
"(P,Q) admit no coupling keep the ordinary token." },
};
} /* namespace */
int rad_spechub_schema_count() { return 2; }
const RadOpSchema* rad_spechub_schema_at(int i) {
return i >= 0 && i < 2 ? &kSchemas[i] : nullptr;
}
namespace {
/* The geometry both hooks and the arg readers agree on. `op` 0 proposes, 1 verifies. A RANGE `M`
* reads as its high bound, which is what a shape hook must do: it sizes buffers before selection has
* collapsed anything, so it describes the whole band. */
int couple_geometry(const RadParam* p, int n, int op, bool range, int64_t* M, int64_t* vocab,
int64_t* n_cand) {
if (!p) return RAD_E_INVAL;
*M = range ? rad_param_getdim(p, n, "M", 0) : rad_param_geti(p, n, "M", 0);
*vocab = rad_param_geti(p, n, "n_vocab", 0);
*n_cand = op ? rad_param_geti(p, n, "n_cand", 0) : 8;
if (*M < 1 || *M > INT32_MAX || *vocab < 1 || *vocab > INT32_MAX) return RAD_E_UNSUPPORTED;
if (*n_cand < 1 || *n_cand > INT32_MAX) return RAD_E_UNSUPPORTED;
if (!op) {
const int64_t round = rad_param_geti(p, n, "round", 0);
const int64_t rounds = rad_param_geti(p, n, "max_rounds", 0);
if (rounds < 1 || rounds > RAD_MTP_COUPLE_MAX_ROUNDS || round < 1 || round > rounds)
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
}
/* Does one operand's extent fit the shape its hook declares? A row-owning kernel reads a whole row,
* so the last axis is structural and every leading one is a row count. */
int span(const RadTensor& t, const RadOpdDesc& d, uint64_t* bytes) {
if (!t.data || (uintptr_t)t.data % 4) return RAD_E_INVAL;
if (t.dtype != d.dtype) return RAD_E_DTYPE;
if (t.rank != d.rank) return RAD_E_SHAPE;
uint64_t words = 1;
for (int j = (int)d.rank - 1; j >= 0; --j) {
if (t.shape[j] < 1 || t.shape[j] > INT32_MAX || (d.shape[j] > 0 && t.shape[j] != d.shape[j]))
return RAD_E_SHAPE;
if (t.stride[j] < 1 || (j == (int)d.rank - 1 && t.stride[j] != 1) ||
(j < (int)d.rank - 1 && (uint64_t)t.stride[j] < words))
return RAD_E_STRIDE;
const uint64_t extent = (uint64_t)(t.shape[j] - 1);
if (extent && (uint64_t)t.stride[j] > (INT64_MAX / 4 - words) / extent) return RAD_E_SHAPE;
words += extent * (uint64_t)t.stride[j];
}
*bytes = words * 4;
if ((uintptr_t)t.data > UINTPTR_MAX - *bytes) return RAD_E_INVAL;
return RAD_OK;
}
} /* namespace */
int rad_mtp_couple_propose_shape(const RadParam* p, int n, int i, RadOpdDesc* out) {
if (!out || i < 0 || i >= 5) return RAD_E_INVAL;
int64_t M, v, nc;
int rc = couple_geometry(p, n, 0, true, &M, &v, &nc);
if (rc != RAD_OK) return rc;
RadOpdDesc d{};
d.idx_const = -1;
d.dtype = RAD_I32;
d.rank = 2;
d.shape[0] = M;
d.shape[1] = 8;
if (i == 0) { d.fill = RAD_FILL_INDEX; d.idx_max = (int32_t)v; }
if (i == 1) d.dtype = RAD_F32;
if (i == 2) { d.rank = 1; d.fill = RAD_FILL_INDEX; d.idx_max = (int32_t)M; }
if (i == 3) { d.dtype = RAD_U32; d.shape[1] = RAD_MTP_COUPLE_DRAW_WORDS; }
if (i == 4) {
/* Rounds are the state plane's leading axis, and `max_rounds` is exactly the bound the caller
* sized it at. */
const int64_t rounds = rad_param_geti(p, n, "max_rounds", 1);
d.dtype = RAD_U32;
d.rank = 3;
d.shape[0] = rounds;
d.shape[1] = M;
d.shape[2] = RAD_MTP_COUPLE_STATE_WORDS;
}
*out = d;
return RAD_OK;
}
int rad_mtp_couple_verify_shape(const RadParam* p, int n, int i, RadOpdDesc* out) {
if (!out || i < 0 || i >= 5) return RAD_E_INVAL;
int64_t M, v, nc;
int rc = couple_geometry(p, n, 1, true, &M, &v, &nc);
if (rc != RAD_OK) return rc;
RadOpdDesc d{};
d.idx_const = -1;
d.dtype = RAD_I32;
d.rank = 2;
d.shape[0] = M;
d.shape[1] = nc;
if (i == 1) d.dtype = RAD_F32;
if (i == 2 || i == 3) {
d.dtype = RAD_U32;
d.shape[1] = i == 2 ? 24 : RAD_MTP_COUPLE_STATE_WORDS;
}
if (i == 4) d.rank = 1;
*out = d;
return RAD_OK;
}
/* The resolved `M` is the arena band's ceiling; this issue may carry fewer live rows, and both
* kernels take the row count from operand 0. Dim 0 is narrowed to the live rows before each
* operand's extent is checked, the wire planes must be eight-byte aligned with an even row stride,
* and separate storage is part of the contract: an aliased pair would let a write land on a read. */
int rad_couple_validate(const RadArgs* a, int op, int64_t* M, int64_t* vocab, int64_t* n_cand) {
if (!a || !a->t || a->n_t != 5) return RAD_E_INVAL;
int rc = couple_geometry(a->p, a->n_p, op, false, M, vocab, n_cand);
if (rc != RAD_OK) return rc;
const int64_t live = a->t[0].rank ? a->t[0].shape[0] : 0;
if (live < 1 || live > *M) return RAD_E_SHAPE;
*M = live;
const int64_t rounds = op ? 1 : rad_param_geti(a->p, a->n_p, "max_rounds", 1);
uint64_t bytes[5] = {};
for (int i = 0; i < 5; ++i) {
RadOpdDesc d{};
rc = op ? rad_mtp_couple_verify_shape(a->p, a->n_p, i, &d)
: rad_mtp_couple_propose_shape(a->p, a->n_p, i, &d);
if (rc != RAD_OK) return rc;
d.shape[0] = *M;
/* `seq_ids` covers the whole batch and the state plane is [rounds, rows]; both are checked
* below rather than against the live row count. */
if (!op && i == 2) d.shape[0] = 0;
if (!op && i == 4) { d.shape[0] = rounds; d.shape[1] = 0; }
/* The sampler exposes a flat token plane and its production [M, 1] one. */
if (op && i == 4 && a->t[i].rank == 2) { d.rank = 2; d.shape[1] = 1; }
if ((rc = span(a->t[i], d, &bytes[i])) != RAD_OK) return rc;
if (!op && i == 2 && a->t[i].shape[0] < *M) return RAD_E_SHAPE;
if (!op && i == 4 && a->t[i].shape[1] < *M) return RAD_E_SHAPE;
const bool wire = op ? (i == 2 || i == 3) : (i == 3 || i == 4);
if (wire && ((uintptr_t)a->t[i].data % 8 || a->t[i].stride[0] % 2 ||
(a->t[i].rank == 3 && a->t[i].stride[1] % 2)))
return RAD_E_INVAL;
}
/* An even ROW stride keeps every shortlist row 8-byte aligned; the innermost stride is 1. */
if (!op && a->t[0].stride[0] % 2) return RAD_E_STRIDE;
for (int i = 0; i < 5; ++i)
for (int j = i + 1; j < 5; ++j) {
const uintptr_t x = (uintptr_t)a->t[i].data, y = (uintptr_t)a->t[j].data;
if (x < y + bytes[j] && y < x + bytes[i]) return RAD_E_INVAL;
}
return RAD_OK;
}
int rad_mtp_couple_propose_args(const RadArgs* a, RadMtpCoupleProposeCall* out) {
if (!out) return RAD_E_INVAL;
int64_t M, v, nc;
const int rc = rad_couple_validate(a, 0, &M, &v, &nc);
if (rc != RAD_OK) return rc;
RadMtpCoupleProposeCall c{};
c.M = M;
c.vocab = v;
c.round = (int)rad_param_geti(a->p, a->n_p, "round", 0);
c.idx = (int32_t*)a->t[0].data;
c.val = (const float*)a->t[1].data;
c.card = (const int32_t*)a->t[2].data;
c.draw = (const uint32_t*)a->t[3].data;
c.state = (uint32_t*)a->t[4].data;
c.ld_idx = a->t[0].stride[0];
c.ld_val = a->t[1].stride[0];
c.ld_draw = a->t[3].stride[0];
c.st_round = a->t[4].stride[0];
c.st_row = a->t[4].stride[1];
*out = c;
return RAD_OK;
}
int rad_mtp_couple_verify_args(const RadArgs* a, RadMtpCoupleVerifyCall* out) {
if (!out) return RAD_E_INVAL;
int64_t M, v, nc;
const int rc = rad_couple_validate(a, 1, &M, &v, &nc);
if (rc != RAD_OK) return rc;
RadMtpCoupleVerifyCall c{};
c.M = M;
c.vocab = v;
c.n_cand = nc;
c.idx = (const int32_t*)a->t[0].data;
c.val = (const float*)a->t[1].data;
c.params = (const uint32_t*)a->t[2].data;
c.state = (const uint32_t*)a->t[3].data;
c.token = (int32_t*)a->t[4].data;
for (int i = 0; i < 5; ++i) c.ld[i] = a->t[i].stride[0];
*out = c;
return RAD_OK;
}
RadKernelInfo rad_spechub_row(int i, RadLaunchFn launch) {
RadKernelInfo r{};
r.name = i ? "spechub_mtp_couple_verify" : "spechub_mtp_couple_propose";
r.op = i ? "mtp_couple_verify" : "mtp_couple_propose";
r.family = "draft";
r.computes = i ? "maximal coupling over the surviving target candidates, FP64 P"
: "x~Q over the final top8, FP64 T1 softmax";
r.shape = i ? "M,n_cand,n_vocab" : "M,n_vocab,round,max_rounds<=8";
r.dtypes = "f32,i32,u32";
r.domain = RAD_DOMAIN_DEVICE;
r.priority = 100;
r.launch = launch;
r.opd_shape = i ? rad_mtp_couple_verify_shape : rad_mtp_couple_propose_shape;
return r;
}
+110
View File
@@ -0,0 +1,110 @@
/* plugin/spechub/spechub.h -- the plugin-private contract between its host half and its kernels.
*
* Plugin-private ON PURPOSE: core/ must never include this, and everything the CORE needs (the wire
* row and the coupling arithmetic) already lives in abi/rad_spechub.h. Only the packed call structs
* and the argument readers are here, shared by the host reference and the device launch.
*/
#ifndef RAD_PLUGIN_SPECHUB_H
#define RAD_PLUGIN_SPECHUB_H
#include "rad_abi.h"
#include "rad_plugin.h" /* rad_param_geti/getdim: the pure readers, inline and total */
#include "rad_spechub.h"
#include <cmath>
#include <cstdint>
#if defined(__HIPCC__)
#define RAD_SPECHUB_HD __host__ __device__
#else
#define RAD_SPECHUB_HD
#endif
/* A draft round's operands, packed once for both the device launch and the host reference. */
struct RadMtpCoupleProposeCall {
int32_t* idx; /* [M, 8] INOUT: this rank's shortlist; column 0 is the proposal */
const float* val; /* [M, 8] the shortlist's scores */
const int32_t* card; /* [batch] RadBatch::seq_ids: the slot the advance writes */
const uint32_t* draw; /* [M, DRAW_WORDS] RadMtpCoupleDraw */
uint32_t* state; /* [rounds, M, STATE_WORDS] RadMtpCoupleState */
int64_t M;
int64_t vocab;
int64_t ld_idx, ld_val, ld_draw, st_round, st_row;
int round;
};
/* The verify's operands: the sampler's own candidate plane, its parameter rows, the bound state
* rows and the token plane the pick already wrote. */
struct RadMtpCoupleVerifyCall {
const int32_t* idx; /* [M, n_cand] */
const float* val; /* [M, n_cand] */
const uint32_t* params; /* [M, 24 words] RadSampleParams */
const uint32_t* state; /* [M, STATE_WORDS] RadMtpCoupleState */
int32_t* token; /* [M] or [M, 1] */
int64_t M, n_cand, vocab, ld[5];
};
int rad_mtp_couple_propose_shape(const RadParam*, int, int, RadOpdDesc*);
int rad_mtp_couple_verify_shape(const RadParam*, int, int, RadOpdDesc*);
int rad_mtp_couple_propose_args(const RadArgs*, RadMtpCoupleProposeCall*);
int rad_mtp_couple_verify_args(const RadArgs*, RadMtpCoupleVerifyCall*);
/* The geometry/validation the shape hooks and the arg readers share. `op` 0 proposes, 1 verifies. */
int rad_couple_validate(const RadArgs*, int op, int64_t* M, int64_t* vocab, int64_t* n_cand);
/* The op set. Two schemas, two device rows and two host-reference rows. */
int rad_spechub_schema_count();
const RadOpSchema* rad_spechub_schema_at(int i);
RadKernelInfo rad_spechub_row(int i, RadLaunchFn launch);
/* The launches. */
int rad_mine_mtp_couple_propose_launch(const RadArgs*, RadStream);
int rad_mine_mtp_couple_verify_launch(const RadArgs*, RadStream);
int rad_ref_mtp_couple_propose(const RadArgs*, RadStream);
int rad_ref_mtp_couple_verify(const RadArgs*, RadStream);
/* One propose row, host and device: x ~ Q over the final eight. Column 0 is what ADV_ROUND and
* ADV_TAKE read, and it becomes x only for a valid sampled row. */
static inline RAD_SPECHUB_HD void rad_mtp_couple_propose_row(const RadMtpCoupleProposeCall& c,
int64_t row) {
RadMtpCoupleState s{};
s.draw = *reinterpret_cast<const RadMtpCoupleDraw*>(c.draw + row * c.ld_draw);
int32_t* idx = c.idx + row * c.ld_idx;
s.round = c.round;
s.x = idx[0];
for (int i = 0; i < 8; ++i) s.ids[i] = -1;
if (s.draw.mode == 1) {
s.status = -1;
if (s.draw.card == c.card[row] &&
rad_mtp_couple_build_q(idx, c.val + row * c.ld_val, c.vocab, &s)) {
const double u = rad_spechub_uniform(s.draw.seed, s.draw.base,
RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)c.round);
s.x = s.ids[rad_mtp_couple_pick(s, u)];
s.status = 1;
idx[0] = s.x;
} else {
s.count = 0;
for (int i = 0; i < 8; ++i) { s.ids[i] = -1; s.q[i] = 0; }
}
}
*reinterpret_cast<RadMtpCoupleState*>(c.state + (c.round - 1) * c.st_round + row * c.st_row) = s;
}
/* One verify row, after sample_pick. A row without a valid bound state keeps the ordinary token. */
static inline RAD_SPECHUB_HD void rad_mtp_couple_verify_row(const RadMtpCoupleVerifyCall& c,
int64_t row) {
const auto& s = *reinterpret_cast<const RadMtpCoupleState*>(c.state + row * c.ld[3]);
if (s.status != 1) return;
const auto& p = *reinterpret_cast<const RadSampleParams*>(c.params + row * c.ld[2]);
if ((p.flags & RAD_SP_GREEDY) || s.draw.seed != p.seed || s.pos != p.pos ||
!rad_mtp_couple_state_valid(s, c.vocab))
return;
int32_t out = -1;
if (rad_mtp_couple_decide(s, c.idx + row * c.ld[0], c.val + row * c.ld[1], c.n_cand, c.vocab,
rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_RESID), &out))
c.token[row * c.ld[4]] = out;
}
#undef RAD_SPECHUB_HD
#endif /* RAD_PLUGIN_SPECHUB_H */
+173
View File
@@ -0,0 +1,173 @@
/* plugin/spechub/spechub.hip -- the device launches for the two coupling ops.
*
* The propose kernel is one thread a row over abi/rad_spechub.h's helpers. The verify is one
* workgroup a row: the masses are computed in parallel, and the sums and walks run on one thread
* in ascending candidate order, the order rad_mtp_couple_decide uses, so the token matches the
* host reference bit for bit.
*
* Strict FP64: fast-math or FMA contraction would reorder those sums and change the answer, hence
* the #error below and -ffp-contract=off in CMakeLists.txt.
*/
#ifdef __FAST_MATH__
#error "the MTP coupling requires strict FP64 arithmetic: build without -ffast-math"
#endif
#include <hip/hip_runtime.h>
#include "spechub.h"
#include "../../libr4d/r4d_emit.h"
namespace {
/* One thread a row: both ops are row-local and the M is the number of sampled positions. */
__global__ void propose(RadMtpCoupleProposeCall c) {
const int64_t row = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (row < c.M) rad_mtp_couple_propose_row(c, row);
}
/* One workgroup a row, 128 threads. The weight and residual planes are in LDS: 16 KiB of FP64 at
* n_cand 1024. */
constexpr int kThreads = 128;
constexpr int64_t kMaxCand = 1024;
__global__ void couple_verify(const int32_t* idx, const float* values, const uint32_t* params,
const uint32_t* state, int32_t* token, int64_t M, int64_t n_cand,
int64_t vocab, int64_t ld0, int64_t ld1, int64_t ld2, int64_t ld3,
int64_t ld4) {
RadMtpCoupleVerifyCall c{ idx, values, params, state, token, M, n_cand, vocab,
{ ld0, ld1, ld2, ld3, ld4 } };
const int64_t row = blockIdx.x;
if (row >= M) return;
/* Above kMaxCand the LDS planes would overflow, so one thread runs the serial helper. */
if (n_cand > kMaxCand) {
if (threadIdx.x == 0) rad_mtp_couple_verify_row(c, row);
return;
}
/* `weight` is P's unnormalised FP64 mass per candidate and `mass` its residual (P-Q)+. The
* workgroup writes them; one thread reads them in ascending candidate order. */
__shared__ double weight[kMaxCand], mass[kMaxCand], pq[8], sum;
__shared__ float top;
__shared__ int eligible, first[8], ix, dominated;
const auto& s = *reinterpret_cast<const RadMtpCoupleState*>(c.state + row * c.ld[3]);
const auto& p = *reinterpret_cast<const RadSampleParams*>(c.params + row * c.ld[2]);
const int32_t* ids = c.idx + row * c.ld[0];
const float* val = c.val + row * c.ld[1];
/* The same eligibility gate as rad_mtp_couple_verify_row: an unbound row keeps the ordinary
* token. */
if (threadIdx.x == 0) {
eligible = 0;
if (s.status == 1 && !(p.flags & RAD_SP_GREEDY) && s.draw.seed == p.seed &&
s.pos == p.pos && rad_mtp_couple_state_valid(s, c.vocab)) {
float maximum = -INFINITY;
bool valid = true;
for (int64_t j = 0; j < c.n_cand; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= c.vocab || val[j] != val[j] || val[j] == INFINITY) {
valid = false;
break;
}
if (val[j] > maximum) maximum = val[j];
}
if (valid && maximum != -INFINITY) { top = maximum; eligible = 1; }
}
}
__syncthreads();
if (!eligible) return;
/* Each thread writes exp(v - max) for a strided slice; no cross-thread reduction, so the sum
* below matches the serial order bit for bit. */
for (int64_t j = threadIdx.x; j < c.n_cand; j += blockDim.x)
if (ids[j] >= 0 && val[j] != -INFINITY) weight[j] = ::exp((double)val[j] - top);
__syncthreads();
if (threadIdx.x == 0) {
sum = 0;
for (int k = 0; k < s.count; ++k) { pq[k] = 0; first[k] = -1; }
for (int64_t j = 0; j < c.n_cand; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
const double w = weight[j];
sum += w;
for (int k = 0; k < s.count; ++k)
if (ids[j] == s.ids[k]) {
if (first[k] < 0) first[k] = (int)j;
pq[k] += w;
break;
}
}
if (!(sum > 0) || !rad_spechub_finite(sum)) eligible = 0;
if (eligible) {
ix = -1;
dominated = true;
for (int k = 0; k < s.count; ++k) {
pq[k] /= sum;
dominated = dominated && pq[k] >= s.q[k];
if (s.ids[k] == s.x) ix = k;
}
if (ix < 0) eligible = 0;
}
}
__syncthreads();
if (!eligible) return;
/* Residual per slot: a Q token contributes max(0, P-Q) once, at its first occurrence
* (`first[k]`); every other candidate contributes its own P. */
for (int64_t j = threadIdx.x; j < c.n_cand; j += blockDim.x) {
double m = 0;
if (ids[j] >= 0 && val[j] != -INFINITY) {
bool in_q = false;
for (int k = 0; k < s.count; ++k)
if (s.ids[k] == ids[j]) {
in_q = true;
if (first[k] == (int)j) m = rad_spechub_positive(pq[k] - s.q[k]);
break;
}
if (!in_q) m = weight[j] / sum;
}
mass[j] = m;
}
__syncthreads();
if (threadIdx.x != 0) return;
/* One thread, ascending candidate index: parallelising these sums would reorder them and
* break bit-exactness with the host reference. */
double resid = 0;
for (int64_t j = 0; j < c.n_cand; ++j) resid += mass[j];
int32_t out = -1;
const double u_resid = rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_RESID);
if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) {
double cdf = u_resid * sum;
for (int64_t j = 0; j < c.n_cand; ++j)
if (ids[j] >= 0 && val[j] != -INFINITY) {
const double w = weight[j];
if (w > 0) { out = ids[j]; cdf -= w; if (cdf < 0) break; }
}
} else if (pq[ix] >= s.q[ix] ||
rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_ACCEPT) * s.q[ix] < pq[ix]) {
out = s.x;
} else {
double cdf = u_resid * resid;
for (int64_t j = 0; j < c.n_cand; ++j) {
if (ids[j] == s.x) continue;
const double m = mass[j];
if (m > 0) { out = ids[j]; cdf -= m; if (cdf < 0) break; }
}
}
c.token[row * c.ld[4]] = out;
}
} /* namespace */
int rad_mine_mtp_couple_propose_launch(const RadArgs* a, RadStream stream) {
RadMtpCoupleProposeCall c{};
const int rc = rad_mtp_couple_propose_args(a, &c);
if (rc != RAD_OK) return rc;
return R4D_EMIT(stream, propose, dim3((unsigned)((c.M + 63) / 64)), dim3(64), 0, c);
}
int rad_mine_mtp_couple_verify_launch(const RadArgs* a, RadStream stream) {
RadMtpCoupleVerifyCall c{};
const int rc = rad_mtp_couple_verify_args(a, &c);
if (rc != RAD_OK) return rc;
/* Separate pointer arguments let graph replay rebind each operand address independently: a
* struct on the host would freeze the addresses it was built with. */
return R4D_EMIT(stream, couple_verify, dim3((unsigned)c.M), dim3(kThreads), 0,
c.idx, c.val, c.params, c.state, c.token, c.M, c.n_cand, c.vocab,
c.ld[0], c.ld[1], c.ld[2], c.ld[3], c.ld[4]);
}