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

+22 -3
View File
@@ -244,6 +244,22 @@ if(RAD_HIP_FOUND)
endforeach()
endif()
# spechub_wiring_test dlopens the built spechub plugin and checks how its rows are classified: the
# device rows must be production kernels and the host oracle rows must stay reference. It needs the
# library path and the same RAD_SPECHUB_WITH_DEVICE answer the plugin was built with.
if(TARGET spechub)
target_link_libraries(spechub_wiring_test PRIVATE ${CMAKE_DL_LIBS})
target_compile_definitions(spechub_wiring_test PRIVATE
RAD_SPECHUB_LIB="${RAD_PLUGIN_OUT}/kernels/spechub.so")
if(RAD_HIP_FOUND)
target_compile_definitions(spechub_wiring_test PRIVATE RAD_SPECHUB_WITH_DEVICE=1)
endif()
add_dependencies(spechub_wiring_test spechub)
# sample_test's coupling case declares a Sampler with draft_coupling set and needs the verify
# op the spechub plugin carries (its host row); it skips when the library is absent.
add_dependencies(sample_test spechub)
endif()
# ================================================================== whole models on the CPU
#
# engine_e2e_test runs the radiance binary on tiny synthetic checkpoints (tests/tiny_model.h) on
@@ -308,14 +324,14 @@ endif()
#
# r4d_selftest is the only check of libr4d's fusion claims: rows declaring a fused kernel
# byte-identical to the ops it replaces, verified by memcmp against the unfused kernels on the same
# inputs. It needs a card and forks a child per row (about six minutes), so it is labelled `slow`;
# the default `ctest` still runs it.
# inputs. It needs a card and forks a child per row (about fifteen minutes on an R9700), so it is
# labelled `slow`; the default `ctest` still runs it.
if(RAD_HIP_FOUND AND TARGET r4d_selftest)
add_test(NAME r4d_selftest
COMMAND r4d_selftest ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
set_tests_properties(r4d_selftest PROPERTIES
LABELS "slow;gpu"
TIMEOUT 900
TIMEOUT 2400
ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home")
endif()
@@ -520,6 +536,9 @@ endif()
# parameters). Cheap, so in the fast tier. libr4d.so is added when built; the script reports
# " SKIP " rather than passing when a plugin will not dump.
set(RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libref.so)
if(TARGET spechub)
list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/spechub.so)
endif()
if(RAD_HIP_FOUND AND TARGET libr4d)
list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
endif()
+1
View File
@@ -15,6 +15,7 @@
#include "rad_quant.h"
#include "rad_runtime.h"
#include "rad_sample.h"
#include "rad_spechub.h"
#include "rad_types.h"
#include "rad_yarn.h"
+38
View File
@@ -19,6 +19,8 @@ ABI_FIELD(RadArchProbe, gen_video)
ABI_FIELD(RadArchProbe, kv_quant_ok)
ABI_FIELD(RadArchProbe, chain_pays)
ABI_FIELD(RadArchProbe, control_vector_ok)
ABI_FIELD(RadArchProbe, tp_attn_rows_ok)
ABI_FIELD(RadArchProbe, state_f16_ok)
ABI_STRUCT(RadArgs)
ABI_FIELD(RadArgs, t)
ABI_FIELD(RadArgs, n_t)
@@ -108,6 +110,9 @@ ABI_FIELD(RadBuildCtx, max_mixed_tok)
ABI_FIELD(RadBuildCtx, kv_quant)
ABI_FIELD(RadBuildCtx, attn_prefill_fp8)
ABI_FIELD(RadBuildCtx, cvec)
ABI_FIELD(RadBuildCtx, tp_attn_rows)
ABI_FIELD(RadBuildCtx, state_dtype)
ABI_FIELD(RadBuildCtx, draft_coupling)
ABI_STRUCT(RadAudioGenBatch)
ABI_FIELD(RadAudioGenBatch, n_lane)
ABI_FIELD(RadAudioGenBatch, lane)
@@ -144,6 +149,16 @@ ABI_FIELD(RadAudioGenBatch, voc_latents)
ABI_FIELD(RadAudioGenBatch, voc_left)
ABI_FIELD(RadAudioGenBatch, voc_right)
ABI_FIELD(RadAudioGenBatch, voc_frame0)
ABI_FIELD(RadAudioGenBatch, prev_slot)
ABI_FIELD(RadAudioGenBatch, prev_pos)
ABI_FIELD(RadAudioGenBatch, prev_used)
ABI_FIELD(RadAudioGenBatch, n_ref)
ABI_FIELD(RadAudioGenBatch, ref_samples)
ABI_FIELD(RadAudioGenBatch, ref_audio)
ABI_FIELD(RadAudioGenBatch, ref_cu)
ABI_FIELD(RadAudioGenBatch, ref_cu_h)
ABI_FIELD(RadAudioGenBatch, ref_frame)
ABI_FIELD(RadAudioGenBatch, ref_frame_h)
ABI_STRUCT(RadAudioGenDecl)
ABI_FIELD(RadAudioGenDecl, name)
ABI_FIELD(RadAudioGenDecl, tmpl)
@@ -176,6 +191,14 @@ ABI_FIELD(RadAudioGenDecl, prompt_whole)
ABI_FIELD(RadAudioGenDecl, first_frame)
ABI_FIELD(RadAudioGenDecl, voc_chunk)
ABI_FIELD(RadAudioGenDecl, voc_context)
ABI_FIELD(RadAudioGenDecl, branches)
ABI_FIELD(RadAudioGenDecl, input_special)
ABI_FIELD(RadAudioGenDecl, tmpl_ref)
ABI_FIELD(RadAudioGenDecl, ref_item)
ABI_FIELD(RadAudioGenDecl, ref_rate)
ABI_FIELD(RadAudioGenDecl, ref_hop)
ABI_FIELD(RadAudioGenDecl, ref_max_samples)
ABI_FIELD(RadAudioGenDecl, ref_max)
ABI_STRUCT(RadControlVector)
ABI_FIELD(RadControlVector, dir)
ABI_FIELD(RadControlVector, scales)
@@ -799,3 +822,18 @@ ABI_FIELD(RadYarn, factor)
ABI_FIELD(RadYarn, low)
ABI_FIELD(RadYarn, high)
ABI_FIELD(RadYarn, magnitude)
ABI_STRUCT(RadMtpCoupleDraw)
ABI_FIELD(RadMtpCoupleDraw, seed)
ABI_FIELD(RadMtpCoupleDraw, base)
ABI_FIELD(RadMtpCoupleDraw, seq)
ABI_FIELD(RadMtpCoupleDraw, card)
ABI_FIELD(RadMtpCoupleDraw, mode)
ABI_STRUCT(RadMtpCoupleState)
ABI_FIELD(RadMtpCoupleState, draw)
ABI_FIELD(RadMtpCoupleState, pos)
ABI_FIELD(RadMtpCoupleState, status)
ABI_FIELD(RadMtpCoupleState, round)
ABI_FIELD(RadMtpCoupleState, x)
ABI_FIELD(RadMtpCoupleState, count)
ABI_FIELD(RadMtpCoupleState, ids)
ABI_FIELD(RadMtpCoupleState, q)
+43 -5
View File
@@ -1,8 +1,8 @@
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 26 and
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 27 and
* RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot
* of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it
* from the test's printout only together with a version bump. */
{ "RadArchProbe", "", 0, 80 },
{ "RadArchProbe", "", 0, 88 },
{ "RadArchProbe", "draft_depth", 0, 4 },
{ "RadArchProbe", "draft_depth_fixed", 4, 4 },
{ "RadArchProbe", "shape_probe_ok", 8, 4 },
@@ -16,6 +16,8 @@
{ "RadArchProbe", "kv_quant_ok", 68, 4 },
{ "RadArchProbe", "chain_pays", 72, 4 },
{ "RadArchProbe", "control_vector_ok", 76, 4 },
{ "RadArchProbe", "tp_attn_rows_ok", 80, 4 },
{ "RadArchProbe", "state_f16_ok", 84, 4 },
{ "RadArgs", "", 0, 64 },
{ "RadArgs", "t", 0, 8 },
{ "RadArgs", "n_t", 8, 4 },
@@ -85,7 +87,7 @@
{ "RadBufDecl", "domain", 60, 4 },
{ "RadBufDecl", "derive", 64, 8 },
{ "RadBufDecl", "kv", 72, 4 },
{ "RadBuildCtx", "", 0, 120 },
{ "RadBuildCtx", "", 0, 136 },
{ "RadBuildCtx", "rank", 0, 4 },
{ "RadBuildCtx", "world_size", 4, 4 },
{ "RadBuildCtx", "max_tok", 8, 8 },
@@ -105,7 +107,10 @@
{ "RadBuildCtx", "kv_quant", 104, 4 },
{ "RadBuildCtx", "attn_prefill_fp8", 108, 4 },
{ "RadBuildCtx", "cvec", 112, 8 },
{ "RadAudioGenBatch", "", 0, 264 },
{ "RadBuildCtx", "tp_attn_rows", 120, 4 },
{ "RadBuildCtx", "state_dtype", 124, 4 },
{ "RadBuildCtx", "draft_coupling", 128, 4 },
{ "RadAudioGenBatch", "", 0, 344 },
{ "RadAudioGenBatch", "n_lane", 0, 8 },
{ "RadAudioGenBatch", "lane", 8, 8 },
{ "RadAudioGenBatch", "lane_h", 16, 8 },
@@ -141,7 +146,17 @@
{ "RadAudioGenBatch", "voc_left", 244, 4 },
{ "RadAudioGenBatch", "voc_right", 248, 4 },
{ "RadAudioGenBatch", "voc_frame0", 256, 8 },
{ "RadAudioGenDecl", "", 0, 224 },
{ "RadAudioGenBatch", "prev_slot", 264, 8 },
{ "RadAudioGenBatch", "prev_pos", 272, 8 },
{ "RadAudioGenBatch", "prev_used", 280, 8 },
{ "RadAudioGenBatch", "n_ref", 288, 8 },
{ "RadAudioGenBatch", "ref_samples", 296, 8 },
{ "RadAudioGenBatch", "ref_audio", 304, 8 },
{ "RadAudioGenBatch", "ref_cu", 312, 8 },
{ "RadAudioGenBatch", "ref_cu_h", 320, 8 },
{ "RadAudioGenBatch", "ref_frame", 328, 8 },
{ "RadAudioGenBatch", "ref_frame_h", 336, 8 },
{ "RadAudioGenDecl", "", 0, 280 },
{ "RadAudioGenDecl", "name", 0, 8 },
{ "RadAudioGenDecl", "tmpl", 8, 8 },
{ "RadAudioGenDecl", "neg_token", 16, 4 },
@@ -173,6 +188,14 @@
{ "RadAudioGenDecl", "first_frame", 204, 4 },
{ "RadAudioGenDecl", "voc_chunk", 208, 8 },
{ "RadAudioGenDecl", "voc_context", 216, 8 },
{ "RadAudioGenDecl", "branches", 224, 4 },
{ "RadAudioGenDecl", "input_special", 228, 4 },
{ "RadAudioGenDecl", "tmpl_ref", 232, 8 },
{ "RadAudioGenDecl", "ref_item", 240, 8 },
{ "RadAudioGenDecl", "ref_rate", 248, 8 },
{ "RadAudioGenDecl", "ref_hop", 256, 8 },
{ "RadAudioGenDecl", "ref_max_samples", 264, 8 },
{ "RadAudioGenDecl", "ref_max", 272, 4 },
{ "RadControlVector", "", 0, 32 },
{ "RadControlVector", "dir", 0, 8 },
{ "RadControlVector", "scales", 8, 8 },
@@ -796,3 +819,18 @@
{ "RadYarn", "low", 4, 4 },
{ "RadYarn", "high", 8, 4 },
{ "RadYarn", "magnitude", 12, 4 },
{ "RadMtpCoupleDraw", "", 0, 32 },
{ "RadMtpCoupleDraw", "seed", 0, 8 },
{ "RadMtpCoupleDraw", "base", 8, 8 },
{ "RadMtpCoupleDraw", "seq", 16, 8 },
{ "RadMtpCoupleDraw", "card", 24, 4 },
{ "RadMtpCoupleDraw", "mode", 28, 4 },
{ "RadMtpCoupleState", "", 0, 152 },
{ "RadMtpCoupleState", "draw", 0, 32 },
{ "RadMtpCoupleState", "pos", 32, 8 },
{ "RadMtpCoupleState", "status", 40, 4 },
{ "RadMtpCoupleState", "round", 44, 4 },
{ "RadMtpCoupleState", "x", 48, 4 },
{ "RadMtpCoupleState", "count", 52, 4 },
{ "RadMtpCoupleState", "ids", 56, 32 },
{ "RadMtpCoupleState", "q", 88, 64 },
+4 -3
View File
@@ -8,7 +8,7 @@
*
* Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every
* struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and
* the layout agrees with the table below, taken at RAD_ABI_VERSION 26 and RAD_FORMAT_VER 2. Under
* the layout agrees with the table below, taken at RAD_ABI_VERSION 27 and RAD_FORMAT_VER 2. Under
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
* headers: nothing else states the layout. When it disagrees the test prints the live table.
@@ -26,6 +26,7 @@
#include "rad_quant.h"
#include "rad_runtime.h"
#include "rad_sample.h"
#include "rad_spechub.h"
#include "rad_types.h"
#include "rad_yarn.h"
@@ -57,8 +58,8 @@ std::vector<Row> cpp_rows() {
};
}
/* The layout at RAD_ABI_VERSION 26 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 26, kTableFormat = 2;
/* The layout at RAD_ABI_VERSION 27 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 27, kTableFormat = 2;
const AbiRow kTable[] = {
#include "abi_layout_table.h"
};
+9
View File
@@ -117,6 +117,7 @@ struct RadBuilder {
std::string drafter_name;
bool drafter_shared = false;
int drafter_pos = -1;
int64_t drafter_short = 0; /* rad_drafter_short_block */
/* The buffers named to rad_buf_concurrent: the ones a second lane touches. */
std::vector<rad_buf> concurrent;
@@ -376,6 +377,14 @@ struct ChainOn {
explicit ChainOn(int on) { g_chain_on = on; }
~ChainOn() { g_chain_on = 0; }
};
extern "C" int rad_drafter_short_block(RadBuilder* b, int64_t block) {
const int64_t full = b ? (b->drafter.block > 0 ? b->drafter.block : b->drafter.depth + 1) : 0;
if (!b || b->drafter.kind != RAD_DRAFT_BLOCK) return RAD_E_STATE;
if (block >= full || block - (full - b->drafter.depth) < 1) return RAD_E_INVAL;
b->drafter_short = block;
return RAD_OK;
}
extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
if (!b || !d || !d->name || !d->modalities) return RAD_E_INVAL;
if (d->modalities == RAD_MM_AUDIO) {
+240 -141
View File
@@ -3308,6 +3308,88 @@ TEST(gemma4_declares_two_kv_groups_and_binds_the_schedule) {
}
}
/* The E2B/E4B form on the same twelve layers: the last four share KV (no cache of their own),
* per-layer embeddings 64 wide, a global class with its own v (attention_k_eq_v 0) and no
* num_global_key_value_heads, so the global layers take num_key_value_heads. */
const char* k_gem4e_keys[] = {
"sliding_window", "global_head_dim", "num_key_value_heads",
"rope_parameters.sliding_attention.rope_theta", "rope_parameters.full_attention.rope_theta",
"rope_parameters.full_attention.partial_rotary_factor", "num_kv_shared_layers",
"final_logit_softcapping", "full_attention_interval", "attention_k_eq_v",
"hidden_size_per_layer_input",
};
const char* k_gem4e_vals[] = { "1024", "512", "16", "10000", "1000000", "0.25", "4", "30", "6", "0",
"64" };
RadModelMeta gemma4_e4b_meta() {
RadModelMeta m = gemma4_meta();
m.name = "test-gemma4-e4b-form";
m.n_kv = (int)(sizeof(k_gem4e_keys) / sizeof(k_gem4e_keys[0]));
m.kv_key = k_gem4e_keys;
m.kv_val = k_gem4e_vals;
return m;
}
/* Layers 8..11 keep no cache: only 0..7 are bound, and each shared layer's attention reads the last
* earlier layer of its class that keeps one (sliding 8..10 -> 7, global 11 -> 5). Every layer runs
* the per-layer branch (gate, gelu times its slice, projection, norm, add), and the step lints
* clean in bf16 and in w4a8, where the junction closes the branch instead of the feed-forward. */
TEST(a_gemma4_e4b_form_shares_kv_and_runs_the_per_layer_branch) {
for (bool w4 : { false, true }) {
RadBuilder b;
if (w4) {
const RadEncoding e = rad_enc_affine(RAD_I4, RAD_F16, 1, 128);
b.encs = { { "attn_q.", e }, { "attn_k.", e }, { "attn_v.", e }, { "attn_o.", e },
{ "ffn_gate_up.", e }, { "ffn_down.", e } };
}
RadModelMeta meta = gemma4_e4b_meta();
RadBuildCtx ctx = build_ctx();
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
CHECK_EQ((int)b.binds.size(), 8);
for (const auto& bd : b.binds) CHECK((int)bd.first < 8);
CHECK_EQ(b.kv_groups[1].d.n_head_kv, 16); /* num_key_value_heads, the global key absent */
CHECK_EQ(count_op(b, "attn_paged"), 12);
CHECK_EQ(count_op(b, "act_mul"), 12);
CHECK_EQ(count_op(b, "embed_lookup"), 2); /* the token table and the per-layer table */
RadBatch batch = decode_batch();
RadCtx c{ .b = &b, .batch = &batch, .world = 1 };
gemma4_bf16::step(&c, &batch);
CHECK_LINT(b, &c);
std::vector<int64_t> src;
for (const auto& i : c.issues) {
const RecOp* o = b.op_of(i.op);
if (o && o->op == "attn_paged") {
CHECK_EQ(i.opd[1].kind, (uint8_t)RAD_OPK_KV);
src.push_back(i.opd[1].offset);
}
}
const std::vector<int64_t> want = { 0, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 5 };
CHECK(src == want);
}
}
/* The per-layer branch is not split across ranks, and a model whose every layer shares KV has no
* cache to read. */
TEST(the_gemma4_e4b_form_is_refused_where_it_cannot_run) {
{
RadBuilder b;
RadModelMeta meta = gemma4_e4b_meta();
RadBuildCtx ctx = build_ctx(0, 2);
CHECK_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_E_UNSUPPORTED);
}
{
const char* vals[] = { "1024", "512", "16", "10000", "1000000", "0.25", "12", "30", "6", "0",
"64" };
RadBuilder b;
RadModelMeta meta = gemma4_e4b_meta();
meta.kv_val = vals;
RadBuildCtx ctx = build_ctx();
CHECK_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_E_INVAL);
}
}
TEST(gemma4_attention_shapes_for_both_classes) {
RadBuilder b;
RadModelMeta meta = gemma4_meta();
@@ -6149,11 +6231,55 @@ void lint_qwen35_fp8_family(Fn declare, StepFn step, const RadModelMeta* meta, i
const auto v = run_passes(b, step, all, rank, world);
CHECK_PASSES(b, v);
for (size_t i = 1; i < v.size(); ++i) CHECK(each_gemm_nt_once(b, *v[i]));
if (!block_drafter || block <= 4) continue;
/* The short block (rad_drafter_short_block): a query pass staged at 4 rows a sequence
* runs the short ops, its selector proposing 3; a block with no ops fails the step. */
CHECK_EQ(b.drafter_short, 4);
const auto ctx2 = context_pass(b, *ver);
const auto qs = query_pass(b, 4, b.drafter_short, b.drafter_short - 1);
const auto vs = run_passes(b, step, { ver.get(), ctx2.get(), qs.get() }, rank, world);
CHECK_PASSES(b, vs);
CHECK(vs[2]->step_fail.empty());
int64_t sel_steps = -1, sel_stride = -1;
for (const RecIssue& i : vs[2]->issues)
if (const RecOp* o = b.op_of(i.op); o && o->op == "dflash_select") {
sel_steps = pint(o, "steps");
sel_stride = pint(o, "anchor_stride");
}
CHECK_EQ(sel_steps, 3);
CHECK_EQ(sel_stride, 4);
const auto qbad = query_pass(b, 4, 6, 5);
const auto vb = run_passes(b, step, { qbad.get() }, rank, world);
CHECK(!vb[0]->step_fail.empty());
}
}
} /* namespace */
/* The GDN state cache's width is a deployment's choice: f32 by default, f16 under
* RadBuildCtx::state_dtype (--state-cache-dtype f16), which the probe says the plugin serves. */
TEST(qwen35_fp8_gdn_state_is_f32_unless_the_deployment_asks_f16) {
MetaKV mk = q35fp8_meta();
RadArchProbe pb{};
CHECK_OK(qwen35_fp8::probe(mk.meta(), &pb));
CHECK_EQ(pb.state_f16_ok, 1);
for (uint32_t want : { (uint32_t)0, (uint32_t)RAD_F16 }) {
RadBuilder b;
RadBuildCtx ctx = build_ctx();
ctx.state_dtype = want;
const int rc = stderr_of_rc([&] { return qwen35_fp8::declare(&b, mk.meta(), &ctx); });
REQUIRE_EQ(rc, RAD_OK);
int n = 0;
for (const RecKV& g : b.kv_groups)
if (g.name == "kv_gdn_state") {
++n;
CHECK_EQ(g.d.dtype, want == RAD_F16 ? RAD_F16 : RAD_F32);
}
CHECK_EQ(n, 1);
CHECK_EQ(noted(b, "GDN state cache f16"), want == RAD_F16);
}
}
/* The fp8 sibling of qwen35_bf16: the same layers with every large linear a block-fp8 gemm_nt_q
* read at fp8a8, one quantiser per activation, and the attention's output gate, multiply and
* quantiser fused into gate_quant_fp8 (the sigmoid/mul pair is the bf16-linear form only). The
@@ -6559,65 +6685,56 @@ TEST(gemma3_steps_lint_clean_at_one_and_two_ranks) {
* pieces of 1024; every collective is on the second lane, the layers' all-reduces a piece at a time
* at `overlap` 1 (two blocks a layer, two pieces a block) and the embedding's whole; the attention and
* the DFlash2 taps run a piece at a time; q|k|v and gate|up read one shared input pair. A prompt's
* first chunk and a later one alike. RADIANCE_PREFILL_PIPELINE=off runs the same step serially. */
* first chunk and a later one alike. */
TEST(gemma3_a_wide_prefill_runs_in_two_pieces_with_its_boundaries_on_the_second_lane) {
MetaKV mk = gemma3_dflash2_meta();
const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, rad::arch::RAD_MX_GROUP);
for (int off : { 0, 1 })
for (int rank = 0; rank < 2; ++rank)
for (int32_t pctx : { 0, 4096 }) {
if (off) setenv("RADIANCE_PREFILL_PIPELINE", "off", 1);
RadBuilder b;
b.encs = { { "blk.", mx } };
RadBuildCtx ctx = spec_ctx(rank, 2, 7);
ctx.max_tok = 2048;
const int rc = stderr_of_rc([&] { return gemma3::declare(&b, mk.meta(), &ctx); });
if (off) unsetenv("RADIANCE_PREFILL_PIPELINE");
REQUIRE_EQ(rc, RAD_OK);
const gemma3::Model& m = gemma3::g_model[rank];
CHECK(m.fuse_mx);
CHECK_EQ(m.pipe_on, !off);
CHECK(m.n_taps > 0);
const auto pf = kit(b, {}, { 2048 }, pctx);
const auto v = run_passes(b, gemma3::step, { pf.get() }, rank, 2);
CHECK_PASSES(b, v);
const RadCtx& c = *v[0];
CHECK(c.step_fail.empty());
const int64_t E = m.g.n_embd, L = (int64_t)m.layers.size();
int ar = 0, ar_lane0 = 0, ar_piece = 0, ar_overlap = 0;
int attn = 0, wide_attn = 0, taps = 0, wide_taps = 0;
for (const RecIssue& i : c.issues) {
const RecOp* o = b.op_of(i.op);
if (!o) continue;
if (o->op == "all_reduce") {
++ar;
ar_lane0 += i.lane == 0;
ar_piece += i.n == 1024 * E;
ar_overlap += pint(o, "overlap") == 1;
}
if (o->op == "attn_paged") { ++attn; wide_attn += i.n > 1024; }
if (o->op == "cast") { ++taps; wide_taps += i.n > 1024; }
}
if (off) {
CHECK(c.joins.empty());
CHECK_EQ(ar_lane0, ar);
CHECK_EQ(attn, (int)L);
continue;
}
CHECK_EQ(ar_lane0, 0);
CHECK_EQ(ar, 4 * (int)L + 1);
CHECK_EQ(ar_piece, 4 * (int)L);
CHECK_EQ(ar_overlap, 4 * (int)L);
CHECK_EQ(attn, 2 * (int)L);
CHECK_EQ(wide_attn, 0);
CHECK_EQ(taps, 2 * m.n_taps);
CHECK_EQ(wide_taps, 0);
CHECK(!c.joins.empty());
for (const gemma3::Layer& l : m.layers) {
CHECK(l.attn.ln_q.q8 == m.pipe_in.q8 && !l.attn.ln_q.shared_in && l.attn.ln_q.op_q);
CHECK(l.mlp.ln_gu.q8 == m.pipe_in.q8 && !l.mlp.ln_gu.shared_in && l.mlp.ln_gu.op_q);
for (int rank = 0; rank < 2; ++rank)
for (int32_t pctx : { 0, 4096 }) {
RadBuilder b;
b.encs = { { "blk.", mx } };
RadBuildCtx ctx = spec_ctx(rank, 2, 7);
ctx.max_tok = 2048;
const int rc = stderr_of_rc([&] { return gemma3::declare(&b, mk.meta(), &ctx); });
REQUIRE_EQ(rc, RAD_OK);
const gemma3::Model& m = gemma3::g_model[rank];
CHECK(m.fuse_mx);
CHECK(m.pipe_on);
CHECK(m.n_taps > 0);
const auto pf = kit(b, {}, { 2048 }, pctx);
const auto v = run_passes(b, gemma3::step, { pf.get() }, rank, 2);
CHECK_PASSES(b, v);
const RadCtx& c = *v[0];
CHECK(c.step_fail.empty());
const int64_t E = m.g.n_embd, L = (int64_t)m.layers.size();
int ar = 0, ar_lane0 = 0, ar_piece = 0, ar_overlap = 0;
int attn = 0, wide_attn = 0, taps = 0, wide_taps = 0;
for (const RecIssue& i : c.issues) {
const RecOp* o = b.op_of(i.op);
if (!o) continue;
if (o->op == "all_reduce") {
++ar;
ar_lane0 += i.lane == 0;
ar_piece += i.n == 1024 * E;
ar_overlap += pint(o, "overlap") == 1;
}
if (o->op == "attn_paged") { ++attn; wide_attn += i.n > 1024; }
if (o->op == "cast") { ++taps; wide_taps += i.n > 1024; }
}
CHECK_EQ(ar_lane0, 0);
CHECK_EQ(ar, 4 * (int)L + 1);
CHECK_EQ(ar_piece, 4 * (int)L);
CHECK_EQ(ar_overlap, 4 * (int)L);
CHECK_EQ(attn, 2 * (int)L);
CHECK_EQ(wide_attn, 0);
CHECK_EQ(taps, 2 * m.n_taps);
CHECK_EQ(wide_taps, 0);
CHECK(!c.joins.empty());
for (const gemma3::Layer& l : m.layers) {
CHECK(l.attn.ln_q.q8 == m.pipe_in.q8 && !l.attn.ln_q.shared_in && l.attn.ln_q.op_q);
CHECK(l.mlp.ln_gu.q8 == m.pipe_in.q8 && !l.mlp.ln_gu.shared_in && l.mlp.ln_gu.op_q);
}
}
}
/* Where the fused fp8 junctions do not resolve, a pipelined deployment falls back to the unfused
@@ -6648,6 +6765,46 @@ TEST(gemma3_without_fused_junctions_every_linear_quantises_into_what_it_reads) {
CHECK(quant >= 2 * (int)m.layers.size());
}
/* Under a lossy --tp-wire the fused all-reduce junctions, which send the exact wire only, still
* serve the steps whose message goes out exact anyway: a decode step's few rows fold every
* junction's all-reduce in, while a prefill chunk above --tp-wire-min-kb keeps the lossy
* all-reduce, unfused. Both families: the MXFP4 trunk's fp8 junction and a w4a8 trunk's int8 one. */
TEST(gemma3_under_a_lossy_wire_small_steps_keep_the_fused_junction) {
MetaKV mk = gemma3_meta();
const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, rad::arch::RAD_MX_GROUP);
const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128);
for (bool is_mx : { true, false })
for (int rank = 0; rank < 2; ++rank) {
RadBuilder b;
const RadEncoding& e = is_mx ? mx : w4;
b.encs = { { "attn_", e }, { "ffn_", e } };
RadBuildCtx ctx = build_ctx(rank, 2);
ctx.tp_wire_lossy = 1;
ctx.tp_wire_min_bytes = 128 * 1024;
REQUIRE_EQ(gemma3::declare(&b, mk.meta(), &ctx), RAD_OK);
const gemma3::Model& m = gemma3::g_model[rank];
if (is_mx) CHECK(m.fuse_mx && m.fuse_mx_ar);
else CHECK(!m.fuse_mx && m.fuse && m.fuse_ar);
auto issued = [&](const RadCtx& c, std::initializer_list<const char*> names) {
int n = 0;
for (const RecIssue& i : c.issues)
if (const RecOp* o = b.op_of(i.op))
for (const char* nm : names) n += o->op == nm;
return n;
};
const auto dec = kit(b, { 1 }, {});
const auto pre = kit(b, {}, { 64 }); /* 64 x 5376 x 2 bytes, above the floor */
const auto v = run_passes(b, gemma3::step, { dec.get(), pre.get() }, rank, 2);
CHECK_PASSES(b, v);
const int fused_dec = issued(*v[0], { "ar_rmsnorm_quant_i8", "ar_rmsnorm_post_quant_fp8" });
const int fused_pre = issued(*v[1], { "ar_rmsnorm_quant_i8", "ar_rmsnorm_post_quant_fp8" });
CHECK(fused_dec > 0);
CHECK_EQ(fused_pre, 0);
/* Every junction the decode step fused is an all-reduce the prefill step issues alone. */
CHECK_EQ(issued(*v[1], { "all_reduce" }), issued(*v[0], { "all_reduce" }) + fused_dec);
}
}
/* The DFlash2 drafter: a block of 8 (depth 7, fixed), taps copied out after the named layers into
* one column-sliced buffer, the mask token from the config, and the drafter's own KV group after
* the trunk's two. Its input_embedding_scale must be the trunk's sqrt(hidden) held in bf16
@@ -8475,13 +8632,13 @@ struct ArchCases {
nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x1c28909125c12f52ull);
add("qwen35_fp8 + DFlash2", [this, sc](RadBuilder* b) {
auto c = sc(1, 7); return qwen35_fp8::declare(b, q35df.meta(), &c); },
qwen35_fp8::step, 7, {}, 0x76bc2f92b452df49ull);
qwen35_fp8::step, 7, {}, 0x5eaef1ee37575caeull);
add("qwen35_w8a8 + DFlash2", [this, sc](RadBuilder* b) {
auto c = sc(1, 7); return w8a8_declare(b, q35w8df.meta(), &c); },
qwen35_w8a8::step, 7, {}, 0x5570932de623edcaull);
qwen35_w8a8::step, 7, {}, 0x5a4f256c6fda0e87ull);
add("qwen35_w8a8 + DFlash2, two ranks", [this, sc](RadBuilder* b) {
auto c = sc(2, 7); return w8a8_declare(b, q35w8df.meta(), &c); },
nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0xec1ca3ad670311bbull);
nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0xb825b9d264795b8eull);
add("qwen35moe_fp8 + MTP", [this, sc](RadBuilder* b) {
auto c = sc(1, 3); return qwen35moe_fp8::declare(b, q35moe.meta(), &c); },
qwen35moe_fp8::step, 3, {}, 0x1bd3b53543cd06eeull);
@@ -9215,30 +9372,12 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) {
}
}
/* RADIANCE_PREFILL_PIPELINE=off turns the pipelined prefill off: the two-rank build is then the serial
* one, graph and steps, as pinned before the pipeline existed. */
TEST(qwen35_pipe_off_is_the_serial_graph_and_steps) {
MetaKV q35 = q35fp8_meta();
setenv("RADIANCE_PREFILL_PIPELINE", "off", 1);
RadBuilder b;
RadBuildCtx ctx = spec_ctx(1, 2, 3);
ctx.max_tok = 4096;
ctx.max_seqs = 8;
ctx.max_ctx = 200000;
const int rc = stderr_of_rc([&] { return qwen35_fp8::declare(&b, q35.meta(), &ctx); });
unsetenv("RADIANCE_PREFILL_PIPELINE");
REQUIRE_EQ(rc, RAD_OK);
CHECK(!qwen35_fp8::g_model[1].pipe_on);
CHECK_EQ(graph_hash(b), 0x36da8d762194e24eull);
CHECK_EQ(pinned_steps(b, qwen35_fp8::step, 1, 2), 0xe4022daff02ec8bdull);
}
/* qwen35_w8a8 at two ranks where libr4d serves the `_had_quant_i8g` norms (a_h.q8_fed): the norms write
* rotated int8 codes, which the pipelined prefill's boundary norms (NormQuantFP8::step_plain) do not issue,
* so the prefill stays serial there: the step whole, nothing on the second lane, no step failure. Where
* the forms are not served each projection quantises its own input and the pipeline runs as on
* qwen35_fp8. (Before the fix the pipeline ran with q8_fed and libr4d refused the boundary norm's E4M3
* codes for the int8 op, failing every one-sequence prefill step of 1024 rows or more.) */
* qwen35_fp8. A pipeline over the int8 codes would hand the int8 op the boundary norm's E4M3 codes,
* which libr4d refuses, failing every such step. */
TEST(qwen35_w8a8_with_int8_codes_from_the_norms_prefills_serially) {
MetaKV mk = with_dflash2(q35w8a8_meta());
for (bool fused : { true, false })
@@ -9332,75 +9471,35 @@ TEST(qwen35_a_wide_prefill_runs_in_two_pieces_with_its_boundaries_on_the_second_
}
}
/* Past two ranks the pipelined prefill is opt-in (RADIANCE_PREFILL_PIPELINE=on, or 1, or true): unset,
* auto or an unknown value, the step is serial; asked, a 2048-row step of one sequence runs in two
* pieces with every collective on the second lane, the layers' all-reduces a piece at a time at
* `overlap` 1 (libr4d's narrow lane rows), the embedding's whole, on every rank. At four and eight
* ranks: neither test model's heads split three ways (nor do Qwen3.8's 4 or TranslateGemma's 16 KV
* heads); plugin_test checks that the three-rank lane rows resolve. */
static void n_rank_pipe_case(int world, bool gemma) {
const char* env = "RADIANCE_PREFILL_PIPELINE";
const char* vals[] = { nullptr, "auto", "maybe", "on", "1", "true" };
for (const char* val : vals)
for (int rank = 0; rank < world; ++rank) {
const int ask = val && (!strcmp(val, "on") || !strcmp(val, "1") || !strcmp(val, "true"));
if (val) setenv(env, val, 1);
RadBuilder b;
RadBuildCtx ctx = spec_ctx(rank, world, 7);
ctx.max_tok = 2048;
MetaKV mk = gemma ? gemma3_dflash2_meta() : with_dflash2(q35fp8_meta());
if (gemma) b.encs = { { "blk.", rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, rad::arch::RAD_MX_GROUP) } };
const int rc = stderr_of_rc([&] {
return gemma ? gemma3::declare(&b, mk.meta(), &ctx) : qwen35_fp8::declare(&b, mk.meta(), &ctx);
});
if (val) unsetenv(env);
REQUIRE_EQ(rc, RAD_OK);
const bool on = gemma ? gemma3::g_model[rank].pipe_on : qwen35_fp8::g_model[rank].pipe_on;
const int64_t L = gemma ? (int64_t)gemma3::g_model[rank].layers.size()
: (int64_t)qwen35_fp8::g_model[rank].layers.size();
CHECK_EQ(on, ask == 1);
const auto pf = kit(b, {}, { 2048 }, 0);
const auto v = run_passes(b, gemma ? gemma3::step : qwen35_fp8::step, { pf.get() }, rank, world);
CHECK_PASSES(b, v);
const RadCtx& c = *v[0];
CHECK(c.step_fail.empty());
int ar = 0, ar_lane0 = 0, ar_overlap = 0, arn = 0;
for (const RecIssue& i : c.issues) {
const RecOp* o = b.op_of(i.op);
if (!o) continue;
if (o->op == "all_reduce") { ++ar; ar_lane0 += i.lane == 0; ar_overlap += pint(o, "overlap") == 1; }
if (o->op.rfind("ar_", 0) == 0) { ++arn; ar_lane0 += i.lane == 0; }
}
if (!ask) {
CHECK(c.joins.empty());
continue;
}
CHECK_EQ(ar_lane0, 0);
CHECK_EQ(ar + arn, 4 * (int)L + 1);
CHECK_EQ(ar_overlap, 4 * (int)L);
CHECK(!c.joins.empty());
}
}
TEST(qwen35_four_ranks_pipeline_only_when_asked) { n_rank_pipe_case(4, false); }
TEST(gemma3_four_ranks_pipeline_only_when_asked) { n_rank_pipe_case(4, true); }
TEST(qwen35_eight_ranks_pipeline_only_when_asked) { n_rank_pipe_case(8, false); }
TEST(gemma3_eight_ranks_pipeline_only_when_asked) { n_rank_pipe_case(8, true); }
/* At two ranks "off", "0" and "false" all run the pipelined prefill's step serially (the old switches
* took 0 for off; such a value must not leave it on). */
TEST(two_ranks_pipeline_off_in_every_spelling) {
MetaKV mk = with_dflash2(q35fp8_meta());
for (const char* v : { "off", "0", "false" }) {
setenv("RADIANCE_PREFILL_PIPELINE", v, 1);
/* Past two ranks the pipelined prefill is off: a 2048-row step of one sequence at four and eight
* ranks runs whole, with nothing on the second lane. */
static void n_rank_serial_case(int world, bool gemma) {
for (int rank = 0; rank < world; ++rank) {
RadBuilder b;
RadBuildCtx ctx = spec_ctx(0, 2, 7);
RadBuildCtx ctx = spec_ctx(rank, world, 7);
ctx.max_tok = 2048;
const int rc = stderr_of_rc([&] { return qwen35_fp8::declare(&b, mk.meta(), &ctx); });
unsetenv("RADIANCE_PREFILL_PIPELINE");
MetaKV mk = gemma ? gemma3_dflash2_meta() : with_dflash2(q35fp8_meta());
if (gemma) b.encs = { { "blk.", rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, rad::arch::RAD_MX_GROUP) } };
const int rc = stderr_of_rc([&] {
return gemma ? gemma3::declare(&b, mk.meta(), &ctx) : qwen35_fp8::declare(&b, mk.meta(), &ctx);
});
REQUIRE_EQ(rc, RAD_OK);
CHECK(!qwen35_fp8::g_model[0].pipe_on);
CHECK(!(gemma ? gemma3::g_model[rank].pipe_on : qwen35_fp8::g_model[rank].pipe_on));
const auto pf = kit(b, {}, { 2048 }, 0);
const auto v = run_passes(b, gemma ? gemma3::step : qwen35_fp8::step, { pf.get() }, rank, world);
CHECK_PASSES(b, v);
const RadCtx& c = *v[0];
CHECK(c.step_fail.empty());
CHECK(c.joins.empty());
int lane1 = 0;
for (const RecIssue& i : c.issues) lane1 += i.lane == 1;
CHECK_EQ(lane1, 0);
}
}
TEST(qwen35_four_ranks_prefill_serially) { n_rank_serial_case(4, false); }
TEST(gemma3_four_ranks_prefill_serially) { n_rank_serial_case(4, true); }
TEST(qwen35_eight_ranks_prefill_serially) { n_rank_serial_case(8, false); }
TEST(gemma3_eight_ranks_prefill_serially) { n_rank_serial_case(8, true); }
/* Under a span a Flash-Next prefill of two intervals runs a pass at a time. At every world its
* connection reads take a pass each and the indexer scores its pass-tall plane in windows, the MTP
+89
View File
@@ -209,4 +209,93 @@ TEST(the_unconditional_branch_is_the_conditional_prompt_at_guidance_one) {
}
}
/* A hybrid language model (paged attention beside a linear-attention state and a convolution
* group, as Qwen3.5's delta-net layers keep) of one branch: every pass stages one sequence a
* request, the state groups' rows are the sequence's slots, and each entry carries its context
* and a one-based num_accepted. The slots held at the prompt are the frames' too; guidance other
* than 1 is refused. */
TEST(a_hybrid_model_of_one_branch_stages_its_state_groups) {
AudioFixture f;
f.prog.audio_gen = decl_chunked();
f.prog.audio_gen.branches = 1;
f.prog.agen_str.name = "hybrid";
f.prog.ctx.max_tok = 64;
f.prog.ctx.max_seqs = 8;
f.prog.kv_groups.emplace_back();
for (int kind : { RAD_KV_FULL, RAD_KV_LINEAR, RAD_KV_CONV }) {
KVGroupInfo g;
g.name = kind == RAD_KV_FULL ? "attn" : kind == RAD_KV_LINEAR ? "state" : "conv";
g.decl.kind = kind;
g.block_size = kind == RAD_KV_FULL ? 16 : 0;
f.prog.kv_groups.push_back(g);
}
f.kv.setup(f.prog.kv_groups, 1 << 20, 256, 4);
CHECK_OK(f.start());
std::string why;
CHECK(f.drv.submit(f.req(2.0f), &why) < 0);
CHECK(has(why, "without guidance"));
CHECK_OK(f.drv.submit(f.req(1.0f), &why));
auto state_rows = [](const RadBatch* b, int32_t* st, int32_t* cv) {
*st = *cv = -2;
for (int i = 0; i < b->n_kv_groups; ++i) {
const RadKVGroupBatch& k = b->kv[i];
if (k.group == 1) continue;
REQUIRE(k.state_index != nullptr && k.block_table != nullptr);
CHECK_EQ(k.block_table[0], k.state_index[0]);
(k.group == 2 ? *st : *cv) = k.state_index[0];
}
};
const RadBatch* b = f.drv.next(0);
REQUIRE(b != nullptr && b->gen == RAD_GEN_PASS_PROMPT);
CHECK_EQ(b->n_seq, (int64_t)1);
CHECK_EQ(b->n_tok, (int64_t)4);
REQUIRE_EQ(b->n_kv_groups, 3);
int32_t st0 = 0, cv0 = 0;
state_rows(b, &st0, &cv0);
CHECK(st0 >= 0 && cv0 >= 0);
REQUIRE(b->ctx_lens != nullptr && b->num_accepted != nullptr);
CHECK_EQ(b->ctx_lens[0], 0);
CHECK_EQ(b->num_accepted[0], 1);
CHECK_EQ(b->agen_b->slot[0], b->agen_b->lane_h[0]); /* one branch: the slot is the lane */
f.answer(b, 0, 0.0f);
CHECK_OK(f.drv.done());
b = f.drv.next(1);
REQUIRE(b != nullptr && b->gen == RAD_GEN_PASS_FRAME);
CHECK_EQ(b->n_seq, (int64_t)1);
CHECK_EQ(b->n_tok, (int64_t)1);
CHECK_EQ(b->positions[0], 4); /* after the four prompt rows */
CHECK_EQ(b->ctx_lens[0], 4);
/* The row the frame is sampled from: the prompt's last, at its slot. */
CHECK_EQ(b->agen_b->prev_pos[0], 3);
CHECK_EQ(b->agen_b->prev_used[0], 4);
CHECK_EQ(b->agen_b->prev_slot[0], b->kv[0].slot_mapping[0] - 1);
CHECK_EQ(b->num_accepted[0], 1);
int32_t st1 = 0, cv1 = 0;
state_rows(b, &st1, &cv1);
CHECK_EQ(st1, st0);
CHECK_EQ(cv1, cv0);
}
/* The driver stages one paged group beside state groups: a second paged group is refused at init,
* by name. */
TEST(a_second_paged_group_is_refused) {
AudioFixture f;
f.prog.audio_gen = decl_chunked();
f.prog.agen_str.name = "two";
f.prog.ctx.max_tok = 64;
f.prog.ctx.max_seqs = 8;
f.prog.kv_groups.emplace_back();
for (int i = 0; i < 2; ++i) {
KVGroupInfo g;
g.name = i ? "b" : "a";
g.decl.kind = RAD_KV_FULL;
g.block_size = 16;
f.prog.kv_groups.push_back(g);
}
f.kv.setup(f.prog.kv_groups, 1 << 20, 256, 4);
CHECK(f.start() < 0);
}
RAD_TEST_MAIN()
+63
View File
@@ -1072,6 +1072,69 @@ TEST(the_drafter_name_survives_the_program_leaving_the_builder) {
CHECK_EQ(p.drafter.depth, 3);
}
/* rad_drafter_short_block applies only to a declared block drafter, and only to a block shorter
* than its own that still proposes a token; anything else is refused at declare, since the core
* would stage a block the plugin has no ops for. */
TEST(a_block_drafters_short_block_is_shorter_and_still_proposes) {
Registry reg;
{
Builder b(reg, make_meta(), make_ctx());
CHECK_EQ(rad_drafter_short_block(&b, 4), RAD_E_STATE); /* nothing declared */
}
{
Builder b(reg, make_meta(), make_ctx());
RadDrafterDecl d{};
d.kind = RAD_DRAFT_SERIAL; d.name = "mtp"; d.depth = 4;
CHECK_OK(rad_declare_drafter(&b, &d));
CHECK_EQ(rad_drafter_short_block(&b, 3), RAD_E_STATE); /* a serial head */
}
{
Builder b(reg, make_meta(), make_ctx());
RadBufDecl bd{};
bd.dtype = RAD_I32; bd.rank = 2; bd.shape[0] = 256; bd.shape[1] = 4;
const rad_buf prop = rad_decl_buffer(&b, "prop", &bd);
RadDrafterDecl d{};
d.kind = RAD_DRAFT_BLOCK; d.name = "df"; d.depth = 4; d.mask_token = 5;
d.proposal = prop; d.proposal_pitch = 4; /* block 5: the anchor + 4 */
CHECK_OK(rad_declare_drafter(&b, &d));
CHECK_EQ(rad_drafter_short_block(&b, 5), RAD_E_INVAL); /* not shorter */
CHECK_EQ(rad_drafter_short_block(&b, 1), RAD_E_INVAL); /* proposes nothing */
CHECK_EQ(b.program().drafter_short_block, 0);
CHECK_OK(rad_drafter_short_block(&b, 3));
CHECK_EQ(b.program().drafter_short_block, 3);
}
}
/* A block drafter's proposal pitch is its row pitch, which the engine reads row s at: left at 0 it
* defaults to depth, and under depth it is refused, since a row could not hold the proposals. */
TEST(a_block_drafters_proposal_pitch_holds_its_proposals) {
Registry reg;
RadBufDecl bd{};
bd.dtype = RAD_I32; bd.rank = 2; bd.shape[0] = 256; bd.shape[1] = 4;
{
Builder b(reg, make_meta(), make_ctx());
RadDrafterDecl d{};
d.kind = RAD_DRAFT_BLOCK; d.name = "df"; d.depth = 4; d.mask_token = 5;
d.proposal = rad_decl_buffer(&b, "prop", &bd);
CHECK_OK(rad_declare_drafter(&b, &d));
CHECK_EQ(b.program().drafter.proposal_pitch, 4);
}
{
Builder b(reg, make_meta(), make_ctx());
RadDrafterDecl d{};
d.kind = RAD_DRAFT_BLOCK; d.name = "df"; d.depth = 4; d.mask_token = 5;
d.proposal = rad_decl_buffer(&b, "prop", &bd); d.proposal_pitch = 3;
CHECK_EQ(rad_declare_drafter(&b, &d), RAD_E_INVAL);
}
{
Builder b(reg, make_meta(), make_ctx());
RadDrafterDecl d{};
d.kind = RAD_DRAFT_SERIAL; d.name = "mtp"; d.depth = 4;
CHECK_OK(rad_declare_drafter(&b, &d));
CHECK_EQ(b.program().drafter.proposal_pitch, 1);
}
}
/* rad_drafter_shared_kv applies only to a declared serial drafter. With none declared, a block
* drafter, or a position no head occupies, it is refused at declare; a head staged the wrong way
* silently costs acceptance. */
+50 -3
View File
@@ -422,12 +422,13 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--model", { "/m/y.rad" } }, { "--download-dir", { "/d" } },
{ "--radiance-home", { "/h1:/h2" } }, { "--kernels", { "libref" } },
{ "--tp", { "2" } }, { "--tp-wire", { "wht6" } }, { "--tp-wire-min-kb", { "64" } },
{ "--tp-attn-split", { "rows" } },
{ "--p2p", { "off" } }, { "--max-num-batched-tokens", { "512" } },
{ "--busy-prefill-chunk", { "256" } }, { "--prefill-interleave", { "2" } },
{ "--max-num-seqs", { "4" } },
{ "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } },
{ "--gpu-headroom-mib", { "128" } }, { "--kv-cache-dtype", { "fp8" } },
{ "--attn-prefill-fp8", { "both" } },
{ "--state-cache-dtype", { "f16" } }, { "--attn-prefill-fp8", { "both" } },
{ "--host-pool-mib", { "1024" } }, { "--host-headroom-mib", { "2048" } },
{ "--embedding-placement", { "vram" } },
{ "--vision-tower-placement", { "ram" } }, { "--ngram-placement", { "disk" } },
@@ -435,7 +436,8 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--placement", { "all_vram" } }, { "--checkpoint-interval", { "256" } },
{ "--prefill-span", { "2" } },
{ "--checkpoint-slots", { "4" } }, { "--checkpoint-policy", { "tip-only" } },
{ "--num-speculative-tokens", { "2" } }, { "--draft-window", { "fixed" } },
{ "--num-speculative-tokens", { "2" } }, { "--draft-window", { "fixed" } }, { "--draft-short-from", { "4" } },
{ "--draft-coupling", { "on" } },
{ "--host", { "127.0.0.1" } }, { "--port", { "8001" } }, { "--api-key", { "k" } },
{ "--served-model-name", { "m" } }, { "--mm-max-patches", { "1024" } },
{ "--control-vector", { "off" } },
@@ -640,6 +642,20 @@ TEST(the_wire_mode_is_one_of_two_names) {
CHECK_EQ(parse({ "--tp-wire", "EXACT" }, &c), RAD_E_INVAL);
}
/* The row split of a prefill's attention is not bit-identical to the head split, so heads is
* the default and anything but the two names stops the server. */
TEST(the_attention_split_is_one_of_two_names) {
Config c;
CHECK_EQ(c.tp_attn_rows, 0);
CHECK_EQ(parse({ "--tp-attn-split", "rows" }, &c), RAD_OK);
CHECK_EQ(c.tp_attn_rows, 1);
CHECK_EQ(parse({ "--tp-attn-split", "heads" }, &c), RAD_OK);
CHECK_EQ(c.tp_attn_rows, 0);
CHECK_EQ(parse({ "--tp-attn-split", "1" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--tp-attn-split", "" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--tp-attn-split", "ROWS" }, &c), RAD_E_INVAL);
}
/* The prefill attention's e4m3 legs are lossy, so the default is off and anything but the four
* names stops the server. */
TEST(the_attention_fp8_mode_is_one_of_four_names) {
@@ -675,6 +691,20 @@ TEST(the_p2p_mode_is_one_of_three_names) {
CHECK_EQ(parse({ "--p2p", "OFF" }, &c), RAD_E_INVAL);
}
TEST(the_state_cache_dtype_is_f32_or_f16) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK_EQ(d.state_cache_dtype, std::string("f32"));
Config c;
CHECK_EQ(parse({ "--state-cache-dtype", "f16" }, &c), RAD_OK);
CHECK_EQ(c.state_cache_dtype, std::string("f16"));
CHECK_EQ(parse({ "--state-cache-dtype", "f32" }, &c), RAD_OK);
CHECK_EQ(c.state_cache_dtype, std::string("f32"));
CHECK_EQ(parse({ "--state-cache-dtype", "bf16" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--state-cache-dtype", "1" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--state-cache-dtype" }, &c), RAD_E_INVAL);
}
TEST(the_kv_cache_dtype_is_one_of_four_names) {
Config c;
CHECK_EQ(parse({ "--kv-cache-dtype", "bf16" }, &c), RAD_OK);
@@ -750,6 +780,22 @@ TEST(the_draft_window_is_fixed_or_adaptive) {
CHECK_EQ(std::string(draft_window_name(DraftWindow::Fixed)), std::string("fixed"));
}
/* --draft-coupling is off unless asked for, and only off and on parse: a misspelt value must not
* start a server on the other path. */
TEST(the_draft_coupling_is_off_or_on) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(!d.draft_coupling);
Config c;
CHECK_EQ(parse({ "--draft-coupling", "on" }, &c), RAD_OK);
CHECK(c.draft_coupling);
CHECK_EQ(parse({ "--draft-coupling", "off" }, &c), RAD_OK);
CHECK(!c.draft_coupling);
for (const char* bad : { "On", "1", "yes", "true", "" })
CHECK_EQ(parse({ "--draft-coupling", bad }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--draft-coupling" }, &c), RAD_E_INVAL);
}
/* An unknown policy name is refused; falling through to the default would make a comparison
* silently measure the default against itself. */
TEST(the_checkpoint_policy_is_one_of_the_three_that_exist) {
@@ -1244,7 +1290,8 @@ TEST(usage_names_every_flag_it_documents) {
* for, so a flag added without a help line is caught. */
const std::string text = stderr_of([] { config_usage("radiance"); });
for (const char* f : { "--model", "--host-pool-mib", "--kv-cache-dtype",
"--num-speculative-tokens", "--draft-window", "--checkpoint-policy",
"--num-speculative-tokens", "--draft-window", "--draft-coupling",
"--checkpoint-policy",
"--prefix-cache-mib", "--prefix-cache-ttl", "--tp-wire",
"--attn-prefill-fp8", "--embedding-placement", "--ngram-placement",
"--kld-record", "--kld-ref", "--default-max-tokens", "--max-tokens-cap",
+80
View File
@@ -56,6 +56,23 @@ struct StatsScheduler : FakeScheduler {
occ->host_cap_bytes = 64 << 20;
return 1;
}
/* The one stored conversation is "conv-7" (engine id 7); "busy" has a request in flight. */
std::vector<std::pair<std::string, int64_t>> released;
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionReleased* out) override {
if (label == "busy") return RAD_E_STATE;
if (label != "conv-7" && id != 7) return RAD_E_NOTFOUND;
released.push_back({ label.empty() ? "id" : label, keep_tokens });
out->sessions = 1;
out->entries = 48 - keep_tokens / 16;
out->tokens = out->entries * 16;
out->device_bytes = out->entries * 4096;
out->host_bytes = out->entries * 2048;
out->snapshots = 2;
out->kept_tokens = keep_tokens;
out->kept_shared = 2;
return RAD_OK;
}
TierCounters tier_counters() const override {
TierCounters c;
c.to_host = 3; c.dropped = 2; c.promoted = 1; c.host_drops = 4; c.failures = 0;
@@ -247,6 +264,69 @@ TEST(sessions_lists_each_conversation_and_what_the_tiers_did) {
CHECK_EQ(s["linear"].value("hit_cut_tokens", (int64_t)0), (int64_t)9000);
}
/* DELETE /sessions forgets one stored conversation by its label or engine id and answers with
* what went and what stayed; an unknown session is 404, one with a request in flight 409, a
* malformed count 400, and an engine without a prefix cache 501. */
TEST(a_session_is_released_by_label_or_id_and_the_answer_says_what_went) {
Dash d(false);
HttpResponse r = d.srv->router().call("DELETE", "/sessions/conv-7");
CHECK_EQ(r.status, 200);
json o = json::parse(r.body, nullptr, false);
CHECK_EQ(o.value("label", ""), std::string("conv-7"));
CHECK_EQ(o.value("entries", (int64_t)0), (int64_t)48);
CHECK_EQ(o.value("tokens", (int64_t)0), (int64_t)768);
CHECK_EQ(o.value("snapshots", (int64_t)0), (int64_t)2);
CHECK_EQ(o["kept"].value("shared", (int64_t)0), (int64_t)2);
CHECK_EQ(o["kept"].value("tokens", (int64_t)0), (int64_t)0);
REQUIRE_EQ(d.sched.released.size(), 1u);
CHECK_EQ(d.sched.released[0].second, (int64_t)0);
/* keep_tokens reaches the scheduler and comes back in the answer. */
r = d.srv->router().call("DELETE", "/sessions/conv-7?keep_tokens=160");
CHECK_EQ(r.status, 200);
o = json::parse(r.body, nullptr, false);
CHECK_EQ(o.value("keep_tokens", (int64_t)0), (int64_t)160);
CHECK_EQ(o.value("entries", (int64_t)0), (int64_t)38);
CHECK_EQ(o["kept"].value("tokens", (int64_t)0), (int64_t)160);
REQUIRE_EQ(d.sched.released.size(), 2u);
CHECK_EQ(d.sched.released[1].second, (int64_t)160);
/* By engine id, and by a label the path cannot carry. */
r = d.srv->router().call("DELETE", "/sessions?id=7");
CHECK_EQ(r.status, 200);
o = json::parse(r.body, nullptr, false);
CHECK_EQ(o.value("id", (int64_t)0), (int64_t)7);
CHECK(!o.contains("label"));
r = d.srv->router().call("DELETE", "/sessions?label=conv-7");
CHECK_EQ(r.status, 200);
CHECK_EQ(d.srv->router().call("DELETE", "/sessions/conv-8").status, 404);
CHECK_EQ(d.srv->router().call("DELETE", "/sessions?id=8").status, 404);
CHECK_EQ(d.srv->router().call("DELETE", "/sessions/busy").status, 409);
CHECK_EQ(d.srv->router().call("DELETE", "/sessions").status, 400);
CHECK_EQ(d.srv->router().call("DELETE", "/sessions?id=seven").status, 400);
CHECK_EQ(d.srv->router().call("DELETE", "/sessions/conv-7?keep_tokens=-1").status, 400);
CHECK_EQ(d.sched.released.size(), 4u);
/* The stored-sessions view carries the counters beside the expiry ones. */
const json s = d.get("/sessions");
CHECK(s.contains("released"));
CHECK(s["released"].contains("entries"));
CHECK(s["released"].contains("snapshots"));
}
TEST(a_session_release_without_a_prefix_cache_is_not_implemented) {
FakeScheduler sched; /* the base: no release_session */
FakeTokenizer tok;
Deps dd;
dd.sched = &sched;
dd.tok = &tok;
ServerOptions o;
o.model_id = "dash";
Server srv(dd, o);
CHECK_EQ(srv.router().call("DELETE", "/sessions/conv-7").status, 501);
}
/* ================================================================== the page's field contract */
/* Every field the page's script reads from /stats (in its update and the request table) and from
+78
View File
@@ -743,6 +743,84 @@ TEST(an_attention_fp8_mode_no_kernel_takes_is_refused_at_startup) {
CHECK(named);
}
/* The row split of a prefill's attention is a graph only a plugin that declares it can build, so
* a plugin that does not (qwen35 here) is refused by the flag's name instead of serving the head
* split under it. */
TEST(an_attention_row_split_no_plugin_serves_is_refused_at_startup) {
World& w = world();
REQUIRE(w.ok);
const Ran r = radiance(w.qwen35, { "--host", "127.0.0.1", "--port", "0", "--tp", "2",
"--tp-attn-split", "rows" },
{ "RADIANCE_HOST_DEVICES=2" }, 120);
const bool named = has(r.log, "--tp-attn-split rows: the '") &&
has(r.log, "plugin does not split attention by rows");
if (r.status == 0 || r.status == 124 || !named)
fprintf(stderr, " exited %d:\n%s\n", r.status, tail(r.log, 20).c_str());
CHECK(r.status != 0);
CHECK(r.status != 124);
CHECK(named);
}
/* --draft-coupling's answers before any request: a value other than off/on is refused by the flag
* parse, and a model whose drafter has no per-round draw to couple is refused at bringup. The same
* model with the flag off is the control: it starts, so the refusals are the flag's and not the
* fixture's. */
TEST(the_coupling_flag_refuses_what_it_cannot_serve_at_startup) {
World& w = world();
REQUIRE(w.ok);
/* qwen35's tiny checkpoint declares no draft head: no serial chain to couple. The spechub
* kernels are loaded beside libref, so the refusal is the drafter's shape and not a missing
* coupling kernel. */
const Ran on = radiance(w.qwen35, { "--kernels", "libref,spechub", "--draft-coupling", "on" },
{}, 120);
const std::string want = "--draft-coupling on requires the linear serial draft chain "
"(RAD_DRAFT_SERIAL with depth > 0)";
if (on.status == 0 || on.status == 124 || !has(on.log, want))
fprintf(stderr, " --draft-coupling on exited %d:\n%s\n", on.status,
tail(on.log, 20).c_str());
CHECK(on.status != 0);
CHECK(on.status != 124);
CHECK(has(on.log, want));
CHECK(has(on.log, "declares drafter '(none)'"));
/* The reference gate is not relaxed: with a production library for the model's ops and the
* spechub library beside it on a machine with no card, the only coupled row left is the host
* oracle, and the start must be refused naming the coupled op. */
if (::access(RAD_E2E_HOME "/kernels/libavx.so", R_OK) == 0) {
std::string gate_log;
const int gate = tiny::run(serving_argv(w.qwen35, { "--kernels", "libavx,spechub",
"--draft-coupling", "on" }),
engine_env({}), &gate_log, 120);
const std::string gate_ref = "1 declared op(s) resolve only to a reference implementation "
"(spechub)";
if (gate == 0 || gate == 124 || !has(gate_log, gate_ref) ||
!has(gate_log, "1 distinct op(s): mtp_couple_verify"))
fprintf(stderr, " serving start exited %d:\n%s\n", gate,
tail(gate_log, 20).c_str());
CHECK(gate != 0);
CHECK(gate != 124);
CHECK(has(gate_log, gate_ref));
CHECK(has(gate_log, "distinct op(s): mtp_couple_verify"));
}
const Ran typo = radiance(w.qwen35, { "--draft-coupling", "yes" }, {}, 120);
const std::string refused = "--draft-coupling takes off or on, not 'yes'";
if (typo.status == 0 || typo.status == 124 || !has(typo.log, refused))
fprintf(stderr, " --draft-coupling yes exited %d:\n%s\n", typo.status,
tail(typo.log, 20).c_str());
CHECK(typo.status != 0);
CHECK(typo.status != 124);
CHECK(has(typo.log, refused));
/* --debug-graph runs declare and plan and exits, so it is a start, not a serve. */
const Ran off = radiance(w.qwen35, { "--debug-graph", "--draft-coupling", "off" }, {}, 120);
if (off.status != 0)
fprintf(stderr, " --draft-coupling off exited %d:\n%s\n", off.status,
tail(off.log, 20).c_str());
CHECK_EQ(off.status, 0);
CHECK(!has(off.log, "MTP coupled LIVE"));
}
/* Two ranks split heads, the FFN and the vocabulary, and sum partial products in an all-reduce,
* so the rounding differs from one rank's; anything more than rounding is a wrong column or row
* (a rank's logits read at another rank's vocabulary offset score near chance). */
+221 -23
View File
@@ -331,6 +331,187 @@ TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) {
}
}
/* GLM's MLA from the TP split threshold: each rank runs its run of the step's rows with all 64
* heads, through q_b, kv_b and o at full width, and an all_gather lays the runs out, instead of
* its heads over every row and an all-reduce. Runs are ceil(T / world) rows, the last one short;
* the gather sends whole runs into an output of world runs. Below the threshold, and at TP1, the
* head form is unchanged, as it is unless the row form is opted into (the default). */
TEST(glm_mla_splits_a_prefill_by_rows_over_ranks_from_the_row_threshold) {
using namespace rad::arch;
for (int world : { 1, 2, 4, 8 })
for (int rank = 0; rank < world; ++rank) {
RadBuilder b;
b.kv_block = 4;
// The container's MLA entries; the row form's names are not among them.
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
b.encs = { { "attn_q_a.weight", fp8 },
{ "attn_kv_a.weight", fp8 },
{ "attn_q_b.weight", fp8 },
{ "attn_output.weight", fp8 },
{ "attn_kv_b.weight", rad_enc_plain(RAD_BF16) } };
Names nm("");
Geom g{};
g.n_embd = 4096;
g.max_tok = 512;
g.max_ctx = 4096;
g.eps = 1e-5;
g.world = world;
g.rank = rank;
RadKVGroupDecl kd{};
kd.kind = RAD_KV_FULL;
kd.dtype = RAD_BF16;
kd.n_head_kv = 1;
kd.head_dim = 256;
const rad_kvgroup kv = rad_decl_kv_group(&b, "latent", &kd);
const int64_t T = 512, R = GlmMla::rows_for(T, world), H = 64 / world;
auto act = [&](ActFP8& a, const char* name, int64_t rows, int64_t width) {
a.x = decl_b(&b, name, RAD_BF16, { rows, width });
return a.declare_qs(&b, nm, g, name, width, rows);
};
GlmMla::Wire w;
REQUIRE_EQ(act(w.input, "normalized", T, 4096), RAD_OK);
w.q_raw = decl_b(&b, "q_raw", RAD_BF16, { T, 1536 });
w.kv_raw = decl_b(&b, "kv_raw", RAD_BF16, { T, 512 });
REQUIRE_EQ(act(w.q_low, "q_low", T, 1536), RAD_OK);
w.latent = decl_b(&b, "latent", RAD_BF16, { T, 512 });
w.out = decl_b(&b, "attn_delta", RAD_BF16, { world * R, 4096 });
w.core.q = decl_b(&b, "query", RAD_BF16, { T, 16384 / world });
w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { T, H, 512 });
w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { T, H, 512 });
REQUIRE_EQ(act(w.attn, "expanded", T, 16384 / world), RAD_OK);
w.core.out = w.attn.x;
w.core.selected = decl_b(&b, "selected", RAD_I32, { T, 513 });
w.core.length = decl_b(&b, "length", RAD_I32, { T });
w.rows.q = decl_b(&b, "rows_query", RAD_BF16, { R, 16384 });
w.rows.q_latent = decl_b(&b, "rows_q_latent", RAD_BF16, { R, 64, 512 });
w.rows.attn_latent = decl_b(&b, "rows_attn_latent", RAD_BF16, { R, 64, 512 });
REQUIRE_EQ(act(w.rows.attn, "rows_expanded", R, 16384), RAD_OK);
w.rows.out = decl_b(&b, "rows_out", RAD_BF16, { R, 4096 });
GlmMla mla;
REQUIRE_EQ(mla.declare(&b, nm, g, 3, w, "model.layers.3.self_attn", kv), RAD_OK);
const bool rows = world > 1;
CHECK_EQ(mla.op_rows_gather != 0, rows);
CHECK_EQ(count_op(b, "all_gather"), rows ? 1 : 0);
CHECK_EQ(count_op(b, "mla_attn"), rows ? 2 : 1);
const RecWeight* head_q = find_w(b, "blk.3.attn_q_b.weight");
REQUIRE(head_q);
CHECK_EQ(head_q->d.shape[0], 16384 / world);
if (!rows) {
CHECK(!find_w(b, "blk.3.attn_q_b_rows.weight"));
continue;
}
const RecWeight* q_b = find_w(b, "blk.3.attn_q_b_rows.weight");
const RecWeight* kv_b = find_w(b, "blk.3.attn_kv_b_rows.weight");
const RecWeight* o = find_w(b, "blk.3.attn_output_rows.weight");
REQUIRE(q_b && kv_b && o);
CHECK_EQ(q_b->d.shard, RAD_SHARD_NONE);
CHECK_EQ(q_b->d.shape[0], 16384);
CHECK_EQ(q_b->d.shape[1], 1536);
CHECK_EQ(kv_b->d.shard, RAD_SHARD_NONE);
CHECK_EQ(kv_b->d.dtype, RAD_BF16);
CHECK_EQ(kv_b->d.shape[0], 32768);
CHECK_EQ(kv_b->d.shape[1], 512);
CHECK_EQ(o->d.shard, RAD_SHARD_NONE);
CHECK_EQ(o->d.shape[0], 4096);
CHECK_EQ(o->d.shape[1], 16384);
// The full-width weights are whole views of the head form's container entries, so
// they take its encoding (block fp8 at f32 scales) and need no name map of their own.
const auto source = [](const RecWeight* w) {
return std::string(w && w->d.source ? w->d.source : "");
};
CHECK_EQ(source(q_b), "blk.3.attn_q_b.weight");
CHECK_EQ(source(find_w(b, "blk.3.attn_q_b_rows.scale")), "blk.3.attn_q_b.weight");
CHECK_EQ(source(kv_b), "blk.3.attn_kv_b.weight");
CHECK_EQ(source(o), "blk.3.attn_output.weight");
CHECK_EQ(source(find_w(b, "blk.3.attn_output_rows.scale")), "blk.3.attn_output.weight");
CHECK_EQ(find_w(b, "blk.3.attn_q_b_rows.scale")->d.dtype, RAD_F32);
for (const auto& map : b.maps) CHECK(map.declared.find("_rows") == std::string::npos);
CHECK_EQ(pstr(&b.ops[mla.rows_q_b.op - 1], "dtype"), "fp8a8f32");
CHECK_EQ(pstr(&b.ops[mla.rows_output.op - 1], "dtype"), "fp8a8f32");
CHECK_EQ(pstr(&b.ops[mla.q_b.op - 1], "dtype"), "fp8a8f32");
const RecOp* attn = &b.ops[mla.op_rows_attn - 1];
CHECK_EQ(pint(attn, "heads"), 64);
CHECK_EQ(pint(attn, "blocks"), 513);
CHECK_EQ(param(attn, "M")->ihi, R);
CHECK(attn->reads ==
std::vector<rad_buf>({ w.rows.q_latent, w.core.selected, w.core.length }));
const RecOp* gather = &b.ops[mla.op_rows_gather - 1];
const RecOp* reduce = &b.ops[mla.op_ar - 1];
CHECK_EQ(pint(gather, "world_size"), world);
CHECK_EQ(pstr(gather, "dtype"), "bf16");
CHECK(!param(gather, "row"));
// The all-reduce's message bound, so the two share one exchange instance.
CHECK_EQ(param(gather, "numel")->ihi, param(reduce, "numel")->ihi);
CHECK(gather->reads == std::vector<rad_buf>({ w.rows.out }));
CHECK(gather->writes == std::vector<rad_buf>({ w.out }));
std::vector<int32_t> slots(T);
RadKVGroupBatch kb{};
kb.group = kv;
kb.slot_mapping = slots.data();
RadBatch batch{};
batch.kv = &kb;
batch.n_kv_groups = 1;
for (int64_t steps : { 300, 255 }) {
batch.n_tok = steps;
RadCtx ctx;
ctx.b = &b;
ctx.rank = rank;
ctx.world = world;
mla.prepare(&ctx, &batch);
mla.finish(&ctx, &batch);
CHECK(ctx.step_fail.empty());
auto issued = [&](rad_op op) {
return std::count_if(ctx.issues.begin(), ctx.issues.end(),
[&](const RecIssue& i) { return i.op == op; });
};
const bool split = steps >= GlmTp::kSplitRows;
CHECK_EQ(issued(mla.q_b.op), split ? 0 : 1);
CHECK_EQ(issued(mla.core.op_attn), split ? 0 : 1);
CHECK_EQ(issued(mla.op_ar), split ? 0 : 1);
CHECK_EQ(issued(mla.op_rows_attn), split ? 1 : 0);
CHECK_EQ(issued(mla.op_rows_gather), split ? 1 : 0);
if (!split) continue;
const int64_t run = (steps + world - 1) / world, first = rank * run,
n = std::min(run, steps - first);
for (const auto& i : ctx.issues) {
if (i.op == mla.rows_q_b.op) {
CHECK_EQ(i.n, n);
CHECK_EQ(i.opd[0].handle, w.q_low.q);
CHECK_EQ(i.opd[0].offset, first * 1536);
CHECK_EQ(i.opd[0].rows, n);
CHECK_EQ(i.opd[2].handle, mla.rows_q_b.w);
CHECK_EQ(i.opd[4].handle, w.rows.q);
CHECK_EQ(i.opd[4].offset, 0);
CHECK_EQ(i.opd[4].rows, n);
} else if (i.op == mla.op_rows_attn) {
CHECK_EQ(i.n, n);
CHECK_EQ(i.opd[1].kind, RAD_OPK_KV);
CHECK_EQ(i.opd[2].handle, w.core.selected);
CHECK_EQ(i.opd[2].offset, first * 513);
CHECK_EQ(i.opd[2].rows, n);
CHECK_EQ(i.opd[3].handle, w.core.length);
CHECK_EQ(i.opd[3].offset, first);
CHECK_EQ(i.opd[3].rows, n);
CHECK_EQ(i.opd[4].handle, w.rows.attn_latent);
} else if (i.op == mla.rows_output.op) {
CHECK_EQ(i.n, n);
CHECK_EQ(i.opd[2].handle, mla.rows_output.w);
CHECK_EQ(i.opd[4].handle, w.rows.out);
CHECK_EQ(i.opd[4].offset, 0);
} else if (i.op == mla.op_rows_gather) {
CHECK_EQ(i.n, run * 4096);
CHECK_EQ(i.opd[0].handle, w.rows.out);
CHECK_EQ(i.opd[0].rows, run);
CHECK_EQ(i.opd[1].handle, w.out);
CHECK_EQ(i.opd[1].rows, world * run);
}
}
// Eight ranks at 300 rows: runs of 38, the last 34.
if (world == 8) CHECK_EQ(n, rank == 7 ? 34 : 38);
}
}
}
TEST(
glm53_native_graph_declares_all_layers_preserves_mixed_formats_and_runs_mtp_only_in_draft_passes) {
using namespace rad::arch;
@@ -366,6 +547,8 @@ TEST(
build.max_seqs = 4;
build.max_ctx = 4096;
build.max_spec = 3;
// With the row form opted into (--tp-attn-split rows).
build.tp_attn_rows = 1;
REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK);
const auto& m = *glm5next::models[rank];
CHECK(m.have_mtp);
@@ -433,9 +616,10 @@ TEST(
CHECK_EQ(std::count(ops.begin(), ops.end(), "all_gather"), 0);
// The split is declared on every rank whatever its step size; only rank 0 issues it here.
const bool split = world > 1;
// 43 routers (MTP included), the 90 mHC reads, and each of the 12 indexers' page
// tables and lengths; the index head gates follow the indexer's rows, ungathered.
CHECK_EQ(count_op(b, "all_gather"), split ? 43 + 90 + 24 : 0);
// 43 routers (MTP included), the 90 mHC reads, each of the 12 indexers' page
// tables and lengths (the index head gates follow the indexer's rows,
// ungathered), and the 11 MLA row forms (the MTP layer keeps its heads).
CHECK_EQ(count_op(b, "all_gather"), split ? 43 + 90 + 24 + 11 : 0);
CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0);
ctx.issues.clear();
batch.draft_pass = -1;
@@ -482,12 +666,17 @@ TEST(
CHECK(ctx.step_fail.empty());
{
// 512 rows reach the split: each router runs on its column slice, each mHC
// read on its chunks and each indexer, its head gates included, on its run
// of query rows, all gathered but the gates; at TP1 nothing changes.
// read on its chunks, each indexer, its head gates included, on its run
// of query rows, and each MLA on its run of rows, all gathered but the
// gates; at TP1 nothing changes.
const auto long_ops = issued_ops(b, ctx);
CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "gemm_nt_f32"), 53);
CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_gather"),
world > 1 ? 42 + 90 + 22 : 0);
world > 1 ? 42 + 90 + 22 + 11 : 0);
// 1 embedding, 45 attention and 45 expert reductions, less the 11 MLA ones.
CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_reduce"),
world > 1 ? 91 - 11 : 0);
CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mla_attn"), 11);
CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre"),
world > 1 ? 0 : 90);
CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre_finish"),
@@ -531,6 +720,7 @@ TEST(
RadArchProbe capabilities{};
REQUIRE_EQ(glm5next::probe(&meta, &capabilities), RAD_OK);
CHECK_EQ(capabilities.shape_probe_ok, 1);
CHECK_EQ(capabilities.tp_attn_rows_ok, 1);
std::array<int, 8> results{};
std::vector<std::thread> probes;
for (int i = 0; i < 8; ++i)
@@ -724,8 +914,8 @@ TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) {
/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and
* must get the real declare's graph: the same ops with the same fixed parameters, only ranged row
* counts and buffer rows smaller. The TP split declares its ops whatever the step size and its
* gathers' message as a range. */
* counts and buffer rows smaller. The TP splits declare its ops whatever the step size and their
* gathers' message as a range, in the head and the row form of the MLA. */
TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) {
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
"index_topk" };
@@ -741,6 +931,7 @@ TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) {
const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
const int world = 8, rank = 3;
for (int rows_split : { 0, 1 })
for (int64_t R : { 256, 3072 }) {
auto encs = [&](RadBuilder& b) {
b.kv_block = 4;
@@ -760,6 +951,7 @@ TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) {
c.max_seqs = 8;
c.max_ctx = 32768;
c.max_spec = 3;
c.tp_attn_rows = rows_split;
RadBuilder full;
encs(full);
REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK);
@@ -1398,7 +1590,8 @@ TEST(kda_state_core_splits_mixed_batches_and_preserves_absolute_prefill_offsets)
/* ==================================================================== the pinned graph and steps */
/* GLM declares and steps the pinned graph and launches at one and eight ranks: a 4096-row prefill
* after history, a mixed step, a decode step, a verify and its draft passes. */
* after history, a mixed step, a decode step, a verify and its draft passes, at eight in both
* MLA forms. */
TEST(glm53_is_the_pinned_graph_and_steps) {
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
"index_topk" };
@@ -1416,9 +1609,11 @@ TEST(glm53_is_the_pinned_graph_and_steps) {
struct Case {
int world;
uint64_t graph, steps;
bool heads_only = false; /* the default: the graph before the row form */
};
const Case cases[] = { { 1, 0x906897570034f5f5ull, 0x68ffc03d2b640d51ull },
{ 8, 0x9f39f6f7a04dc4d3ull, 0x3818eedb4ac10d1bull } };
{ 8, 0x1d378152c40f8834ull, 0x82ed1094dbf4b637ull },
{ 8, 0x9f39f6f7a04dc4d3ull, 0x3818eedb4ac10d1bull, true } };
for (const Case& cs : cases) {
RadBuilder b;
b.kv_block = 4;
@@ -1434,11 +1629,13 @@ TEST(glm53_is_the_pinned_graph_and_steps) {
ctx.max_tok = 4096;
ctx.max_seqs = 8;
ctx.max_ctx = 200000;
ctx.tp_attn_rows = cs.heads_only ? 0 : 1;
REQUIRE_EQ(glm5next::declare(&b, &meta, &ctx), RAD_OK);
const uint64_t g = graph_hash(b);
const uint64_t s = pinned_steps(b, glm5next::step, 0, cs.world);
fprintf(stderr, " pin: glm5next world %d: graph 0x%016llxull, steps 0x%016llxull\n",
cs.world, (unsigned long long)g, (unsigned long long)s);
fprintf(stderr, " pin: glm5next world %d%s: graph 0x%016llxull, steps 0x%016llxull\n",
cs.world, cs.heads_only ? " heads only" : "",
(unsigned long long)g, (unsigned long long)s);
CHECK_EQ(g, cs.graph);
CHECK_EQ(s, cs.steps);
}
@@ -1827,11 +2024,12 @@ RAD_TEST_MAIN()
/* ==================================================================== the row rule */
/* GlmTp::run_rows is the one rule the indexer's runs follow: 4 * ceil(T / (4 * world)) for the
* indexer's 4-byte lengths, ceil(T / world) for a row of whole 16-byte words. At the split threshold, around a chunk and at the largest step, for every
* world: run_of covers the step once with no overlap, the last run short where the step ends
* inside it, and a rank whose run lies wholly past a small step takes the first run instead, so
* the planes it writes and gathers are never unwritten. */
/* GlmTp::run_rows is the one rule the MLA's and the indexer's runs follow: ceil(T / world) for
* the MLA's 8192-byte rows, 4 * ceil(T / (4 * world)) for the indexer's 4-byte lengths. At the
* split threshold, around a chunk and at the largest step, for every world: run_of covers the
* step once with no overlap, the last run short where the step ends inside it, and a rank whose
* run lies wholly past a small step takes the first run instead, so the planes it writes and
* gathers are never unwritten. */
TEST(glm_tp_row_rule_rounds_to_whole_words_and_covers_a_step_once) {
using namespace rad::arch;
for (int world : { 1, 2, 4, 8 })
@@ -1840,6 +2038,7 @@ TEST(glm_tp_row_rule_rounds_to_whole_words_and_covers_a_step_once) {
const int64_t narrow = GlmTp::run_rows(T, world, 4);
CHECK_EQ(wide, (T + world - 1) / world);
CHECK_EQ(narrow, 4 * ((T + 4 * world - 1) / (4 * world)));
CHECK_EQ(GlmMla::rows_for(T, world), wide);
CHECK_EQ(DsaCache::part_rows(T, world), narrow);
CHECK(world * wide >= T);
CHECK(world * narrow >= T);
@@ -2195,12 +2394,11 @@ std::string as_expert_zero(std::string n) {
} /* namespace */
/* Every weight the plugin declares reads an entry the served container holds: under its own name,
* or through `source` for a view (a scale plane), and every GEMM names the dtype its weight's
* stored encoding calls for: `fp8a8f32` on the f32-scaled block FP8, `mxfp4a8` on the MXFP4
* experts, `bf16` on the plain linears. The encodings come from the table, as the container would
* answer. A weight declared under a name the container does not hold, or a GEMM at a dtype its
* weight's encoding does not call for, passes every host test and leaves bands with no kernel at
* the eight-card start. */
* or through `source` for a view (a scale plane, the row form's full-width projections), and
* every GEMM names the dtype its weight's stored encoding calls for: `fp8a8f32` on the f32-scaled
* block FP8, `mxfp4a8` on the MXFP4 experts, `bf16` on the plain linears. The encodings come
* from the table, as the container would answer. A full-width view declared as its own weight
* at `fp8a8` passed every host test and left 88 bands with no kernel at the eight-card start. */
TEST(glm53_declares_the_served_containers_names_and_their_encodings) {
const Glm53Container& c = glm53_container();
MetaKV mk = glm53_vl_meta();
+35
View File
@@ -219,6 +219,41 @@ TEST(a_restart_serves_the_complete_copy_when_the_hub_cannot_be_reached) {
}
}
/* A hub whose repo holds safetensors beside a torch copy of the same weights and a codec that only
* ships as a .pth: the copies (pytorch_model*.pth, a pickle .bin) are skipped, the codec is
* fetched, since the checkpoint reader reads it (core/format/torch_zip.h). */
const char* kCodecRepo =
"#!/bin/sh\n"
"out=''; url=''; prev=''\n"
"for a in \"$@\"; do\n"
" [ \"$prev\" = -o ] && out=\"$a\"\n"
" case \"$a\" in https://*) url=\"$a\";; esac\n"
" prev=\"$a\"\n"
"done\n"
"case \"$url\" in *api/models*)\n"
" printf '[{\"type\":\"file\",\"path\":\"model.safetensors\",\"size\":3},"
"{\"type\":\"file\",\"path\":\"codec.pth\",\"size\":3},"
"{\"type\":\"file\",\"path\":\"pytorch_model.pth\",\"size\":3},"
"{\"type\":\"file\",\"path\":\"pytorch_model.bin\",\"size\":3}]'; exit 0;; esac\n"
"[ -n \"$out\" ] && printf abc > \"$out\"\n"
"exit 0\n";
TEST(a_pth_that_is_not_the_weights_again_is_fetched_beside_the_safetensors) {
NEED_ARTIFACT(hfget_beside_this_binary());
if (!on_path("jq")) SKIP("no jq on PATH, which hfget.sh needs");
TempDir root;
REQUIRE(!root.path.empty());
FakeCurl curl(kCodecRepo);
const std::string cmd = "sh '" + hfget_beside_this_binary() +
"' radiance-test-owner/radiance-test-model '" + root.path +
"' >/dev/null 2>&1";
CHECK_EQ(std::system(cmd.c_str()), 0);
CHECK(fs::exists(root.path + "/model.safetensors"));
CHECK(fs::exists(root.path + "/codec.pth"));
CHECK(!fs::exists(root.path + "/pytorch_model.pth"));
CHECK(!fs::exists(root.path + "/pytorch_model.bin"));
}
/* With no --download-dir and neither XDG_CACHE_HOME nor HOME there is nowhere to fetch to, which
* is refused by name before anything runs. */
TEST(a_repo_id_with_nowhere_to_fetch_to_is_refused) {
+182
View File
@@ -3257,6 +3257,188 @@ TEST(the_tiers_are_told_the_cache_s_block_ids_and_not_the_requests) {
}
}
/* ================================================================== release on request
*
* A client that deleted a conversation, or kept a prefix of it and replaced the rest, forgets it
* through the session table: by label, from the tip inwards, host copy and snapshots with it.
* What another conversation also walks stays, as does what a live sequence holds.
*/
/* Publishes `tokens` under `id` with a session label, as the scheduler does at a turn's close,
* and frees the sequence, as it does right after. */
static void publish_turn(Fixture& f, uint64_t id, const std::vector<int32_t>& tokens,
const std::string& label) {
CHECK_OK(f.kv.add_sequence(id));
CHECK_OK(f.kv.ensure(id, (int64_t)tokens.size()));
std::vector<std::vector<int32_t>> bt;
for (int32_t g : f.pc.cached_groups()) bt.push_back(f.kv.block_table(id, g));
CHECK_OK(f.pc.insert(id, tokens, {}, bt, (int64_t)tokens.size(), label));
f.kv.free_sequence(id);
}
/* The label's rows in the session table. */
static std::vector<IdleTiers::SessionInfo> rows_of(IdleTiers& t, const std::string& label) {
std::vector<IdleTiers::SessionInfo> out;
for (const IdleTiers::SessionInfo& s : t.sessions())
if (s.label == label) out.push_back(s);
return out;
}
TEST(a_released_conversation_goes_from_the_tip_down_to_what_another_one_shares) {
Fixture f;
CHECK_OK(f.build(/*with_linear=*/false, /*ckpt_slots=*/0));
IdleTiers t;
CHECK_OK(t.configure(tier_config(1 << 20, 1024)));
f.pc.set_tiers(&t);
/* Conversation A over three turns under three request ids: each turn extends the last. The
* first two blocks are a system prompt conversation B opens with too. */
const auto a1 = tok_run(100, 64); /* 4 blocks */
auto a2 = a1; for (int i = 0; i < 32; ++i) a2.push_back(700 + i); /* 6 */
auto a3 = a2; for (int i = 0; i < 32; ++i) a3.push_back(800 + i); /* 8 */
publish_turn(f, 1, a1, "chat-a");
publish_turn(f, 2, a2, "chat-a");
publish_turn(f, 3, a3, "chat-a");
auto b = tok_run(100, 32); for (int i = 0; i < 64; ++i) b.push_back(900 + i); /* 6 */
publish_turn(f, 4, b, "chat-b");
CHECK_EQ(f.pc.size(), 12ll); /* 8 + 4 own blocks of B */
REQUIRE_EQ(rows_of(t, "chat-a").size(), 1u); /* one row per conversation */
CHECK_EQ(rows_of(t, "chat-a")[0].n_tokens, 128ll);
/* Every entry has its host copy. */
copy_now(t);
CHECK_EQ(t.arena().used_slots(), 12);
const int64_t pool_before = f.kv.free_blocks(G_FULL);
SessionRelease r;
CHECK_EQ(f.pc.release_session("chat-c", 0, 0, &r), RAD_E_NOTFOUND);
CHECK_EQ(f.pc.release_session("", 0, 0, &r), RAD_E_INVAL);
CHECK_OK(f.pc.release_session("chat-a", 0, 0, &r));
CHECK_EQ(r.sessions, 1ll);
CHECK_EQ(r.entries, 6ll); /* 8 less the 2 B walks too */
CHECK_EQ(r.tokens, 96ll);
CHECK_EQ(r.kept_shared, 2ll);
CHECK_EQ(r.kept_live, 0ll);
CHECK_EQ(r.kept_tokens, 0ll);
CHECK(r.device_bytes > 0);
CHECK_EQ(r.host_bytes, 6 * 1024ll);
/* Pool and arena got the six back; the index holds B's chain and the shared start. */
CHECK_EQ(f.kv.free_blocks(G_FULL), pool_before + 6);
CHECK_EQ(t.arena().used_slots(), 6);
CHECK_EQ(f.pc.size(), 6ll);
CHECK_EQ(f.pc.stats().released, 6ll);
/* A's next turn hits the shared system prompt and nothing more; B is whole. */
CHECK_EQ(f.pc.lookup(a3, {}).n_attn_tokens, 32);
CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 80);
CHECK_EQ(rows_of(t, "chat-a").size(), 0u);
REQUIRE_EQ(rows_of(t, "chat-b").size(), 1u);
CHECK_EQ(rows_of(t, "chat-b")[0].n_tokens, 96ll);
/* Released twice is not found the second time. */
CHECK_EQ(f.pc.release_session("chat-a", 0, 0, &r), RAD_E_NOTFOUND);
}
TEST(keep_tokens_leaves_the_chains_start_standing_in_whole_blocks) {
Fixture f;
CHECK_OK(f.build(/*with_linear=*/false, /*ckpt_slots=*/0));
IdleTiers t;
CHECK_OK(t.configure(tier_config(1 << 20, 1024)));
f.pc.set_tiers(&t);
auto b = tok_run(100, 32); for (int i = 0; i < 64; ++i) b.push_back(900 + i); /* 6 blocks */
publish_turn(f, 4, b, "chat-b");
/* 40 tokens keep three blocks: the one holding token 40 goes with them. */
SessionRelease r;
CHECK_OK(f.pc.release_session("chat-b", 0, 40, &r));
CHECK_EQ(r.entries, 3ll);
CHECK_EQ(r.kept_tokens, 48ll);
CHECK_EQ(r.kept_shared, 0ll);
CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 48);
/* The row stays, cut to the kept prefix: the client extends it again. */
REQUIRE_EQ(rows_of(t, "chat-b").size(), 1u);
CHECK_EQ(rows_of(t, "chat-b")[0].n_tokens, 48ll);
const uint64_t id = rows_of(t, "chat-b")[0].id;
/* The same by engine id, keeping more than is left: nothing goes, nothing breaks. */
CHECK_OK(f.pc.release_session("", id, 200, &r));
CHECK_EQ(r.entries, 0ll);
CHECK_EQ(r.kept_tokens, 48ll);
CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 48);
/* A later turn extends the stub into a full row again. */
publish_turn(f, 5, b, "chat-b");
REQUIRE_EQ(rows_of(t, "chat-b").size(), 1u);
CHECK_EQ(rows_of(t, "chat-b")[0].n_tokens, 96ll);
CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 80);
}
TEST(a_release_takes_the_sessions_snapshots_past_the_kept_prefix_and_leaves_live_blocks) {
Fixture f;
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/4));
IdleTiers t;
IdleTiers::Config tc = tier_config(1 << 20, 1024);
tc.ckpt_bytes = f.kv.checkpoint_bytes();
tc.ckpt_slots = 4;
CHECK_OK(t.configure(tc));
f.pc.set_tiers(&t);
const auto a = tok_run(100, 128); /* 8 blocks, checkpoints at 64, 128 */
const std::vector<BlockHash> hs = chain_of(a);
CHECK_OK(f.kv.add_sequence(3));
CHECK_OK(f.kv.ensure(3, 128));
ckpt_at(f, 3, hs, 64);
ckpt_at(f, 3, hs, 128);
f.pc.begin_step();
{
std::vector<std::vector<int32_t>> bt;
for (int32_t g : f.pc.cached_groups()) bt.push_back(f.kv.block_table(3, g));
CHECK_OK(f.pc.insert(3, a, {}, bt, 128, "chat-a"));
}
f.kv.free_sequence(3);
CHECK_EQ(f.kv.free_checkpoint_slots(), 2ll);
CHECK_EQ(rows_of(t, "chat-a")[0].snapshots, 2ll);
/* A waiting request restored the chain and holds it; a running one adopted the first
* five blocks. Both keep their blocks through a release. */
std::vector<std::vector<int32_t>> found;
const CacheHit h = f.pc.lookup(a, {}, &found);
CHECK_EQ(h.n_attn_tokens, 112);
CHECK_OK(f.kv.add_sequence(9));
std::vector<int32_t> five(found[0].begin(), found[0].begin() + 5);
CHECK_OK(f.kv.adopt(9, f.pc.cached_groups()[0], five, 80));
f.pc.begin_step();
SessionRelease r;
CHECK_OK(f.pc.release_session("chat-a", 0, 64, &r));
/* Blocks 4..7 are past the kept 64 tokens; block 4 is live, 5..7 go. */
CHECK_EQ(r.entries, 3ll);
CHECK_EQ(r.kept_live, 1ll);
CHECK_EQ(r.kept_tokens, 64ll);
/* The snapshot at 128 sat on block 7 and went with it; the one at 64 is on the kept prefix. */
CHECK_EQ(r.snapshots, 1ll);
CHECK_EQ(f.kv.free_checkpoint_slots(), 3ll);
const std::vector<int64_t> left = f.pc.checkpoints(3);
REQUIRE_EQ(left.size(), 1u);
CHECK_EQ(left[0], 64ll);
CHECK_EQ(f.pc.stats().ckpt_released, 1ll);
/* The live block is still indexed and the sequence still reads it; the row reaches it. */
CHECK_EQ(f.kv.block_refcount(G_FULL, five[4]), 2);
REQUIRE_EQ(rows_of(t, "chat-a").size(), 1u);
CHECK_EQ(rows_of(t, "chat-a")[0].n_tokens, 80ll);
CHECK_EQ(f.pc.lookup(a, {}).n_attn_tokens, 80);
CHECK_EQ(f.pc.lookup(a, {}).n_linear_tokens, 64);
/* The sequence is gone: the block it held goes on the next release. */
f.kv.free_sequence(9);
CHECK_OK(f.pc.release_session("chat-a", 0, 64, &r));
CHECK_EQ(r.entries, 1ll);
CHECK_EQ(r.kept_live, 0ll);
CHECK_EQ(f.pc.lookup(a, {}).n_attn_tokens, 64);
CHECK_EQ(f.pc.lookup(a, {}).n_linear_tokens, 64);
CHECK_EQ(rows_of(t, "chat-a")[0].n_tokens, 64ll);
}
/* ================================================================== the pool in bytes
*
* Blocks and tokens cannot be summed across KV groups: a recurrent group has no token axis and
+382
View File
@@ -0,0 +1,382 @@
/* mtp_couple_plan_test.cpp -- the draw the engine stages for a serial drafting row, resolved
* against a step plan (core/sched/mtp_couple_plan.h, called by Engine::stage_couple_draws).
*
* The coupling failed twice before its first draft, and both failures were here rather than in the
* ABI:
*
* - The draw plane was sized from nothing, so every row lookup missed and the first step that
* drafted refused with "has no plan entry on its card" -- the engine started and then could
* not take one coupled step. The plane is now sized from cfg_.max_seqs, and the rule refuses a
* plane that is too small instead of silently missing.
* - A row whose card carries another sequence's draw is stale: the plugin refuses the staged
* draw, so the row is refused here, named, before any pass reads it.
*
* The plan is the real StepPlan the scheduler produces; only its entries are built by hand, since
* the rule reads nothing else off it.
*/
#include "rad_test.h"
#include "sched/mtp_couple_bind.h"
#include "sched/mtp_couple_plan.h"
#include <cstring>
#include <string>
#include <vector>
using namespace rad;
namespace {
/* One plan entry for a sequence on a card, with the pre-commit output size the draw coordinates
* on. `greedy` is the request's own choice (top_k 1). */
StepEntry entry(Request* r, uint64_t seq, int32_t card, size_t output, bool greedy) {
r->sp = SamplingParams{};
r->sp.top_k = greedy ? 1 : 0;
r->sp.temp = 1.0f;
r->output.assign(output, 0);
StepEntry e;
e.req = r;
e.seq = seq;
e.card = card;
return e;
}
Scheduler::SerialRow row(uint64_t seq, int32_t card) {
Scheduler::SerialRow r;
r.seq = seq;
r.card = card;
return r;
}
} /* namespace */
/* The staged draw names the plan entry on the row's card: sequence, card, the PRE-commit output
* size as the coordinate, the request's seed and whether it samples. Cards the plan does not use
* stay zero, so a row landing on one of them is refused rather than served a stale draw. */
TEST(the_staged_draw_names_the_plan_entry_on_the_rows_card) {
Request a, b, c;
StepPlan plan;
plan.e.push_back(entry(&a, 11, 3, 7, false));
plan.e.push_back(entry(&b, 22, 5, 9, true));
const Scheduler::SerialRow rows[] = { row(11, 3), row(22, 5) };
std::vector<RadMtpCoupleDraw> by_card(8);
RadMtpCoupleDraw stage[2];
std::string why;
REQUIRE_EQ(mtp_couple_plan_stage(plan, 8, rows, 2, &by_card, stage, &why), RAD_OK);
CHECK_EQ(stage[0].seq, (uint64_t)11);
CHECK_EQ(stage[0].card, 3);
CHECK_EQ(stage[0].base, (uint64_t)7);
CHECK_EQ(stage[0].seed, a.sp.seed);
CHECK_EQ(stage[0].mode, 1u);
/* A greedy request keeps the head's proposal instead of sampling x~Q. */
CHECK_EQ(stage[1].seq, (uint64_t)22);
CHECK_EQ(stage[1].card, 5);
CHECK_EQ(stage[1].mode, 0u);
/* Card 0 carried no entry: zeroed, so its seq names nothing a row could match. */
CHECK_EQ(by_card[0].seq, (uint64_t)0);
CHECK_EQ(by_card[7].seq, (uint64_t)0);
(void)c;
}
/* THE FIRST-DRAFT REGRESSION: a plane sized for fewer slots than the step can use would make every
* row miss. It is refused by name -- never a silent miss, and never a start that cannot draft. */
TEST(a_draw_plane_sized_for_fewer_slots_than_the_step_uses_is_refused) {
Request a;
StepPlan plan;
plan.e.push_back(entry(&a, 11, 30, 7, false));
const Scheduler::SerialRow rows[] = { row(11, 30) };
std::vector<RadMtpCoupleDraw> empty;
RadMtpCoupleDraw stage[1];
std::string why;
const int st = mtp_couple_plan_stage(plan, 32, rows, 1, &empty, stage, &why);
if (st == RAD_OK || why.find("holds 0 card slot(s)") == std::string::npos)
fprintf(stderr, " status %d, why '%s'\n", st, why.c_str());
CHECK_EQ(st, RAD_E_STATE);
CHECK(why.find("holds 0 card slot(s), the step can use 32") != std::string::npos);
}
/* A drafting row whose card names another sequence is stale: the staged draw would name a card the
* advance writes for someone else, which the plugin refuses. Refused here, naming the row. */
TEST(a_row_whose_card_names_another_sequence_is_refused) {
Request a;
StepPlan plan;
plan.e.push_back(entry(&a, 11, 3, 7, false));
const Scheduler::SerialRow rows[] = { row(11, 3), row(33, 3) };
std::vector<RadMtpCoupleDraw> by_card(8);
RadMtpCoupleDraw stage[2];
std::string why;
const int st = mtp_couple_plan_stage(plan, 8, rows, 2, &by_card, stage, &why);
if (st == RAD_OK || why.find("drafting row 1 (sequence 33, card 3)") == std::string::npos)
fprintf(stderr, " status %d, why '%s'\n", st, why.c_str());
CHECK_EQ(st, RAD_E_STATE);
CHECK(why.find("drafting row 1 (sequence 33, card 3) has no plan entry on its card") !=
std::string::npos);
}
/* ================================================== THE VERIFY POSITION CONTRACT
*
* The sampler stages row k of a request at `n_out + k`, `n_out` being that request's committed
* output length when the step is built. Round rd is verified at row k = rd - 1, so the state bound
* after the drafting step must carry `n_out + (rd - 1)` for the `n_out` the NEXT step will see.
*
* These tests walk successive steps through the REAL staging function, the REAL bind rule
* (core/sched/mtp_couple_bind.h) and the REAL row check (rad_mtp_couple_binds), with the request's
* output growing the way a commit grows it.
*
* `pre-commit base + accepted count` equals that length for every commit of a running request and
* differs only when a max_tokens or context cut emits fewer tokens, which closes the request. The
* bind skips a request that is not Running, and a one-ahead position is checked not to satisfy
* rad_mtp_couple_binds. */
namespace {
/* A sampled state as the propose kernel would leave it for `draw`, at round `rd` and position
* `pos`: one Q token, x drawn from it, status 1. */
RadMtpCoupleState sampled(const RadMtpCoupleDraw& draw, int rd, uint64_t pos) {
RadMtpCoupleState s{};
s.draw = draw;
s.round = rd;
s.status = 1;
s.count = 1;
s.x = 100 + rd;
for (int i = 0; i < 8; ++i) s.ids[i] = -1; /* the proposer's padding */
s.ids[0] = s.x;
s.q[0] = 1.0;
s.pos = pos;
return s;
}
/* One step's staging through mtp_couple_plan_stage, for request `r` on `card`. */
RadMtpCoupleDraw stage_one(Request* r, uint64_t seq, int32_t card, std::string* why) {
StepPlan plan;
plan.e.push_back(entry(r, seq, card, r->output.size(), false));
const Scheduler::SerialRow rows[] = { row(seq, card) };
std::vector<RadMtpCoupleDraw> by_card(8);
RadMtpCoupleDraw stage[1];
if (mtp_couple_plan_stage(plan, 8, rows, 1, &by_card, stage, why) != RAD_OK) return {};
return stage[0];
}
/* The card's slot after a step that accepted `n_acc - 1` drafts: the bind checks each round's
* state against the token the card holds for it. */
StepSlot slot_for(const int32_t* tok, int rounds, int n_acc) {
StepSlot S{};
S.acc = n_acc - 1;
S.n_acc = n_acc;
for (int rd = 1; rd <= rounds; ++rd) S.tok[rd] = tok[rd];
return S;
}
} /* namespace */
/* VARYING n_acc, SEVERAL ROUNDS, A CUT COMMIT. Every round of a live request binds at the length
* its commit left, which is the position the next build samples it at. The cut commit closes the
* request; its rows bind nothing, and the old formula's position for them is provably not a row the
* sampler would stage. */
TEST(the_bound_position_is_the_verify_rows_sampling_position) {
const int kRounds = 3;
/* The card's one-based acceptance (S.n_acc) and what the commit actually appended, per step.
* emitted == n_acc while the request runs; the last step is the cut: the card accepted all
* three drafts (n_acc 4), the token budget let two through, and the commit closed the request
* with "length". A step after it does not exist for this request. */
const int n_acc[] = { 1, 4, 3, 4 };
const int emitted[] = { 1, 4, 3, 2 };
const int steps = (int)(sizeof n_acc / sizeof n_acc[0]);
Request r;
r.id = 7;
r.sp = SamplingParams{};
r.sp.temp = 1.0f;
r.state = ReqState::Running;
std::vector<RadMtpCoupleState> bound; /* the states bound after the previous step */
uint64_t prev_base = 0; /* the previous draw's pre-commit coordinate */
int prev_n_acc = 0; /* and the card's one-based acceptance of it */
for (int step = 0; step < steps; ++step) {
std::string why;
const RadMtpCoupleDraw draw = stage_one(&r, r.id, 2, &why);
REQUIRE_EQ(why, std::string());
/* The draw's base is the PRE-commit length: the draft's own coordinate, not the verify's. */
CHECK_EQ(draw.base, (uint64_t)r.output.size());
/* The build of THIS step runs over the states bound at the previous one, at the length
* that commit left. Every round lands on its row. */
if (!bound.empty()) {
for (int k = 0; k < kRounds; ++k) {
const uint64_t n_out = (uint64_t)r.output.size();
CHECK(rad_mtp_couple_binds(bound[(size_t)k], r.id, draw.seed, n_out, k,
bound[(size_t)k].x, 1 << 20));
/* The old formula on the same states: identical while the previous commit emitted
* its whole acceptance, one ahead per missing token otherwise. */
const uint64_t old_pos = prev_base + (uint64_t)prev_n_acc + (uint64_t)k;
CHECK_EQ(old_pos == n_out + (uint64_t)k,
emitted[step - 1] == n_acc[step - 1]);
}
}
/* The commit, and the request's state afterwards: a cut closes it. */
for (int j = 0; j < emitted[step]; ++j) r.output.push_back(0);
const bool live = emitted[step] == n_acc[step];
r.state = live ? ReqState::Running : ReqState::Finished;
/* The bind, after the commit, through the production rule. The point is what the
* scheduler's commit snapshot would carry: this fixture owns the request, so it is built
* here directly. */
MtpCoupleBindPoint bp;
bp.found = true;
bp.live = r.state == ReqState::Running;
bp.n_out = (uint64_t)r.output.size();
CHECK_EQ(bp.live, live);
const int32_t tok[] = { 11, 21, 22, 23 };
const StepSlot S = slot_for(tok, kRounds, n_acc[step]);
RadMtpCoupleState rb[(size_t)kRounds * 3]{};
for (int rd = 1; rd <= kRounds; ++rd) {
rb[(size_t)(rd - 1) * 3] = sampled(draw, rd, 0);
rb[(size_t)(rd - 1) * 3].x = tok[rd]; /* the card's proposal */
rb[(size_t)(rd - 1) * 3].ids[0] = tok[rd];
}
RadMtpCoupleState out[RAD_MTP_COUPLE_MAX_ROUNDS]{};
int n_bound = -1;
std::string bwhy;
CHECK_EQ(mtp_couple_bind_rounds(bp, draw, rb, 3, kRounds, S, 1 << 20, out, &n_bound,
&bwhy), RAD_OK);
/* NOT LIVE, NOT BOUND: a terminal row must not read as a coupled verify. */
CHECK_EQ(n_bound, live ? kRounds : 0);
for (int rd = 1; rd <= (live ? kRounds : 0); ++rd) {
const uint64_t want = (uint64_t)r.output.size() + (uint64_t)(rd - 1);
CHECK_EQ(out[rd - 1].pos, want);
CHECK(rad_mtp_couple_binds(out[rd - 1], r.id, draw.seed,
(uint64_t)r.output.size(), rd - 1, tok[rd], 1 << 20));
}
/* THE REGRESSION: where the old formula would have bound this step's rounds, the row
* check fails as soon as the commit emitted fewer than the card accepted. */
if (!live) {
for (int rd = 1; rd <= kRounds; ++rd) {
const uint64_t old_pos = draw.base + (uint64_t)n_acc[step] + (uint64_t)(rd - 1);
CHECK(old_pos != (uint64_t)r.output.size() + (uint64_t)(rd - 1));
CHECK(!rad_mtp_couple_binds(sampled(draw, rd, old_pos), r.id, draw.seed,
(uint64_t)r.output.size(), rd - 1, tok[rd], 1 << 20));
}
}
prev_base = draw.base;
prev_n_acc = n_acc[step];
bound.assign(out, out + (live ? kRounds : 0));
if (!live) break; /* the request is closed: no further step drafts it */
}
}
/* STALE STATES ARE REJECTED. A round from another step, a round whose position is off by one, and
* a token the row does not propose all fail the rule -- the coupling never applies a law this step
* did not draw. */
TEST(a_state_from_another_step_is_refused) {
Request r;
r.id = 11;
r.sp = SamplingParams{};
r.sp.temp = 1.0f;
std::string why;
const RadMtpCoupleDraw d = stage_one(&r, r.id, 3, &why);
REQUIRE_EQ(why, std::string());
const uint64_t n_out = 5;
const RadMtpCoupleState good = sampled(d, 1, rad_mtp_couple_verify_pos(n_out, 1));
CHECK(rad_mtp_couple_binds(good, r.id, d.seed, n_out, 0, good.x, 1 << 20));
/* One position ahead: the old arithmetic's answer. */
CHECK(!rad_mtp_couple_binds(sampled(d, 1, rad_mtp_couple_verify_pos(n_out, 1) + 1), r.id,
d.seed, n_out, 0, good.x, 1 << 20));
/* Another step's round. */
CHECK(!rad_mtp_couple_binds(sampled(d, 2, rad_mtp_couple_verify_pos(n_out, 2)), r.id,
d.seed, n_out, 0, good.x, 1 << 20));
/* Another seed, another sequence. */
CHECK(!rad_mtp_couple_binds(good, r.id, d.seed + 1, n_out, 0, good.x, 1 << 20));
CHECK(!rad_mtp_couple_binds(good, r.id + 1, d.seed, n_out, 0, good.x, 1 << 20));
/* The row proposes a token this state did not draw, and a state with no Q at all. */
CHECK(!rad_mtp_couple_binds(good, r.id, d.seed, n_out, 0, good.x + 1, 1 << 20));
RadMtpCoupleState greedy = good;
greedy.status = 0;
greedy.draw.mode = 0;
CHECK(!rad_mtp_couple_binds(greedy, r.id, d.seed, n_out, 0, good.x, 1 << 20));
}
/* REQUEST AND SLOT REUSE. Two requests take turns on the same card, so each step's staged draw
* names the sequence currently on it. The previous request's rounds are not accepted by the new
* one's rows, whichever position they carry. */
TEST(a_reused_card_serves_the_sequence_that_is_on_it) {
Request a, b;
a.id = 21;
b.id = 22;
a.sp = SamplingParams{};
b.sp = SamplingParams{};
a.output.assign(4, 0);
b.output.assign(9, 0);
std::string why;
const RadMtpCoupleDraw da = stage_one(&a, a.id, 5, &why);
REQUIRE_EQ(why, std::string());
const RadMtpCoupleDraw db = stage_one(&b, b.id, 5, &why);
REQUIRE_EQ(why, std::string());
CHECK_EQ(da.seq, (uint64_t)21);
CHECK_EQ(db.seq, (uint64_t)22);
/* a's rounds, at a's length, do not bind a row of b -- not even at b's position. */
const RadMtpCoupleState sa = sampled(da, 1, rad_mtp_couple_verify_pos((uint64_t)b.output.size(), 1));
CHECK(!rad_mtp_couple_binds(sa, b.id, db.seed, (uint64_t)b.output.size(), 0, sa.x, 1 << 20));
/* b's own state does. */
const RadMtpCoupleState sb = sampled(db, 1, rad_mtp_couple_verify_pos((uint64_t)b.output.size(), 1));
CHECK(rad_mtp_couple_binds(sb, b.id, db.seed, (uint64_t)b.output.size(), 0, sb.x, 1 << 20));
}
/* A sampled round the proposer could not turn into Q (status -1, greedy proposal kept) binds
* without failing the step and is counted; the sampler's row check then does not couple it. A
* status -1 round under another draw is still refused. */
TEST(a_round_without_a_valid_shortlist_binds_uncoupled) {
Request r;
r.id = 31;
r.sp = SamplingParams{};
r.sp.temp = 1.0f;
r.output.assign(6, 0);
std::string why;
const RadMtpCoupleDraw draw = stage_one(&r, r.id, 2, &why);
REQUIRE_EQ(why, std::string());
REQUIRE_EQ(draw.mode, 1u);
const int32_t tok[] = { 0, 101, 57, 103 };
const StepSlot S = slot_for(tok, 3, 4);
RadMtpCoupleState rb[3];
for (int rd = 1; rd <= 3; ++rd) rb[rd - 1] = sampled(draw, rd, 0);
rb[1] = RadMtpCoupleState{};
rb[1].draw = draw;
rb[1].round = 2;
rb[1].status = -1;
rb[1].x = 57;
for (int i = 0; i < 8; ++i) rb[1].ids[i] = -1;
MtpCoupleBindPoint bp;
bp.found = true;
bp.live = true;
bp.n_out = r.output.size();
RadMtpCoupleState out[RAD_MTP_COUPLE_MAX_ROUNDS]{};
int n_bound = -1, n_malformed = -1;
CHECK_EQ(mtp_couple_bind_rounds(bp, draw, rb, 1, 3, S, 1 << 20, out, &n_bound, &why,
&n_malformed), RAD_OK);
CHECK_EQ(n_bound, 3);
CHECK_EQ(n_malformed, 1);
CHECK(rad_mtp_couple_binds(out[0], r.id, draw.seed, bp.n_out, 0, 101, 1 << 20));
CHECK(!rad_mtp_couple_binds(out[1], r.id, draw.seed, bp.n_out, 1, 57, 1 << 20));
CHECK(rad_mtp_couple_binds(out[2], r.id, draw.seed, bp.n_out, 2, 103, 1 << 20));
RadMtpCoupleDraw other = draw;
other.base += 1;
rb[1].draw = other;
CHECK_EQ(mtp_couple_bind_rounds(bp, draw, rb, 1, 3, S, 1 << 20, out, &n_bound, &why,
&n_malformed), RAD_E_STATE);
}
RAD_TEST_MAIN()
+9 -4
View File
@@ -3,7 +3,7 @@
#
# THE PLUGINS RADIANCE SHIPS, BUILT THE WAY A THIRD PARTY BUILDS THEIRS. The tree's build is
# installed into a prefix; then every plugin directory -- the kernel libraries, the quantisers,
# every architecture -- is configured ON ITS OWN against that prefix with find_package(radiance),
# every architecture, the plugins under plugin/ -- is configured ON ITS OWN against that prefix with find_package(radiance),
# built, and installed into a home of its own. Nothing in the tree's build is reused: what is
# tested is the installed package a stranger would have.
#
@@ -47,8 +47,8 @@ run "$W/logs/install.log" cmake --install "$B" --prefix "$P"
dirs="libref libquant"
[ -d "$S/libavx" ] && [ -f "$B/radiance_home/kernels/libavx.so" ] && dirs="$dirs libavx"
for d in "$S"/arch/*/; do
[ -f "$d/CMakeLists.txt" ] && dirs="$dirs arch/$(basename "$d")"
for d in "$S"/arch/*/ "$S"/plugin/*/; do
[ -f "$d/CMakeLists.txt" ] && dirs="$dirs $(basename "$(dirname "$d")")/$(basename "$d")"
done
# The device libraries: built out of tree only with the tree's HIP compiler, and left out of every
# comparison below without it.
@@ -59,15 +59,20 @@ done
[ -n "$HIPC" ] && dirs="$dirs $devlibs"
is_dev() { case " $devlibs " in *" $1 "*) return 0 ;; esac; return 1; }
# Each plugin installs its plugin file under $H and anything else it ships (libr4d's r4d_selftest)
# under the package's prefix, as a third party installing into that radiance would.
for d in $dirs; do
n=$(basename "$d")
say "building $d against the installed package"
extra=""
is_dev "$n" && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT
-DRAD_HIP_VOPD_REPEATABLE=$VOPD"
# A bundled plugin under plugin/ may carry device rows beside its host ones; it gets the tree's
# HIP compiler as a third party would pass theirs.
case "$d" in plugin/*) [ -n "$HIPC" ] && extra="-DCMAKE_HIP_COMPILER=$HIPC" ;; esac
# shellcheck disable=SC2086
run "$W/logs/$n.configure.log" cmake -S "$S/$d" -B "$W/b/$n" -G "$GEN" \
-DCMAKE_PREFIX_PATH="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
-DCMAKE_PREFIX_PATH="$P" -DCMAKE_INSTALL_PREFIX="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
run "$W/logs/$n.build.log" cmake --build "$W/b/$n" -j "$J"
run "$W/logs/$n.install.log" cmake --install "$W/b/$n"
done
+74 -13
View File
@@ -900,12 +900,9 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) {
"8192:ar_oneshot_3rank_exact 524288:ar_oneshot_3rank_exact "
"41943040:ar_twoshot_3rank_exact ");
/* At `overlap` 1 (a pipelined prefill's all-reduce beside compute) the two-shot band takes the
* lane row at three, four and eight ranks, exact and, where it exists, lossy (at three and
* eight launched as the wide rows unless R4D_AR_LANE_3_8=1); the
* one-shot band has no lane row past two ranks. The lists split at the eight-rank one-shot edge
* as above; at eight ranks the band between it and the wide one-shot bound stays on the plain
* two-shot. */
/* At `overlap` 1 (an all-reduce beside compute) the four-rank two-shot band takes the lane
* rows, exact and lossy; the one-shot band has no lane row past two ranks. Three and eight ranks
* have no lane row and keep the plain two-shot. */
auto lane = [&](int world, int exact) {
Geometry g;
g.set_i("world_size", world);
@@ -915,16 +912,14 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) {
g.set_i("overlap", 1);
return r.build_bands("all_reduce", "numel", width, chunk * width, g);
};
CHECK_EQ(band_names(lane(3, 1)), "8192:ar_oneshot_3rank_exact 524288:ar_oneshot_3rank_exact "
"5242880:ar_twoshot_3rank_exact_lane ");
CHECK_EQ(band_names(lane(4, 1)), "8192:ar_oneshot_4rank_exact 524288:ar_oneshot_4rank_exact "
"5242880:ar_twoshot_4rank_exact_lane ");
CHECK_EQ(band_names(lane(8, 1)), "8192:ar_oneshot_8rank_exact 524288:ar_twoshot_8rank_exact "
"5242880:ar_twoshot_8rank_exact_lane ");
CHECK_EQ(band_names(lane(3, 0)), "8192:ar_twoshot_3rank_ti8_lane 524288:ar_twoshot_3rank_ti8_lane "
"5242880:ar_twoshot_3rank_ti8_lane ");
CHECK_EQ(band_names(lane(4, 0)), "8192:ar_twoshot_4rank_ti8_lane 524288:ar_twoshot_4rank_ti8_lane "
"5242880:ar_twoshot_4rank_ti8_lane ");
CHECK_EQ(band_names(lane(3, 1)), "8192:ar_oneshot_3rank_exact 524288:ar_oneshot_3rank_exact "
"5242880:ar_twoshot_3rank_exact ");
CHECK_EQ(band_names(lane(8, 1)), "8192:ar_oneshot_8rank_exact 524288:ar_twoshot_8rank_exact "
"5242880:ar_twoshot_8rank_exact ");
/* Above the two-shot's bound the one-shot takes the message back. */
CHECK_EQ(band_names(bands(4, 1, 131072)),
@@ -1049,7 +1044,8 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) {
}
/* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves
* every M up to its bound, a decode step's rows and a prefill chunk alike. */
* every M up to its bound, a decode step's rows and a prefill chunk alike. At 64 heads the rows
* row ranks above both. */
TEST(libr4d_resolves_the_mla_attention_by_rows) {
const std::string so = libr4d();
if (so.empty()) return;
@@ -1063,6 +1059,71 @@ TEST(libr4d_resolves_the_mla_attention_by_rows) {
g.set_s("dtype", "bf16");
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 2048, g)), "2048:mla_attn_matrix_bf16 ");
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 48, g)), "48:mla_attn_matrix_bf16 ");
// All 64 heads of a row, as GLM's prefill split by rows runs it: the rows row.
g.set_i("heads", 64);
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 512, g)), "512:mla_attn_rows_bf16 ");
g.set_i("heads", 16);
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 512, g)), "512:mla_attn_matrix_bf16 ");
}
/* GLM-5.3-Flash's MLA split by rows at eight ranks (arch/common/rad_block_glm_mla.h), with the
* parameters its ops declare against the container's encodings (block fp8 at f32 scales): every
* band of every op the row form adds resolves on the device, up to a 4096-token step's run of
* 512 rows. A form libr4d does not serve would stop a TP8 start at "resolved to no kernel". */
TEST(libr4d_resolves_every_band_of_glm_mla_split_by_rows) {
const std::string so = libr4d();
if (so.empty()) return;
Registry r;
CHECK(r.load_plugin(so, 0) >= 0);
r.set_device_fact(RAD_FACT_P2P, 1);
auto all_resolve = [&](const char* op, const char* ranged, int64_t lo, int64_t hi,
const Geometry& g) {
const std::vector<Band> bands = r.build_bands(op, ranged, lo, hi, g);
bool ok = !bands.empty();
for (const Band& x : bands) ok = ok && x.dom[RAD_DOMAIN_DEVICE].row;
if (!ok) std::fprintf(stderr, " %s: %s\n", op, band_names(bands).c_str());
return ok;
};
const int64_t R = 512;
for (const auto& [n, k] : { std::pair<int64_t, int64_t>{ 16384, 1536 }, { 4096, 16384 } }) {
Geometry g;
g.set_i("N", n);
g.set_i("K", k);
g.set_i("group", 128);
g.set_s("dtype", "fp8a8f32");
CHECK(all_resolve("gemm_nt_q", "M", 1, R, g));
}
for (const char* mode : { "absorb", "expand" }) {
Geometry g;
g.set_i("heads", 64);
g.set_i("head_dim", 256);
g.set_i("latent_dim", 512);
g.set_s("mode", mode);
g.set_s("dtype", "bf16");
CHECK(all_resolve("mla_project", "M", 1, R, g));
}
{
Geometry g;
g.set_i("latent_dim", 512);
g.set_i("heads", 64);
g.set_i("blocks", 513);
g.set_i("block_size", 4);
g.set_s("dtype", "bf16");
CHECK(all_resolve("mla_attn", "M", 1, R, g));
}
{
Geometry g;
g.set_i("n", 16384);
g.set_i("group", 128);
g.set_s("dtype", "bf16");
CHECK(all_resolve("quant_act_fp8", "M", 1, 4096, g));
}
{
Geometry g;
g.set_i("world_size", 8);
g.set_s("dtype", "bf16");
CHECK(all_resolve("all_gather", "numel", 4096, 4096 * 4096, g));
}
}
/* ================================================================== constraints that are not intervals */
+45
View File
@@ -270,6 +270,51 @@ int main() {
}
}
fails += grouped_cases(cases);
{
/* A run of rows and a slice of columns give the bytes the whole product has there: GLM's
* MLA split by rows computes q_b and o over a rank's rows at full width, the head form
* over every row at a slice of the columns (or of K, as eight rank partials). */
const int M = 130, N = 1024, K = 512, kb = K / 128, r0 = 37, mr = 33, c0 = 256, nc = 256;
std::vector<uint8_t> a((size_t)M * K), w((size_t)N * K);
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
std::uniform_real_distribution<float> oct(-6.f, 6.f);
for (auto& v : as) v = std::exp2(oct(rng));
for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f;
auto gemm = [&](int rows, int cols, int row0, int col0, std::vector<uint16_t>& y) {
y.assign((size_t)rows * cols, 0x7777);
RadTensor t[7] = { mat(a.data() + (size_t)row0 * K, RAD_F8E4M3, rows, K, K),
mat(as.data() + (size_t)row0 * kb, RAD_F32, rows, kb, kb),
mat(w.data() + (size_t)col0 * K, RAD_F8E4M3, cols, K, K),
mat(ws.data() + (size_t)(col0 / 128) * kb, RAD_F32, cols / 128, kb,
kb),
mat(y.data(), RAD_BF16, rows, cols, cols), RadTensor{}, RadTensor{} };
RadParam p[5]{};
p[0] = { "M", RAD_P_INT, rows };
p[1] = { "N", RAD_P_INT, cols };
p[2] = { "K", RAD_P_INT, K };
p[3] = { "group", RAD_P_INT, 128 };
p[4].key = "dtype";
p[4].kind = RAD_P_STR;
p[4].sval = "fp8a8f32";
RadArgs ar{};
ar.t = t;
ar.n_t = 7;
ar.p = p;
ar.n_p = 5;
return r4d_rad_fp8_f32scale(&ar, nullptr);
};
std::vector<uint16_t> whole, part;
++cases;
bool same = gemm(M, N, 0, 0, whole) == RAD_OK && gemm(mr, nc, r0, c0, part) == RAD_OK;
for (int r = 0; same && r < mr; ++r)
for (int c = 0; c < nc; ++c)
same = same && part[(size_t)r * nc + c] == whole[(size_t)(r0 + r) * N + c0 + c];
std::printf("%s rows %d..%d x columns %d..%d alone against the %dx%d product\n",
same ? "ok " : "FAIL", r0, r0 + mr, c0, c0 + nc, M, N);
fails += !same;
}
std::printf("%d case(s), %d failure(s)\n", cases, fails);
return fails ? 1 : 0;
}
+421 -51
View File
@@ -5,7 +5,9 @@
* blocks and neighbours share most blocks but rarely a table position. The conflict counters
* (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. Both pairings run on the
* same operands: the union at the case's table width, the positional pairing on the table
* widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches. */
* widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches.
* The rows row (attend_rows, 64 heads of one row a workgroup) runs on its own cases, and a mixed
* TP step runs both ways, split by heads over the matrix row and by rows over the rows row. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
@@ -21,6 +23,7 @@
extern "C" void r4d_mla_matrix_pin_form(int form);
extern "C" void r4d_mla_matrix_stats(unsigned long long* out);
extern "C" void r4d_mla_rows_pin_form(int form);
namespace {
@@ -106,9 +109,9 @@ void topk_tables(int rows, int blocks, int context, int swaps, std::mt19937& rng
}
}
int run(const Case& c, std::mt19937& rng) {
const int M = c.rows, H = c.heads, B = c.blocks;
std::vector<int> bt, len;
/* The case's page tables and visible lengths; returns the pages the cache holds. */
int fill_tables(const Case& c, std::mt19937& rng, std::vector<int>& bt, std::vector<int>& len) {
const int M = c.rows, B = c.blocks;
int pages = 0;
if (c.fill == Fill::topk) {
topk_tables(M, B, c.context, c.swaps, rng, bt, len, pages);
@@ -144,25 +147,73 @@ int run(const Case& c, std::mt19937& rng) {
len[r] = r % 5 == 4 ? 0 : B * BS - 1 - r % 7;
}
}
return pages;
}
RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
RadTensor t{};
t.data = p;
t.dtype = dt;
t.rank = (uint32_t)shape.size();
int64_t st = 1;
for (int i = (int)shape.size() - 1; i >= 0; --i) {
t.shape[i] = shape[i];
t.stride[i] = st;
st *= shape[i];
}
return t;
}
/* An f64 softmax over each row's own table. */
std::vector<double> reference(int M, int H, int B, int pages, const std::vector<int>& bt,
const std::vector<int>& len, const std::vector<uint16_t>& qb,
const std::vector<uint16_t>& kvb, double scale) {
std::vector<double> want((size_t)M * H * D);
std::vector<double> sc;
for (int r = 0; r < M; ++r)
for (int h = 0; h < H; ++h) {
const int live = std::min(std::max(len[r], 0), B * BS);
sc.assign(live, -INFINITY);
double mx = -INFINITY;
auto row_of = [&](int j) -> const uint16_t* {
const int pg = bt[(size_t)r * B + j / BS];
return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr;
};
const uint16_t* qr = &qb[((size_t)r * H + h) * D];
for (int j = 0; j < live; ++j) {
const uint16_t* k = row_of(j);
if (!k) continue;
double dot = 0;
for (int d = 0; d < D; ++d)
dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]);
sc[j] = dot * scale;
mx = std::max(mx, sc[j]);
}
std::vector<double> acc(D, 0.0);
double sum = 0;
for (int j = 0; j < live; ++j) {
if (sc[j] == -INFINITY) continue;
const double w = std::exp(sc[j] - mx);
sum += w;
const uint16_t* k = row_of(j);
for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]);
}
for (int d = 0; d < D; ++d)
want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0;
}
return want;
}
int run(const Case& c, std::mt19937& rng) {
const int M = c.rows, H = c.heads, B = c.blocks;
std::vector<int> bt, len;
const int pages = fill_tables(c, rng, bt, len);
std::normal_distribution<float> nrm(0.f, 1.f);
std::vector<uint16_t> qb((size_t)M * H * D), kvb((size_t)pages * BS * D);
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
auto tens = [](void* p, uint32_t dt, std::vector<int64_t> shape) {
RadTensor t{};
t.data = p;
t.dtype = dt;
t.rank = (uint32_t)shape.size();
int64_t st = 1;
for (int i = (int)shape.size() - 1; i >= 0; --i) {
t.shape[i] = shape[i];
t.stride[i] = st;
st *= shape[i];
}
return t;
};
RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, D }),
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }),
@@ -202,40 +253,7 @@ int run(const Case& c, std::mt19937& rng) {
a.scratch_bytes = need;
}
/* the f64 reference */
std::vector<double> want((size_t)M * H * D);
std::vector<double> sc;
for (int r = 0; r < M; ++r)
for (int h = 0; h < H; ++h) {
const int live = std::min(std::max(len[r], 0), B * BS);
sc.assign(live, -INFINITY);
double mx = -INFINITY;
auto row_of = [&](int j) -> const uint16_t* {
const int pg = bt[(size_t)r * B + j / BS];
return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr;
};
const uint16_t* qr = &qb[((size_t)r * H + h) * D];
for (int j = 0; j < live; ++j) {
const uint16_t* k = row_of(j);
if (!k) continue;
double dot = 0;
for (int d = 0; d < D; ++d)
dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]);
sc[j] = dot * scale;
mx = std::max(mx, sc[j]);
}
std::vector<double> acc(D, 0.0);
double sum = 0;
for (int j = 0; j < live; ++j) {
if (sc[j] == -INFINITY) continue;
const double w = std::exp(sc[j] - mx);
sum += w;
const uint16_t* k = row_of(j);
for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]);
}
for (int d = 0; d < D; ++d)
want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0;
}
const std::vector<double> want = reference(M, H, B, pages, bt, len, qb, kvb, scale);
/* Both pairings on the same operands: the positional one, on the table widened past the
* union's lists, and at the case's own width the launcher's choice, the union, which must
@@ -326,6 +344,324 @@ int run(const Case& c, std::mt19937& rng) {
return fails;
}
/* The rows row (attend_rows): one query row and 64 heads a workgroup, as GLM's prefill runs MLA
* split by rows. Each form against the f64 softmax and the forms bit for bit against each other
* (the element-wise key load; 32 heads a workgroup, whose heads sum alike); unsplit, a run of the
* rows against the same rows of the whole batch, since a rank computing its run must produce the
* bytes the batch would. */
int run_rows(const Case& c, std::mt19937& rng) {
const int M = c.rows, H = c.heads, B = c.blocks;
std::vector<int> bt, len;
const int pages = fill_tables(c, rng, bt, len);
std::normal_distribution<float> nrm(0.f, 1.f);
std::vector<uint16_t> qb((size_t)M * H * D), kvb((size_t)pages * BS * D);
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
const double scale = 0.0625;
const std::vector<double> want = reference(M, H, B, pages, bt, len, qb, kvb, scale);
std::vector<char> scratch;
auto launch = [&](int first, int rows, int form, std::vector<uint16_t>& out) {
const size_t q0 = (size_t)first * H * D;
RadTensor t[5] = { tens(qb.data() + q0, RAD_BF16, { rows, H, D }),
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
tens(bt.data() + (size_t)first * B, RAD_I32, { rows, B }),
tens(len.data() + first, RAD_I32, { rows }),
tens(out.data() + q0, RAD_BF16, { rows, H, D }) };
RadParam p[6]{};
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
const long long vals[5] = { rows, D, H, B, BS };
for (int i = 0; i < 5; ++i) {
p[i].key = keys[i];
p[i].kind = RAD_P_INT;
p[i].ival = vals[i];
}
p[5].key = "scale";
p[5].kind = RAD_P_F64;
p[5].dval = scale;
RadArgs a{};
a.t = t;
a.n_t = 5;
a.p = p;
a.n_p = 6;
if (c.scratch) {
const int64_t need = r4d_rad_mla_attn_matrix_scratch(&a);
scratch.assign((size_t)need + 16, 0);
a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
a.scratch_bytes = need;
}
if (form < 0) return r4d_rad_mla_attn_matrix(&a, nullptr);
r4d_mla_rows_pin_form(form);
const int rc = r4d_rad_mla_attn_rows(&a, nullptr);
r4d_mla_rows_pin_form(0);
return rc;
};
int fails = 0;
std::vector<uint16_t> rule;
for (int form : { 3, 1, 2, 0 }) {
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
const int rc = launch(0, M, form, out);
if (rc != RAD_OK) {
std::printf("%-40s form %d launch returned %d FAIL\n", c.name.c_str(), form, rc);
++fails;
continue;
}
double max_err = 0;
long bad = 0;
for (size_t i = 0; i < out.size(); ++i) {
const float got = rad_bf16_to_f32(out[i]);
const double e = std::fabs(got - want[i]);
if (!std::isfinite(got) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad;
if (std::isfinite(got)) max_err = std::max(max_err, e);
}
bool ok = bad == 0;
std::string note;
/* A split follows the workgroup count, which 32 heads a workgroup doubles; under 32 rows
* the rule is the matrix row's kernel. */
if (form == 3)
rule = out;
else if (form == 0 && M < 32) {
std::vector<uint16_t> matrix((size_t)M * H * D, 0xffff);
const int mrc = launch(0, M, -1, matrix);
if (mrc != RAD_OK || matrix != out) {
note = " (the rule under 32 rows is not the matrix row)";
ok = false;
}
} else if ((form == 1 || !c.scratch) && out != rule) {
note = " (differs from form 3)";
ok = false;
}
std::printf("%-40s form %d M %3d H %2d blocks %3d max_abs %.2e bad %ld%s %s\n",
c.name.c_str(), form, M, H, B, max_err, bad, note.c_str(), ok ? "PASS" : "FAIL");
fails += !ok;
}
if (!c.scratch && M >= 3 && !rule.empty()) {
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
const int rc = launch(1, M - 2, 3, out);
bool same = rc == RAD_OK, untouched = true;
for (int r = 0; r < M; ++r)
for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) {
if (r == 0 || r == M - 1)
untouched = untouched && out[i] == 0xffff;
else
same = same && out[i] == rule[i];
}
std::printf("%-40s rows 1..%d alone: %s, rows outside %s %s\n", c.name.c_str(), M - 2,
same ? "bit-identical to the batch" : "DIFFER from the batch",
untouched ? "untouched" : "WRITTEN", same && untouched ? "PASS" : "FAIL");
fails += !(same && untouched);
}
return fails;
}
/* A TP step's attention both ways on one operand set: by heads, each of `world` ranks running
* the matrix row on its heads of every row (views into the whole [T, 64, 512]), and by rows, each
* rank the rows row on its run of ceil(T / world) rows with every head, the last run short. The
* step mixes what a step batch carries, decode rows first: single-row decodes on scattered tables,
* a verify window of four rows on one table, then a prefill continuing past the DSA budget and a
* fresh prompt's first chunk. Both forms against the f64 softmax; how far apart they are is
* printed. */
int run_split(const char* name, int world, int fresh_rows, std::mt19937& rng) {
constexpr int H = 64, B = 65;
std::vector<int> bt, len;
int pages = 0;
auto append = [&](const std::vector<int>& t, const std::vector<int>& l, int segment_pages) {
for (int v : t) bt.push_back(v >= 0 ? v + pages : v);
len.insert(len.end(), l.begin(), l.end());
pages += segment_pages;
};
{ /* three decodes, each its own table with holes */
std::vector<int> t((size_t)3 * B), l(3);
for (int r = 0; r < 3; ++r) {
for (int b = 0; b < B; ++b) t[(size_t)r * B + b] = b % 13 == 5 ? -1 : (b * 5 + r * 17) % (3 * B);
l[r] = B * BS - 1 - 3 * r;
}
append(t, l, 3 * B);
}
{ /* a verify window: four rows of one sequence on one table */
std::vector<int> t((size_t)4 * B), l(4);
for (int r = 0; r < 4; ++r) {
for (int b = 0; b < B; ++b) t[(size_t)r * B + b] = (b * 3 + 1) % B;
l[r] = B * BS - 4 + r + 1;
}
append(t, l, B);
}
{ /* a prefill past the DSA budget: every row its own top blocks */
std::vector<int> t, l;
int segment = 0;
topk_tables(23, B, 1200, 4, rng, t, l, segment);
append(t, l, segment);
}
{ /* a fresh prompt's chunk: causal on one table, rows starting at position 0 */
std::vector<int> t((size_t)fresh_rows * B, -1), l(fresh_rows);
for (int r = 0; r < fresh_rows; ++r) {
for (int b = 0; b <= r / BS && b < B; ++b) t[(size_t)r * B + b] = b;
l[r] = r + 1;
}
append(t, l, B);
}
const int T = (int)len.size();
std::normal_distribution<float> nrm(0.f, 1.f);
std::vector<uint16_t> qb((size_t)T * H * D), kvb((size_t)pages * BS * D);
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
const double scale = 0.0625;
const std::vector<double> want = reference(T, H, B, pages, bt, len, qb, kvb, scale);
auto launch = [&](bool by_rows, int first, int rows, int h0, int heads,
std::vector<uint16_t>& out) {
const size_t at = ((size_t)first * H + h0) * D;
RadTensor t[5] = { tens(qb.data() + at, RAD_BF16, { rows, heads, D }),
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
tens(bt.data() + (size_t)first * B, RAD_I32, { rows, B }),
tens(len.data() + first, RAD_I32, { rows }),
tens(out.data() + at, RAD_BF16, { rows, heads, D }) };
t[0].stride[0] = t[4].stride[0] = (int64_t)H * D;
RadParam p[6]{};
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
const long long vals[5] = { rows, D, heads, B, BS };
for (int i = 0; i < 5; ++i) {
p[i].key = keys[i];
p[i].kind = RAD_P_INT;
p[i].ival = vals[i];
}
p[5].key = "scale";
p[5].kind = RAD_P_F64;
p[5].dval = scale;
RadArgs a{};
a.t = t;
a.n_t = 5;
a.p = p;
a.n_p = 6;
if (!by_rows) return r4d_rad_mla_attn_matrix(&a, nullptr);
/* Runs this short take the matrix kernel by rule; the rows kernel is what is under test. */
r4d_mla_rows_pin_form(3);
const int rc = r4d_rad_mla_attn_rows(&a, nullptr);
r4d_mla_rows_pin_form(0);
return rc;
};
std::vector<uint16_t> heads_out((size_t)T * H * D, 0xffff), rows_out((size_t)T * H * D, 0xffff);
const int per_heads = H / world, run = (T + world - 1) / world;
int fails = 0;
/* What each rank's run buffer holds after its rows: written through the same launches into
* the plane at the run's rows, then copied out as the all_gather moves it, rank r's run of
* `run` rows to rows [r * run, (r + 1) * run) of a [world * run] output. */
std::vector<uint16_t> gathered((size_t)world * run * H * D, 0xffff);
for (int rank = 0; rank < world; ++rank) {
fails += launch(false, 0, T, rank * per_heads, per_heads, heads_out) != RAD_OK;
const int first = rank * run, n = std::min(run, T - first);
if (n > 0) fails += launch(true, first, n, 0, H, rows_out) != RAD_OK;
std::vector<uint16_t> part((size_t)run * H * D, 0xeeee);
for (int r = 0; r < n; ++r)
std::copy(rows_out.begin() + (size_t)(first + r) * H * D,
rows_out.begin() + (size_t)(first + r + 1) * H * D,
part.begin() + (size_t)r * H * D);
std::copy(part.begin(), part.end(), gathered.begin() + (size_t)rank * run * H * D);
}
bool placed = true;
for (size_t i = 0; i < (size_t)T * H * D; ++i) placed = placed && gathered[i] == rows_out[i];
if (!placed) {
std::printf("%-40s the gathered runs do not land on their rows FAIL\n", name);
++fails;
}
long bad[2] = { 0, 0 };
double max_err[2] = { 0, 0 }, apart = 0;
for (size_t i = 0; i < want.size(); ++i) {
const float got[2] = { rad_bf16_to_f32(heads_out[i]), rad_bf16_to_f32(rows_out[i]) };
for (int f = 0; f < 2; ++f) {
const double e = std::fabs(got[f] - want[i]);
if (!std::isfinite(got[f]) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad[f];
if (std::isfinite(got[f])) max_err[f] = std::max(max_err[f], e);
}
apart = std::max(apart, (double)std::fabs(got[0] - got[1]));
}
const bool ok = !fails && !bad[0] && !bad[1];
std::printf("%-40s T %3d world %d run %2d last %2d heads max_abs %.2e bad %ld rows max_abs "
"%.2e bad %ld apart %.2e %s\n",
name, T, world, run, T - (world - 1) * run, max_err[0], bad[0], max_err[1], bad[1],
apart, ok ? "PASS" : "FAIL");
return !ok;
}
/* The head form against the row form, row by row and bit by bit, on a TP8 prefill chunk past the
* DSA budget: the head form is the paired union tile (eight heads of rows 2i and 2i+1), the row
* form's two kernels are the 16-head matrix tile (r4d_mla_rows_pin_form(4)) and the rows kernel.
* The union's first row of a pair walks its own table in its own order, as the 16-head tile does,
* so it must agree to the bit; the second row and the rows kernel sum in other orders, within
* rounding. Printed: rows bit-identical, elements differing, and the largest step in bf16 units. */
int run_rowwise(std::mt19937& rng) {
constexpr int H = 64, B = 65, M = 16;
std::vector<int> bt, len;
int pages = 0;
topk_tables(M, B, 1200, 16, rng, bt, len, pages);
std::normal_distribution<float> nrm(0.f, 1.f);
std::vector<uint16_t> qb((size_t)M * H * D), kvb((size_t)pages * BS * D);
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
auto launch = [&](int kernel, int h0, int heads, std::vector<uint16_t>& out) {
RadTensor t[5] = { tens(qb.data() + (size_t)h0 * D, RAD_BF16, { M, heads, D }),
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }),
tens(out.data() + (size_t)h0 * D, RAD_BF16, { M, heads, D }) };
t[0].stride[0] = t[4].stride[0] = (int64_t)H * D;
RadParam p[6]{};
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
const long long vals[5] = { M, D, heads, B, BS };
for (int i = 0; i < 5; ++i) {
p[i].key = keys[i];
p[i].kind = RAD_P_INT;
p[i].ival = vals[i];
}
p[5].key = "scale";
p[5].kind = RAD_P_F64;
p[5].dval = 0.0625;
RadArgs a{};
a.t = t;
a.n_t = 5;
a.p = p;
a.n_p = 6;
if (kernel < 2) return r4d_rad_mla_attn_matrix(&a, nullptr);
r4d_mla_rows_pin_form(3);
const int rc = r4d_rad_mla_attn_rows(&a, nullptr);
r4d_mla_rows_pin_form(0);
return rc;
};
std::vector<uint16_t> head((size_t)M * H * D), m16((size_t)M * H * D), rows((size_t)M * H * D);
int rc = 0;
for (int r = 0; r < 8; ++r) rc |= launch(0, r * 8, 8, head);
rc |= launch(1, 0, H, m16);
rc |= launch(2, 0, H, rows);
auto ord = [](uint16_t h) { return (h & 0x8000) ? -(int)(h & 0x7fff) : (int)h; };
int fails = rc != RAD_OK;
for (const auto& [name, got] : { std::pair<const char*, const std::vector<uint16_t>*>{
"16-head tile", &m16 },
{ "rows kernel", &rows } }) {
int same_even = 0, same_odd = 0, max_ulp = 0;
long diff = 0;
double max_abs = 0;
for (size_t i = 0; i < head.size(); ++i)
max_abs = std::max(max_abs, (double)std::fabs(rad_bf16_to_f32((*got)[i]) -
rad_bf16_to_f32(head[i])));
for (int r = 0; r < M; ++r) {
bool same = true;
for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) {
const int u = std::abs(ord((*got)[i]) - ord(head[i]));
same = same && !u;
diff += u != 0;
max_ulp = std::max(max_ulp, u);
}
(r % 2 ? same_odd : same_even) += same;
}
/* The 16-head tile must give the union's first rows bit for bit. */
const bool ok = std::strcmp(name, "16-head tile") || same_even == M / 2;
std::printf("rowwise: %-12s vs head form (union pairs): rows bit-identical %d/%d first, "
"%d/%d second of a pair; %ld of %d elements differ, at most %d bf16 steps, "
"max abs %.2e %s\n",
name, same_even, M / 2, same_odd, M / 2, diff, M * H * D, max_ulp, max_abs,
ok ? "PASS" : "FAIL");
fails += !ok;
}
return fails;
}
/* The launcher prints the running totals every 1024th counted launch and must leave them
* standing: 1024 one-chunk launches of a pair, then the hook reads exactly 1024 passes. */
int periodic_report() {
@@ -406,6 +742,18 @@ int main(int argc, char** argv) {
{ "ragged, holes and bad pages", 7, 8, 17, Fill::ragged, 0, 0, false, 0, -1 },
{ "ragged, split", 3, 8, 17, Fill::ragged, 0, 0, true, 0, -1, false },
};
/* The rows row at 64 heads, and at 32, which it serves with two groups a workgroup. */
std::vector<Case> rows_cases = {
{ "rows: prefill, one table", 8, 64, 65, Fill::prefill },
{ "rows: topk d=4", 8, 64, 65, Fill::topk, 4, 600 },
{ "rows: topk d=16, 513 blocks", 3, 64, 513, Fill::topk, 16, 8192 },
{ "rows: repeated pages", 6, 64, 33, Fill::repeat },
{ "rows: ragged, holes and bad pages", 7, 64, 17, Fill::ragged },
{ "rows: ragged, split", 3, 64, 17, Fill::ragged, 0, 0, true },
{ "rows: prefill, one row, split", 1, 64, 65, Fill::prefill, 0, 0, true },
{ "rows: 32 heads", 5, 32, 33, Fill::prefill },
{ "rows: 32 heads, topk d=4, split", 2, 32, 33, Fill::topk, 4, 400, true },
};
const char* filter = argc > 1 ? argv[1] : nullptr;
int fails = 0;
for (size_t i = 0; i < cases.size(); ++i) {
@@ -413,6 +761,28 @@ int main(int argc, char** argv) {
std::mt19937 rng(20261018u + (unsigned)i);
fails += run(cases[i], rng);
}
for (size_t i = 0; i < rows_cases.size(); ++i) {
if (filter && rows_cases[i].name.find(filter) == std::string::npos) continue;
std::mt19937 rng(20261020u + (unsigned)i);
fails += run_rows(rows_cases[i], rng);
}
if (!filter || std::strstr("rowwise", filter)) {
std::mt19937 rng(20261022u);
fails += run_rowwise(rng);
}
/* T 45 over eight ranks: runs of 6, the last of 3; 37 over four: 10 and 7; 48: whole runs. */
const struct {
const char* name;
int world, fresh;
} splits[] = { { "split: heads vs rows, 8 ranks", 8, 15 },
{ "split: heads vs rows, 8 ranks, T 300", 8, 270 },
{ "split: heads vs rows, 4 ranks", 4, 7 },
{ "split: heads vs rows, whole runs", 8, 18 } };
for (size_t i = 0; i < sizeof splits / sizeof splits[0]; ++i) {
if (filter && !std::strstr(splits[i].name, filter)) continue;
std::mt19937 rng(20261021u + (unsigned)i);
fails += run_split(splits[i].name, splits[i].world, splits[i].fresh, rng);
}
if (!filter) fails += periodic_report();
std::printf("%d failure(s)\n", fails);
return fails ? 1 : 0;
+71
View File
@@ -1017,6 +1017,9 @@ TEST(op_vocabulary) {
"conv1d", "conv_t1d", "snake", "cfg_topk_sample", "rvq_embed", "frame_mix_store",
"end_status", "resample_nearest", "fourier_embed", "win_input", "win_prep", "win_finish",
"chan_split", "interleave2", "iota", "cu_repeat", "int_affine", "frame_store",
/* Fish Audio drama-3's (arch/fishomni): the repetition-aware choice between two draws,
* and its codec encoder's residual quantiser step. */
"ras_pick", "vq_encode",
/* The video generator's (MiniMax-H3): its DiT's modulated norm and sampler step, its
* decoder's patch unfold, tiles, stitch and positions, and the vocoder's alias-free
* activation. */
@@ -1045,6 +1048,8 @@ TEST(op_vocabulary) {
"vol_index", "attn_na3d",
/* Unlimited-OCR's SAM tower: windowed attention with decomposed relative position. */
"sam_attn",
/* A pipelined prefill's first-piece KV length, a device length less a device offset. */
"sub_i32",
};
for (const char* op : kOps) {
if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op);
@@ -7438,6 +7443,68 @@ TEST(conv1d_act_clamp_bounds_the_output) {
CHECK_EQ(y.at(2), -1.0f); CHECK_EQ(y.at(3), -0.75f);
}
/* conv1d `stride`: Fish Audio's causal downsampling conv (modded_dac.py, CausalConvNet), the reach
* k less the stride padded on the left. k 4, stride 2 over [1..8] pads 2: windows [0 0 1 2],
* [1 2 3 4], [3 4 5 6], [5 6 7 8] against taps 1, 10, 100, 1000 are 2100, 4321, 6543, 8765. A
* second sequence [1 2 3 4] starts its own padding; a bound that is not a whole stride, and a
* stride on the symmetric form, are refused. `cu_div` reads the same bounds in samples. */
TEST(conv1d_stride_downsamples_each_sequence_causally) {
T x(RAD_F32, {12, 1}); x.f({1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4});
T w(RAD_F32, {1, 1, 4}); w.f({1, 10, 100, 1000});
T cu(RAD_I32, {3}); cu.n({0, 8, 12});
T y(RAD_F32, {6, 1});
A a; a.t(x).t(w).t(cu).tnull().t(y).i("M", 12).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("causal", 1).i("stride", 2).s("dtype", "f32");
CHECK_OK(run("conv1d", a));
CHECK_EQ(y.at(0), 2100.0f); CHECK_EQ(y.at(1), 4321.0f);
CHECK_EQ(y.at(2), 6543.0f); CHECK_EQ(y.at(3), 8765.0f);
CHECK_EQ(y.at(4), 2100.0f); CHECK_EQ(y.at(5), 4321.0f);
T cu2(RAD_I32, {3}); cu2.n({0, 7, 12});
A b; b.t(x).t(w).t(cu2).tnull().t(y).i("M", 12).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("causal", 1).i("stride", 2).s("dtype", "f32");
CHECK_EQ(run("conv1d", b), RAD_E_SHAPE);
T w3(RAD_F32, {1, 1, 3}); w3.f({1, 1, 1});
A c; c.t(x).t(w3).t(cu).tnull().t(y).i("M", 12).i("cin", 1).i("cout", 1).i("k", 3)
.i("dil", 1).i("stride", 2).s("dtype", "f32");
CHECK_EQ(run("conv1d", c), RAD_E_SHAPE);
/* The same bounds in units of 4 rows (samples, 4 a row): the same rows; a bound that is not
* a whole number of strides in rows is refused. */
T y2(RAD_F32, {6, 1});
T cu4(RAD_I32, {3}); cu4.n({0, 32, 48});
A d; d.t(x).t(w).t(cu4).tnull().t(y2).i("M", 12).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("causal", 1).i("stride", 2).i("cu_div", 4).s("dtype", "f32");
CHECK_OK(run("conv1d", d));
for (int64_t i = 0; i < 6; ++i) CHECK_EQ(y2.at(i), y.at(i));
T cu6(RAD_I32, {3}); cu6.n({0, 28, 48});
A e; e.t(x).t(w).t(cu6).tnull().t(y2).i("M", 12).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("causal", 1).i("stride", 2).i("cu_div", 4).s("dtype", "f32");
CHECK_EQ(run("conv1d", e), RAD_E_SHAPE);
}
/* vq_encode by hand. in_w scales the first channel by 2; codebook rows 0 and 2 point the same way
* (a cosine tie, so the lower index), row 1 the other; out_w the identity and out_b
* [0.5, -0.5]. Row [4, 1]: e [8, 1], code 0, x - [1.5, -0.5] = [2.5, 1.5]. Row [-1, 3]: e [-2, 3],
* code 1, x - [0.5, 1.5] = [-1.5, 1.5]. Row [0, 0]: e 0, every cosine 0, code 0. */
TEST(vq_encode_takes_the_nearest_code_by_cosine_and_leaves_the_residual) {
T x(RAD_F32, {3, 2}); x.f({4, 1, -1, 3, 0, 0});
T iw(RAD_F32, {2, 2}); iw.f({2, 0, 0, 1});
T ib(RAD_F32, {2}); ib.f({0, 0});
T cb(RAD_F32, {3, 2}); cb.f({1, 0, 0, 2, 3, 0});
T ow(RAD_F32, {2, 2}); ow.f({1, 0, 0, 1});
T ob(RAD_F32, {2}); ob.f({0.5f, -0.5f});
T codes(RAD_I32, {3}); codes.n({-1, -1, -1});
A a; a.t(x).t(iw).t(ib).t(cb).t(ow).t(ob).t(codes).i("M", 3).i("n", 2).i("dim", 2)
.i("bins", 3).s("dtype", "f32");
CHECK_OK(run("vq_encode", a));
CHECK_EQ(codes.iat(0), 0); CHECK_EQ(codes.iat(1), 1); CHECK_EQ(codes.iat(2), 0);
CHECK_EQ(x.at(0), 2.5f); CHECK_EQ(x.at(1), 1.5f);
CHECK_EQ(x.at(2), -1.5f); CHECK_EQ(x.at(3), 1.5f);
CHECK_EQ(x.at(4), -1.5f); CHECK_EQ(x.at(5), 0.5f);
A b; b.t(x).t(iw).t(ib).t(cb).t(ow).t(ob).t(codes).i("M", 3).i("n", 2).i("dim", 2)
.i("bins", 4).s("dtype", "f32");
CHECK_EQ(run("vq_encode", b), RAD_E_SHAPE);
}
/* snake_aa's paddings, with the activation the identity (alpha 0: sin(0 u) = 0). Ratio 2, filters
* of 4: P = 1. Sequence [10, 20, 40] pads to [10, 10, 20, 40, 40]; the transposed f_up [1, 2, 3, 4]
* gives [10, 20, 40, 60, 50, 80, 100, 160, 160, 240, 120, 160], doubled and cropped by 3 a side:
@@ -8578,6 +8645,9 @@ std::vector<Geo> geometries() {
G("frame_mix_store", "M", 2, a.i("M", R).i("n_embd", 8).i("L", 3).i("stride", 4)
.i("rep", 2).s("dtype", "bf16")),
G("end_status", "M", 2, a.i("M", R).i("end", 5).i("rep", 2)),
G("ras_pick", "M", 2, a.i("M", R).i("win", 4).i("lo", 1).i("hi", 9).i("rep", 1)),
G("vq_encode", "M", 3, a.i("M", R).i("n", 16).i("dim", 4).i("bins", 24)
.s("dtype", "f32")),
G("resample_nearest", "M", 6, a.i("M", R).i("n", 8).s("dtype", "f32")),
G("fourier_embed", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
G("win_input", "M", 8, a.i("M", R).i("n_lat", 4).i("n_zero", 2).i("n_cond", 3)
@@ -8590,6 +8660,7 @@ std::vector<Geo> geometries() {
G("iota", "M", 4, a.i("M", R).i("start", 0).i("step", 1)),
G("cu_repeat", "M", 3, a.i("M", R).i("mult", 2)),
G("int_affine", "M", 3, a.i("M", R).s("src", "0 -1 2").s("mul", "2 0 4").s("add", "-1 5 -3")),
G("sub_i32", "M", 3, a.i("M", R)),
G("frame_store", "M", 2, a.i("M", R).i("n_codes", 4).i("stride", 6).i("rep", 2)
.i("skip", 0)),
G("rms_mod", "M", 4, a.i("M", R).i("n", 8).d("eps", 1e-6).i("gated", 1).s("dtype", "bf16")),
+28
View File
@@ -965,6 +965,34 @@ TEST(an_op_on_the_second_lane_outside_its_window_is_refused_by_name) {
CHECK(std::strstr(f.ctx.step_error(), "outside its declared window") != nullptr);
}
/* Lane 0 joins pending lane-1 work before an op outside the window on either side: a transient of an
* op declared before the window may share bytes with a concurrent buffer as much as one declared
* after it. Inside the window lane 0 runs beside lane 1. */
TEST(an_op_outside_the_window_on_lane_0_joins_the_second_lane_first) {
Fixture f;
f.P.scratch_regions = 2;
rad_buf x = f.add_buffer("x", RAD_BF16, 64, 4, 0);
rad_op a0 = f.add_op("gemm_nt", "M", { 8192 }, { k_scr_seen0 }, { "s0" }, nullptr, {});
rad_op a1 = f.add_op("gemm_nt", "M", { 8192 }, { k_scr_seen1 }, { "s1" }, nullptr, {});
rad_op a2 = f.add_op("gemm_nt", "M", { 8192 }, { k_scr_seen0 }, { "s0" }, nullptr, {});
f.P.lane1_w0 = f.P.lane1_w1 = (int32_t)a1;
CHECK_OK(f.start());
CHECK_OK(f.step(4, 0, [&](Ctx& c) {
RadOperand opd[1] = { RAD_B(x) };
for (rad_op before_or_after : { a0, a2 }) {
CHECK_OK(c.set_lane(1));
CHECK_OK(c.issue(a1, opd, 1, RAD_N_BATCH));
CHECK_OK(c.set_lane(0));
CHECK(c.lane1_pending());
CHECK_OK(c.issue(a1, opd, 1, RAD_N_BATCH)); /* inside: no join */
CHECK(c.lane1_pending());
CHECK_OK(c.issue(before_or_after, opd, 1, RAD_N_BATCH));
CHECK(!c.lane1_pending());
}
}));
}
/* Operands are positional (spec §2.3), so a miscount is silent numerical garbage at the kernel,
* not a diagnosable failure. The runtime checks the given arity against the schema. */
TEST(operand_arity_is_checked_against_the_schema) {
+186 -3
View File
@@ -11,6 +11,7 @@
#include "gbnf_oracle.h"
#include "sample/grammar.h"
#include "sample/host_ref.h"
#include "sample/mtp_couple_evidence.h"
#include "sample/sampler.h"
#include "sample/vocab_view.h"
#include "text/tokenizer.h"
@@ -1496,6 +1497,7 @@ struct HostChain {
int64_t nv = 0;
bool ok = false;
int st = RAD_OK;
int64_t step_no = 0; /* the engine step the next step() stages for */
static inline HostChain* cur = nullptr;
static void trampoline(RadCtx* c, const RadBatch*) {
@@ -1503,11 +1505,15 @@ struct HostChain {
}
HostChain(int64_t n_vocab, int64_t max_seqs, int max_spec, const VocabView* vocab = nullptr,
int64_t max_candidates = 8)
int64_t max_candidates = 8, const char* second_plugin = nullptr,
bool draft_coupling = false)
: nv(n_vocab) {
/* libref alone: it is the implementation under test, and a directory scan would also
* pick up whatever else was built beside it. */
if (reg.load_plugin(home() + "/kernels/libref.so", 0) < 0) return;
/* A second library by name, for an op libref does not carry (the coupling's verify op is
* the spechub plugin's, host row included). */
if (second_plugin && reg.load_plugin(home() + "/kernels/" + second_plugin, 0) < 0) return;
RadModelMeta meta{};
meta.arch_id = "sampler_chain";
meta.name = "sampler_chain";
@@ -1542,6 +1548,7 @@ struct HostChain {
cfg.max_spec = max_spec;
cfg.max_hist = 64;
cfg.max_candidates = max_candidates;
cfg.draft_coupling = draft_coupling;
if (s.declare(&b, cfg) < 0) return;
if (b.finish() < 0) return;
prog = std::move(b.program());
@@ -1570,7 +1577,7 @@ struct HostChain {
const int b = s.begin_request(r->id, r->sp, &err);
if (b < 0) return b;
}
const int bs = s.build_step(reqs);
const int bs = s.build_step(reqs, step_no++);
if (bs < 0) return bs;
int64_t n = 0;
s.staged_params(&n);
@@ -1610,6 +1617,27 @@ Request make_req(uint64_t id, std::vector<int32_t> prompt, const SamplingParams&
return r;
}
/* The per-round states the engine binds after a live commit: `rounds` sampled states of `id`,
* each at `first_pos + rd - 1`, proposing the matching draft token. */
void couple_states(uint64_t id, uint64_t seed, const int32_t* draft, int rounds,
uint64_t first_pos, RadMtpCoupleState* out) {
for (int rd = 1; rd <= rounds; ++rd) {
RadMtpCoupleState& c = out[rd - 1];
c = RadMtpCoupleState{};
c.draw.seq = id;
c.draw.seed = seed;
c.draw.mode = 1;
c.round = rd;
c.status = 1;
c.count = 1;
c.x = draft[rd - 1];
for (int i = 0; i < 8; ++i) c.ids[i] = -1;
c.ids[0] = c.x;
c.q[0] = 1.0;
c.pos = first_pos + (uint64_t)(rd - 1);
}
}
SamplingParams greedy_params() {
SamplingParams sp;
sp.temp = 0.0f;
@@ -3291,4 +3319,159 @@ TEST(a_dry_row_with_breakers_has_its_raw_logprob) {
CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
}
RAD_TEST_MAIN()
/* ================================================== the coupled verify row */
/* THE COUPLED STATE AT THE SAMPLER'S OWN BUILD.
*
* The engine binds a round's state at `n_out + (round - 1)` (core/sched/mtp_couple_bind.h, through
* rad_mtp_couple_verify_pos), and build_step stages row k of the request at `n_out + k`, taking the
* state only when it names that exact row (rad_mtp_couple_binds). This drives the REAL build_step
* with the coupling on: the bound rounds become the draft rows' states, the bonus row stays
* unbound, and a state one position ahead -- what the engine's old `base + n_acc` formula produced
* once a commit came up short -- is refused. A refused row is deliberately silent in production;
* here it is the assertion.
*
* The verify op is declared by the spechub plugin, whose host row (ref_mtp_couple_verify) is what
* makes the declaration succeed here; build_step alone is driven, so the op never runs. */
TEST(the_coupled_state_is_staged_only_at_the_row_it_was_bound_for) {
HostChain ch(64, 2, 3, nullptr, 8, "spechub.so", true);
if (!ch.ok) {
fprintf(stderr, " SKIP %s: libref/spechub did not load from %s/kernels\n",
::radtest::current(), home().c_str());
return;
}
SamplingParams sp;
sp.temp = 1.0f;
const int32_t draft[3] = { 21, 22, 23 };
Request r = make_req(7, { 1, 2, 3 }, sp);
r.draft = draft;
r.n_draft = 3;
std::string err;
CHECK_OK(ch.s.begin_request(r.id, r.sp, &err));
/* The states the engine binds after a live commit, at the positions it writes them. */
const uint64_t n_out = r.output.size();
auto states_at = [&](uint64_t first_pos, RadMtpCoupleState* out) {
couple_states(r.id, r.sp.seed, draft, 3, first_pos, out);
};
RadMtpCoupleState bound[3];
states_at(rad_mtp_couple_verify_pos(n_out, 1), bound);
CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3));
std::vector<Request*> reqs = { &r };
CHECK_OK(ch.s.build_step(reqs));
int64_t n = 0;
const DeviceSampleParams* p = ch.s.staged_params(&n);
CHECK_EQ(n, 4); /* three draft rows and the bonus row */
CHECK(ch.s.staged_any_couple());
for (int k = 0; k < 3; ++k) {
CHECK_EQ(ch.s.staged_couple(k).round, k + 1);
CHECK_EQ(ch.s.staged_couple(k).x, draft[k]);
CHECK_EQ(ch.s.staged_couple(k).pos, rad_mtp_couple_verify_pos(n_out, k + 1));
/* The row is sampled at the position its state names -- asserted against the row itself,
* not through the formula, so a drifted formula cannot move both sides together. */
CHECK_EQ(p[k].pos, n_out + (uint64_t)k);
CHECK_EQ(ch.s.staged_couple(k).pos, p[k].pos);
}
CHECK_EQ(ch.s.staged_couple(3).round, 0); /* the bonus row carries no law */
/* A position one ahead of the row: every row is refused, so the batch issues no verify. */
RadMtpCoupleState ahead[3];
states_at(rad_mtp_couple_verify_pos(n_out, 1) + 1, ahead);
CHECK_OK(ch.s.set_mtp_couple(r.id, ahead, 3));
CHECK_OK(ch.s.build_step(reqs));
CHECK(!ch.s.staged_any_couple());
for (int k = 0; k < 4; ++k) CHECK_EQ(ch.s.staged_couple(k).round, 0);
/* REUSE: an ended request's binding is gone, and a new one starts unbound. */
ch.s.end_request(r.id);
CHECK_EQ(ch.s.set_mtp_couple(r.id, bound, 3), RAD_E_NOTFOUND);
Request r2 = make_req(8, { 1, 2, 3 }, sp);
r2.draft = draft;
r2.n_draft = 3;
CHECK_OK(ch.s.begin_request(r2.id, r2.sp, &err));
CHECK_OK(ch.s.build_step({ &r2 }));
CHECK(!ch.s.staged_any_couple());
}
/* THE SNAPSHOT THE EVIDENCE READS.
*
* In the coupled serial path build_step stages the bound rows, then the drafter's build_greedy
* clears any_couple_ and replaces the staged rows before collect_step's wait returns. An evidence
* line gated on staged_any_couple() therefore never fires -- and forced, it would list the greedy
* pass's rows. This drives the real chain for two requests: build_step, run() issuing the verify
* op, build_greedy (where issue_serial_drafter calls it), then the evidence decision over the
* frozen snapshot. The negatives are what the line must not count: a terminal request, another
* step's snapshot, and a host row. */
TEST(the_coupled_evidence_survives_the_drafters_greedy_build) {
HostChain ch(64, 2, 3, nullptr, 8, "spechub.so", true);
if (!ch.ok) {
fprintf(stderr, " SKIP %s: libref/spechub did not load from %s/kernels\n",
::radtest::current(), home().c_str());
return;
}
SamplingParams sp;
sp.temp = 1.0f;
const int32_t draft[3] = { 21, 22, 23 };
Request a = make_req(7, { 1, 2, 3 }, sp);
Request b = make_req(8, { 4, 5, 6 }, sp);
a.draft = b.draft = draft;
a.n_draft = b.n_draft = 3;
std::string err;
for (Request* r : { &a, &b }) {
CHECK_OK(ch.s.begin_request(r->id, r->sp, &err));
RadMtpCoupleState bound[3];
couple_states(r->id, r->sp.seed, draft, 3, rad_mtp_couple_verify_pos(r->output.size(), 1),
bound);
CHECK_OK(ch.s.set_mtp_couple(r->id, bound, 3));
}
std::vector<float> lg(8 * 64, 0.0f); /* two requests, 3 draft rows + bonus each */
for (int row = 0; row < 8; ++row) lg[(size_t)row * 64 + 5] = 5.0f;
std::vector<int32_t> tok;
CHECK_OK(ch.step({ &a, &b }, lg, &tok));
const int64_t step = ch.step_no - 1;
const Sampler::CoupleBuild& cb = ch.s.couple_build();
CHECK_EQ(cb.step, step);
CHECK_EQ(cb.rows, (int64_t)6);
REQUIRE_EQ(cb.seqs.size(), (size_t)2);
CHECK_EQ(cb.seqs[0].first, (uint64_t)7);
CHECK_EQ(cb.seqs[0].second, (int64_t)3);
CHECK_EQ(cb.seqs[1].first, (uint64_t)8);
CHECK_EQ(cb.seqs[1].second, (int64_t)3);
/* run() issued the verify op for THIS build, not merely staged rows for it. */
CHECK_EQ(ch.s.staged_couple_issued_step(), step);
/* The drafter's greedy passes, where issue_serial_drafter runs them: after the build, before
* the wait. The old gate is false now; the snapshot is not the greedy pass's. */
CHECK_OK(ch.s.build_greedy(4));
CHECK(!ch.s.staged_any_couple());
CHECK_EQ(ch.s.couple_build().step, step);
CHECK_EQ(ch.s.couple_build().rows, (int64_t)6);
auto all_live = [](uint64_t) { return true; };
MtpCoupleEvidence ev = mtp_couple_evidence(cb, step, RAD_DOMAIN_DEVICE, all_live);
CHECK_EQ(ev.rows, (int64_t)6);
CHECK(ev.device);
CHECK_EQ(ev.seqs, std::string("7,8"));
/* A terminal request is not counted: b finished while the step ran. */
ev = mtp_couple_evidence(cb, step, RAD_DOMAIN_DEVICE, [](uint64_t s) { return s == 7; });
CHECK_EQ(ev.rows, (int64_t)3);
CHECK_EQ(ev.seqs, std::string("7"));
/* Nothing live, or another step's snapshot: no evidence. */
CHECK_EQ(mtp_couple_evidence(cb, step, RAD_DOMAIN_DEVICE, [](uint64_t) { return false; }).rows,
(int64_t)0);
CHECK_EQ(mtp_couple_evidence(cb, step + 1, RAD_DOMAIN_DEVICE, all_live).rows, (int64_t)0);
/* A host row is reported as host, not read as a device verify. */
ev = mtp_couple_evidence(cb, step, RAD_DOMAIN_HOST, all_live);
CHECK(!ev.device);
CHECK_EQ(ev.rows, (int64_t)6);
}
RAD_TEST_MAIN()
+10
View File
@@ -444,6 +444,16 @@ struct FakePC : IPrefixCache {
std::vector<uint64_t> holds, releases;
void hold(const Request& r) override { holds.push_back(r.id); }
void release(const Request& r) override { releases.push_back(r.id); }
/* What the scheduler asked to be released, recorded; the answer is canned. */
struct Released { std::string label; uint64_t id; int64_t keep_tokens; };
std::vector<Released> released_calls;
int release_rc = RAD_OK;
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out) override {
released_calls.push_back({ label, id, keep_tokens });
if (out) { *out = SessionRelease{}; out->sessions = 1; out->entries = 5; out->tokens = 80; }
return release_rc;
}
/* What the reserve asked for, call by call. */
std::vector<int64_t> trims;
int64_t trim(int64_t n) override {
+318 -10
View File
@@ -4,6 +4,7 @@
#include "rad_test.h"
#include "mm/processor.h"
#include "sched/mtp_couple_bind.h"
#include "sched/scheduler.h"
#include "sched/advance_impl.h"
#include "sched/derive.h"
@@ -358,6 +359,7 @@ TEST(window_prefill_writes_interval_snapshots_before_the_tail) {
f.cfg.checkpoint_policy = policy;
REQUIRE_EQ(f.start(), RAD_OK);
CHECK(f.sch.geometry().window_ckpt);
CHECK(f.sch.geometry().window_periodic);
int64_t pos = 0;
std::vector<int64_t> snapshots;
@@ -400,6 +402,7 @@ TEST(tip_only_window_prefill_writes_only_the_tail_snapshot) {
f.cfg.checkpoint_policy = "tip-only";
REQUIRE_EQ(f.start(), RAD_OK);
CHECK(f.sch.geometry().window_ckpt);
CHECK(!f.sch.geometry().window_periodic);
int64_t ckpt = -1;
CHECK_EQ(f.sch.plan_chunk(0, 1100, 512, &ckpt), 512ll);
@@ -1380,6 +1383,49 @@ TEST(cancellation_frees_blocks_immediately) {
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Cancelled);
}
/* A release of a conversation with a request of it in flight is refused, whether that request
* is queued or running: the cache would skip its blocks as live and the request's close would
* publish the whole chain again, so the client would have been told of a release that did not
* happen. Once the request is gone the release reaches the cache with what the client asked. */
TEST(a_session_release_waits_for_the_conversations_own_request) {
Fixture f;
f.build(/*blocks=*/40, /*states=*/64);
CHECK_OK(f.start());
auto r = f.request(160, 64);
r->session_label = "chat-7";
const uint64_t a = f.add(std::move(r));
CHECK(a != 0);
SessionRelease out;
/* Queued, not yet admitted. */
CHECK_EQ(f.sch.release_session("chat-7", 0, 0, &out), RAD_E_STATE);
CHECK_EQ(f.sch.release_session("", a, 0, &out), RAD_E_STATE);
CHECK_EQ(f.pc.released_calls.size(), 0u);
/* Running. */
CHECK(f.sch.step() != nullptr);
f.commit_plain();
CHECK_EQ(f.sch.release_session("chat-7", 0, 32, &out), RAD_E_STATE);
/* Another conversation is not in its way. */
CHECK_OK(f.sch.release_session("chat-8", 0, 0, &out));
REQUIRE_EQ(f.pc.released_calls.size(), 1u);
CHECK(f.pc.released_calls[0].label == "chat-8");
/* Finished: the release goes through with label, id and the kept prefix as given. */
CHECK_OK(f.sch.cancel(a));
CHECK_OK(f.sch.reap(a));
CHECK_OK(f.sch.release_session("chat-7", 0, 48, &out));
REQUIRE_EQ(f.pc.released_calls.size(), 2u);
CHECK(f.pc.released_calls[1].label == "chat-7");
CHECK_EQ(f.pc.released_calls[1].keep_tokens, 48ll);
CHECK_EQ(out.entries, 5ll);
/* Nothing named is a bad request, not a cache call. */
CHECK_EQ(f.sch.release_session("", 0, 0, &out), RAD_E_INVAL);
CHECK_EQ(f.pc.released_calls.size(), 2u);
}
/* A reap while the step is still on the device. Common: the server reaps as soon as a sink
* finishes, and cancelling finishes it, so every mid-decode disconnect lands here. Releasing the
* Request now would destroy it under commit(); returning its slot now would let a newly admitted
@@ -1586,6 +1632,204 @@ TEST(rejection_rolls_back_paged_kv_and_moves_the_linear_read_offset) {
CHECK_EQ(f.sch.plan().e[0].conv_cursor, (cursor_before + 3) % W);
}
/* THE COUPLED BIND AFTER A REAL COMMIT.
*
* Engine::finish_serial_drafter binds each round at the request's committed output length, read
* from the plan after commit -- the value the next Sampler::build_step stages that row at. This
* drives the same rule (sched/mtp_couple_bind.h) against the real Scheduler::commit: a live
* commit, a max_tokens cut, and a card reused by a new request afterwards.
*
* The old engine formula (the draw's pre-commit base + the slot's one-based n_acc) agrees on every
* commit of a request that is still running, and drifts by exactly the tokens a cut withheld. A
* commit that emits fewer than the card accepted has closed the request; its plan entry is carried
* for the bind, but the request will never sample again. Binding it would put a coupled verify on
* a terminal row, which reads as a live round in the log without being one. */
TEST(the_coupled_bind_skips_a_request_the_commit_closed) {
Fixture f;
f.build();
f.cfg.n_spec = 3;
CHECK_OK(f.start());
const int64_t vocab = f.prog.meta.n_vocab;
int32_t draft[3] = { 21, 22, 23 };
auto readback = [&](uint64_t seq, uint64_t base, int rounds) {
RadMtpCoupleDraw d{};
d.seq = seq;
d.base = base;
d.mode = 1;
std::vector<RadMtpCoupleState> rb((size_t)rounds);
for (int rd = 1; rd <= rounds; ++rd) {
RadMtpCoupleState& s = rb[(size_t)(rd - 1)];
s.draw = d;
s.round = rd;
s.status = 1;
s.count = 1;
s.x = draft[rd - 1]; /* what the card holds for that round */
for (int i = 0; i < 8; ++i) s.ids[i] = -1;
s.ids[0] = s.x;
s.q[0] = 1.0;
}
return rb;
};
auto slot = [&]() {
StepSlot S{};
S.acc = 3;
S.n_acc = 4;
for (int rd = 1; rd <= 3; ++rd) S.tok[rd] = draft[rd - 1];
return S;
};
/* ---- a live commit: three drafts accepted, the request keeps running. */
const uint64_t a = f.submit(160, 64);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
CHECK_OK(f.sch.set_draft(a, draft, 3));
REQUIRE(f.sch.step() != nullptr);
const uint64_t a_base = f.sch.find(a)->output.size(); /* the draw's pre-commit coordinate */
CHECK_OK(f.commit(9, 0, [](const StepEntry&) { return 3; }));
REQUIRE(f.sch.find(a) != nullptr);
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running);
CHECK_EQ((int)f.sch.find(a)->output.size(), (int)a_base + 4);
MtpCoupleBindPoint pa;
pa.found = f.sch.committed_seq(a, &pa.n_out, &pa.live);
CHECK(pa.found);
CHECK(pa.live);
CHECK_EQ(pa.n_out, (uint64_t)f.sch.find(a)->output.size());
const std::vector<RadMtpCoupleState> rba = readback(a, a_base, 3);
const StepSlot Sa = slot();
RadMtpCoupleState bound[RAD_MTP_COUPLE_MAX_ROUNDS]{};
int n_bound = -1;
std::string why;
CHECK_EQ(mtp_couple_bind_rounds(pa, rba[0].draw, rba.data(), 1, 3, Sa, vocab, bound,
&n_bound, &why), RAD_OK);
CHECK_EQ(n_bound, 3);
for (int k = 0; k < 3; ++k) {
/* The next build stages row k at n_out + k. */
CHECK_EQ(bound[k].pos, pa.n_out + (uint64_t)k);
CHECK(rad_mtp_couple_binds(bound[k], a, rba[0].draw.seed, pa.n_out, k, draft[k], vocab));
}
/* The old formula on the same data: identical, because this commit emitted its whole
* acceptance. */
for (int k = 0; k < 3; ++k)
CHECK_EQ(a_base + 4 + (uint64_t)k, pa.n_out + (uint64_t)k);
/* ---- a cut commit: the card accepted three drafts, the budget lets two through. */
const uint64_t b = f.submit(160, /*max_tokens=*/3);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11); /* b's first output token */
CHECK_OK(f.sch.set_draft(a, draft, 3));
CHECK_OK(f.sch.set_draft(b, draft, 3));
REQUIRE(f.sch.step() != nullptr);
const uint64_t b_base = f.sch.find(b)->output.size();
CHECK_OK(f.commit(9, 0, [&](const StepEntry& e) { return e.seq == b ? 3 : 0; }));
REQUIRE(f.sch.find(b) != nullptr);
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Finished);
CHECK_EQ((int)f.sch.find(b)->output.size(), 3); /* 1 + 2, not 1 + 4 */
/* The commit snapshot still names b -- the terminal step is carried into the bind -- but it is
* not live: nothing binds, so no coupled verify is staged for a request that is gone. */
MtpCoupleBindPoint pb;
pb.found = f.sch.committed_seq(b, &pb.n_out, &pb.live);
CHECK(pb.found);
CHECK(!pb.live);
CHECK_EQ(pb.n_out, (uint64_t)f.sch.find(b)->output.size());
const std::vector<RadMtpCoupleState> rbb = readback(b, b_base, 3);
const StepSlot Sb = slot();
CHECK_EQ(mtp_couple_bind_rounds(pb, rbb[0].draw, rbb.data(), 1, 3, Sb, vocab, bound,
&n_bound, &why), RAD_OK);
CHECK_EQ(n_bound, 0);
/* THE OLD FORMULA would have bound b's rounds at base + n_acc + k -- two past the length it
* actually committed, on a row no build will stage. */
for (int k = 0; k < 3; ++k) {
const uint64_t old_pos = b_base + 4 + (uint64_t)k;
CHECK(old_pos != pb.n_out + (uint64_t)k);
RadMtpCoupleState stale = rbb[(size_t)k];
stale.pos = old_pos;
CHECK(!rad_mtp_couple_binds(stale, b, rbb[0].draw.seed, pb.n_out, k, draft[k], vocab));
}
/* ---- reuse: the next request on a card binds at its own length, and the closed request's
* rounds are not accepted by it. */
const uint64_t c = f.submit(160, 64);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
CHECK_OK(f.sch.set_draft(c, draft, 3));
REQUIRE(f.sch.step() != nullptr);
const uint64_t c_base = f.sch.find(c)->output.size();
CHECK_OK(f.commit(9, 0, [](const StepEntry&) { return 3; }));
MtpCoupleBindPoint pc;
pc.found = f.sch.committed_seq(c, &pc.n_out, &pc.live);
CHECK(pc.found);
CHECK(pc.live);
CHECK_EQ(pc.n_out, (uint64_t)f.sch.find(c)->output.size());
CHECK_EQ(pc.n_out, c_base + 4);
CHECK(!rad_mtp_couple_binds(rbb[0], c, rbb[0].draw.seed, pc.n_out, 0, draft[0], vocab));
RadMtpCoupleState own = readback(c, c_base, 1)[0];
own.pos = rad_mtp_couple_verify_pos(pc.n_out, 1);
CHECK(rad_mtp_couple_binds(own, c, own.draw.seed, pc.n_out, 0, draft[0], vocab));
}
/* THE BIND POINT OUTLIVES A REAP.
*
* commit() retires the step, and a request it finished that the next step does not carry is pinned
* by nothing any more. The server calls reap() from an HTTP thread as soon as it sees the finish,
* and reap() destroys the Request -- while Engine::finish_serial_drafter still has to bind that
* row. The bind point is therefore copied by commit under the scheduler lock
* (Scheduler::committed_seq), not read off the plan's StepEntry::req, which is dangling by then.
* This reaps a non-carried terminal request between commit and bind: the plan-pointer version
* could only answer by reading freed memory, and the snapshot answers from the copy.
*/
TEST(the_committed_bind_point_outlives_a_reap) {
Fixture f;
f.build();
f.cfg.n_spec = 3;
CHECK_OK(f.start());
const int64_t vocab = f.prog.meta.n_vocab;
int32_t draft[3] = { 21, 22, 23 };
const uint64_t a = f.submit(160, 64); /* live through the commit */
const uint64_t b = f.submit(160, /*max_tokens=*/3); /* closed on it by the cut */
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
CHECK_OK(f.sch.set_draft(a, draft, 3));
CHECK_OK(f.sch.set_draft(b, draft, 3));
REQUIRE(f.sch.step() != nullptr);
CHECK_OK(f.commit(9, 0, [&](const StepEntry& e) { return e.seq == b ? 3 : 0; }));
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Finished);
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running);
/* The server's reap lands between commit and bind: b's Request is destroyed here. */
CHECK_OK(f.sch.reap(b));
CHECK(f.sch.find(b) == nullptr);
MtpCoupleBindPoint pb;
pb.found = f.sch.committed_seq(b, &pb.n_out, &pb.live);
CHECK(pb.found);
CHECK(!pb.live); /* terminal: nothing binds */
CHECK_EQ(pb.n_out, (uint64_t)3);
MtpCoupleBindPoint pa;
pa.found = f.sch.committed_seq(a, &pa.n_out, &pa.live);
CHECK(pa.found);
CHECK(pa.live);
CHECK_EQ(pa.n_out, (uint64_t)f.sch.find(a)->output.size());
RadMtpCoupleState rb[RAD_MTP_COUPLE_MAX_ROUNDS]{};
RadMtpCoupleState out[RAD_MTP_COUPLE_MAX_ROUNDS]{};
StepSlot S{};
S.acc = 3;
S.n_acc = 4;
for (int rd = 1; rd <= 3; ++rd) S.tok[rd] = draft[rd - 1];
int n_bound = -1;
std::string why;
CHECK_EQ(mtp_couple_bind_rounds(pb, RadMtpCoupleDraw{}, rb, 1, 3, S, vocab, out, &n_bound,
&why), RAD_OK);
CHECK_EQ(n_bound, 0);
}
/* A decode benchmark needs the request to last as long as asked, not as long as the model
* chooses. EOS still stops an ordinary request, and max_tokens still stops one ignoring EOS. */
TEST(ignore_eos_runs_to_max_tokens_and_nothing_else_changes) {
@@ -3327,6 +3571,33 @@ TEST(every_row_names_one_of_the_cards_step_slots) {
/* The context pass mirrors the trunk step row for row: the drafter reads hidden states
* positionally, so a sequence the commit finished keeps its rows (as padding that stores nothing),
* or every later sequence would draft from its neighbour's states. */
/* The load a block drafter's short block is chosen by counts the running sequences the step just
* run produced a token for, not one it finished; the choice switches on at the threshold and off
* only two below it. */
TEST(a_block_drafters_short_block_follows_the_decoded_sequences_with_hysteresis) {
Fixture f;
f.build();
f.cfg.n_spec = 7;
CHECK_OK(f.start());
uint64_t a = f.submit(160, /*max_tokens=*/1);
f.submit(160, 64);
f.submit(160, 64);
CHECK(f.sch.step() != nullptr);
CHECK_EQ((int)f.sch.plan().e.size(), 3);
f.commit_plain();
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Finished);
CHECK_EQ(f.sch.decoded_seqs(), 2);
bool on = false;
const int64_t from = 16;
const int64_t load[] = { 15, 16, 15, 14, 15, 13, 14, 16 };
const bool want[] = { 0, 1, 1, 0, 0, 0, 0, 1 };
for (size_t i = 0; i < sizeof load / sizeof load[0]; ++i) {
on = Scheduler::short_block_on(on, load[i], from);
CHECK_EQ(on, want[i]);
}
}
TEST(a_block_drafter_context_pass_keeps_the_rows_of_a_finished_sequence) {
Fixture f;
f.build();
@@ -4176,7 +4447,7 @@ constexpr int kBlk = 8, kBlkDepth = 7;
constexpr int32_t kBlkMask = 99;
/* The host's driver: both passes built after the commit, from the committed sequence. */
BlockRun block_reference(int steps) {
BlockRun block_reference(int steps, int blk = kBlk, int depth = kBlkDepth) {
Fixture f;
std::vector<uint64_t> ids;
ahead_setup(f, kBlkDepth, ids);
@@ -4187,7 +4458,7 @@ BlockRun block_reference(int steps) {
Scheduler::BlockRow rows[4];
for (int t = 0; t < steps; ++t) {
CHECK_OK(ahead_commit(f, t));
CHECK_EQ(f.sch.block_begin(kBlk, kBlkDepth, 0, kBlkMask, rows, 4), 3);
CHECK_EQ(f.sch.block_begin(blk, depth, 0, kBlkMask, rows, 4), 3);
const RadBatch* cb = f.sch.block_context(t + 1);
if (!cb) { CHECK(cb != nullptr); return run; }
run.context.push_back(read_rows(cb, f.sch.plan(), f.kv));
@@ -4198,7 +4469,7 @@ BlockRun block_reference(int steps) {
for (int i = 0; i < 3; ++i) { StepEntry e; e.seq = rows[i].seq; qp.e.push_back(e); }
run.query.push_back(read_rows(qb, qp, f.kv));
f.sch.block_end();
ahead_publish(f, ids, kBlkDepth, t + 1);
ahead_publish(f, ids, depth, t + 1);
b = f.sch.step();
if (!b) break;
run.trunk.push_back(read_rows(b, f.sch.plan(), f.kv));
@@ -4211,7 +4482,7 @@ BlockRun block_reference(int steps) {
* passes built before the commit with the query rows placed by ADV_BLOCK, the proposals into the
* slots (ADV_BTAKE), expect_draft and step_next with ADV_TRUNK, then the commit, block_end, the
* drafts published and promote_next. */
BlockRun block_pipelined(int steps) {
BlockRun block_pipelined(int steps, int blk = kBlk, int depth = kBlkDepth) {
Fixture f;
std::vector<uint64_t> ids;
ahead_setup(f, kBlkDepth, ids);
@@ -4241,7 +4512,7 @@ BlockRun block_pipelined(int steps) {
++run.card_host_disagree;
}
CHECK_EQ(f.sch.block_begin(kBlk, kBlkDepth, 0, kBlkMask, rows, 4, /*on_card=*/true), 3);
CHECK_EQ(f.sch.block_begin(blk, depth, 0, kBlkMask, rows, 4, /*on_card=*/true), 3);
const RadBatch* cb = f.sch.block_context(t + 1);
if (!cb) { CHECK(cb != nullptr); return run; }
run.context.push_back(read_rows(cb, f.sch.plan(), f.kv));
@@ -4254,19 +4525,20 @@ BlockRun block_pipelined(int steps) {
StepPlan qp;
for (int i = 0; i < 3; ++i) { StepEntry e; e.seq = rows[i].seq; qp.e.push_back(e); }
run.query.push_back(read_rows(qb, qp, f.kv));
/* The block's proposals for step t + 1, taken behind the anchor. */
/* The block's proposals for step t + 1, taken behind the anchor, at the drafter's pitch
* (its own block's depth): a short block fills a row's front. */
std::vector<int32_t> prop((size_t)3 * kBlkDepth);
for (int i = 0; i < 3; ++i)
for (int j = 0; j < kBlkDepth; ++j)
for (int j = 0; j < depth; ++j)
prop[(size_t)(i * kBlkDepth + j)] = ahead_draft(rows[i].seq, t + 1, j);
AdvanceArgs tk = f.sch.advance_args(0);
tk.mode = ADV_BTAKE;
tk.round = kBlkDepth;
tk.round = depth;
tk.src = prop.data();
tk.src_pitch = kBlkDepth;
tk.st = slots.data();
for (int i = 0; i < tk.n_seq; ++i) adv_row(tk, i);
for (int i = 0; i < 3; ++i) f.sch.expect_draft(rows[i].seq, kBlkDepth);
for (int i = 0; i < 3; ++i) f.sch.expect_draft(rows[i].seq, depth);
const RadBatch* nb = f.sch.step_next();
if (nb) {
@@ -4277,7 +4549,7 @@ BlockRun block_pipelined(int steps) {
}
CHECK_OK(ahead_commit(f, t));
f.sch.block_end();
ahead_publish(f, ids, kBlkDepth, t + 1);
ahead_publish(f, ids, depth, t + 1);
if (nb) {
f.sch.promote_next();
b = nb;
@@ -4335,6 +4607,42 @@ TEST(a_block_drafter_on_the_card_runs_the_passes_the_hosts_driver_runs) {
CHECK(a.out == b.out);
}
/* The same at DFlash2's short block (--draft-short-from: 4 rows, 3 proposals), which the card's driver
* runs once enough sequences decode (Engine::block_shape): the query pass of the short block, its
* proposals taken from the front of each row at the drafter's pitch, and the step issued ahead
* verifying 3 of them. */
TEST(a_block_drafters_short_block_on_the_card_runs_the_passes_the_hosts_driver_runs) {
const int T = 24;
const BlockRun a = block_reference(T, 4, 3);
const BlockRun b = block_pipelined(T, 4, 3);
CHECK_EQ(b.ahead, T);
CHECK_EQ(b.card_host_disagree, 0);
REQUIRE_EQ(a.trunk.size(), (size_t)T + 1);
REQUIRE_EQ(a.trunk.size(), b.trunk.size());
REQUIRE_EQ(a.context.size(), b.context.size());
REQUIRE_EQ(a.query.size(), b.query.size());
for (size_t t = 0; t < a.trunk.size(); ++t) {
CHECK(a.trunk[t] == b.trunk[t]);
CHECK_EQ(b.trunk[t].bad_slots, 0);
}
for (size_t t = 0; t < a.context.size(); ++t) {
BatchRows ca = a.context[t], cb = b.context[t];
ca.tok.clear();
cb.tok.clear();
const bool same_c = ca == cb, same_q = a.query[t] == b.query[t];
CHECK(same_c);
CHECK(same_q);
if (!same_c || !same_q)
std::fprintf(stderr, " step %zu: context %s, query %s\n", t,
same_c ? "same" : "differs", same_q ? "same" : "differs");
CHECK_EQ(a.context[t].bad_slots, 0);
CHECK_EQ(b.context[t].bad_slots, 0);
CHECK_EQ(a.query[t].bad_slots, 0);
CHECK_EQ(b.query[t].bad_slots, 0);
}
CHECK(a.out == b.out);
}
/* ================================================================== the token budget per token */
/* A verify step emits up to 1 + n_spec tokens at once. The budget (max_tokens, and the context)
* is applied token by token before each reaches the sink: trimming `output` afterwards would leave
+109 -2
View File
@@ -7,7 +7,9 @@
#include "rad_test.h"
#include "plugin/registry.h"
#include "rad_builder.h"
#include <cstring>
#include <map>
#include <set>
#include <string>
@@ -88,8 +90,8 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second);
}
const std::set<std::pair<std::string, std::string>> want = {
{ "anima", "" }, { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" },
{ "flux3distilled", "" },
{ "anima", "" }, { "breeze", "" }, { "embeddinggemma2", "" },
{ "fishomni", "bsgemm-moe" }, { "flux3", "" }, { "flux3distilled", "" },
{ "gemma3", "" }, { "gemma4", "" },
{ "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" },
{ "llama", "fp8_e4m3" }, { "qwen35", "" },
@@ -134,4 +136,109 @@ TEST(every_shipped_family_has_at_most_one_plugin_for_an_imported_checkpoint) {
CHECK(!w8->arch_serves_imports);
}
/* drama-3's input as fish-speech's server writes it (chunking.py, generate.py): each speaker's turn
* tagged and stripped, turns on lines of their own, untagged text speaker 0's; refused when empty,
* when it holds a token only the prompt builder writes, or when it names a speaker other than 0..15
* the canonical way. A refusal leaves its reason in the output. */
TEST(fishomni_writes_the_input_as_the_reference_server_does) {
Registry r;
const int st = r.load_dir(dir_of("architectures"), {});
if (st == RAD_E_IO && r.plugins().empty())
ARTIFACT_MISSING("the architecture plugins under " + dir_of("architectures"));
CHECK_OK(st);
const Plugin* p = r.plugin("fishomni");
REQUIRE(p != nullptr);
REQUIRE(p->arch_text_prepare != nullptr);
auto prep = [&](const char* in, std::string* out) {
char buf[512] = {};
const int64_t n = p->arch_text_prepare(RAD_TEXT_INPUT, in, buf, sizeof buf);
*out = buf;
return n;
};
const struct { const char* in; const char* want; } ok[] = {
{ "Hello there.", "<|speaker:0|> Hello there." },
{ " Hello there. \n", "<|speaker:0|> Hello there." },
{ "\xe3\x80\x80Hello\xc2\xa0", "<|speaker:0|> Hello" }, /* U+3000, U+00A0 */
{ "<|speaker:0|> Are you ready? <|speaker:1|> Always.",
"<|speaker:0|> Are you ready?\n<|speaker:1|> Always." },
{ "Hi <|speaker:12|>Hey <|speaker:3|> ", "<|speaker:0|> Hi\n<|speaker:12|> Hey" },
{ "<|speaker:2|>[laughs] Fine.", "<|speaker:2|> [laughs] Fine." },
};
for (const auto& c : ok) {
std::string got;
const int64_t n = prep(c.in, &got);
if (got != c.want) fprintf(stderr, " '%s' -> '%s'\n", c.in, got.c_str());
CHECK_EQ(n, (int64_t)std::strlen(c.want));
CHECK_EQ(got, std::string(c.want));
}
const struct { const char* in; const char* why; } refused[] = {
{ " \t", "empty" },
{ "<|speaker:1|> ", "empty" },
{ "Say <|im_end|> now", "<|im_end|>" },
{ "<|voice|>", "<|voice|>" },
{ "a <|semantic:12|> b", "<|semantic:" },
{ "<|speaker:16|> hi", "speaker tags" },
{ "<|speaker:01|> hi", "speaker tags" },
{ "<|speaker_change|> hi", "speaker tags" },
};
for (const auto& c : refused) {
std::string why;
CHECK(prep(c.in, &why) < 0);
if (why.find(c.why) == std::string::npos) fprintf(stderr, " '%s': %s\n", c.in, why.c_str());
CHECK(why.find(c.why) != std::string::npos);
}
/* A short buffer still gets the length to retry with, and the instructions (which the model
* refuses before they get here) pass as written. */
char tiny[4] = {};
CHECK_EQ(p->arch_text_prepare(RAD_TEXT_INPUT, "Hello", tiny, sizeof tiny),
(int64_t)std::strlen("<|speaker:0|> Hello"));
char buf[64] = {};
CHECK_EQ(p->arch_text_prepare(RAD_TEXT_INSTRUCTIONS, " calm ", buf, sizeof buf), 6);
CHECK_EQ(std::string(buf), std::string(" calm "));
}
/* A reference's transcript as generate.py's build_drama3_prompt writes it after "Text: ": speaker
* 0's tag and a space before untagged text, which is otherwise kept as given; white space before a
* leading tag moved behind it. The input's rules refuse the same tokens. */
TEST(fishomni_tags_a_reference_transcript_as_the_prompt_builder_does) {
Registry r;
const int st = r.load_dir(dir_of("architectures"), {});
if (st == RAD_E_IO && r.plugins().empty())
ARTIFACT_MISSING("the architecture plugins under " + dir_of("architectures"));
CHECK_OK(st);
const Plugin* p = r.plugin("fishomni");
REQUIRE(p != nullptr);
REQUIRE(p->arch_text_prepare != nullptr);
auto prep = [&](const char* in, std::string* out) {
char buf[512] = {};
const int64_t n = p->arch_text_prepare(RAD_TEXT_REFERENCE, in, buf, sizeof buf);
*out = buf;
return n;
};
const struct { const char* in; const char* want; } ok[] = {
{ "We asked over twenty people.", "<|speaker:0|> We asked over twenty people." },
{ " Two spaces kept. ", "<|speaker:0|> Two spaces kept. " },
{ " <|speaker:1|>Hi there", "<|speaker:1|> Hi there" },
{ "<|speaker:3|> Hello. <|speaker:4|> Hi.", "<|speaker:3|> Hello. <|speaker:4|> Hi." },
};
for (const auto& c : ok) {
std::string got;
const int64_t n = prep(c.in, &got);
if (got != c.want) fprintf(stderr, " '%s' -> '%s'\n", c.in, got.c_str());
CHECK_EQ(n, (int64_t)std::strlen(c.want));
CHECK_EQ(got, std::string(c.want));
}
const struct { const char* in; const char* why; } refused[] = {
{ " \n ", "empty" },
{ "Then <|im_start|> came", "<|im_start|>" },
{ "<|speaker:20|> hi", "speaker tags" },
};
for (const auto& c : refused) {
std::string why;
CHECK(prep(c.in, &why) < 0);
if (why.find(c.why) == std::string::npos) fprintf(stderr, " '%s': %s\n", c.in, why.c_str());
CHECK(why.find(c.why) != std::string::npos);
}
}
RAD_TEST_MAIN()
+146
View File
@@ -0,0 +1,146 @@
/* tests/spechub_accept_test.cpp -- the coupling's acceptance against the greedy drafter's.
*
* spechub_couple_test pins the output law. This file pins the acceptance rate, against the rule the
* engine applies without the coupling, over the same candidate stream and uniforms:
*
* greedy the head proposes its argmax and the draft survives when it equals the target's own
* sampled token. The rate is P(argmax Q).
* coupled the head proposes x ~ Q and rad_mtp_couple_decide keeps it with probability
* min(1, P(x)/Q(x)). The rate is sum_i min(P_i, Q_i).
*
* Neither rate dominates. A flat draft over a spread target favours the coupling; a peaked target
* whose argmax the head shares favours the greedy draft, because Q is the head's law at temperature
* 1 whatever the request's temperature is. Both cases are checked against their closed forms.
*/
#include "rad_test.h"
#include "rad_sample.h"
#include "rad_spechub.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <vector>
namespace {
std::vector<double> softmax(const std::vector<float>& v) {
const float top = *std::max_element(v.begin(), v.end());
std::vector<double> p(v.size());
double sum = 0;
for (size_t i = 0; i < v.size(); ++i) { p[i] = std::exp((double)v[i] - top); sum += p[i]; }
for (double& x : p) x /= sum;
return p;
}
/* Inverse CDF over a law with a uniform in [0, 1). */
int32_t pick(const std::vector<double>& p, double u) {
double c = u;
for (size_t i = 0; i < p.size(); ++i) { c -= p[i]; if (c < 0) return (int32_t)i; }
return (int32_t)p.size() - 1;
}
struct Rates { double greedy, coupled, want_greedy, want_coupled; int64_t n; };
/* Both rules over `trials` positions of one (target, head) pair; ids are 0..7 in both. */
Rates measure(const std::vector<float>& pval, const std::vector<float>& qval, int trials) {
std::vector<int32_t> ids;
for (int i = 0; i < 8; ++i) ids.push_back(i);
const std::vector<double> P = softmax(pval), Q = softmax(qval);
const int32_t argmax_q = (int32_t)(std::max_element(qval.begin(), qval.end()) - qval.begin());
const uint64_t seed = 90210;
int64_t greedy_ok = 0, coupled_ok = 0;
for (int k = 0; k < trials; ++k) {
const uint64_t pos = (uint64_t)k;
/* The target's own draw at this position, independent of the head. */
if (pick(P, rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_PICK)) == argmax_q) ++greedy_ok;
RadMtpCoupleState s{};
s.draw.seed = seed;
s.draw.base = pos;
s.draw.mode = 1;
s.round = 1;
s.status = 1;
float qv[8];
for (int i = 0; i < 8; ++i) qv[i] = qval[(size_t)i];
CHECK(rad_mtp_couple_build_q(ids.data(), qv, 8, &s));
s.x = s.ids[rad_mtp_couple_pick(
s, rad_spechub_uniform(seed, pos, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
int32_t out = -1;
CHECK(rad_mtp_couple_decide(s, ids.data(), pval.data(), 8, 8,
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID), &out));
if (out == s.x) ++coupled_ok;
}
Rates r{};
r.n = trials;
r.greedy = (double)greedy_ok / trials;
r.coupled = (double)coupled_ok / trials;
r.want_greedy = P[(size_t)argmax_q];
for (size_t i = 0; i < P.size(); ++i) r.want_coupled += std::min(P[i], Q[i]);
std::fprintf(stderr, " acceptance over %d positions: greedy %.4f (P(argmax Q) %.4f), "
"coupled %.4f (sum min(P, Q) %.4f)\n",
trials, r.greedy, r.want_greedy, r.coupled, r.want_coupled);
return r;
}
} /* namespace */
/* A spread target and a flatter head: the coupling accepts more than the greedy draft. */
TEST(the_coupling_accepts_more_than_the_greedy_draft_on_a_spread_target) {
const Rates r = measure({ 3.10f, 2.95f, 2.40f, 1.80f, 1.10f, 0.40f, -0.60f, -2.00f },
{ 2.60f, 2.55f, 2.30f, 2.00f, 1.60f, 1.20f, 0.60f, -0.40f }, 20000);
const double sig = std::sqrt(0.25 / (double)r.n);
CHECK_NEAR(r.greedy, r.want_greedy, 5.0 * sig);
CHECK_NEAR(r.coupled, r.want_coupled, 5.0 * sig);
CHECK(r.want_coupled > r.want_greedy + 10.0 * sig);
CHECK(r.coupled > r.greedy);
}
/* A peaked target (a low temperature) whose argmax the head shares: the greedy draft is accepted
* almost always, while x ~ Q at temperature 1 often proposes a token the target rarely draws. */
TEST(the_greedy_draft_accepts_more_on_a_peaked_target) {
const Rates r = measure({ 6.00f, 2.00f, 1.50f, 1.00f, 0.50f, 0.00f, -1.00f, -2.00f },
{ 2.00f, 1.20f, 1.00f, 0.80f, 0.40f, 0.00f, -0.50f, -1.00f }, 20000);
const double sig = std::sqrt(0.25 / (double)r.n);
CHECK_NEAR(r.greedy, r.want_greedy, 5.0 * sig);
CHECK_NEAR(r.coupled, r.want_coupled, 5.0 * sig);
CHECK(r.want_greedy > r.want_coupled + 10.0 * sig);
CHECK(r.greedy > r.coupled);
}
/* The proposal is a draw from Q, the FP64 softmax of the shortlist, not its argmax: over many
* rounds every candidate with mass appears at its frequency under Q. */
TEST(the_drafted_token_is_sampled_from_the_heads_own_law) {
const std::vector<float> qval = { 1.0f, 0.4f, -0.3f, -1.2f };
int32_t qidx[8];
float qv[8];
for (int i = 0; i < 8; ++i) { qidx[i] = i < 4 ? i : -1; qv[i] = i < 4 ? qval[(size_t)i] : -INFINITY; }
double sum = 0, Q[4] = {};
for (int i = 0; i < 4; ++i) { Q[i] = std::exp((double)qval[(size_t)i] - 1.0); sum += Q[i]; }
for (int i = 0; i < 4; ++i) Q[i] /= sum;
const int trials = 20000;
int64_t seen[4] = {};
for (int k = 0; k < trials; ++k) {
RadMtpCoupleState s{};
s.draw.seed = 7;
s.draw.base = (uint64_t)k;
s.draw.mode = 1;
s.round = 1;
s.status = 1;
CHECK(rad_mtp_couple_build_q(qidx, qv, 8, &s));
const int32_t x = s.ids[rad_mtp_couple_pick(
s, rad_spechub_uniform(7, (uint64_t)k, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
CHECK(x >= 0 && x < 4);
++seen[x];
}
for (int i = 0; i < 4; ++i) {
const double got = (double)seen[i] / (double)trials;
const double sigma = std::sqrt(Q[i] * (1.0 - Q[i]) / (double)trials);
CHECK_NEAR(got, Q[i], 5.0 * sigma + 1e-9);
}
}
RAD_TEST_MAIN()
+282
View File
@@ -0,0 +1,282 @@
/* tests/spechub_cooperative_test.cpp -- the cooperative verify against the serial one.
*
* The cooperative kernel writes P's weights and the residual mass across the workgroup and then
* walks both planes in ascending candidate order on one thread. That is a REORDERING of the
* compute, not of the arithmetic -- and the arithmetic is the ABI here, so the claim has to be
* checked rather than argued.
*
* What this file checks, over the same rows, the same states and the same uniforms:
*
* PARITY the cooperative decision emits the same token as rad_mtp_couple_decide (the serial
* reference the plugin's host row runs) on every row of every width case.
*
* WIDTHS 129, 1024 and 1025 candidates. 1025 is the case that falls out of the shared-plane
* band into the general single-threaded algorithm; it must still agree.
*
* HOSTILE a row with a hole in the middle, a duplicate id, an -inf candidate, and a row whose
* state does not bind -- all of which the planes must treat exactly as the serial walk
* does.
*
* The kernel itself is not launched here: this steps the host half of the same algorithm through
* the same phases, so a divergence would have to live in the device code alone. The device rows
* are checked against the host rows by the op oracle (RADIANCE_OP_ORACLE).
*/
#include "rad_test.h"
#include "rad_sample.h"
#include "rad_spechub.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace {
/* The cooperative algorithm, on the host: the same phases the kernel runs, over the same shared
* planes. Deliberately a transcription of the kernel's body, so a change to one that is not made to
* the other shows up as a mismatch against rad_mtp_couple_decide. */
bool cooperative_decide(const RadMtpCoupleState& s, const std::vector<int32_t>& ids,
const std::vector<float>& val, int64_t vocab, double u_accept,
double u_resid, int32_t* out) {
const int64_t n_cand = (int64_t)ids.size();
std::vector<double> weight((size_t)n_cand, 0.0), mass((size_t)n_cand, 0.0);
double pq[8] = {};
int first[8];
double sum = 0;
float top = -INFINITY;
int ix = -1;
bool dominated = true;
/* PHASE 1: the gate, exactly the kernel's. */
bool eligible = false;
if (s.status == 1) {
float maximum = -INFINITY;
bool valid = true;
for (int64_t j = 0; j < n_cand; ++j) {
if (ids[(size_t)j] < 0) continue;
if (ids[(size_t)j] >= vocab || val[(size_t)j] != val[(size_t)j] ||
val[(size_t)j] == INFINITY) {
valid = false;
break;
}
if (val[(size_t)j] > maximum) maximum = val[(size_t)j];
}
if (valid && maximum != -INFINITY) { top = maximum; eligible = true; }
}
if (!eligible) return false;
/* PHASE 2: the weights, per slot. */
for (int64_t j = 0; j < n_cand; ++j)
if (ids[(size_t)j] >= 0 && val[(size_t)j] != -INFINITY)
weight[(size_t)j] = std::exp((double)val[(size_t)j] - top);
/* PHASE 3: the ordered sum and the Q aggregation. */
for (int k = 0; k < s.count; ++k) { pq[k] = 0; first[k] = -1; }
for (int64_t j = 0; j < n_cand; ++j) {
if (ids[(size_t)j] < 0 || val[(size_t)j] == -INFINITY) continue;
const double w = weight[(size_t)j];
sum += w;
for (int k = 0; k < s.count; ++k)
if (ids[(size_t)j] == s.ids[k]) {
if (first[k] < 0) first[k] = (int)j;
pq[k] += w;
break;
}
}
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
for (int k = 0; k < s.count; ++k) {
pq[k] /= sum;
dominated = dominated && pq[k] >= s.q[k];
if (s.ids[k] == s.x) ix = k;
}
if (ix < 0) return false;
/* PHASE 4: the residual mass, per slot. */
for (int64_t j = 0; j < n_cand; ++j) {
double m = 0;
if (ids[(size_t)j] >= 0 && val[(size_t)j] != -INFINITY) {
bool in_q = false;
for (int k = 0; k < s.count; ++k)
if (s.ids[k] == ids[(size_t)j]) {
in_q = true;
if (first[k] == (int)j) m = rad_spechub_positive(pq[k] - s.q[k]);
break;
}
if (!in_q) m = weight[(size_t)j] / sum;
}
mass[(size_t)j] = m;
}
/* PHASE 5: the ordered walk. */
double resid = 0;
for (int64_t j = 0; j < n_cand; ++j) resid += mass[(size_t)j];
int32_t result = -1;
if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) {
double cdf = u_resid * sum;
for (int64_t j = 0; j < n_cand; ++j)
if (ids[(size_t)j] >= 0 && val[(size_t)j] != -INFINITY) {
const double w = weight[(size_t)j];
if (w > 0) { result = ids[(size_t)j]; cdf -= w; if (cdf < 0) break; }
}
} else if (pq[ix] >= s.q[ix] || u_accept * s.q[ix] < pq[ix]) {
result = s.x;
} else {
double cdf = u_resid * resid;
for (int64_t j = 0; j < n_cand; ++j) {
if (ids[(size_t)j] == s.x) continue;
const double m = mass[(size_t)j];
if (m > 0) { result = ids[(size_t)j]; cdf -= m; if (cdf < 0) break; }
}
}
*out = result;
return true;
}
/* A bound state over the first `qcount` ids of the plane. */
RadMtpCoupleState bound_state(const std::vector<int32_t>& ids, int qcount, uint64_t seed,
uint64_t pos) {
RadMtpCoupleState s{};
s.draw.seed = seed;
s.draw.base = pos;
s.draw.mode = 1;
s.round = 1;
s.status = 1;
s.pos = pos;
int32_t qidx[8];
float qv[8];
for (int i = 0; i < 8; ++i) {
qidx[i] = i < qcount ? ids[(size_t)i] : -1;
qv[i] = i < qcount ? -0.3f * (float)i : -INFINITY;
}
CHECK(rad_mtp_couple_build_q(qidx, qv, (int64_t)ids.size() + 1024, &s));
s.x = s.ids[rad_mtp_couple_pick(
s, rad_spechub_uniform(seed, pos, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
return s;
}
} /* namespace */
/* PARITY AT EVERY WIDTH. 129, 1024 and 1025 candidates, 64 rows each, the same state and uniforms:
* the cooperative decision must equal the serial reference on every row. 1025 is the width that
* leaves the shared-plane band, so it exercises both paths. */
TEST(the_cooperative_decision_equals_the_serial_reference_at_every_width) {
for (int64_t n : { 129, 1024, 1025 }) {
std::vector<int32_t> ids((size_t)n);
std::vector<float> val((size_t)n);
for (int64_t i = 0; i < n; ++i) {
ids[(size_t)i] = (int32_t)i;
/* A long decaying tail: the nucleus is narrow and the residual is a small, spread set,
* which is where a mass-plane mistake would show. */
val[(size_t)i] = 6.0f - 0.01f * (float)i;
}
int64_t agree = 0, refusals = 0;
for (int k = 0; k < 64; ++k) {
const uint64_t pos = (uint64_t)(n + k);
const RadMtpCoupleState s = bound_state(ids, 8, 4242, pos);
const double ua = rad_spechub_uniform(4242, pos, RAD_SAMPLE_KEY_ACCEPT);
const double ur = rad_spechub_uniform(4242, pos, RAD_SAMPLE_KEY_RESID);
int32_t serial = -7, coop = -7;
const bool ok_s = rad_mtp_couple_decide(s, ids.data(), val.data(), n, n, ua, ur,
&serial);
const bool ok_c = cooperative_decide(s, ids, val, n, ua, ur, &coop);
CHECK_EQ(ok_c, ok_s);
if (!ok_s) { ++refusals; continue; }
if (serial == coop) ++agree;
}
CHECK_EQ(agree + refusals, (int64_t)64);
CHECK_EQ(refusals, (int64_t)0);
CHECK_EQ(agree, (int64_t)64);
}
}
/* HOSTILE PLANES. A hole in the middle, a duplicate id and an -inf candidate: the cooperative
* planes must treat each exactly as the serial walk does, including the duplicate-first rule that
* makes a repeated candidate contribute its Q mass once. */
TEST(the_cooperative_decision_agrees_on_hostile_candidate_planes) {
std::vector<int32_t> ids = { 0, 1, -1, 3, 3, 5, 6, -1, 8, 9 };
std::vector<float> val = { 4.0f, 3.0f, -INFINITY, 1.5f, 1.4f, 0.5f, -1.0f, -INFINITY,
-2.0f, -INFINITY };
int64_t agree = 0, refused = 0;
for (int k = 0; k < 256; ++k) {
const uint64_t pos = (uint64_t)k;
/* Q's shortlist holds each id ONCE -- a duplicate there is a malformed shortlist, which
* build_q refuses by design -- while the CANDIDATE plane keeps its duplicate 3, which is the
* duplicate-first rule the two decisions must share. */
int32_t qidx[8];
float qv[8];
const int32_t qids[6] = { 0, 1, 3, 5, 6, 8 };
for (int i = 0; i < 8; ++i) {
qidx[i] = i < 6 ? qids[i] : -1;
qv[i] = i < 6 ? -0.3f * (float)i : -INFINITY;
}
RadMtpCoupleState s{};
s.draw.seed = 77;
s.draw.base = pos;
s.draw.mode = 1;
s.round = 1;
s.status = 1;
s.pos = pos;
CHECK(rad_mtp_couple_build_q(qidx, qv, 16, &s));
s.x = s.ids[rad_mtp_couple_pick(
s, rad_spechub_uniform(77, pos, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
const double ua = rad_spechub_uniform(77, pos, RAD_SAMPLE_KEY_ACCEPT);
const double ur = rad_spechub_uniform(77, pos, RAD_SAMPLE_KEY_RESID);
int32_t serial = -7, coop = -7;
const bool ok_s =
rad_mtp_couple_decide(s, ids.data(), val.data(), (int64_t)ids.size(), 16, ua, ur,
&serial);
const bool ok_c = cooperative_decide(s, ids, val, 16, ua, ur, &coop);
CHECK_EQ(ok_c, ok_s);
if (!ok_s) { ++refused; continue; }
CHECK_EQ(coop, serial);
++agree;
}
/* The duplicate id 3 appears twice; the plane is well formed, so no row should refuse. */
CHECK_EQ(refused, (int64_t)0);
CHECK_EQ(agree, (int64_t)256);
}
/* THE GATE IS `rad_mtp_couple_state_valid`, AND IT IS THE SAME TEST ON BOTH SIDES. `decide` is total
* over a candidate plane -- it answers whatever bytes it is given -- so the refusal that keeps an
* uncoupled or stale row from overwriting the pick's token lives in the row gate both the kernel and
* the sampler apply before calling it. This pins that gate rather than pretending `decide` checks a
* state it is never given. */
TEST(an_unbound_row_is_refused_by_the_shared_gate) {
std::vector<int32_t> ids = { 0, 1, 2, 3 };
std::vector<float> val = { 3.0f, 2.5f, 1.0f, -0.5f };
RadMtpCoupleState s = bound_state(ids, 4, 9, 100);
CHECK(rad_mtp_couple_state_valid(s, 8));
/* status 0: a greedy row, which has no Q to couple against. */
RadMtpCoupleState bad = s;
bad.status = 0;
CHECK(!rad_mtp_couple_state_valid(bad, 8));
/* A q[] that no longer sums to 1: the draft's law is gone, so there is nothing to couple to. */
bad = s;
bad.q[0] += 0.25;
CHECK(!rad_mtp_couple_state_valid(bad, 8));
/* An id outside the vocabulary, and an x outside the support. */
bad = s;
bad.ids[0] = 99;
CHECK(!rad_mtp_couple_state_valid(bad, 8));
bad = s;
bad.x = 6;
CHECK(!rad_mtp_couple_state_valid(bad, 8));
/* AND THE KERNEL GATES ON THE SAME THING. Its eligibility test is `s.status == 1 &&
* !(p.flags & RAD_SP_GREEDY) && s.draw.seed == p.seed && s.pos == p.pos &&
* rad_mtp_couple_state_valid(s, vocab)`, so a state that fails the validator above is refused
* before any plane is touched. The cooperative host transcription begins with that same gate:
* a status-0 state makes it refuse without writing. */
RadMtpCoupleState unbound = s;
unbound.status = 0;
int32_t out = -7;
CHECK(!cooperative_decide(unbound, ids, val, 8, 0.5, 0.5, &out));
CHECK_EQ(out, (int32_t)-7); /* nothing was written */
}
RAD_TEST_MAIN()
+521
View File
@@ -0,0 +1,521 @@
/* tests/spechub_couple_test.cpp -- the MTP coupling's arithmetic, checked against its own law.
*
* What can silently go wrong in a maximal coupling, and what each test pins:
*
* 1. THE COMPOSED LAW. A coupling is correct when the emitted token is distributed as the
* TARGET's P, whatever the draft's Q was. The test builds a (P, Q) pair, draws many tokens
* through the coupling, and compares the empirical frequencies against P. This is the one
* property that a wrong acceptance rule, a wrong residual or a swapped mass cannot survive.
*
* 2. THE ACCEPTANCE RULE ITSELF. A draft token is accepted when it equals the token the target
* itself drew at that position: with Q = delta_x the coupling must return x on every draw.
* With P(x) >= Q(x) it must accept unconditionally, because there is no residual to fall
* back on.
*
* 3. THE UNDERFLOW AND DUPLICATE RULES. r(x) is exactly zero on rejection (distinct doubles never
* subtract to 0), so the residual walk can skip x. A candidate that appears twice contributes
* its mass once. Both are properties of the shared helpers, checked directly.
*
* 4. THE Q BUILD. build_q drops entries that underflow, refuses duplicate ids, and stores exactly
* the law the draw walks -- so the numbers in state.q[] are the law, not a normalised copy of
* it that drifted.
*
* Nothing here talks to a card or to libr4d: the helpers are abi/rad_spechub.h, which the plugin and
* the engine both compile.
*/
#include "rad_test.h"
#include "rad_sample.h"
#include "rad_spechub.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <map>
#include <random>
#include <vector>
namespace {
/* A state as the propose kernel would leave it: Q over `ids` from `scores`, x drawn from Q. */
RadMtpCoupleState make_state(const std::vector<int32_t>& ids, const std::vector<float>& scores,
int64_t vocab, uint64_t seed, uint64_t base, int round) {
RadMtpCoupleState s{};
s.draw.seed = seed;
s.draw.base = base;
s.draw.seq = 1;
s.draw.card = 0;
s.draw.mode = 1;
s.round = round;
s.status = 1;
std::vector<int32_t> id8(8, -1);
std::vector<float> v8(8, -INFINITY);
for (size_t i = 0; i < ids.size() && i < 8; ++i) { id8[i] = ids[i]; v8[i] = scores[i]; }
CHECK(rad_mtp_couple_build_q(id8.data(), v8.data(), vocab, &s));
const double u = rad_spechub_uniform(seed, base, RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)round);
s.x = s.ids[rad_mtp_couple_pick(s, u)];
return s;
}
/* The target's candidate plane: ids in [0, n), softmax scores. */
void target_plane(int n, std::vector<int32_t>* ids, std::vector<float>* val) {
ids->clear();
val->clear();
for (int i = 0; i < n; ++i) {
ids->push_back(i);
val->push_back(-0.15f * (float)i); /* a decaying, non-uniform target */
}
}
} /* namespace */
/* THE COMPOSED LAW. Whatever Q is, the coupling's output must be distributed as the target's P.
*
* The draft must be DRAWN FROM Q ON EVERY TRIAL, which is what a round does. Holding x fixed and
* repeating one draw measures the acceptance rate of a single proposal -- P(x)/Q(x) -- not the
* composed distribution, and fails against P however correct the rule is.
*
* The tolerance is five sigma of a binomial at this sample count, so a wrong accept rule (mass on
* x alone) or a naive residual (a renormalised P over the non-Q tokens only) cannot pass. */
TEST(the_coupled_token_is_distributed_as_the_target) {
const uint64_t seed = 424242;
const int n = 8;
std::vector<int32_t> ids;
std::vector<float> val;
target_plane(n, &ids, &val);
/* P from the same FP64 formula the verify uses. */
double sum = 0, P[8] = {};
float top = -INFINITY;
for (float v : val) top = std::max(top, v);
for (int i = 0; i < n; ++i) { P[i] = std::exp((double)val[i] - top); sum += P[i]; }
for (int i = 0; i < n; ++i) P[i] /= sum;
/* Q deliberately differs from P: three tokens, in a different order of preference. */
const int32_t qids[8] = { 0, 1, 2, -1, -1, -1, -1, -1 };
const float qval[8] = { 0.0f, -0.5f, -1.0f, -INFINITY, -INFINITY, -INFINITY, -INFINITY,
-INFINITY };
const int draws = 40000;
std::map<int32_t, int64_t> seen;
for (int k = 0; k < draws; ++k) {
const uint64_t trial = (uint64_t)k;
/* A fresh draft from the same shortlist on every trial, at that trial's coordinate. */
RadMtpCoupleState s{};
s.draw.seed = seed;
s.draw.base = trial;
s.draw.mode = 1;
s.round = 1;
s.status = 1;
CHECK(rad_mtp_couple_build_q(qids, qval, 8, &s));
const double u_draft =
rad_spechub_uniform(seed, trial, RAD_MTP_COUPLE_KEY_DRAFT + 1);
s.x = s.ids[rad_mtp_couple_pick(s, u_draft)];
int32_t out = -1;
CHECK(rad_mtp_couple_decide(s, ids.data(), val.data(), n, 8,
rad_spechub_uniform(seed, trial, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(seed, trial, RAD_SAMPLE_KEY_RESID), &out));
++seen[out];
}
for (int i = 0; i < n; ++i) {
const double want = P[i];
const double got = (double)seen[(int32_t)i] / (double)draws;
const double sigma = std::sqrt(want * (1.0 - want) / (double)draws);
CHECK_NEAR(got, want, 5.0 * sigma + 1e-9);
}
/* Every survivor can be emitted: a rule that lost a tail token would show as a zero here. */
CHECK_EQ((int64_t)seen.size(), (int64_t)n);
}
/* A DRAFT THE TARGET DOMINATES ON EVERY Q TOKEN IS ACCEPTED UNCONDITIONALLY: P(x) >= Q(x), so the
* residual is empty and the ratio test has nothing to reject. The state here has ONE Q token, which
* is the case a softmax over two tokens cannot give (two equal Q tokens of 0.5 each need P above
* 0.5 on both, which a normalised P over three tokens cannot do). */
TEST(a_draft_the_target_dominates_is_always_accepted) {
RadMtpCoupleState one = make_state({ 2 }, { 0.0f }, 8, 9, 0, 1);
CHECK_EQ(one.count, 1);
CHECK_EQ(one.x, 2);
std::vector<int32_t> ids = { 0, 1, 2 };
std::vector<float> peak = { -20.0f, -20.0f, 9.0f }; /* P(2) ~ 1, Q(2) = 1 */
for (int k = 0; k < 500; ++k) {
int32_t out = -1;
CHECK(rad_mtp_couple_decide(one, ids.data(), peak.data(), 3, 8,
rad_spechub_uniform(7, (uint64_t)k, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(7, (uint64_t)k, RAD_SAMPLE_KEY_RESID),
&out));
CHECK_EQ(out, 2);
}
/* AND WHERE P IS SHORT OF Q THE RATIO RULE APPLIES: the same Q token with a target that barely
* admits it is rejected most of the time, and the fallback can never emit x. */
std::vector<float> flat = { 4.0f, 4.0f, -4.0f }; /* P(2) is small */
int rejected = 0;
for (int k = 0; k < 2000; ++k) {
int32_t out = -1;
CHECK(rad_mtp_couple_decide(one, ids.data(), flat.data(), 3, 8,
rad_spechub_uniform(7, (uint64_t)k, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(7, (uint64_t)k, RAD_SAMPLE_KEY_RESID),
&out));
if (out != 2) { ++rejected; CHECK(out == 0 || out == 1); }
}
CHECK(rejected > 0);
}
/* THE RESIDUAL IS (P - Q)+ AND r(x) IS EXACTLY ZERO ON REJECTION. Here Q puts more mass on x than P
* does, so x is sometimes rejected and the token must come from the OTHERS. The check that matters
* is that y is never x on a rejected draw: r(x) contributes +0 exactly, which is what lets the walk
* skip x without changing the total. */
TEST(a_rejected_draft_falls_back_to_the_residual_support) {
RadMtpCoupleState s = make_state({ 0, 1 }, { 0.0f, 0.0f }, 8, 11, 0, 1); /* Q(0) = Q(1) = 0.5 */
CHECK_EQ(s.count, 2);
std::vector<int32_t> ids = { 0, 1, 2 };
/* P(0) = 0.09, so Q(0) = 0.5 exceeds it and x = 0 is rejected most of the time. */
std::vector<float> val = { 0.0f, 2.2f, 1.0f };
int accepted = 0, rejected = 0;
for (int k = 0; k < 4000; ++k) {
int32_t out = -1;
CHECK(rad_mtp_couple_decide(s, ids.data(), val.data(), 3, 8,
rad_spechub_uniform(3, (uint64_t)k, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(3, (uint64_t)k, RAD_SAMPLE_KEY_RESID),
&out));
if (out == s.x) ++accepted;
else { ++rejected; CHECK(out != s.x); }
}
CHECK(accepted > 0);
CHECK(rejected > 0);
}
/* build_q STORES THE LAW IT WALKS. A shortlist with a hole, a -inf score and a duplicate id: the
* stored q[] sums to 1, the duplicate is refused, and the hole contributes nothing. */
TEST(build_q_refuses_malformed_shortlists_and_drops_zero_mass) {
RadMtpCoupleState s{};
/* A hole at slot 1 and -inf at slot 3: two live candidates. */
const int32_t ids[8] = { 4, -1, 7, 9, -1, -1, -1, -1 };
const float val[8] = { 0.0f, 0.0f, -1.0f, -INFINITY, 0.0f, 0.0f, 0.0f, 0.0f };
CHECK(rad_mtp_couple_build_q(ids, val, 16, &s));
CHECK_EQ(s.count, 2);
CHECK_EQ(s.ids[0], 4);
CHECK_EQ(s.ids[1], 7);
CHECK_EQ(s.ids[2], -1);
CHECK_NEAR(s.q[0] + s.q[1], 1.0, 1e-15);
/* A duplicate id is a broken shortlist, not something to aggregate. */
const int32_t dup[8] = { 4, 4, -1, -1, -1, -1, -1, -1 };
CHECK(!rad_mtp_couple_build_q(dup, val, 16, &s));
CHECK_EQ(s.count, 0);
/* An id outside the vocabulary, and a NaN score, are both refused. */
const int32_t wide[8] = { 99, -1, -1, -1, -1, -1, -1, -1 };
CHECK(!rad_mtp_couple_build_q(wide, val, 16, &s));
const float nan_val[8] = { NAN, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
const int32_t one[8] = { 2, -1, -1, -1, -1, -1, -1, -1 };
CHECK(!rad_mtp_couple_build_q(one, nan_val, 16, &s));
/* Every candidate at -inf has no support at all. */
float all_inf[8];
for (int i = 0; i < 8; ++i) all_inf[i] = -INFINITY;
CHECK(!rad_mtp_couple_build_q(one, all_inf, 16, &s));
CHECK_EQ(s.count, 0);
}
/* state_valid IS THE ONE RULE BOTH SIDES REFUSE A ROW BY. A status-0 row, a q[] that does not sum to
* one, an id outside the vocabulary, x missing from the support, and a round outside the band are
* all refused -- because a verifier that accepted any of them would couple against a law that is
* not the draft's. */
TEST(state_valid_refuses_every_malformed_row) {
RadMtpCoupleState s = make_state({ 0, 1 }, { 0.0f, -0.2f }, 8, 5, 0, 2);
CHECK(rad_mtp_couple_state_valid(s, 8));
RadMtpCoupleState bad = s;
bad.status = 0;
CHECK(!rad_mtp_couple_state_valid(bad, 8));
bad = s; bad.q[0] += 0.5; /* no longer sums to 1 */
CHECK(!rad_mtp_couple_state_valid(bad, 8));
bad = s; bad.ids[0] = 99; /* outside the vocabulary */
CHECK(!rad_mtp_couple_state_valid(bad, 8));
bad = s; bad.x = 6; /* x is not in the support */
CHECK(!rad_mtp_couple_state_valid(bad, 8));
bad = s; bad.round = 0; /* outside the band */
CHECK(!rad_mtp_couple_state_valid(bad, 8));
bad = s; bad.round = RAD_MTP_COUPLE_MAX_ROUNDS + 1;
CHECK(!rad_mtp_couple_state_valid(bad, 8));
bad = s; bad.draw.mode = 0; /* a greedy row's state has no Q */
CHECK(!rad_mtp_couple_state_valid(bad, 8));
bad = s; bad.ids[1] = -1; /* a hole above count must carry no mass */
CHECK(!rad_mtp_couple_state_valid(bad, 8) || s.count < 2);
}
/* THE UNIFORM IS THE SPECIFIED DRAW, and it is 53-bit: two seeds that differ in one bit must give
* different numbers, and the range must be [0, 1) with no value at 1. This is the number the
* acceptance compares P(x) against, so a uniform that repeated would make two draft positions
* accept together. */
TEST(the_coupling_uniform_is_the_specified_53_bit_draw) {
for (uint64_t pos = 0; pos < 32; ++pos) {
const double u = rad_spechub_uniform(1234, pos, RAD_SAMPLE_KEY_ACCEPT);
CHECK(u >= 0.0 && u < 1.0);
/* 53 bits: a multiple of 2^-53, exactly. */
CHECK_EQ(u, std::floor(u * 9007199254740992.0) / 9007199254740992.0);
}
CHECK(rad_spechub_uniform(1, 0, RAD_SAMPLE_KEY_ACCEPT) !=
rad_spechub_uniform(2, 0, RAD_SAMPLE_KEY_ACCEPT));
CHECK(rad_spechub_uniform(1, 0, RAD_SAMPLE_KEY_ACCEPT) !=
rad_spechub_uniform(1, 1, RAD_SAMPLE_KEY_ACCEPT));
CHECK(rad_spechub_uniform(1, 0, RAD_SAMPLE_KEY_ACCEPT) !=
rad_spechub_uniform(1, 0, RAD_SAMPLE_KEY_RESID));
}
/* THE WIRE ROWS ARE THE SIZE THE PLANES ARE ADDRESSED AT. A field inserted into either struct would
* shift every later operand of a plane the host writes and the device reads. */
TEST(the_coupling_wire_rows_keep_their_layout) {
CHECK_EQ(sizeof(RadMtpCoupleDraw), (size_t)32);
CHECK_EQ(sizeof(RadMtpCoupleState), (size_t)152);
CHECK_EQ(RAD_MTP_COUPLE_DRAW_WORDS, (size_t)8);
CHECK_EQ(RAD_MTP_COUPLE_STATE_WORDS, (size_t)38);
CHECK_EQ(offsetof(RadMtpCoupleState, q) % 8, (size_t)0);
}
namespace {
/* Upper tail of a chi-square with k degrees of freedom (Wilson-Hilferty). */
double chi2_tail(double x, int k) {
if (k <= 0) return 1.0;
const double z = (std::cbrt(x / k) - (1 - 2.0 / (9 * k))) / std::sqrt(2.0 / (9 * k));
return 0.5 * std::erfc(z / std::sqrt(2.0));
}
/* P as the verify computes it: the FP64 softmax over live ids at finite values, by token id. */
std::vector<double> target_law(const std::vector<int32_t>& ids, const std::vector<float>& v,
int vocab) {
std::vector<double> P((size_t)vocab, 0.0);
float top = -INFINITY;
for (size_t j = 0; j < ids.size(); ++j)
if (ids[j] >= 0) top = std::max(top, v[j]);
double s = 0;
for (size_t j = 0; j < ids.size(); ++j)
if (ids[j] >= 0 && v[j] != -INFINITY) {
const double w = std::exp((double)v[j] - top);
P[(size_t)ids[j]] += w;
s += w;
}
for (double& p : P) p /= s;
return P;
}
/* A tiny autoregressive target and head over kV tokens: logits are a hash of the context. The
* target keeps its top 4 (a top-k filter) at temperature 0.7, so the head's shortlist always holds
* tokens outside P's support. */
constexpr int kV = 6;
void ctx_logits(const std::vector<int32_t>& ctx, uint64_t salt, float* out) {
uint64_t h = salt;
for (int32_t t : ctx) h = rad_sample_splitmix64(h ^ (uint64_t)(t + 1) * 0x100000001b3ull);
for (int i = 0; i < kV; ++i)
out[i] = (float)((double)(rad_sample_splitmix64(h + (uint64_t)i) >> 40) / 16777216.0 * 4.0 - 2.0);
}
void ar_target(const std::vector<int32_t>& ctx, std::vector<int32_t>* ids, std::vector<float>* v) {
float l[kV];
ctx_logits(ctx, 0xabcdef, l);
int ord[kV];
for (int i = 0; i < kV; ++i) ord[i] = i;
std::sort(ord, ord + kV, [&](int a, int b) { return l[a] > l[b] || (l[a] == l[b] && a < b); });
ids->assign((size_t)kV, -1);
v->assign((size_t)kV, -INFINITY);
for (int i = 0; i < 4; ++i) { (*ids)[(size_t)i] = ord[i]; (*v)[(size_t)i] = l[ord[i]] / 0.7f; }
}
void ar_head(const std::vector<int32_t>& ctx, int32_t* id8, float* v8) {
float l[kV];
ctx_logits(ctx, 0x123457, l);
for (int i = 0; i < 8; ++i) { id8[i] = i < kV ? i : -1; v8[i] = i < kV ? l[i] : -INFINITY; }
}
/* sample_pick's rule for the bonus row: an f32 inverse CDF at the seed's own stream. */
int32_t f32_pick(const std::vector<int32_t>& ids, const std::vector<float>& v, uint64_t seed,
uint64_t pos) {
float mx = -INFINITY, sum = 0;
for (size_t i = 0; i < ids.size(); ++i) if (ids[i] >= 0) mx = std::max(mx, v[i]);
for (size_t i = 0; i < ids.size(); ++i) if (ids[i] >= 0) sum += std::exp(v[i] - mx);
const float u = rad_sample_uniform01(seed ^ RAD_SAMPLE_KEY_PICK, pos);
float cum = 0;
int32_t last = -1;
for (size_t i = 0; i < ids.size(); ++i) {
if (ids[i] < 0) continue;
if (v[i] > -INFINITY) last = ids[i];
cum += std::exp(v[i] - mx) / sum;
if (u < cum) return ids[i];
}
return last;
}
} /* namespace */
/* The composed law over many random (P, Q) pairs: targets with holes and -inf candidates, heads
* of one to eight tokens that may lie outside P's support. Each case is a chi-square of the
* emitted tokens against P, and the acceptance rate is checked against sum min(P, Q). */
TEST(the_coupled_token_follows_the_target_for_random_target_and_head_pairs) {
std::mt19937_64 rng(12345);
const int cases = 60, draws = 20000;
int low_p = 0;
for (int c = 0; c < cases; ++c) {
const int vocab = 16 + (int)(rng() % 48);
const int n = 4 + (int)(rng() % (uint64_t)(vocab - 4));
std::vector<int32_t> pool((size_t)vocab);
for (int i = 0; i < vocab; ++i) pool[(size_t)i] = i;
std::shuffle(pool.begin(), pool.end(), rng);
std::vector<int32_t> ids(pool.begin(), pool.begin() + n);
std::vector<float> val((size_t)n);
const float spread = 1.5f + (float)(c % 4);
for (int j = 0; j < n; ++j)
val[(size_t)j] = spread * (float)((double)(rng() >> 11) * 0x1p-53 * 2.0 - 1.0);
for (int j = 1; j < n; ++j) {
const uint64_t r = rng() % 10;
if (r == 0) ids[(size_t)j] = -1;
else if (r == 1) val[(size_t)j] = -INFINITY;
}
const std::vector<double> P = target_law(ids, val, vocab);
const int qn = 1 + (int)(rng() % 8);
std::shuffle(pool.begin(), pool.end(), rng);
int32_t qid[8];
float qv[8];
for (int i = 0; i < 8; ++i) {
qid[i] = i < qn ? pool[(size_t)i] : -1;
qv[i] = i < qn ? spread * (float)((double)(rng() >> 11) * 0x1p-53 * 2.0 - 1.0) : -INFINITY;
}
const uint64_t seed = rng();
RadMtpCoupleState base{};
base.draw.seed = seed;
base.draw.mode = 1;
base.status = 1;
base.round = 1;
CHECK(rad_mtp_couple_build_q(qid, qv, vocab, &base));
double want_acc = 0;
{
std::vector<double> Q((size_t)vocab, 0.0);
for (int i = 0; i < base.count; ++i) Q[(size_t)base.ids[i]] = base.q[i];
for (int i = 0; i < vocab; ++i) want_acc += std::min(P[(size_t)i], Q[(size_t)i]);
}
std::vector<int64_t> cnt((size_t)vocab, 0);
int64_t acc = 0;
for (int t = 0; t < draws; ++t) {
RadMtpCoupleState s = base;
s.draw.base = (uint64_t)t;
s.x = s.ids[rad_mtp_couple_pick(
s, rad_spechub_uniform(seed, s.draw.base, RAD_MTP_COUPLE_KEY_DRAFT + 1))];
int32_t out = -1;
CHECK(rad_mtp_couple_decide(s, ids.data(), val.data(), n, vocab,
rad_spechub_uniform(seed, (uint64_t)t, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(seed, (uint64_t)t, RAD_SAMPLE_KEY_RESID),
&out));
CHECK(out >= 0 && out < vocab);
if (out < 0 || out >= vocab) return;
++cnt[(size_t)out];
acc += out == s.x;
}
double chi = 0;
int dof = -1;
for (int i = 0; i < vocab; ++i) {
if (P[(size_t)i] == 0) { CHECK_EQ(cnt[(size_t)i], (int64_t)0); continue; }
const double e = P[(size_t)i] * draws;
chi += ((double)cnt[(size_t)i] - e) * ((double)cnt[(size_t)i] - e) / e;
++dof;
}
if (chi2_tail(chi, dof) < 1e-4) ++low_p;
const double sd = std::sqrt(want_acc * (1 - want_acc) / draws) + 1e-9;
CHECK_NEAR((double)acc / draws, want_acc, 5.0 * sd);
}
/* 60 independent cases at p < 1e-4: a correct coupling fails none of them in expectation. */
CHECK(low_p <= 1);
}
/* The engine's flow over whole steps: a depth-2 linear draft at (base, round), verify rows at
* n_out + k bound with rad_mtp_couple_binds, the first rejection ending the step, the bonus row by
* the ordinary pick, and the next step drafting again from the committed text. The joint law of the
* first three emitted tokens must be the target's own autoregressive law. */
TEST(the_emitted_sequence_follows_the_target_over_coupled_steps) {
const int L = 3, depth = 2, trials = 150000;
std::map<std::vector<int32_t>, int64_t> cnt;
for (int t = 0; t < trials; ++t) {
const uint64_t seed = rad_sample_splitmix64(0x5eed0000ull + (uint64_t)t);
std::vector<int32_t> out;
while ((int)out.size() < L) {
const uint64_t n_out = out.size();
RadMtpCoupleState st[depth];
std::vector<int32_t> ctx = out;
for (int r = 1; r <= depth; ++r) {
int32_t id8[8];
float v8[8];
ar_head(ctx, id8, v8);
RadMtpCoupleState s{};
s.draw.seed = seed;
s.draw.base = n_out;
s.draw.seq = 1;
s.draw.mode = 1;
s.status = 1;
s.round = r;
CHECK(rad_mtp_couple_build_q(id8, v8, kV, &s));
s.x = s.ids[rad_mtp_couple_pick(
s, rad_spechub_uniform(seed, n_out, RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)r))];
s.pos = rad_mtp_couple_verify_pos(n_out, r);
st[r - 1] = s;
ctx.push_back(s.x);
}
ctx = out;
for (int k = 0; k <= depth && (int)out.size() < L; ++k) {
std::vector<int32_t> ids;
std::vector<float> v;
ar_target(ctx, &ids, &v);
const uint64_t pos = n_out + (uint64_t)k;
int32_t y = -1;
bool more = true;
if (k < depth) {
CHECK(rad_mtp_couple_binds(st[k], 1, seed, n_out, k, st[k].x, kV));
CHECK(rad_mtp_couple_decide(st[k], ids.data(), v.data(), (int64_t)ids.size(),
kV, rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID),
&y));
more = y == st[k].x;
} else {
y = f32_pick(ids, v, seed, pos);
}
out.push_back(y);
ctx.push_back(y);
if (!more) break;
}
}
out.resize((size_t)L);
++cnt[out];
}
double chi = 0;
int dof = -1;
for (int code = 0; code < kV * kV * kV; ++code) {
std::vector<int32_t> seq((size_t)L);
for (int i = 0, c = code; i < L; ++i, c /= kV) seq[(size_t)i] = c % kV;
double p = 1;
std::vector<int32_t> ctx;
for (int i = 0; i < L; ++i) {
std::vector<int32_t> ids;
std::vector<float> v;
ar_target(ctx, &ids, &v);
p *= target_law(ids, v, kV)[(size_t)seq[(size_t)i]];
ctx.push_back(seq[(size_t)i]);
}
const auto it = cnt.find(seq);
const double got = it == cnt.end() ? 0.0 : (double)it->second;
if (p == 0) { CHECK_EQ(got, 0.0); continue; }
const double e = p * trials;
chi += (got - e) * (got - e) / e;
++dof;
}
const double tail = chi2_tail(chi, dof);
std::fprintf(stderr, " joint law of %d tokens over %d trials: chi2 %.1f, %d dof, p %.3f\n", L,
trials, chi, dof, tail);
CHECK(tail > 1e-4);
}
RAD_TEST_MAIN()
+115
View File
@@ -0,0 +1,115 @@
/* spechub_wiring_test.cpp -- what the loader and the reference gate see of the spechub plugin.
*
* The device rows must be production rows and the host rows reference rows; were the whole
* library marked reference, the reference gate would refuse the coupled ops at bringup. The check
* loads the real DSO as the loader does (dlopen and the exported symbols) and asserts the domain
* and the reference answer per row. A host build has only the reference rows and must stay
* classified as such.
*/
#include "rad_test.h"
#include "rad_abi.h"
#include <dlfcn.h>
#include <map>
#include <string>
#include <vector>
namespace {
struct Plugin {
void* handle = nullptr;
const RadPluginInfo* (*info)() = nullptr;
int (*reference)() = nullptr;
int (*kern_ref)(int) = nullptr;
int (*count)() = nullptr;
const RadKernelInfo* (*at)(int) = nullptr;
bool open(const char* path) {
handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!handle) return false;
info = (const RadPluginInfo* (*)())dlsym(handle, "rad_plugin_info");
reference = (int (*)())dlsym(handle, "rad_plugin_reference");
kern_ref = (int (*)(int))dlsym(handle, "rad_kernel_reference");
count = (int (*)())dlsym(handle, "rad_kernel_count");
at = (const RadKernelInfo* (*)(int))dlsym(handle, "rad_kernel_at");
return info && reference && count && at;
}
~Plugin() { if (handle) dlclose(handle); }
};
/* The rule rad_reference_ops applies, over the rows as the loader would classify them: an op is on
* the reference when no row for it is a non-reference row. */
std::vector<std::string> reference_only_ops(const Plugin& p, const std::vector<int>& is_ref) {
std::map<std::string, bool> has_real;
for (int i = 0; i < p.count(); ++i) {
const RadKernelInfo* k = p.at(i);
if (!k) continue;
bool& real = has_real[k->op];
real = real || !is_ref[(size_t)i];
}
std::vector<std::string> out;
for (const auto& kv : has_real)
if (!kv.second) out.push_back(kv.first);
return out;
}
} /* namespace */
TEST(spechub_wiring_the_device_rows_are_production_and_the_oracle_rows_are_reference) {
Plugin p;
REQUIRE(p.open(RAD_SPECHUB_LIB));
CHECK_EQ(p.info()->kind, (int)RAD_PLUGIN_KERNEL);
CHECK_EQ(std::string(p.info()->name), std::string("spechub"));
/* The per-row answer must exist: without it the loader falls back to the library answer, which
* is what mis-classified the device rows. */
REQUIRE(p.kern_ref != nullptr);
/* And the library as a whole is NOT a reference library -- otherwise the loader sorts it below
* the kernel libraries it serves beside and every row inherits the flag. */
CHECK_EQ(p.reference(), 0);
std::vector<int> is_ref;
int dev = 0, host = 0;
for (int i = 0; i < p.count(); ++i) {
const RadKernelInfo* k = p.at(i);
REQUIRE(k != nullptr);
const int r = p.kern_ref(i);
is_ref.push_back(r);
if (k->domain == RAD_DOMAIN_DEVICE) {
++dev;
/* A device row is a kernel, never a reference: this is the line that decides whether a
* coupled run may start at all. */
CHECK_EQ(r, 0);
CHECK(std::string(k->name).rfind("ref_", 0) != 0);
} else {
++host;
CHECK_EQ(k->domain, (int)RAD_DOMAIN_HOST);
/* The host oracle beside it keeps its reference status. */
CHECK_EQ(r, 1);
CHECK(std::string(k->name).rfind("ref_", 0) == 0);
}
}
CHECK_EQ(dev + host, p.count());
#ifdef RAD_SPECHUB_WITH_DEVICE
CHECK_EQ(dev, 2);
CHECK_EQ(host, 2);
#else
CHECK_EQ(dev, 0);
CHECK_EQ(host, 2);
#endif
/* Both ops must have at least one production row on a device build. This is the property the
* gate reads: with it, the coupling is servable without --debug-accept-reference-kernels. */
const std::vector<std::string> refonly = reference_only_ops(p, is_ref);
#ifdef RAD_SPECHUB_WITH_DEVICE
CHECK_EQ(refonly.size(), (size_t)0);
#else
/* No card: both ops are oracle-only, and the gate must still see them as such. */
CHECK_EQ(refonly.size(), (size_t)2);
#endif
}
RAD_TEST_MAIN()
+136
View File
@@ -174,6 +174,142 @@ TEST(a_speech_model_takes_optional_instructions_and_renders_its_unconditional_pr
CHECK(m.last().neg_tokens.empty());
}
/* A model that declares input_special (its speaker tags are special tokens) has its input
* tokenised with them, and one of one branch refuses any guidance but 1 under its field; other
* models' input stays plain text. */
TEST(a_model_that_asks_has_its_input_read_with_special_tokens_and_one_branch_has_no_guidance) {
Speech s;
s.gen.inf.tmpl_plain = "<s>{input}";
s.gen.inf.default_steps = 0;
s.gen.inf.input_special = true;
s.gen.inf.branches = 1;
s.f->tok.last_parse_special = false;
CHECK_EQ(s.post({ { "input", "hi" } }).status, 200);
CHECK(s.f->tok.last_parse_special);
CHECK_EQ(s.refused({ { "input", "hi" }, { "guidance_scale", 2.0 } }),
std::string("guidance_scale"));
CHECK_EQ(s.post({ { "input", "hi" }, { "guidance_scale", 1.0 } }).status, 200);
/* A model that declares no template with instructions refuses them by name. */
s.gen.inf.tmpl.clear();
CHECK_EQ(s.refused({ { "input", "hi" }, { "instructions", "calm" } }),
std::string("instructions"));
CHECK_EQ(s.post({ { "input", "hi" } }).status, 200);
Speech m;
m.gen.inf.tmpl_plain = "<s>{input}";
m.gen.inf.default_steps = 0;
CHECK_EQ(m.post({ { "input", "hi" } }).status, 200);
CHECK(!m.f->tok.last_parse_special);
}
/* A 16-bit mono WAV of the given samples at `rate`. */
static std::string wav_of(const std::vector<int16_t>& x, uint32_t rate) {
std::string d;
for (int16_t v : x) {
d.push_back((char)(v & 0xff));
d.push_back((char)((v >> 8) & 0xff));
}
auto u32 = [](uint32_t v) {
std::string b;
for (int i = 0; i < 4; ++i) b.push_back((char)((v >> (8 * i)) & 0xff));
return b;
};
auto u16 = [](uint16_t v) { return std::string{ (char)(v & 0xff), (char)(v >> 8) }; };
return "RIFF" + u32((uint32_t)(36 + d.size())) + "WAVEfmt " + u32(16) + u16(1) + u16(1) +
u32(rate) + u32(rate * 2) + u16(2) + u16(16) + "data" + u32((uint32_t)d.size()) + d;
}
/* A model that clones a voice takes references: each clip decoded at its rate and padded to
* whole frames, the prompt its references' template with each one's header, transcript and a row
* a frame (token 0, the clips' frames numbered in order), the rest of the rows -1. A data: URL and
* bare base64 both carry a clip. Refused by name: references on a model without them, too many,
* a reference without its text or clip or with an unknown field, a clip past the budget, and
* instructions beside them. */
TEST(a_cloning_model_takes_references_as_clips_and_transcripts_in_its_prompt) {
if (!mm::decoder_available()) return;
Speech s;
s.gen.inf.tmpl_plain = "<s>{input}";
s.gen.inf.tmpl_ref = "<s>R{references}|{input}";
s.gen.inf.ref_item = "[{index}:{text}]{audio}.";
s.gen.inf.ref_rate = 8000;
s.gen.inf.ref_hop = 4;
s.gen.inf.ref_max_samples = 16;
s.gen.inf.ref_max = 2;
s.gen.inf.default_steps = 0;
s.gen.inf.branches = 1;
const std::string w1 = wav_of({ 1000, -2000, 3000, 4000, 5000 }, 8000);
const std::string w2 = wav_of({ -16384, 16384 }, 8000);
const std::string b1 = base64_encode((const uint8_t*)w1.data(), w1.size());
const std::string b2 = base64_encode((const uint8_t*)w2.data(), w2.size());
json refs = json::array({ json{ { "audio", b1 }, { "text", "one" } },
json{ { "audio", "data:audio/wav;base64," + b2 },
{ "text", "two" } } });
CHECK_EQ(s.post({ { "input", "hi" }, { "references", refs } }).status, 200);
const gen::AudioRequest& q = s.last();
/* "<s>R", "[1:one]", 2 frames, ".", "[2:two]", 1 frame, ".", "|hi". */
const std::string head = "<s>R[1:one]";
std::vector<int32_t> want_tok, want_frame;
auto text = [&](const std::string& t) {
for (unsigned char c : t) { want_tok.push_back(c); want_frame.push_back(-1); }
};
auto frames = [&](int32_t f0, int32_t n) {
for (int32_t f = 0; f < n; ++f) { want_tok.push_back(0); want_frame.push_back(f0 + f); }
};
text(head);
frames(0, 2);
text(".[2:two]");
frames(2, 1);
text(".|hi");
CHECK(q.tokens == want_tok);
CHECK(q.ref_frame == want_frame);
REQUIRE(q.ref_cu.size() == 3);
CHECK_EQ(q.ref_cu[1], 8);
CHECK_EQ(q.ref_cu[2], 12);
REQUIRE(q.ref_audio.size() == 12);
CHECK(std::fabs(q.ref_audio[0] - 1000.0f / 32768.0f) < 1e-6f);
CHECK(std::fabs(q.ref_audio[1] + 2000.0f / 32768.0f) < 1e-6f);
CHECK_EQ(q.ref_audio[5], 0.0f);
CHECK_EQ(q.ref_audio[7], 0.0f);
CHECK(std::fabs(q.ref_audio[8] + 0.5f) < 1e-6f);
CHECK_EQ(q.ref_audio[11], 0.0f);
/* Without references the plain prompt, and no clips. */
CHECK_EQ(s.post({ { "input", "hi" }, { "references", json::array() } }).status, 200);
CHECK(s.last().ref_cu.empty() && s.last().ref_frame.empty() && s.last().ref_audio.empty());
const json one = json{ { "audio", b1 }, { "text", "one" } };
CHECK_EQ(s.refused({ { "input", "hi" }, { "references", json::array({ one, one, one }) } }),
std::string("references"));
CHECK_EQ(s.refused({ { "input", "hi" }, { "references", one } }), std::string("references"));
CHECK_EQ(s.refused({ { "input", "hi" },
{ "references", json::array({ json{ { "audio", b1 } } }) } }),
std::string("references[0].text"));
CHECK_EQ(s.refused({ { "input", "hi" },
{ "references", json::array({ json{ { "text", "x" } } }) } }),
std::string("references[0].audio"));
CHECK_EQ(s.refused({ { "input", "hi" },
{ "references", json::array({ json{ { "audio", b1 }, { "text", "x" },
{ "speaker", 1 } } }) } }),
std::string("references[0].speaker"));
CHECK_EQ(s.refused({ { "input", "hi" },
{ "references", json::array({ json{ { "audio", "@@@" },
{ "text", "x" } } }) } }),
std::string("references[0].audio"));
/* 8 and 8 samples fit the 16; a third frame past them does not. */
const std::string w3 = wav_of(std::vector<int16_t>(9, 7), 8000);
const std::string b3 = base64_encode((const uint8_t*)w3.data(), w3.size());
CHECK_EQ(s.refused({ { "input", "hi" },
{ "references", json::array({ one, json{ { "audio", b3 },
{ "text", "x" } } }) } }),
std::string("references[1].audio"));
CHECK_EQ(s.refused({ { "input", "hi" }, { "instructions", "calm" }, { "references", refs } }),
std::string("instructions"));
CHECK_EQ(s.refused({ { "input", "hi" },
{ "references", json::array({ json{ { "audio", b1 },
{ "text", "REFUSE" } } }) } }),
std::string("references[0].text"));
Speech m;
CHECK_EQ(m.refused(Speech::body({ { "references", refs } })), std::string("references"));
}
/* ================================================================== the response */
/* The whole piece: the windows in order whatever order they were played in, as a WAV whose header
+448
View File
@@ -0,0 +1,448 @@
/* torch_zip_test.cpp -- a PyTorch checkpoint read as data (core/format/torch_zip.h).
*
* Each case writes a torch.save archive the way torch lays one out (stored zip entries, a protocol
* 2 pickle of the state dict naming its storages by persistent id) with a small writer of the same
* subset, then reads it back: the tensors' names, dtypes, shapes and bytes, a nested dict, a
* parameter, a ZIP64 directory. The refusals are the point as much as the reads: a global outside
* the weights-only allow-list (the shape every malicious pickle has), an opcode it does not use, a
* compressed or truncated entry and a tensor its storage does not hold are each refused by name,
* with nothing run.
*
* RAD_TEST_TORCH_PTH, when set, names a real checkpoint (Fish Audio's codec.pth) that is opened as
* well; the case is skipped without it.
*/
#include "rad_test.h"
#include "format/torch_zip.h"
#include "format/checkpoint.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <unistd.h>
#include <vector>
using namespace rad;
namespace {
/* ------------------------------------------------------------------ the pickle */
struct Pkl {
std::string b;
void op(char c) { b += c; }
void u32(uint32_t v) { for (int i = 0; i < 4; ++i) b += (char)((v >> (8 * i)) & 0xff); }
void str(const std::string& s) { op('X'); u32((uint32_t)s.size()); b += s; }
void global(const std::string& mod, const std::string& name) { op('c'); b += mod + "\n" + name + "\n"; }
void integer(int64_t v) {
if (v >= 0 && v < 256) { op('K'); b += (char)v; }
else { op('J'); u32((uint32_t)(int32_t)v); }
}
void tuple_of(const std::vector<int64_t>& v) { op('('); for (int64_t x : v) integer(x); op('t'); }
void ordered_dict() { global("collections", "OrderedDict"); op(')'); op('R'); }
};
struct Tensor {
std::string name, storage_cls, key;
std::vector<int64_t> shape, stride;
int64_t offset = 0, numel = 0; /* the storage's elements */
bool parameter = false;
};
/* One tensor's _rebuild_tensor_v2 call, optionally wrapped as a parameter. */
void put_tensor(Pkl& p, const Tensor& t, const std::string& storage_mod = "torch") {
if (t.parameter) p.global("torch._utils", "_rebuild_parameter");
p.global("torch._utils", "_rebuild_tensor_v2");
p.op('(');
p.op('(');
p.str("storage");
p.global(storage_mod, t.storage_cls);
p.str(t.key);
p.str("cpu");
p.integer(t.numel);
p.op('t');
p.op('Q');
p.integer(t.offset);
p.tuple_of(t.shape);
p.tuple_of(t.stride);
p.op((char)0x89); /* requires_grad False */
p.ordered_dict();
p.op('t');
p.op('R');
if (t.parameter) {
/* (tensor, requires_grad, hooks): the tensor is below; build the argument tuple around it. */
p.op((char)0x89);
p.ordered_dict();
p.op((char)0x87); /* TUPLE3 */
p.op('R');
}
}
/* A state dict of `ts`, and `nested` under "generator." as a second dict. */
std::string state_dict(const std::vector<Tensor>& ts, const std::vector<Tensor>& nested = {}) {
Pkl p;
p.op((char)0x80);
p.b += (char)2;
p.ordered_dict();
p.op('(');
for (const Tensor& t : ts) {
p.str(t.name);
put_tensor(p, t);
}
if (!nested.empty()) {
p.str("generator");
p.ordered_dict();
p.op('(');
for (const Tensor& t : nested) {
p.str(t.name);
put_tensor(p, t);
}
p.op('u');
}
p.str("epoch"); /* a value that is not a tensor: skipped */
p.integer(7);
p.op('u');
/* The state dict's _metadata, as torch writes it: BUILD with a dict state. */
p.op('}');
p.op('b');
p.op('.');
return p.b;
}
/* ------------------------------------------------------------------ the zip */
struct ZipEntry { std::string name, data; uint16_t method = 0; };
void le(std::string* s, uint64_t v, int bytes) {
for (int i = 0; i < bytes; ++i) s->push_back((char)((v >> (8 * i)) & 0xff));
}
/* Stored entries, each local header's extra field padded so the data starts 64-byte aligned (as
* torch.save aligns storages), then the central directory, ZIP64 records when asked. */
std::string zip_of(const std::vector<ZipEntry>& es, bool zip64 = false) {
std::string out, cd;
for (const ZipEntry& e : es) {
const uint64_t off = out.size();
const uint64_t base = off + 30 + e.name.size() + 4;
const uint64_t pad = (64 - base % 64) % 64;
le(&out, 0x04034b50, 4); le(&out, 20, 2); le(&out, 0, 2); le(&out, e.method, 2);
le(&out, 0, 4); le(&out, 0, 4);
le(&out, e.data.size(), 4); le(&out, e.data.size(), 4);
le(&out, e.name.size(), 2); le(&out, 4 + pad, 2);
out += e.name;
le(&out, 0xcafe, 2); le(&out, pad, 2); out.append((size_t)pad, '\0');
out += e.data;
std::string ex;
uint32_t loff32 = (uint32_t)off;
if (zip64) {
le(&ex, 1, 2); le(&ex, 8, 2); le(&ex, off, 8);
loff32 = 0xffffffffu;
}
le(&cd, 0x02014b50, 4); le(&cd, 45, 2); le(&cd, 45, 2); le(&cd, 0, 2); le(&cd, e.method, 2);
le(&cd, 0, 4); le(&cd, 0, 4);
le(&cd, e.data.size(), 4); le(&cd, e.data.size(), 4);
le(&cd, e.name.size(), 2); le(&cd, ex.size(), 2); le(&cd, 0, 2);
le(&cd, 0, 2); le(&cd, 0, 2); le(&cd, 0, 4); le(&cd, loff32, 4);
cd += e.name + ex;
}
const uint64_t cd_off = out.size();
out += cd;
if (zip64) {
const uint64_t z = out.size();
le(&out, 0x06064b50, 4); le(&out, 44, 8); le(&out, 45, 2); le(&out, 45, 2);
le(&out, 0, 4); le(&out, 0, 4); le(&out, es.size(), 8); le(&out, es.size(), 8);
le(&out, cd.size(), 8); le(&out, cd_off, 8);
le(&out, 0x07064b50, 4); le(&out, 0, 4); le(&out, z, 8); le(&out, 1, 4);
}
le(&out, 0x06054b50, 4); le(&out, 0, 2); le(&out, 0, 2);
le(&out, zip64 ? 0xffff : es.size(), 2); le(&out, zip64 ? 0xffff : es.size(), 2);
le(&out, zip64 ? 0xffffffffu : cd.size(), 4); le(&out, zip64 ? 0xffffffffu : cd_off, 4);
le(&out, 0, 2);
return out;
}
std::string floats(std::initializer_list<float> v) {
std::string s(v.size() * 4, '\0');
std::memcpy(s.data(), v.begin(), s.size());
return s;
}
/* The archive of `pkl` with the storages "0" and "1": 6 and 4 floats. */
std::string archive(const std::string& pkl, bool zip64 = false, uint16_t method = 0) {
return zip_of({ { "ck/data.pkl", pkl, method }, { "ck/byteorder", "little" },
{ "ck/data/0", floats({ 1, 2, 3, 4, 5, 6 }) },
{ "ck/data/1", floats({ 7, 8, 9, 10 }) } },
zip64);
}
std::vector<Tensor> two() {
return { Tensor{ "a.weight", "FloatStorage", "0", { 2, 3 }, { 3, 1 }, 0, 6 },
Tensor{ "a.bias", "FloatStorage", "1", { 2 }, { 1 }, 2, 4, true } };
}
const TorchTensor* by_name(const TorchZipFile& f, const std::string& n) {
for (const TorchTensor& t : f.tensors())
if (t.name == n) return &t;
return nullptr;
}
float f32_at(const TorchTensor& t, int i) {
float v;
std::memcpy(&v, t.data + 4 * i, 4);
return v;
}
} /* namespace */
/* The tensors as torch.save wrote them: names, dtype, shape, the bytes at the storage offset, a
* parameter's tensor, a nested dict's names dotted and an integer skipped; in a plain and a ZIP64
* directory. */
TEST(a_state_dict_reads_back_as_its_tensors) {
for (bool z64 : { false, true }) {
const std::string bytes = archive(state_dict(two(), { Tensor{ "x", "FloatStorage", "0",
{ 3 }, { 1 }, 3, 6 } }),
z64);
TorchZipFile f;
std::string why;
REQUIRE_EQ(f.open_bytes((const uint8_t*)bytes.data(), bytes.size(), &why), (int)RAD_OK);
CHECK_EQ(f.tensors().size(), (size_t)3);
const TorchTensor* w = by_name(f, "a.weight");
REQUIRE(w != nullptr);
CHECK_EQ(w->dtype, (uint32_t)RAD_F32);
CHECK(w->shape == std::vector<int64_t>({ 2, 3 }));
CHECK_EQ(w->bytes, (uint64_t)24);
CHECK_EQ(f32_at(*w, 5), 6.0f);
CHECK_EQ((uintptr_t)w->data % 64, (uintptr_t)bytes.data() % 64); /* mapped in place */
const TorchTensor* bias = by_name(f, "a.bias");
REQUIRE(bias != nullptr);
CHECK_EQ(f32_at(*bias, 0), 9.0f); /* storage 1 from element 2 */
CHECK_EQ(f32_at(*bias, 1), 10.0f);
const TorchTensor* x = by_name(f, "generator.x");
REQUIRE(x != nullptr);
CHECK_EQ(f32_at(*x, 0), 4.0f);
}
}
/* What a malicious or foreign file holds is refused by name before anything is read past it: a
* global outside the allow-list (os.system, builtins.eval), a storage class that is not one, an
* opcode the subset does not use, a compressed entry, a pickle cut short, and a tensor that runs
* past its storage or is not contiguous in it. */
TEST(anything_outside_the_weights_only_subset_is_refused_by_name) {
auto refused = [](const std::string& bytes, const char* want) {
TorchZipFile f;
std::string why;
const int st = f.open_bytes((const uint8_t*)bytes.data(), bytes.size(), &why);
CHECK(st < 0);
CHECK(has(why, want));
if (!has(why, want)) std::fprintf(stderr, " want %s, why: %s\n", want, why.c_str());
};
{
Pkl p;
p.op((char)0x80); p.b += (char)2;
p.global("os", "system");
p.op('('); p.str("echo pwned"); p.op('t'); p.op('R'); p.op('.');
refused(archive(p.b), "'os.system'");
}
{
Pkl p;
p.op((char)0x80); p.b += (char)2;
p.str("builtins"); p.str("eval"); p.op((char)0x93);
p.op('.');
refused(archive(p.b), "'builtins.eval'");
}
{
std::vector<Tensor> ts = two();
ts[0].storage_cls = "DoubleStorage";
refused(archive(state_dict(ts)), "torch.DoubleStorage");
}
{
std::string pk = state_dict(two());
pk.insert(pk.size() - 1, 1, 'i'); /* INST, an old way to build any object */
refused(archive(pk), "opcode 0x69");
}
refused(archive(state_dict(two()), false, 8), "compressed");
{
const std::string pk = state_dict(two());
refused(archive(pk.substr(0, pk.size() / 2)), "pickle");
}
{
std::vector<Tensor> ts = two();
ts[1].shape = { 3 }; /* three floats from element 2 of a 4-float storage */
refused(archive(state_dict(ts)), "does not fit its storage");
}
{
std::vector<Tensor> ts = two();
ts[0].stride = { 1, 2 }; /* a transposed view */
refused(archive(state_dict(ts)), "not contiguous");
}
refused(zip_of({ { "data.pkl", state_dict(two()) } }), "no <archive>/data.pkl");
refused(std::string("PK\x03\x04 is a local header, and this is not an archive"),
"end-of-central-directory");
}
/* Pickles that are well-formed but hostile to the reader: a dict that holds itself (the memo makes
* one in a few bytes, and a recursive walk would never end), a dict shared by two parents, and a
* shape whose element count wraps 64 bits to one the storage holds. */
TEST(a_cyclic_dict_and_a_wrapping_shape_are_refused) {
auto refused = [](const std::string& pkl, const char* want) {
const std::string bytes = archive(pkl);
TorchZipFile f;
std::string why;
const int st = f.open_bytes((const uint8_t*)bytes.data(), bytes.size(), &why);
CHECK(st < 0);
CHECK(has(why, want));
if (!has(why, want)) std::fprintf(stderr, " want %s, why: %s\n", want, why.c_str());
};
{
Pkl p;
p.op((char)0x80); p.b += (char)2;
p.op('}'); p.op('q'); p.b += (char)0;
p.str("self"); p.op('h'); p.b += (char)0; p.op('s');
p.op('.');
refused(p.b, "reached twice");
}
{
Pkl p;
p.op((char)0x80); p.b += (char)2;
p.op('}');
p.str("a"); p.op('}'); p.op('q'); p.b += (char)1; p.op('s');
p.str("b"); p.op('h'); p.b += (char)1; p.op('s');
p.op('.');
refused(p.b, "reached twice");
}
{
/* (2^62 + 1, 4) at strides (4, 1): the product wraps to 4, which storage "0" holds. */
Pkl p;
p.op((char)0x80); p.b += (char)2;
p.ordered_dict();
p.op('(');
p.str("big");
p.global("torch._utils", "_rebuild_tensor_v2");
p.op('(');
p.op('('); p.str("storage"); p.global("torch", "FloatStorage"); p.str("0"); p.str("cpu");
p.integer(6); p.op('t'); p.op('Q');
p.integer(0);
p.op('(');
p.op((char)0x8a); p.b += (char)8;
le(&p.b, ((uint64_t)1 << 62) + 1, 8);
p.integer(4);
p.op('t');
p.tuple_of({ 4, 1 });
p.op((char)0x89); p.ordered_dict(); p.op('t'); p.op('R');
p.op('u');
p.op('.');
refused(p.b, "past 64 bits");
}
}
/* Malformed archives, made by cutting a valid one at every length and by mutating its bytes, are
* refused or read without a read outside the buffer: every tensor accepted lies inside it and
* holds exactly the bytes its shape names. The buffer is an exact-size heap block, so a sanitiser
* build sees any overrun. */
TEST(malformed_archives_are_refused_or_read_inside_the_file) {
const std::vector<std::string> seeds = { archive(state_dict(two())),
archive(state_dict(two(), two()), true) };
int64_t accepted = 0, refused = 0;
auto run = [&](const std::string& s) {
std::vector<uint8_t> buf(s.begin(), s.end());
TorchZipFile f;
std::string why;
if (f.open_bytes(buf.data(), buf.size(), &why) < 0) {
++refused;
return;
}
++accepted;
for (const TorchTensor& t : f.tensors()) {
uint64_t n = (uint64_t)rad_dtype_bits(t.dtype) / 8;
for (int64_t d : t.shape) n *= (uint64_t)d;
CHECK_EQ(n, t.bytes);
CHECK(t.data >= buf.data() && t.data <= buf.data() + buf.size() &&
t.bytes <= (uint64_t)(buf.data() + buf.size() - t.data));
}
};
for (const std::string& s : seeds)
for (size_t n = 0; n < s.size(); ++n) run(s.substr(0, n));
uint64_t x = 0x9e3779b97f4a7c15ull;
auto next = [&]() { /* splitmix64: a fixed sequence, so a failure reproduces */
uint64_t z = (x += 0x9e3779b97f4a7c15ull);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
return z ^ (z >> 31);
};
for (int it = 0; it < 20000; ++it) {
std::string s = seeds[next() % seeds.size()];
for (int k = 1 + (int)(next() % 8); k-- > 0;) {
const size_t at = next() % s.size();
static const uint8_t kEdge[] = { 0x00, 0x01, 0x7f, 0x80, 0xff };
switch (next() % 3) {
case 0: s[at] = (char)next(); break;
case 1: s[at] = (char)(s[at] ^ (1 << (next() % 8))); break;
default: s[at] = (char)kEdge[next() % 5]; break;
}
}
run(s);
}
std::fprintf(stderr, " %lld refused, %lld read\n", (long long)refused, (long long)accepted);
CHECK(refused > 0);
CHECK(accepted > 0);
}
/* A .pth beside the safetensors joins the checkpoint under its stem, so a plugin maps
* `codec.<name>`; a torch copy of the model's own weights is passed over, and a file the reader
* refuses is left out with a warning rather than failing the checkpoint. */
TEST(a_pth_beside_the_safetensors_joins_the_checkpoint_under_its_stem) {
std::string d = radtest::tmp_path("tz.XXXXXX");
REQUIRE(mkdtemp(d.data()) != nullptr);
auto write = [&](const std::string& name, const std::string& bytes) {
FILE* f = std::fopen((d + "/" + name).c_str(), "wb");
REQUIRE(f != nullptr);
std::fwrite(bytes.data(), 1, bytes.size(), f);
std::fclose(f);
};
/* A one-tensor safetensors model and its config. */
{
std::string hdr = "{\"w\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4]}}";
while (hdr.size() % 8) hdr += ' ';
std::string st;
le(&st, hdr.size(), 8);
st += hdr + floats({ 1 });
write("model.safetensors", st);
write("config.json", "{\"model_type\": \"tiny\"}");
}
write("codec.pth", archive(state_dict(two())));
write("pytorch_model.pth", archive(state_dict(two())));
{
Pkl p;
p.op((char)0x80); p.b += (char)2;
p.global("os", "system");
p.op('.');
write("optimizer.pth", archive(p.b));
}
Checkpoint ck;
REQUIRE_EQ(ck.open(d), (int)RAD_OK);
CHECK(ck.find("w") != nullptr);
const SrcTensor* w = ck.find("codec.a.weight");
REQUIRE(w != nullptr);
CHECK_EQ(w->rad_dtype, (uint32_t)RAD_F32);
CHECK(w->shape == std::vector<int64_t>({ 2, 3 }));
CHECK(ck.find("codec.a.bias") != nullptr);
CHECK(ck.find("pytorch_model.a.weight") == nullptr);
CHECK(ck.find("optimizer.a.weight") == nullptr);
std::filesystem::remove_all(d);
}
/* A real torch.save checkpoint, when one is named: every tensor's bytes inside the file. */
TEST(a_real_checkpoint_named_by_the_environment_reads) {
const char* p = std::getenv("RAD_TEST_TORCH_PTH");
if (!p || !*p) SKIP("RAD_TEST_TORCH_PTH names no checkpoint");
TorchZipFile f;
std::string why;
REQUIRE_EQ(f.open(p, &why), (int)RAD_OK);
CHECK(!f.tensors().empty());
uint64_t bytes = 0;
for (const TorchTensor& t : f.tensors()) bytes += t.bytes;
std::fprintf(stderr, " %s: %zu tensors, %.1f MiB\n", p, f.tensors().size(),
(double)bytes / (1 << 20));
}
RAD_TEST_MAIN()
+9
View File
@@ -285,6 +285,15 @@ TEST(the_api_key_gate_holds_every_route_but_the_probes) {
CHECK_EQ(ask(post("/tokenize", R"({"prompt":"a"})", "Authorization: Bearer k\r\n")).status, 200);
CHECK_EQ(ask("OPTIONS /v1/chat/completions HTTP/1.1\r\nHost: t\r\n"
"Access-Control-Request-Headers: authorization\r\n\r\n").status, 204);
/* A release changes the server's state like any other route: it takes the key, and a
* browser's preflight for it is allowed the method. */
CHECK_EQ(ask("DELETE /sessions/chat-7 HTTP/1.1\r\nHost: t\r\n\r\n").status, 401);
CHECK(ask("DELETE /sessions/chat-7 HTTP/1.1\r\nHost: t\r\nAuthorization: Bearer k\r\n\r\n")
.status != 401);
const Reply pre = ask("OPTIONS /sessions/chat-7 HTTP/1.1\r\nHost: t\r\n"
"Access-Control-Request-Method: DELETE\r\n\r\n");
CHECK_EQ(pre.status, 204);
CHECK(has(pre.header("Access-Control-Allow-Methods"), "DELETE"));
/* Headers that announce 100 MB and no body: the 401 comes without waiting for it. */
const Reply big = ask("POST /v1/completions HTTP/1.1\r\nHost: t\r\nContent-Type: application/json\r\n"
"Content-Length: 100000000\r\n\r\n");