feat(sampler): port linear MTP coupling and cooperative verify upstream

Port GitHub PRs #12 and #13 onto Codeberg upstream main, retaining upstream kernel-chain handling. Include the source Clang target-attribute fixes required by the host build; omit the KFD header workaround and unrelated fork work.

Co-Authored-By: Claude Code <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
committed 2026-10-22 22:58:08 +02:00
1 parent 123c439684
commit d912c694f3
37 files changed
+3730 -23

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
# spechub -- the linear-MTP coupling kernels.
#
# A kernel plugin and nothing else: abi/ is the whole contract, so this builds in radiance's tree or
# standalone against an installed prefix
# (`cmake -S spechub -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`; see cmake/RadAddPlugin.cmake).
#
# It declares TWO ops, `mtp_couple_propose` and `mtp_couple_verify`, with one device row and one host
# reference row each. The coupling's arithmetic is NOT here: abi/rad_spechub.h defines it inline, host
# and device, so the reference, the kernel above it and the engine's own checks are one definition.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(spechub LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
set(SPECHUB_COMMON
${CMAKE_CURRENT_SOURCE_DIR}/spechub.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ref_spechub.cpp
${CMAKE_CURRENT_SOURCE_DIR}/exports.cpp)
if(NOT RAD_HIP_FOUND)
message(STATUS "spechub: this radiance has no device build -- only the host reference is built")
rad_add_plugin(spechub kernels SOURCES ${SPECHUB_COMMON})
else()
# The owning project must enable HIP itself; enable_language() is project scope. The top-level tree
# does it with -DRAD_WITH_HIP=ON, and a standalone build must do the same after project().
get_property(spechub_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
if(NOT "HIP" IN_LIST spechub_langs)
message(FATAL_ERROR "spechub: HIP_SOURCES need `enable_language(HIP)` in this project (set "
"-DRAD_WITH_HIP=ON, or enable it after project()).")
endif()
rad_add_plugin(spechub kernels SOURCES ${SPECHUB_COMMON}
HIP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/spechub.hip)
target_compile_definitions(spechub PRIVATE RAD_SPECHUB_WITH_DEVICE=1)
endif()
# -ffp-contract=off is a correctness flag here, not a tuning choice: the coupling sums FP64 masses in
# ascending candidate order and compares them against a 53-bit uniform, so an FMA that fused a
# multiply into one of those sums would move the answer off the reference the tests check.
target_compile_options(spechub PRIVATE -ffp-contract=off)
+103
View File
@@ -0,0 +1,103 @@
/* plugin/spechub/exports.cpp -- the plugin's export block.
*
* The whole kernel-plugin set (schema count/at, kernel count/at, ABI version, info) and nothing else.
* The rows themselves, their schemas and their argument readers are in spechub.cpp; the launches are
* spechub.hip (device) and ref_spechub.cpp (host).
*
* REFERENCE IS PER ROW HERE, not per library. This library carries a real device kernel AND the
* host oracle beside it; `rad_plugin_reference` is a whole-library answer, so returning 1 would
* mark the device rows as reference too and the engine's reference gate would refuse to serve the
* coupled path at all (RAD_E_NOKERNEL before the first request). The device rows therefore report
* 0 and the host rows 1 through `rad_kernel_reference`, and `rad_plugin_reference` stays 0 so the
* library is not ranked below the kernel libraries it belongs with. On a machine with no card only
* the two reference rows exist, and the gate then correctly refuses the coupling: there is no
* device kernel to serve it.
*
* What puts a coupled row into serving is the architecture declaring the op, which it only does
* with RADIANCE_MTP_COUPLED=1; the plugin and the loader never read that switch.
*/
#include "spechub.h"
#include "../../libr4d/r4d_emit.h" /* only for the three globals it declares */
/* THE DISPATCH LOG IS THIS DSO'S OWN. r4d_emit.h routes every launch through this recorder so a test
* can name the functions it dispatched, but the loader maps plugins RTLD_LOCAL: a plugin cannot
* import libr4d's copy, and an unresolved symbol refuses the whole library at load. Defining them
* here gives r4d_emit.h exactly what it declares and leaves the recorder inert -- nothing in this
* plugin sets the log. It is a tool's, never consulted on a serving path. */
const void** r4d_dispatch_log = nullptr;
int r4d_dispatch_cap = 0;
int r4d_dispatch_n = 0;
namespace {
const RadPluginInfo kInfo = {
RAD_PLUGIN_KERNEL, "spechub", "0.1.0",
"Linear-MTP maximal coupling: a Q draw per round and the coupled target verify", "gfx1201",
};
} /* namespace */
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
/* Mixed library: 0, and the per-row answer below does the classifying. */
extern "C" int rad_plugin_reference(void) { return 0; }
/* Row layout is [device 0, device 1, ref 0, ref 1] with a card, [ref 0, ref 1] without. The
* device rows are the production kernels; the host rows are the oracle rad-kbench checks them
* against and the only thing a card-less machine can run. */
extern "C" int rad_kernel_reference(int i) {
#ifdef RAD_SPECHUB_WITH_DEVICE
return (i == 0 || i == 1) ? 0 : 1;
#else
(void)i;
return 1;
#endif
}
extern "C" int rad_kernel_schema_count(void) { return rad_spechub_schema_count(); }
extern "C" const RadOpSchema* rad_kernel_schema_at(int i) { return rad_spechub_schema_at(i); }
/* Two device rows and the two host references beside them, in that order. A card-less machine loads
* the same library and resolves only the reference rows. */
extern "C" int rad_kernel_count(void) {
#ifdef RAD_SPECHUB_WITH_DEVICE
return 4;
#else
return 2;
#endif
}
extern "C" const RadKernelInfo* rad_kernel_at(int i) {
const int op = i & 1;
#ifdef RAD_SPECHUB_WITH_DEVICE
if (i == 0 || i == 1) {
static const RadKernelInfo r[2] = {
rad_spechub_row(0, rad_mine_mtp_couple_propose_launch),
rad_spechub_row(1, rad_mine_mtp_couple_verify_launch),
};
return &r[i];
}
#endif
static const RadKernelInfo ref[2] = {
[] {
RadKernelInfo x = rad_spechub_row(0, rad_ref_mtp_couple_propose);
x.name = "ref_mtp_couple_propose";
x.domain = RAD_DOMAIN_HOST;
x.priority = 0;
return x;
}(),
[] {
RadKernelInfo x = rad_spechub_row(1, rad_ref_mtp_couple_verify);
x.name = "ref_mtp_couple_verify";
x.domain = RAD_DOMAIN_HOST;
x.priority = 0;
return x;
}(),
};
#ifdef RAD_SPECHUB_WITH_DEVICE
if (i < 2 || i > 3) return nullptr;
return &ref[op];
#else
if (i < 0 || i > 1) return nullptr;
return &ref[i];
#endif
}
+26
View File
@@ -0,0 +1,26 @@
/* plugin/spechub/ref_spechub.cpp -- the two coupling ops on the host.
*
* ONE ROW AT A TIME, in the same order and with the same arithmetic as the kernel: these functions
* call the very same abi/rad_spechub.h helpers the device launch is built from, so an op and its
* reference cannot drift. What they add is the row loop and the same eligibility gate.
*
* This is the oracle rad-kbench checks the device rows against, and the only implementation a
* machine with no card can run.
*/
#include "spechub.h"
int rad_ref_mtp_couple_propose(const RadArgs* a, RadStream) {
RadMtpCoupleProposeCall c{};
const int rc = rad_mtp_couple_propose_args(a, &c);
if (rc != RAD_OK) return rc;
for (int64_t row = 0; row < c.M; ++row) rad_mtp_couple_propose_row(c, row);
return RAD_OK;
}
int rad_ref_mtp_couple_verify(const RadArgs* a, RadStream) {
RadMtpCoupleVerifyCall c{};
const int rc = rad_mtp_couple_verify_args(a, &c);
if (rc != RAD_OK) return rc;
for (int64_t row = 0; row < c.M; ++row) rad_mtp_couple_verify_row(c, row);
return RAD_OK;
}
+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);
/* THE PROPOSE'S HOST ARITHMETIC, host and device. One definition of "x ~ Q over the final eight":
* column 0 is what ADV_ROUND/ADV_TAKE take, and it becomes x only for a valid sampled row. */
static inline RAD_SPECHUB_HD void rad_mtp_couple_propose_row(const RadMtpCoupleProposeCall& c,
int64_t row) {
RadMtpCoupleState s{};
s.draw = *reinterpret_cast<const RadMtpCoupleDraw*>(c.draw + row * c.ld_draw);
int32_t* idx = c.idx + row * c.ld_idx;
s.round = c.round;
s.x = idx[0];
for (int i = 0; i < 8; ++i) s.ids[i] = -1;
if (s.draw.mode == 1) {
s.status = -1;
if (s.draw.card == c.card[row] &&
rad_mtp_couple_build_q(idx, c.val + row * c.ld_val, c.vocab, &s)) {
const double u = rad_spechub_uniform(s.draw.seed, s.draw.base,
RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)c.round);
s.x = s.ids[rad_mtp_couple_pick(s, u)];
s.status = 1;
idx[0] = s.x;
} else {
s.count = 0;
for (int i = 0; i < 8; ++i) { s.ids[i] = -1; s.q[i] = 0; }
}
}
*reinterpret_cast<RadMtpCoupleState*>(c.state + (c.round - 1) * c.st_round + row * c.st_row) = s;
}
/* THE VERIFY'S, after sample_pick. Rows without a valid bound state keep the ordinary token. */
static inline RAD_SPECHUB_HD void rad_mtp_couple_verify_row(const RadMtpCoupleVerifyCall& c,
int64_t row) {
const auto& s = *reinterpret_cast<const RadMtpCoupleState*>(c.state + row * c.ld[3]);
if (s.status != 1) return;
const auto& p = *reinterpret_cast<const RadSampleParams*>(c.params + row * c.ld[2]);
if ((p.flags & RAD_SP_GREEDY) || s.draw.seed != p.seed || s.pos != p.pos ||
!rad_mtp_couple_state_valid(s, c.vocab))
return;
int32_t out = -1;
if (rad_mtp_couple_decide(s, c.idx + row * c.ld[0], c.val + row * c.ld[1], c.n_cand, c.vocab,
rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_RESID), &out))
c.token[row * c.ld[4]] = out;
}
#undef RAD_SPECHUB_HD
#endif /* RAD_PLUGIN_SPECHUB_H */
+182
View File
@@ -0,0 +1,182 @@
/* plugin/spechub/spechub.hip -- the device launches for the two coupling ops.
*
* The kernels are one workgroup per sampled row, and the workgroup is the whole parallel machine
* the verify needs: the cuts, the residual mass and the walk are all row-local. The arithmetic
* itself is abi/rad_spechub.h (inline, host and device), so this file is a launch and nothing more
* -- which is why the host reference and the kernel can be compared on the same bytes.
*
* STRICT FP64. The coupling sums FP64 masses in ascending candidate order and compares them against
* a 53-bit uniform; --fast-math would let the compiler contract those sums and change the answer.
* The #error below is the compile-time half of that, and CMakeLists sets -ffp-contract=off.
*/
#ifdef __FAST_MATH__
#error "the MTP coupling requires strict FP64 arithmetic: build without -ffast-math"
#endif
#include <hip/hip_runtime.h>
#include "spechub.h"
#include "../../libr4d/r4d_emit.h"
namespace {
/* One thread a row: both ops are row-local and the M is the number of sampled positions. */
__global__ void propose(RadMtpCoupleProposeCall c) {
const int64_t row = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (row < c.M) rad_mtp_couple_propose_row(c, row);
}
/* ONE WORKGROUP A ROW, 128 threads. The verify's planes are shared: at n_cand 1024 the weights and
* the residual masses are 16 KiB of FP64, and the mass walk reads them once per candidate rather
* than once per thread. */
constexpr int kThreads = 128;
constexpr int64_t kMaxCand = 1024;
__global__ void couple_verify(const int32_t* idx, const float* values, const uint32_t* params,
const uint32_t* state, int32_t* token, int64_t M, int64_t n_cand,
int64_t vocab, int64_t ld0, int64_t ld1, int64_t ld2, int64_t ld3,
int64_t ld4) {
RadMtpCoupleVerifyCall c{ idx, values, params, state, token, M, n_cand, vocab,
{ ld0, ld1, ld2, ld3, ld4 } };
const int64_t row = blockIdx.x;
if (row >= M) return;
/* ABOVE THE NARROW BAND the general algorithm runs single-threaded: the shared planes are sized
* for kMaxCand and a wider row would overrun them. That is the 1025-and-above fallback, and it is
* the same FP64 order the cooperative path below keeps. */
if (n_cand > kMaxCand) {
if (threadIdx.x == 0) rad_mtp_couple_verify_row(c, row);
return;
}
/* THE TWO COOPERATIVE PLANES. `weight` is P's unnormalised FP64 mass per candidate and `mass` is
* the residual (P-Q)+ per candidate; both are written by the whole workgroup and read in
* ASCENDING candidate order afterwards, which is the order the serial algorithm sums in. */
__shared__ double weight[kMaxCand], mass[kMaxCand], pq[8], sum;
__shared__ float top;
__shared__ int eligible, first[8], ix, dominated;
const auto& s = *reinterpret_cast<const RadMtpCoupleState*>(c.state + row * c.ld[3]);
const auto& p = *reinterpret_cast<const RadSampleParams*>(c.params + row * c.ld[2]);
const int32_t* ids = c.idx + row * c.ld[0];
const float* val = c.val + row * c.ld[1];
/* The eligibility gate is the DECIDE's own: the same state, seed, position and target check, so
* an unbound row writes nothing and keeps the ordinary token. */
if (threadIdx.x == 0) {
eligible = 0;
if (s.status == 1 && !(p.flags & RAD_SP_GREEDY) && s.draw.seed == p.seed &&
s.pos == p.pos && rad_mtp_couple_state_valid(s, c.vocab)) {
float maximum = -INFINITY;
bool valid = true;
for (int64_t j = 0; j < c.n_cand; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= c.vocab || val[j] != val[j] || val[j] == INFINITY) {
valid = false;
break;
}
if (val[j] > maximum) maximum = val[j];
}
if (valid && maximum != -INFINITY) { top = maximum; eligible = 1; }
}
}
__syncthreads();
if (!eligible) return;
/* THE FP64 MASS, done COOPERATIVELY: each thread takes a strided slice of the candidates and
* writes exp(v - max) into its own slot. No cross-thread reduction happens here -- the sum below
* is still walked in ascending order by one thread, which is what keeps the sum bit-identical to
* the serial algorithm. */
for (int64_t j = threadIdx.x; j < c.n_cand; j += blockDim.x)
if (ids[j] >= 0 && val[j] != -INFINITY) weight[j] = ::exp((double)val[j] - top);
__syncthreads();
if (threadIdx.x == 0) {
sum = 0;
for (int k = 0; k < s.count; ++k) { pq[k] = 0; first[k] = -1; }
for (int64_t j = 0; j < c.n_cand; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
const double w = weight[j];
sum += w;
for (int k = 0; k < s.count; ++k)
if (ids[j] == s.ids[k]) {
if (first[k] < 0) first[k] = (int)j;
pq[k] += w;
break;
}
}
if (!(sum > 0) || !rad_spechub_finite(sum)) eligible = 0;
if (eligible) {
ix = -1;
dominated = true;
for (int k = 0; k < s.count; ++k) {
pq[k] /= sum;
dominated = dominated && pq[k] >= s.q[k];
if (s.ids[k] == s.x) ix = k;
}
if (ix < 0) eligible = 0;
}
}
__syncthreads();
if (!eligible) return;
/* THE RESIDUAL MASS, COOPERATIVELY. A Q token contributes max(0, P-Q) ONCE, at its first
* occurrence (`first[k]`), which is the duplicate-first rule; every other candidate contributes
* its own P. The plane is written per slot, so the walk below reads it in candidate order. */
for (int64_t j = threadIdx.x; j < c.n_cand; j += blockDim.x) {
double m = 0;
if (ids[j] >= 0 && val[j] != -INFINITY) {
bool in_q = false;
for (int k = 0; k < s.count; ++k)
if (s.ids[k] == ids[j]) {
in_q = true;
if (first[k] == (int)j) m = rad_spechub_positive(pq[k] - s.q[k]);
break;
}
if (!in_q) m = weight[j] / sum;
}
mass[j] = m;
}
__syncthreads();
if (threadIdx.x != 0) return;
/* THE ORDERED WALK. One thread, ascending candidate index, exactly the serial algorithm's
* arithmetic: the sums above and this walk are what the coupling's bit-exactness rests on, and
* parallelising either would reorder them. */
double resid = 0;
for (int64_t j = 0; j < c.n_cand; ++j) resid += mass[j];
int32_t out = -1;
const double u_resid = rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_RESID);
if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) {
double cdf = u_resid * sum;
for (int64_t j = 0; j < c.n_cand; ++j)
if (ids[j] >= 0 && val[j] != -INFINITY) {
const double w = weight[j];
if (w > 0) { out = ids[j]; cdf -= w; if (cdf < 0) break; }
}
} else if (pq[ix] >= s.q[ix] ||
rad_spechub_uniform(p.seed, p.pos, RAD_SAMPLE_KEY_ACCEPT) * s.q[ix] < pq[ix]) {
out = s.x;
} else {
double cdf = u_resid * resid;
for (int64_t j = 0; j < c.n_cand; ++j) {
if (ids[j] == s.x) continue;
const double m = mass[j];
if (m > 0) { out = ids[j]; cdf -= m; if (cdf < 0) break; }
}
}
c.token[row * c.ld[4]] = out;
}
} /* namespace */
int rad_mine_mtp_couple_propose_launch(const RadArgs* a, RadStream stream) {
RadMtpCoupleProposeCall c{};
const int rc = rad_mtp_couple_propose_args(a, &c);
if (rc != RAD_OK) return rc;
return R4D_EMIT(stream, propose, dim3((unsigned)((c.M + 63) / 64)), dim3(64), 0, c);
}
int rad_mine_mtp_couple_verify_launch(const RadArgs* a, RadStream stream) {
RadMtpCoupleVerifyCall c{};
const int rc = rad_mtp_couple_verify_args(a, &c);
if (rc != RAD_OK) return rc;
/* Separate pointer arguments let graph replay rebind each operand address independently: a
* struct on the host would freeze the addresses it was built with. */
return R4D_EMIT(stream, couple_verify, dim3((unsigned)c.M), dim3(kThreads), 0,
c.idx, c.val, c.params, c.state, c.token, c.M, c.n_cand, c.vocab,
c.ld[0], c.ld[1], c.ld[2], c.ld[3], c.ld[4]);
}