radiance 1.14.0

New models and formats:
- libr3d: a kernel library for RDNA3 (gfx11) cards
- nomic-embed-text-v2-moe (the nomicbert plugin)
- Gemma 4 E2B with its per-layer MLP width, and Google's unmodified E2B/E4B directories in bf16
- DeepSeek-V4.1-Flash converted straight from its release: the Engram tables, the fused imatrix and
  rad-convert --chat-template for a release that ships no template
- GGUF Q8_0, Q4_K and Q6_K tensors import as their planes; rad-convert writes them without a recipe
- Qwen3.8-Flash-Next-FP8 converts and serves through qwen4exp_fp8

Speed:
- hc_read's decode kernels as one grid (34.7 -> 25.2 us at 4 rows) and its tiled up-mix pipelined
- gemm_fp8a8: the narrow form's scales staged through LDS (Flash-Next int8 at 32 rows 83.6 -> 68.3
  us), the gated three-tile form at 8 waves (gate_up at 48 rows 272.9 -> 180.6 us)
- Qwen3.8-27B: the delta net's out-projection read beside its decode recurrent update (x1 19.40 ->
  19.10 ms a step), and the verify's split-KV attention sized by context depth (x3 at 180K 42.4 ->
  40.3 ms a step)
- Hy-Memory (HYV3) decode: fused QK norm, RoPE and KV store, residual adds folded into the norms,
  coalesced one-token expert GEMMs
- spechub: the coupled verify walks the live candidates only (151 -> 31 us a launch)

Speculation:
- DFlash2: lossless coupled acceptance at T > 0 (--draft-coupling on)
- A block drafter's proposals verified as a tree, on by default for the Gemma 4 31B's DFlash2, with
  a block-16 tree that runs its short block under load

Features:
- Decode-hot residency: --draft-expert-placement host, --expert-profile, --expert-pin-top, and
  --expert-stats FILE for the routed experts each layer selects
- --ngram-placement ram=DIR: one n-gram table shared by engines on separate cards
- Prefix cache: --prefix-resume exact (default) resumes a hit on the cold run's own chunk grid, so it
  answers bit-identically; snapshots at a head other prompts share, from 528-token prompts, and for
  tip-only one drafter window below the tip; hits on models whose KV groups have different block
  sizes; the snapshot store keeps a floor of 8 ahead of --host-headroom-mib
- Typed tool-call argument tags; rad-chatparse --request renders and reads back one request as the
  server does
- MiniMax-H3: keyframes ride a latent upscale
- Gemma 3's fused all-reduce junction on the lossy wire

Fixes:
- A speculative step shorter than its band (an MTP step of 4 rows at gqa 8) no longer stops the
  engine with a scratch refusal at issue (#293)
- --p2p off: prefill back to 1.12.0's rate; 1.13.0's push check read a host-memory slot over the link
  twice (#323)
- A chat template that cannot render a conversation is refused at load, not mid-request
- imatrix entries found under llama.cpp's spelling; the W4A8 prefill's tail scale read; the GDN conv
  kernels on an f32 weight; dense integer rows at the group they compute (a Q8_0 weight at group 32)
- --expert-profile refuses a profile recorded on another model
- hc_read's one-grid wait traps past its deadline instead of reading a stale value

Changes: Plugin ABI 31, unchanged. RADIANCE_DRAFT_TREE, DFLASH2_TREE_NODES, DFLASH2_TREE_TEMP and
DFLASH_Q_TEMP are gone (trees run where the probe says they pay; temperatures 1.25 / 0.6).
This commit is contained in:
Deadcode committed 2026-10-29 12:04:24 +01:00
1 parent 481fcd5df0
commit 4a61d7296b
160 files changed
+8790 -6819

No files matched your search

+3 -3
View File
@@ -594,9 +594,9 @@ set_tests_properties(ops_doc PROPERTIES
TIMEOUT ${RAD_TEST_TIMEOUT}
ENVIRONMENT "ROCR_VISIBLE_DEVICES=99")
# docs/KERNELS.md is generated by rad-kbench and merged by hand; a partial merge leaves a
# library's "rows not reached" header from one run above a table from another (v1.13.0: 239
# against 243 rows). The counts must agree with each other and with the headline; cheap.
# docs/KERNELS.md is generated by rad-kbench and merged by hand; a partial merge can leave a
# library's "rows not reached" header from one run above a table from another. The counts must
# agree with each other and with the headline; cheap.
if(EXISTS ${CMAKE_SOURCE_DIR}/docs/KERNELS.md)
add_test(NAME kernel_report_check
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/kernel_report_check.sh
+2
View File
@@ -22,6 +22,7 @@ ABI_FIELD(RadArchProbe, kv_stream_ok)
ABI_FIELD(RadArchProbe, control_vector_ok)
ABI_FIELD(RadArchProbe, tp_attn_rows_ok)
ABI_FIELD(RadArchProbe, state_f16_ok)
ABI_FIELD(RadArchProbe, tree_pays)
ABI_STRUCT(RadArgs)
ABI_FIELD(RadArgs, t)
ABI_FIELD(RadArgs, n_t)
@@ -117,6 +118,7 @@ ABI_FIELD(RadBuildCtx, tp_attn_rows)
ABI_FIELD(RadBuildCtx, state_dtype)
ABI_FIELD(RadBuildCtx, draft_coupling)
ABI_FIELD(RadBuildCtx, weight_prefetch_off)
ABI_FIELD(RadBuildCtx, draft_tree)
ABI_STRUCT(RadAudioGenBatch)
ABI_FIELD(RadAudioGenBatch, n_lane)
ABI_FIELD(RadAudioGenBatch, lane)
+79 -1
View File
@@ -40,7 +40,8 @@ struct Slab {
USED = SLOT + kGroups * kTok, /* [kGroups][kSeq] */
BT = USED + kGroups * kSeq, /* [kGroups][kSeq][kPitch] */
FIRST = BT + kGroups * kSeq * kPitch, /* [kGroups][kSeq] */
END = FIRST + kGroups * kSeq
PAR = FIRST + kGroups * kSeq, /* [kTok] spec_parent, when a test stages trees */
END = PAR + kTok
};
alignas(16) int32_t w[END] = {};
StepSlot st[kSeq];
@@ -219,6 +220,83 @@ TEST(the_cards_acceptance_is_accept_greedy_and_the_end_of_generation_cut) {
CHECK(partial > 100);
}
/* The same over trees (rad_drafter_tree): a row whose spec_parent marks a tree verify is accepted
* by accept_tree's walk (the lowest-numbered child that is the target's pick at its parent, from
* the bonus token down), cut at the first end-of-generation token, and the StepSlot carries the
* accepted nodes for ADV_COMPACT. Random trees of 0-8 nodes over {1, 2, 3}, so siblings often
* share a token and the lowest-numbered one must win. Seeded; a failure prints the case. */
TEST(the_cards_tree_acceptance_is_accept_tree_and_the_end_of_generation_cut) {
const uint32_t seed = 0x7ee5eedu;
uint32_t rng = seed;
int bad = 0, deep = 0, branched = 0, cut_cases = 0;
for (int c = 0; c < 10000 && !bad; ++c) {
Slab s(ADV_ACCEPT);
s.a.parent_off = Slab::PAR * 4;
for (int t = 0; t < Slab::kTok; ++t) s.w[Slab::PAR + t] = -2;
int n_eog = 0;
int32_t eog_ids[3];
for (int32_t t : { 2, 3, 8 }) if (lcg(rng) % 4 == 0) eog_ids[n_eog++] = t;
for (int j = 0; j < n_eog; ++j) s.eog[j] = eog_ids[j];
s.a.n_eog = n_eog;
auto is_eog = [&](int32_t t) {
return std::find(eog_ids, eog_ids + n_eog, t) != eog_ids + n_eog;
};
const int n_rows = 1 + (int)(lcg(rng) % 4);
int k = 0, out_row = 0;
struct Want { int card, acc, tok, head; int32_t path[8]; } want[4];
for (int i = 0; i < n_rows; ++i) {
const int n_spec = (int)(lcg(rng) % 9);
const int n_tok = 1 + n_spec;
const int ctx = (int)(lcg(rng) % 1000);
const int rtok = k; /* a decode row: its first token is the bonus */
s.row(i, true, k, n_tok, ctx, i, rtok, out_row, n_spec);
int32_t draft[8] = {}, parent[8] = {}, target[9] = {};
s.w[Slab::TOK + rtok] = 50;
s.w[Slab::PAR + rtok] = -1; /* the root: this row is a tree verify */
for (int j = 1; j <= n_spec; ++j) {
parent[j - 1] = (int32_t)(lcg(rng) % (uint32_t)j);
draft[j - 1] = 1 + (int32_t)(lcg(rng) % 3);
s.w[Slab::TOK + rtok + j] = draft[j - 1];
s.w[Slab::PAR + rtok + j] = (rtok - k) + parent[j - 1];
branched += parent[j - 1] != j - 1;
}
for (int r = 0; r <= n_spec; ++r) {
target[r] = 1 + (int32_t)(lcg(rng) % 3);
s.src[out_row + r] = target[r];
}
int32_t out[9] = {}, path[8] = {}, acc = -1;
CHECK_OK(accept_tree(draft, parent, n_spec, target, out, path, &acc));
const int32_t cut = accept_cut_at_eog(out, acc, is_eog);
deep += cut >= 2;
cut_cases += cut < acc;
want[i] = { i, cut, out[cut], ctx + cut, {} };
std::memcpy(want[i].path, path, sizeof path);
out_row += 1 + n_spec;
k += n_tok;
}
s.run();
for (int i = 0; i < n_rows && !bad; ++i) {
const StepSlot& S = s.st[want[i].card];
bool ok = S.acc == want[i].acc && S.tok[0] == want[i].tok && S.n_acc == want[i].acc + 1 &&
S.head == want[i].head && S.ctx == want[i].head + 1 && S.npath == want[i].acc;
for (int t = 0; ok && t < want[i].acc; ++t) ok = S.path[t] == want[i].path[t];
if (!ok) {
bad = 1;
CHECK(ok);
std::fprintf(stderr, " seed 0x%x, case %d, row %d: card acc %d tok %d npath %d; "
"host acc %d tok %d\n", seed, c, i, S.acc, S.tok[0], S.npath,
want[i].acc, want[i].tok);
}
}
}
CHECK_EQ(bad, 0);
/* The draw reaches branching trees, accepted paths of two nodes or more, and the cut. */
CHECK(branched > 1000);
CHECK(deep > 100);
CHECK(cut_cases > 100);
}
/* ================================================================== ADV_TRUNK */
/* A verify step issued ahead takes its rows from the StepSlots: the bonus token and the head's
+10 -1
View File
@@ -119,6 +119,8 @@ struct RadBuilder {
bool drafter_shared = false;
int drafter_pos = -1;
int64_t drafter_short = 0; /* rad_drafter_short_block */
/* A tree drafter's parents buffer (rad_drafter_tree), 0 for a chain. */
rad_buf drafter_parents = 0;
/* The buffers named to rad_buf_concurrent: the ones a second lane touches. */
std::vector<rad_buf> concurrent;
@@ -399,6 +401,11 @@ extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) {
b->drafter_pos = pos_offset;
return RAD_OK;
}
extern "C" int rad_drafter_tree(RadBuilder* b, rad_buf parents) {
if (!b || b->drafter.kind != RAD_DRAFT_BLOCK || parents == 0) return RAD_E_STATE;
b->drafter_parents = parents;
return RAD_OK;
}
/* The core's chaining decision as the recorder answers it (it has no chaining backend): 0 unless a
* test holds a ChainOn, to see where a plugin places work when launches chain. */
static int g_chain_on = 0;
@@ -411,7 +418,9 @@ struct ChainOn {
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;
if (b->drafter_parents ? (block < 2 || block >= full)
: (block >= full || block - (full - b->drafter.depth) < 1))
return RAD_E_INVAL;
b->drafter_short = block;
return RAD_OK;
}
+48 -2
View File
@@ -4705,8 +4705,8 @@ TEST(the_gemma4_e4b_form_replicates_kv_heads_at_four_ranks) {
/* A double-wide MLP is per layer: layers 0..7 declare gate_up [2F, E] and down [E, F] with F =
* intermediate_size, layers 8..11 [4F, E] and [E, 2F], and every activation op carries its layer's
* width. The shared `gate_up` and `ffn` buffers hold the widest layer, so a narrow layer's slice
* keeps the wide row pitch. */
* width. The narrow layers use the `gate_up` and `ffn` buffers and the wide ones `gate_up_wide`
* and `ffn_wide`, each at its own row width. */
TEST(a_gemma4_e2b_form_declares_the_double_wide_layers) {
RadBuilder b;
RadModelMeta meta = gemma4_e2b_meta();
@@ -7120,6 +7120,52 @@ TEST(gemma4_31b_dflash2_folds_both_passes_prologues) {
}
}
/* The block-16 DFlash2 drafter (the DBloom fine-tune) as a tree: its query pass also runs at its
* short block of 8 rows (rad_drafter_short_block), whose selector grows a 7-node tree at an anchor
* stride of 8, beside its own block's 15 at 16; a block it has no ops for fails the step. A
* 7-node tree over the block-16 drafter (--num-speculative-tokens 7) declares the same short
* block. At block 8 the drafter declares none. */
TEST(gemma4_31b_dflash2_block16_tree_runs_its_short_block) {
for (int b16 = 0; b16 < 3; ++b16)
for (int world : { 1, 4 }) {
G431Df2 f;
for (size_t i = 0; i < f.keys.size(); ++i)
if (!std::strcmp(f.keys[i], "draft.block_size")) f.vals[i] = b16 ? "16" : "8";
const int64_t own = b16 == 2 ? 7 : b16 ? 15 : 7; /* the tree's nodes */
const RadModelMeta meta = f.meta();
RadBuilder b;
g431df2_encs(b, true);
RadBuildCtx ctx = build_ctx(0, world);
ctx.max_tok = 2048;
ctx.max_spec = (int)own;
ctx.draft_tree = 1;
REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK);
REQUIRE(b.drafter_parents != 0);
CHECK_EQ(b.drafter_short, b16 ? 8 : 0);
const int64_t full = b16 ? 16 : 8;
std::vector<int64_t> blocks = { full };
if (b16) blocks.push_back(8);
for (int64_t rows : blocks) {
const auto qry = query_pass(b, 2, rows, rows - 1);
const auto v = run_passes(b, gemma4_bf16::step, { qry.get() }, 0, world);
REQUIRE(steps_ok(v));
int64_t nodes = -1, stride = -1, n_tree = 0;
for (const RecIssue& is : v[0]->issues)
if (const RecOp* o = b.op_of(is.op); o && o->op == "dflash_tree") {
nodes = pint(o, "nodes");
stride = pint(o, "anchor_stride");
++n_tree;
}
CHECK_EQ(n_tree, 1);
CHECK_EQ(nodes, std::min<int64_t>(own, rows - 1));
CHECK_EQ(stride, rows);
}
const auto qbad = query_pass(b, 2, 4, 3);
const auto vb = run_passes(b, gemma4_bf16::step, { qbad.get() }, 0, world);
CHECK(!vb[0]->step_fail.empty());
}
}
/* DFlash2's query pass issues each residual add with the norm after it, as one add_rmsnorm where it
* resolves: after every attention (the feed-forward norm) and every feed-forward (the next layer's
* attention norm, after the last the final norm), ten on the 31B's five layers, no add left and
+45 -3
View File
@@ -1105,6 +1105,37 @@ TEST(a_block_drafters_short_block_is_shorter_and_still_proposes) {
}
}
/* A tree drafter (rad_drafter_tree) takes a short block too: a block-16 tree of 15 nodes declares
* one of 8 rows, over which the drafter grows a tree of its own of up to 7 nodes; and a tree of 7
* nodes over the same block, where a chain's rule (rows past the 9 that propose nothing) would refuse
* it. */
TEST(a_tree_drafter_takes_a_short_block) {
Registry reg;
Builder b(reg, make_meta(), make_ctx());
RadBufDecl bd{};
bd.dtype = RAD_I32; bd.rank = 2; bd.shape[0] = 256; bd.shape[1] = 15;
const rad_buf prop = rad_decl_buffer(&b, "prop", &bd);
const rad_buf par = rad_decl_buffer(&b, "par", &bd);
RadDrafterDecl d{};
d.kind = RAD_DRAFT_BLOCK; d.name = "df"; d.depth = 15; d.block = 16; d.mask_token = 5;
d.proposal = prop; d.proposal_pitch = 15;
CHECK_OK(rad_declare_drafter(&b, &d));
CHECK_OK(rad_drafter_tree(&b, par));
CHECK_EQ(rad_drafter_short_block(&b, 16), RAD_E_INVAL); /* not shorter */
CHECK_EQ(rad_drafter_short_block(&b, 1), RAD_E_INVAL); /* no row to propose */
CHECK_OK(rad_drafter_short_block(&b, 8));
CHECK_EQ(b.program().drafter_short_block, 8);
Builder b7(reg, make_meta(), make_ctx());
const rad_buf prop7 = rad_decl_buffer(&b7, "prop", &bd);
const rad_buf par7 = rad_decl_buffer(&b7, "par", &bd);
RadDrafterDecl d7 = d;
d7.depth = 7; d7.proposal = prop7;
CHECK_OK(rad_declare_drafter(&b7, &d7));
CHECK_OK(rad_drafter_tree(&b7, par7));
CHECK_OK(rad_drafter_short_block(&b7, 8));
CHECK_EQ(b7.program().drafter_short_block, 8);
}
/* 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) {
@@ -1826,8 +1857,9 @@ TEST(a_widened_weight_cannot_also_be_relayouted) {
CHECK(any_error(b, "a widening and a relayout"));
}
/* The other direction, the d3 readout: an f32 checkpoint tensor declared bf16 (what the device
* logits kernel reads) is narrowed by the loader, and the stored form is one plain bf16 plane. */
/* The other direction: an f32 checkpoint tensor declared bf16 (a readout head, which the device
* logits kernel reads as bf16) is narrowed by the loader, and the stored form is one plain bf16
* plane. */
TEST(an_f32_source_declared_bf16_is_narrowed_at_load) {
NEED_EXTRA(reg)
Builder b(reg, make_meta(), make_ctx());
@@ -2208,7 +2240,9 @@ TEST(the_home_search_path_splits_on_colons_and_the_first_home_with_a_file_wins)
* weight by weight names its producing tool, which no plugin claims: the family's one quantised
* plugin serves it (or its only plugin), and two quantised plugins are refused by name rather than
* chosen between. A plugin that declines imports (rad_arch_serves_imports, radtest_archq_w8) is
* still selected by its own descriptor, but is neither counted nor picked for an import. */
* still selected by its own descriptor, but is neither counted nor picked for an import. Block fp8
* (`fp8_e4m3`) reads stock, so a family that claims no plugin for it is served the same way
* without the import flag. */
TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) {
const std::string archq = home() + "/testarchq";
NEED_ARTIFACT(archq + "/radtest_archq_fp8.so");
@@ -2266,6 +2300,14 @@ TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) {
CHECK_OK(pick(bare, "quark-mxfp4", true, &lp, &log));
CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_plain"));
CHECK_EQ(pick(all, "fp8", false, &lp, &log), RAD_OK);
CHECK_OK(pick(bare, "fp8_e4m3", false, &lp, &log));
CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_plain"));
CHECK_EQ(lp.arch_quant, std::string());
CHECK_OK(pick(one, "fp8_e4m3", false, &lp, &log));
CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_fp8"));
CHECK_EQ(pick(all, "fp8_e4m3", false, &lp, &log), RAD_E_NOTFOUND);
CHECK_EQ(pick(bare, "w4", false, &lp, &log), RAD_E_NOTFOUND);
CHECK(has(log, "is served at"));
/* A second quantised plugin that declines imports leaves them to the first. */
CHECK_OK(pick(w8, "quark-mxfp4", true, &lp, &log));
+46 -2
View File
@@ -152,7 +152,9 @@ TEST(routed_expert_metadata_accepts_the_deepseek_and_glm_config_spellings) {
/* The descriptor derives from quant_method and fmt whoever set them, including rad-convert's
* --set: a bf16 checkpoint converted to block fp8 states that format and selects the fp8 plugin,
* so the container never names one format and selects another's plugin. */
* so the container never names one format and selects another's plugin. transformers' fp8 states
* no fmt and is E4M3 (Qwen3.8-Flash-Next-FP8), so it is the same descriptor; another method
* without a fmt is its name alone. */
TEST(the_descriptor_is_quant_method_and_fmt_whoever_set_them) {
const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) },
"{\"model_type\":\"qwen3_5\",\"hidden_size\":256}");
@@ -161,9 +163,12 @@ TEST(the_descriptor_is_quant_method_and_fmt_whoever_set_them) {
CHECK_EQ(ck.meta().quant, std::string());
MetaOwn m = ck.meta();
m.set("quantization_config.quant_method", "fp8");
CHECK_EQ(quant_descriptor(m), std::string("fp8"));
CHECK_EQ(quant_descriptor(m), std::string("fp8_e4m3"));
m.set("quantization_config.fmt", "e4m3");
CHECK_EQ(quant_descriptor(m), std::string("fp8_e4m3"));
MetaOwn ct = ck.meta();
ct.set("quantization_config.quant_method", "compressed-tensors");
CHECK_EQ(quant_descriptor(ct), std::string("compressed-tensors"));
}
/* Google's bf16 E2B needs no `--set quantization_config.quant_method`: its per-layer embeddings
@@ -3043,6 +3048,45 @@ TEST(a_compressed_tensors_fp8_release_reads_stock_with_no_import_refusal) {
CHECK_EQ(f[5], (float)((128 + 5) % 7 - 3) * -2.0f);
}
/* Qwen3.8-Flash-Next-FP8 ships its n-gram table as FP8 shards, `X.shard_<i>.weight`, under one
* scale, `X.weight_scale`. Joined along rows they are one table with one scale, byte for byte:
* `fp8_e4m3*bf16[*x*]`, the scale plane its single element, and the rows decode by it. */
TEST(fp8_shards_under_one_shared_scale_are_one_table_with_one_scale) {
T sc{ "t.weight_scale", "BF16", { 1 }, {} };
sc.bytes.resize(2);
rad_store_f32(sc.bytes.data(), RAD_BF16, 0, 0.5f);
const std::string dir = write_checkpoint(
{ fp8("t.shard_0.weight", { 3, 128 }), fp8("t.shard_1.weight", { 2, 128 }), sc }, kConfig);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("t", RAD_MAP_CONCAT, { "t.shard_0.weight", "t.shard_1.weight" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "t", false, &w, &why), RAD_OK);
CHECK(w.trivial && !w.imported);
REQUIRE_EQ(w.enc.n_planes, 2);
CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_F8E4M3);
CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_BF16);
CHECK_EQ(w.enc.plane[1].block[0], (int64_t)0);
CHECK_EQ(w.enc.plane[1].block[1], (int64_t)0);
CHECK_EQ(w.rows, (int64_t)5);
std::vector<float> f(128);
REQUIRE_EQ(ckpt_rows_f32(w, 3, 1, f.data(), &why), RAD_OK); /* shard 1's row 0 */
CHECK_EQ(f[5], (float)(5 % 7 - 3) * 0.5f);
std::vector<uint16_t> sp(1);
REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 1, sp.data(), &why), RAD_OK);
CHECK_EQ(rad_load_f32(sp.data(), RAD_BF16, 0), 0.5f);
std::vector<uint8_t> raw(128);
REQUIRE_EQ(ckpt_plane_rows(w, 0, 3, 1, raw.data(), &why), RAD_OK);
CHECK_EQ(rad_load_f32(raw.data(), RAD_F8E4M3, 5), (float)(5 % 7 - 3));
/* One shard alone is the same table, and a scale of another name is not borrowed. */
prog.name_map.push_back(map("u", RAD_MAP_COPY, { "t.shard_1.weight" }));
REQUIRE_EQ(ckpt_resolve(ck, prog, "u", false, &w, &why), RAD_OK);
CHECK(w.trivial);
}
/* Per-row FP8 is `fp8_e4m3*<s>[1x*]` whether the scale ships as [N, 1] (compressed-tensors'
* channel strategy) or [N], and byte for byte: the plane is the shipped scales in row order. */
TEST(a_per_row_fp8_weight_is_one_scale_per_row_in_either_shape) {
+34
View File
@@ -101,6 +101,21 @@ TEST(a_flag_missing_its_argument_is_refused_rather_than_read_past) {
CHECK_EQ(config_parse(a.argc(), a.argv.data(), &c), RAD_E_INVAL);
}
/* --draft-short-from takes a count, 0 for never, or auto (the default): the engine resolves auto to
* never for a chain and to two decoding sequences for a tree drafter. */
TEST(draft_short_from_takes_a_count_never_or_auto) {
Config c;
CHECK_EQ(c.draft_short_from, -1ll);
CHECK_OK(parse({ "--draft-short-from", "4" }, &c));
CHECK_EQ(c.draft_short_from, 4ll);
CHECK_OK(parse({ "--draft-short-from", "0" }, &c));
CHECK_EQ(c.draft_short_from, 0ll);
CHECK_OK(parse({ "--draft-short-from", "auto" }, &c));
CHECK_EQ(c.draft_short_from, -1ll);
CHECK_EQ(parse_fresh({ "--draft-short-from", "-2" }), RAD_E_INVAL);
CHECK_EQ(parse_fresh({ "--draft-short-from", "some" }), RAD_E_INVAL);
}
/* KL mode records or scores, never both, and requires that direction's inputs. Guessing between
* them could make a quantised model the reference. */
TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) {
@@ -792,6 +807,25 @@ TEST(the_embedding_is_ram_or_vram_and_the_ngram_table_takes_four) {
CHECK_EQ(parse({ "--ngram-placement" }, &c), RAD_E_INVAL);
}
/* ram=DIR is ram whose pinned copy is a shared file in DIR; a later plain placement drops the
* directory, and no other tier takes one. */
TEST(the_ngram_table_takes_a_directory_for_a_shared_ram_copy) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(d.ngram_share_dir.empty());
Config s;
CHECK_EQ(parse({ "--ngram-placement", "ram=/tmp/x" }, &s), RAD_OK);
CHECK(s.ngram_placement == TablePlacement::Ram);
CHECK_EQ(s.ngram_share_dir, std::string("/tmp/x"));
CHECK_EQ(parse({ "--ngram-placement", "ram=/tmp/x", "--ngram-placement", "ram" }, &s), RAD_OK);
CHECK(s.ngram_placement == TablePlacement::Ram);
CHECK(s.ngram_share_dir.empty());
Config c;
for (const char* bad : { "ram=", "vram=/tmp/x", "disk=/tmp/x", "auto=/tmp/x" })
CHECK_EQ(parse({ "--ngram-placement", bad }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--embedding-placement", "ram=/tmp/x" }, &c), RAD_E_INVAL);
}
/* --draft-window takes exactly two names; the default is kDraftWindowDefault, which the help text
* also states. Whether the window can adapt (a serial drafter, depth above zero) is decided by the
* scheduler with the program in hand, not the parser. */
+4
View File
@@ -113,6 +113,7 @@ void populated(LiveSnapshot& s) {
s.link.ar_calls = 50; s.link.ar_bytes = 5000; s.link.h2d_bytes = 900; s.link.d2h_bytes = 800;
s.link.ssd_reads = 4; s.link.ssd_bytes = 400; s.link.stream_bytes = 700;
s.link.prefetched = 2; s.link.prefetch_bytes = 300; s.link.staged_bytes = 200;
s.link.kv_streaming = true; s.link.kv_stream_active = true; s.link.kv_stream_bytes = 600;
s.passes.present = true;
s.passes.played = 10; s.passes.recorded = 2;
}
@@ -228,6 +229,9 @@ TEST(stats_carries_the_engine_the_requests_and_the_snapshot) {
CHECK_EQ(s["experts"]["tiers"][t].value("units", (int64_t)0), (int64_t)(t + 1));
}
CHECK_EQ(s["link"].value("stream_bytes", (int64_t)0), (int64_t)700);
CHECK_EQ(s["link"].value("kv_stream_bytes", (int64_t)0), (int64_t)600);
CHECK(s["link"].value("kv_streaming", false));
CHECK(s["link"].value("kv_stream_active", false));
CHECK_EQ(s["passes"].value("played", (int64_t)0), (int64_t)10);
CHECK_EQ(s["ckpt_evictions"].value("store_full", (int64_t)0), (int64_t)3);
CHECK_EQ(s["hit_cuts"].value("no_snapshot", (int64_t)0), (int64_t)2);
+185 -5
View File
@@ -205,6 +205,14 @@ struct World {
std::string qwen35_spec;
/* Qwen3-ASR: an audio tower over a Qwen3 decoder, served from the checkpoint. */
std::string qwen3asr;
/* The 31B's shape at toy sizes (five sliding layers and a global one, a 64-token window) with
* a DFlash2 drafter on a 64-token window (tiny_model.h: DFlash2), converted as
* data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe converts the 31B: served by gemma4_bf16,
* the trunk w4a8 and the drafter block fp8. */
std::string g31, g31_draft, g31_df2;
/* The same with a 1024-token window, the 31B's own: a snapshot at 512-1023 lies inside it and
* holds every row from position 0. */
std::string g31w, g31w_df2;
std::string corpus; /* six documents, two sharing a 300-token head; 1820 tokens */
std::string corpus_short; /* four documents, 760 tokens */
std::string corpus_tiny; /* two documents, 300 tokens, for libref's slow fp8 GEMMs */
@@ -230,8 +238,13 @@ struct World {
gemma4_kv = dir / "gemma4_kv";
qwen35_spec = dir / "qwen35_spec";
qwen3asr = dir / "qwen3asr";
g31 = dir / "g31";
g31_draft = dir / "g31_draft";
g31_df2 = dir / "g31_df2.rad";
g31w = dir / "g31w";
g31w_df2 = dir / "g31w_df2.rad";
for (const std::string* d : { &qwen35, &lfm2, &gemma4, &llama, &qwen35_kv, &gemma4_kv,
&qwen35_spec, &qwen3asr, &llama_int4 })
&qwen35_spec, &qwen3asr, &llama_int4, &g31, &g31_draft, &g31w })
if (mkdir(d->c_str(), 0755) != 0) return;
tiny::Qwen35 qkv;
qkv.head_dim = 128;
@@ -242,6 +255,17 @@ struct World {
gkv.head_dim = 64;
gkv.global_kv_heads = 2;
gkv.global_head_dim = 128;
tiny::Gemma4 g31s;
g31s.layers = 6;
g31s.interval = 6;
g31s.hidden = 256;
g31s.ffn = 512;
g31s.heads = 2;
g31s.head_dim = 128;
g31s.global_head_dim = 256;
g31s.window = 64;
tiny::Gemma4 g31ws = g31s;
g31ws.window = 1024;
if (!tiny::write_qwen35(qwen35, {}) || !tiny::write_lfm2(lfm2, {}) ||
!tiny::write_gemma4(gemma4, {}) || !tiny::write_llama(llama, {}) ||
!tiny::write_qwen35(qwen35_kv, qkv) || !tiny::write_gemma4(gemma4_kv, gkv) ||
@@ -253,7 +277,9 @@ struct World {
std::string(tiny::kLlamaFp8Recipe) + tiny::kLlamaI8HeadRule) ||
!tiny::write_llama_ct_int4(llama_int4, {}, true) ||
!tiny::write_text(dir / "llama_int4.recipe", tiny::kInt4ImportRecipe) ||
!tiny::write_text(dir / "llama_mxfp4.recipe", tiny::kLlamaMxfp4Recipe))
!tiny::write_text(dir / "llama_mxfp4.recipe", tiny::kLlamaMxfp4Recipe) ||
!tiny::write_gemma4(g31, g31s) || !tiny::write_gemma4(g31w, g31ws) ||
!tiny::write_dflash2(g31_draft, {}))
return;
tiny::Rng r(11);
@@ -286,6 +312,22 @@ struct World {
return;
}
}
std::string recipes = __FILE__;
recipes = recipes.substr(0, recipes.find_last_of('/')) + "/../data/recipes/";
/* Checked against libref, which serves it here: a card's library serves none of these
* toy shapes. */
for (const auto& [ckpt, out] : { std::pair<std::string, std::string>{ g31, g31_df2 },
std::pair<std::string, std::string>{ g31w, g31w_df2 } }) {
const int st = tiny::run({ RAD_E2E_CONVERT, ckpt, "--draft-model", g31_draft, "-o", out,
"--recipe", recipes + "gemma4-31b-dense-bf16-w4a8-df2.recipe",
"--set", "quantization_config.quant_method=compressed-tensors",
"--kernels", "libref" },
engine_env(), &convert_log);
if (st != 0) {
fprintf(stderr, " rad-convert exited %d:\n%s\n", st, tail(convert_log).c_str());
return;
}
}
ok = true;
}
@@ -768,13 +810,13 @@ TEST(an_attention_row_split_no_plugin_serves_is_refused_at_startup) {
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
/* qwen35's tiny checkpoint declares no draft head: no 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)";
const std::string want = "--draft-coupling on requires a linear draft chain (a serial head or "
"a block drafter with a coupled walk, 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());
@@ -1792,6 +1834,144 @@ TEST(a_prompt_resumed_from_the_prefix_cache_returns_what_a_cold_run_does) {
CHECK_EQ(s.stop(), 0);
}
/* What a -v server's block drafter proposed ("drafter 'dflash2': sequence N proposes t1 .. tk"),
* by request in the order they were sent: the server numbers requests consecutively, and the
* first one proposes in every case below. Read after stop(), so every line is in. */
std::vector<std::vector<std::string>> proposals(const std::string& log, size_t n_req) {
std::map<uint64_t, std::vector<std::string>> by_id;
static const std::string kSeq = ": sequence ", kProp = " proposes";
for (size_t at = log.find(kProp); at != std::string::npos; at = log.find(kProp, at + 1)) {
const size_t sol = log.rfind('\n', at) + 1, eol = log.find('\n', at);
const size_t s = log.find(kSeq, sol);
if (s == std::string::npos || s > at || log.find("drafter '", sol) > s) continue;
const uint64_t id = std::strtoull(log.c_str() + s + kSeq.size(), nullptr, 10);
by_id[id].push_back(log.substr(at, eol == std::string::npos ? std::string::npos : eol - at));
}
std::vector<std::vector<std::string>> out(n_req);
if (by_id.empty()) return out;
const uint64_t first = by_id.begin()->first;
for (size_t i = 0; i < n_req; ++i) {
auto it = by_id.find(first + i);
if (it != by_id.end()) out[i] = it->second;
}
return out;
}
/* A block drafter after a prefix hit, on the tiny 31B with its DFlash2 drafter: a follow-up turn
* and a repeat of a prompt each resume from the window snapshot taken at the earlier prompt's tail,
* and add fewer tokens than the drafter's 64-token window. The drafter's window rides in that
* snapshot, saved behind the drafter's context pass, so the hit is kept whole, and the drafter
* drafts from the first decode step and proposes, draft by draft, what a cold run's does. Without
* its window in the snapshot the hit leaves a hole in the drafter's own cache, and draft refill
* ends it at an interval snapshot at least that window before the prompt's end, recomputing what
* the hit had cached: the drafts are a cold run's, but the hit is not whole. With the snapshot
* saved before the context pass, it would propose from rows that pass had not yet written; the
* drafts would differ and, rejected, change no token. The warm server runs --prefix-resume
* nearest, which takes the tail snapshot a block short of the prompt's end; exact takes it where
* the prompt's last chunk starts, more than the drafter's window short here. */
TEST(a_block_drafter_after_a_prefix_hit_proposes_what_a_cold_run_does) {
REQUIRE(world().ok);
const std::vector<int32_t> first = prompt_ids(41, 300), repeat = prompt_ids(43, 200);
std::vector<int32_t> follow = first;
json warm[2], cold[2];
std::vector<std::vector<std::string>> warm_p, cold_p;
{
Server s;
REQUIRE(s.start(world().g31_df2, { "--num-speculative-tokens", "7",
"--checkpoint-interval", "64", "--max-num-seqs", "4",
"--prefix-resume", "nearest", "-v" }));
for (int32_t t : tokens_of(post(s.port, "/completion", completion(first, 16))))
follow.push_back(t);
for (int32_t t : prompt_ids(42, 8)) follow.push_back(t);
(void)post(s.port, "/completion", completion(repeat, 16));
warm[0] = post(s.port, "/completion", completion(follow, 24));
warm[1] = post(s.port, "/completion", completion(repeat, 24));
CHECK_EQ(s.stop(), 0);
warm_p = proposals(s.output(), 4);
}
{
Server s;
REQUIRE(s.start(world().g31_df2, { "--num-speculative-tokens", "7", "--no-prefix-cache",
"--max-num-seqs", "4", "-v" }));
cold[0] = post(s.port, "/completion", completion(follow, 24));
cold[1] = post(s.port, "/completion", completion(repeat, 24));
CHECK_EQ(s.stop(), 0);
cold_p = proposals(s.output(), 2);
}
/* The warm server's third and fourth requests are the cold one's first and second. */
const char* what[2] = { "follow-up turn", "repeated prompt" };
const int64_t n_prompt[2] = { (int64_t)follow.size(), (int64_t)repeat.size() };
for (int i = 0; i < 2; ++i) {
const int64_t cached = timing(warm[i], "cache_n");
/* Whole: draft refill would end the hit at least the drafter's 64-token window short. */
const bool whole = cached > n_prompt[i] - 64;
const int64_t d = timing(warm[i], "draft_n"), dc = timing(cold[i], "draft_n");
const std::vector<std::string>& wp = warm_p[(size_t)i + 2];
const std::vector<std::string>& cp = cold_p[(size_t)i];
if (!(whole && dc > 0 && d == dc && wp == cp))
fprintf(stderr, " %s: %lld of %lld tokens cached, %lld drafted (cold %lld), %zu "
"proposals (cold %zu), %s\n", what[i], (long long)cached,
(long long)n_prompt[i], (long long)d, (long long)dc, wp.size(), cp.size(),
wp == cp ? "the same" : "not the same");
CHECK(whole);
CHECK(dc > 0);
CHECK_EQ(d, dc);
CHECK(wp == cp);
CHECK(tokens_of(warm[i]) == tokens_of(cold[i]));
}
}
/* A prompt resumed from a window snapshot, on the tiny 31B: gemma4_bf16 declares the sliding layers
* windowed, and the cache does not index them (arch/gemma4's tiny model declares them full and takes
* no snapshot). A 600-token prompt takes a snapshot a block short of its end at the default
* 2048-token interval, and a longer prompt that shares it resumes there: the sliding layers from
* the snapshot, the global ones from the cached blocks, the rest of the prompt as a prefill from the
* snapshot. The reply, and every probability in it, equals a cold run's; so does a repeat of the
* longer prompt, which resumes from its own snapshot. Under a 64-token window the snapshot holds the
* window behind its position, and under a 1024-token one (the 31B's) every row from 0; with the
* drafter off and on. The snapshot floor (Scheduler::kWindowSnapshotMin) is --prefix-resume
* nearest's: under exact, a prompt shorter than one prefill chunk takes no tail snapshot. */
TEST(a_prompt_resumed_from_a_window_snapshot_returns_what_a_cold_run_does) {
REQUIRE(world().ok);
const std::vector<int32_t> a = prompt_ids(51, 600);
std::vector<int32_t> b = a;
for (int32_t t : prompt_ids(52, 60)) b.push_back(t);
for (const std::string* model : { &world().g31_df2, &world().g31w_df2 }) {
for (const char* spec : { "0", "7" }) {
json cold;
{
Server s;
REQUIRE(s.start(*model, { "--num-speculative-tokens", spec, "--no-prefix-cache" }));
cold = post(s.port, "/completion", completion(b, 24, 0.0, 0, 3));
CHECK_EQ(s.stop(), 0);
}
Server s;
REQUIRE(s.start(*model, { "--num-speculative-tokens", spec,
"--prefix-resume", "nearest" }));
(void)post(s.port, "/completion", completion(a, 24, 0.0, 0, 3));
const json shared = post(s.port, "/completion", completion(b, 24, 0.0, 0, 3));
const json again = post(s.port, "/completion", completion(b, 24, 0.0, 0, 3));
const int64_t c1 = timing(shared, "cache_n"), c2 = timing(again, "cache_n");
/* The snapshot sits at Scheduler::kWindowSnapshotMin (512) or above. */
const bool same = tokens_of(shared) == tokens_of(cold) &&
tokens_of(again) == tokens_of(cold) &&
shared["completion_probabilities"] == cold["completion_probabilities"] &&
again["completion_probabilities"] == cold["completion_probabilities"];
if (!(c1 >= 512 && c1 < 600 && c2 > c1 && same))
fprintf(stderr, " %s, %s drafts: cached %lld then %lld, %s a cold run's\n",
model->c_str(), spec, (long long)c1, (long long)c2,
same ? "equal to" : "NOT equal to");
CHECK(c1 >= 512);
CHECK(c1 < 600);
CHECK(c2 > c1);
REQUIRE(cold.contains("completion_probabilities"));
CHECK_EQ(tokens_of(cold).size(), (size_t)24);
CHECK(same);
CHECK_EQ(s.stop(), 0);
}
}
}
/* The row a running server's /diagnostics reports for `option`, or null. */
json config_row(int port, const std::string& option) {
Call c;
+157
View File
@@ -8,17 +8,20 @@
#include "rad_test.h"
#include "format/radfile.h"
#include "format/table_copy.h"
#include "format/table_share.h"
#include "format/tunecache.h"
#include "format/imatrix.h"
#include "format/safetensors.h"
#include "format/checkpoint.h"
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <functional>
#include <signal.h>
#include <string>
#include <sys/file.h>
#include <sys/wait.h>
#include <unordered_map>
#include <vector>
@@ -450,6 +453,160 @@ TEST(a_table_copied_into_locked_memory_is_the_mapping_byte_for_byte) {
f.close();
}
/* --ngram-placement ram=DIR: the first holder to open the file fills it, a later one finds it
* ready (a second descriptor in one process is a second holder, since flock locks belong to the
* open file description), and the file goes when the last holder leaves. A file whose header is
* not this table's is never overwritten, since a live engine may have it mapped. */
TEST(a_shared_table_file_is_filled_once_and_deleted_by_the_last_holder) {
const std::string dir = radtest::tmp_path("share");
REQUIRE(::mkdir(dir.c_str(), 0777) == 0 || errno == EEXIST);
const std::string container = write_tmp("share-container", ramp(8192, 1));
REQUIRE(!container.empty());
const int64_t n = 64 << 10;
const std::string id = table_share_id(container, 4096, n);
CHECK_EQ(id.size(), (size_t)16);
CHECK_EQ(table_share_id(container, 4096, n), id);
CHECK(table_share_id(container, 8192, n) != id);
CHECK(table_share_id(container, 4096, n + 1) != id);
CHECK(table_share_id(radtest::tmp_path("share-absent"), 4096, n).empty());
TableShare a, b, bad;
std::string why;
CHECK_OK(table_share_open(dir, id, n, &a, &why));
CHECK(a.filler && !a.ready);
CHECK(!table_share_is_ready(dir, id, n));
const std::vector<uint8_t> table = ramp(n, 3);
REQUIRE_EQ(::pwrite(a.fd, table.data(), (size_t)n, kTableShareHeader), (ssize_t)n);
CHECK_OK(table_share_mark_ready(&a, n, id, &why));
CHECK(a.ready);
CHECK(table_share_is_ready(dir, id, n));
CHECK(!table_share_is_ready(dir, id, n * 2));
struct stat st{};
REQUIRE_EQ(::stat(a.path.c_str(), &st), 0);
CHECK_EQ((int64_t)st.st_size, table_share_file_bytes(n));
CHECK_EQ(table_share_file_bytes(n), kTableShareHeader + ((int64_t)2 << 20));
CHECK_OK(table_share_open(dir, id, n, &b, &why));
CHECK(b.ready && !b.filler);
CHECK_EQ(b.lock_fd, -1);
std::vector<uint8_t> back((size_t)n);
REQUIRE_EQ(::pread(b.fd, back.data(), (size_t)n, kTableShareHeader), (ssize_t)n);
CHECK(back == table);
/* The same name, asked for a table of another length. */
CHECK_EQ(table_share_open(dir, id, n * 2, &bad, &why), (int)RAD_E_INVAL);
CHECK(bad.fd == -1);
CHECK(why.find("exists") != std::string::npos);
/* A file at another table's name whose header names this one: the id in the header is checked. */
const std::string other = table_share_id(container, 0, n);
const std::string other_path = dir + "/ngram-" + other + ".tab";
std::vector<uint8_t> head(4096);
REQUIRE_EQ(::pread(a.fd, head.data(), head.size(), 0), (ssize_t)head.size());
{
const int fd = ::open(other_path.c_str(), O_RDWR | O_CREAT, 0644);
REQUIRE(fd >= 0);
REQUIRE_EQ(::pwrite(fd, head.data(), head.size(), 0), (ssize_t)head.size());
REQUIRE_EQ(::ftruncate(fd, table_share_file_bytes(n)), 0);
::close(fd);
}
CHECK_EQ(table_share_open(dir, other, n, &bad, &why), (int)RAD_E_INVAL);
CHECK_EQ(::access(other_path.c_str(), F_OK), 0);
::unlink(other_path.c_str());
const std::string path = a.path, lock_path = a.lock_path;
table_share_close(&a);
CHECK(a.fd == -1);
CHECK_EQ(::access(path.c_str(), F_OK), 0); /* b still holds it, after a's wait for it */
table_share_close(&b);
CHECK(::access(path.c_str(), F_OK) != 0);
CHECK(::access(lock_path.c_str(), F_OK) != 0);
/* A filler that leaves without marking the table ready leaves nothing behind, and the next
* holder fills. */
TableShare c, d;
CHECK_OK(table_share_open(dir, id, n, &c, &why));
CHECK(c.filler);
table_share_close(&c);
CHECK(::access(path.c_str(), F_OK) != 0);
CHECK_OK(table_share_open(dir, id, n, &d, &why));
CHECK(d.filler && !d.ready);
table_share_close(&d);
}
/* A shared file costs the header and the table's rounding to 2 MiB. From kTableShareMin on that is
* under an eighth of the table, and kTableShareMin is the least such bound for every size above
* it; the n-gram gather's two-byte scale would be a 4 MiB file, so it keeps a private copy. */
TEST(a_table_is_shared_only_where_the_file_costs_little_beside_it) {
CHECK(2 < kTableShareMin);
CHECK_EQ(table_share_file_bytes(2), (int64_t)4 << 20);
const int64_t huge = (int64_t)2 << 20;
for (int64_t n : { kTableShareMin, kTableShareMin + 1, kTableShareMin + huge - 1,
(int64_t)47 << 30 })
CHECK((table_share_file_bytes(n) - n) * 8 < n);
const int64_t below = kTableShareMin - huge + 1;
CHECK((table_share_file_bytes(below) - below) * 8 >= below);
}
/* Engines stopped together leave together. A holder that leaves while another still holds the
* file waits for it, so the file goes even when the other dies before its own close (killed at a
* stop timeout; its locks go with it). A holder that gets the lock on a file already deleted, with
* a new engine's file at the name, leaves the new one alone. */
TEST(a_shared_table_file_goes_when_its_holders_leave_together) {
const std::string dir = radtest::tmp_path("share-leave");
REQUIRE(::mkdir(dir.c_str(), 0777) == 0 || errno == EEXIST);
const std::string container = write_tmp("share-leave-container", ramp(8192, 1));
REQUIRE(!container.empty());
const int64_t n = 64 << 10;
const std::string id = table_share_id(container, 4096, n);
REQUIRE(!id.empty());
std::string why;
TableShare a;
CHECK_OK(table_share_open(dir, id, n, &a, &why));
REQUIRE(a.filler);
CHECK_OK(table_share_mark_ready(&a, n, id, &why));
const std::string path = a.path, lock_path = a.lock_path;
int ready[2];
REQUIRE_EQ(::pipe(ready), 0);
const pid_t child = ::fork();
REQUIRE(child >= 0);
if (child == 0) {
TableShare b;
std::string bwhy;
char c = table_share_open(dir, id, n, &b, &bwhy) == RAD_OK && b.ready ? 'y' : 'n';
(void)!::write(ready[1], &c, 1);
::usleep(300 * 1000);
::_exit(0);
}
char c = 0;
CHECK_EQ(::read(ready[0], &c, 1), (ssize_t)1);
CHECK_EQ(c, 'y');
table_share_close(&a);
CHECK(::access(path.c_str(), F_OK) != 0);
CHECK(::access(lock_path.c_str(), F_OK) != 0);
::waitpid(child, nullptr, 0);
::close(ready[0]);
::close(ready[1]);
TableShare p, q, r;
CHECK_OK(table_share_open(dir, id, n, &p, &why));
REQUIRE(p.filler);
CHECK_OK(table_share_mark_ready(&p, n, id, &why));
CHECK_OK(table_share_open(dir, id, n, &q, &why));
CHECK(q.ready);
REQUIRE_EQ(::flock(q.fd, LOCK_UN), 0); /* q is on its way out too */
table_share_close(&p);
CHECK(::access(path.c_str(), F_OK) != 0);
CHECK_OK(table_share_open(dir, id, n, &r, &why));
CHECK(r.filler);
table_share_close(&q);
CHECK_EQ(::access(path.c_str(), F_OK), 0);
CHECK_EQ(::access(lock_path.c_str(), F_OK), 0);
table_share_close(&r);
CHECK(::access(path.c_str(), F_OK) != 0);
}
/* ------------------------------------------------------------------ reserving and writing */
TEST(a_weight_is_written_in_pieces_in_any_order) {
const std::string p = radtest::tmp_path("pieces");
+3 -3
View File
@@ -1434,9 +1434,9 @@ TEST(gbnf_a_length_bound_past_two_thousand_is_held_exactly) {
}
/* Bounded repetitions of one operand share one chain of links, so a schema's many length bounds
* cost its longest once rather than their sum. 200 properties at `maxLength: 4000` were 200 chains,
* past the compile budget (a tool schema like that is refused in full); shared, they compile, and
* every bound, short or long, string or array, is still held exactly. */
* cost its longest once rather than their sum. 200 properties at `maxLength: 4000` as 200 chains
* would exceed the compile budget; shared, they compile, and every bound, short or long, string
* or array, is held exactly. */
TEST(gbnf_bounds_over_one_operand_share_their_links) {
auto bv = bpe_like(59, 1500);
std::string props = R"("a":{"type":"string","maxLength":4000},"b":{"type":"string","maxLength":7},)"
+3 -7
View File
@@ -3,13 +3,9 @@
#
# docs/KERNELS.md is generated by `rad-kbench --report` and reviewed by hand. A hand-merged
# regeneration can carry a per-library "N row(s) not reached" header from one run and the table
# below it from another: at v1.13.0 the libr4d header says 239 while its table lists 243 rows
# (the four kv_store_streamed rows landed in 486c9331 without the count moving), so the section
# total (378) and the headline "132 of 510 declared row(s) were reached" both read four rows
# short of the tables. The generator cannot produce this from one run -- header and table come
# from one vector -- so the report is checked here, and a partially regenerated file fails.
#
# A check that cannot fail is not a check (docs/DEVLOG-decode-floor.md).
# below it from another, so the section total and the headline "R of D declared row(s) were
# reached" disagree with the tables. One run cannot produce this (header and table come from one
# vector), so a partially regenerated file fails here.
set -u
REPORT=$1
test -f "$REPORT" || { echo "kernel_report_check: no report at $REPORT"; exit 1; }
+89 -2
View File
@@ -1857,6 +1857,35 @@ TEST(kv_window_snapshot_only_where_a_hit_resumes_from_it) {
CHECK_OK(kv.configure(g, cfg, p.kv()));
CHECK(!kv.has_window_snapshot());
CHECK_EQ(kv.checkpoint_bytes(), 0ll);
CHECK(!kv.drafter_window_snapshot());
}
{ /* the same, where the engine saves behind the drafter's context pass: the drafter's window
* rides in the snapshot, every page of it */
std::vector<KVGroupInfo> g = hybrid_groups(/*with_linear=*/false);
w.drafter = true;
g.push_back(w);
Pools p;
CHECK_OK(configure_pools(p, cfg));
KVManager kv;
kv.set_drafter_window_snapshot(true);
CHECK_OK(kv.configure(g, cfg, p.kv()));
CHECK(kv.has_window_snapshot());
CHECK(kv.drafter_window_snapshot());
const KVGroupPlan* d = kv.plan((int32_t)g.size() - 1);
REQUIRE(d && d->win_snap && d->drafter);
CHECK_EQ(kv.checkpoint_bytes(), d->window_blocks * d->bytes_per_block);
}
{ /* beside linear state the flag changes nothing: a hit there re-prefills the window */
std::vector<KVGroupInfo> g = hybrid_groups();
w.drafter = true;
g.push_back(w);
Pools p;
CHECK_OK(configure_pools(p, cfg));
KVManager kv;
kv.set_drafter_window_snapshot(true);
CHECK_OK(kv.configure(g, cfg, p.kv()));
CHECK(!kv.has_window_snapshot());
CHECK(!kv.drafter_window_snapshot());
}
}
@@ -2364,6 +2393,64 @@ TEST(a_capped_lookup_lands_on_a_checkpoint_at_or_below_the_cap) {
CHECK_EQ(f.pc.lookup(prompt, {}, nullptr, &cap).n_attn_tokens, 320);
}
/* tip-only under a drafter whose KV the cache does not hold (--draft-refill): a hit must end the
* drafter's window before the prompt's end, on a snapshot no more than max_give_back below the tip.
* Keeping the tip alone leaves no such snapshot once retention runs, the capped lookup keeps the
* whole hit, and the request decodes without drafts (measured: 8 x 22k-token sessions, 5 of 8 ran
* unspeculated, decode 424-521 t/s against 738-754 under geometric backoff). With the floor set,
* the policy also keeps the deepest snapshot at or below tip - floor. */
TEST(tip_only_keeps_a_snapshot_below_the_drafter_floor) {
std::vector<int64_t> keep;
KeepTipOnly bare;
bare.select({64, 128, 192, 256}, &keep);
CHECK_EQ(keep.size(), (size_t)1);
CHECK_EQ(keep[0], 256ll);
KeepTipOnly floored;
floored.set_floor(100);
floored.select({64, 128, 192, 256}, &keep);
CHECK_EQ(keep.size(), (size_t)2);
CHECK_EQ(keep[0], 128ll); /* the deepest at or below 256 - 100 */
CHECK_EQ(keep[1], 256ll);
floored.select({200, 256}, &keep); /* nothing below the floor: the tip alone */
CHECK_EQ(keep.size(), (size_t)1);
CHECK_EQ(floored.held(4096, 64), 2ll);
CHECK_EQ(bare.held(4096, 64), 1ll);
}
TEST(a_refill_capped_hit_after_tip_only_retention_still_gives_the_drafter_its_window) {
Fixture f;
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/4));
f.pc.set_policy(std::make_unique<KeepTipOnly>());
f.pc.set_drafter_floor(100);
auto prompt = tok_run(7000, 336);
publish(f, 1, prompt, 320);
const std::vector<BlockHash> hs = chain_of(prompt);
for (int64_t pos = 64; pos <= 256; pos += 64) {
f.pc.begin_step();
ckpt_at(f, 1, hs, pos);
}
/* Another session's reservation finds the store full: retention runs over every session. */
auto other = tok_run(90000, 128);
const std::vector<BlockHash> ho = chain_of(other);
f.pc.begin_step();
int32_t s = -1;
CHECK_OK(f.pc.reserve_checkpoint(2, 64, ho[3], &s));
const std::vector<int64_t> left = f.pc.checkpoints(1);
CHECK_EQ(left.size(), (size_t)2);
CHECK_EQ(left[0], 128ll);
CHECK_EQ(left[1], 256ll);
/* Scheduler::admit_one's cap for a drafter window of 100: end the hit 100 before the prompt's
* end, give back at most 200. */
HitCap cap;
cap.tokens = (int64_t)prompt.size() - 100;
cap.max_give_back = 200;
const CacheHit c = f.pc.lookup(prompt, {}, nullptr, &cap);
CHECK_EQ(c.n_linear_tokens, 128);
CHECK_EQ(c.given_back, 128);
}
/* A checkpoint at a prompt's tail, off the interval, is one the next turn resumes from: lookup
* takes the deepest snapshot under the hit at any block boundary. */
TEST(a_checkpoint_at_the_tail_of_a_prompt_is_found_and_the_deepest_wins) {
@@ -2430,8 +2517,8 @@ TEST(checkpoint_interval_must_be_a_block_multiple) {
* A model can keep KV at different strides: DeepSeek-V4's compressed attention stores one row per
* r tokens (a block of r) beside groups at one row a token. The cache indexes every such group at
* the lcm of their blocks, an entry holding lcm / B blocks of a B-token group, so a hit ends on a
* block of each and adopt() takes every group. Leaving the finer groups out left the trunk a hole
* the scheduler refuses every hit for.
* block of each and adopt() takes every group. A group left out would leave the trunk a hole, and
* the scheduler refuses every hit on such a model.
*/
static KVGroupInfo gdn_group(std::vector<int32_t> layers) {
KVGroupInfo k;
+12 -2
View File
@@ -982,6 +982,8 @@ TEST(op_vocabulary) {
/* The fused fp8 forms. A host run needs every op covered, so these keep a host-backend run
* from failing with "site 'host' is unavailable for this band". */
"rmsnorm_quant_fp8", "gated_quant_fp8", "gemm_nt_q_gated", "dflash_select",
/* Tree verification (rad_drafter_tree): the drafter's tree and the attention over it. */
"dflash_tree", "attn_paged_tree",
"rmsnorm_had_quant_i8",
"gated_had_quant_i8",
"dequant",
@@ -1064,15 +1066,17 @@ TEST(op_vocabulary) {
}
CHECK_EQ(api().kernel_count(), (int)(sizeof(kOps) / sizeof(kOps[0])));
/* The two structural constraints, and only those; everything else must match anything. */
/* The structural constraint on the paged block, and only that; everything else must match
* anything. attn_paged_tree is attn_paged's row with the tree operand, the same constraint. */
CHECK_EQ(kern("attn_paged")->n_constraints, 1);
CHECK(std::strcmp(kern("attn_paged")->constraints[0].key, "block_size") == 0);
CHECK_EQ(kern("attn_paged_tree")->n_constraints, 1);
CHECK_EQ(kern("kv_store")->n_constraints, 1);
CHECK_EQ(kern("gemm_nt")->n_constraints, 0);
CHECK_EQ(kern("gdn_chunk_scan")->n_constraints, 0);
int constrained = 0;
for (int i = 0; i < api().kernel_count(); ++i) constrained += api().kernel_at(i)->n_constraints > 0;
CHECK_EQ(constrained, 2);
CHECK_EQ(constrained, 3);
}
/* ================================================================== the numerics
@@ -9670,6 +9674,8 @@ std::vector<Geo> geometries() {
.s("dtype", "fp8a8").s("act", "silu")),
G("dflash_select", "M", 2, a.i("M", R).i("steps", 3).i("top_k", 4).i("rank", 8)
.i("n_vocab", 30).s("dtype", "bf16")),
G("dflash_tree", "M", 2, a.i("M", R).i("steps", 3).i("top_k", 4).i("rank", 8)
.i("n_vocab", 30).i("nodes", 3).s("dtype", "bf16")),
G("gemm_nt", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "f32")),
G("gemm_nt_bias", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "f32")),
G("gemm_nt_q", "M", 3, a.i("M", R).i("N", 20).i("K", 256).i("group", 128).s("dtype", "fp8a8")),
@@ -9681,6 +9687,10 @@ std::vector<Geo> geometries() {
G("attn_paged", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2).i("block_size", 4)
.i("causal", 1).i("window", 0).s("q_dtype", "f32")
.s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)),
G("attn_paged_tree", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2)
.i("block_size", 4).i("causal", 1).i("window", 0)
.s("q_dtype", "f32").s("kv_dtype", "f32").i("n_head", 4)
.i("ctx", 9)),
G("attn_dense", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 1)
.s("dtype", "f32").i("n_head", 4)),
/* One-row segments, so M is also the segment count (n_seq, the description's hint for
+86
View File
@@ -3012,6 +3012,92 @@ TEST(a_grammar_masks_each_draft_position_against_the_drafts_before_it) {
CHECK_EQ(p[3].flags & RAD_SP_MASK, 0);
}
/* The same over a tree (rad_drafter_tree): row k is masked against the state after its own
* ancestors, not after drafts 0..k-1, a refused path kills that row only, and the grammar's request
* still speculates. The tree: a, then b and c both after a, then x after c. */
TEST(a_grammar_masks_each_tree_row_against_its_ancestors) {
SimpleVocab v({ "a", "b", "c", "x", "<call>", "z" });
HostChain ch(6, 1, 4, &v);
NEED_CHAIN(ch)
auto row = [](std::initializer_list<std::pair<int, float>> hot) {
std::vector<float> r(6, 0.0f);
for (auto [t, x] : hot) r[(size_t)t] = x;
return r;
};
std::vector<float> lg;
for (const auto& r : { row({ { 1, 5.0f } }), /* root: only a */
row({ { 3, 5.0f }, { 2, 1.0f } }), /* after a: b or c */
row({ { 0, 5.0f } }), /* after a b: only x */
row({ { 1, 5.0f } }), /* after a c: only x */
row({ { 5, 5.0f } }) }) /* after a c x: nothing */
lg.insert(lg.end(), r.begin(), r.end());
SamplingParams sp = greedy_params();
sp.grammar = "root ::= \"a\" ( \"b\" | \"c\" ) \"x\"";
Request a = make_req(1, { 5 }, sp);
const int32_t da[4] = { 0, 1, 2, 3 };
const int32_t pa[4] = { 0, 1, 1, 3 };
a.n_draft = 4;
a.draft = da;
a.draft_parent = pa;
CHECK(ch.s.allows_speculation(1));
std::vector<int32_t> tok;
int64_t n = 0;
CHECK_OK(ch.step({ &a }, lg, &tok));
/* Row 2 (a b) and row 3 (a c) take the same mask though a chain would have walked b then c;
* row 4's path is complete, so it stays unmasked without failing the request. */
CHECK(tok == (std::vector<int32_t>{ 0, 2, 3, 3, 5 }));
const DeviceSampleParams* p = ch.s.staged_params(&n);
for (int k = 0; k < 4; ++k) CHECK((p[k].flags & RAD_SP_MASK) != 0);
CHECK_EQ(p[4].flags & RAD_SP_MASK, 0);
CHECK(ch.s.take_failed().empty());
/* Rolled back: the grammar accepts a path from its start. */
CHECK_OK(ch.s.accept_token(1, 0));
CHECK_OK(ch.s.accept_token(1, 2));
CHECK_OK(ch.s.accept_token(1, 3));
}
/* accept_tree walks from the bonus token to the lowest-numbered child that is the target's pick at
* its parent, as long as one is; the emitted tokens are the target's picks along that path. A
* chain-shaped tree (or no parents) accepts what accept_greedy does. */
TEST(accept_tree_follows_the_lowest_child_the_target_agrees_with) {
/* node 1: 7 (under 0), node 2: 8 (under 0), node 3: 9 (under 2), node 4: 9 (under 1),
* node 5: 4 (under 3) */
const int32_t draft[5] = { 7, 8, 9, 9, 4 };
const int32_t parent[5] = { 0, 0, 2, 1, 3 };
int32_t out[6] = {}, path[5] = {}, n = -1;
/* The target picks 8 at the bonus, 9 at node 2, 4 at node 3, 6 at node 5. */
const int32_t t1[6] = { 8, 1, 9, 4, 1, 6 };
CHECK_OK(accept_tree(draft, parent, 5, t1, out, path, &n));
CHECK_EQ(n, 3);
CHECK((std::vector<int32_t>(path, path + 3) == std::vector<int32_t>{ 2, 3, 5 }));
CHECK((std::vector<int32_t>(out, out + 4) == std::vector<int32_t>{ 8, 9, 4, 6 }));
/* Both children of the bonus carry the target's pick: the lower-numbered one is taken. */
const int32_t d2[3] = { 5, 5, 6 };
const int32_t p2[3] = { 0, 0, 2 };
const int32_t t2[4] = { 5, 3, 6, 2 };
CHECK_OK(accept_tree(d2, p2, 3, t2, out, path, &n));
CHECK_EQ(n, 1);
CHECK_EQ(path[0], 1);
CHECK((std::vector<int32_t>(out, out + 2) == std::vector<int32_t>{ 5, 3 }));
/* No child agrees: only the bonus token's pick is emitted. */
const int32_t t3[6] = { 1, 1, 1, 1, 1, 1 };
CHECK_OK(accept_tree(draft, parent, 5, t3, out, path, &n));
CHECK_EQ(n, 0);
CHECK_EQ(out[0], 1);
/* A chain, with or without parents, is accept_greedy. */
const int32_t dc[3] = { 4, 5, 6 };
const int32_t pc[3] = { 0, 1, 2 };
const int32_t tc[4] = { 4, 5, 9, 1 };
int32_t og[4] = {}, ng = -1;
CHECK_OK(accept_greedy(dc, 3, tc, og, &ng));
for (const int32_t* pp : { pc, (const int32_t*)nullptr }) {
CHECK_OK(accept_tree(dc, pp, 3, tc, out, path, &n));
CHECK_EQ(n, ng);
CHECK((std::vector<int32_t>(out, out + n + 1) == std::vector<int32_t>(og, og + ng + 1)));
}
}
/* A grammar that admits nothing (complete, and no end-of-generation token in the vocabulary)
* fails its request, not the step: the step returns success, the request is reported once, and
* the next take is empty. */
+2
View File
@@ -363,6 +363,7 @@ struct FakePC : IPrefixCache {
FakeKV* kv = nullptr;
int32_t attn = 0, lin = 0, src = -1;
int32_t branch_at = 0; /* CacheHit::branch_at, as the real cache reports it */
int64_t drafter_floor = -1; /* set_drafter_floor's last value, -1 never called */
int32_t next_slot = 0;
int32_t reserved = 0;
int64_t evicted = 0, ckpt_evicted = 0;
@@ -427,6 +428,7 @@ struct FakePC : IPrefixCache {
return h;
}
const std::vector<int32_t>& cached_groups() const override { return groups; }
void set_drafter_floor(int64_t tokens) override { drafter_floor = tokens; }
/* What the scheduler published and asked to be evicted, recorded rather than acted on: these
* tests check that the scheduler publishes before it frees and evicts before it preempts, not
+205 -15
View File
@@ -166,9 +166,9 @@ struct Fixture {
cfg.max_ctx = max_ctx;
cfg.checkpoint_interval = 256;
cfg.prefix_cache = true;
/* The tests below were written for the nearest resume rule (a tail snapshot at the last
* quantum boundary, a hit at any snapshot or block); the exact rule's own tests set
* prefix_exact (--prefix-resume exact, the default). */
/* The fixture runs --prefix-resume nearest (a tail snapshot at the last quantum
* boundary, a hit at any snapshot or block); the exact-resume tests set prefix_exact
* (--prefix-resume exact, the engine's default) themselves. */
cfg.prefix_exact = false;
/* Config::n_spec defaults to -1 (`auto`), which engine_bringup resolves; this fixture
* skips that, and DraftController::configure refuses a negative depth. Speculation tests
@@ -314,8 +314,8 @@ TEST(chunk_geometry_rounds_the_checkpoint_interval_up_to_a_legal_chunk) {
}
/* A model with no linear state checkpoints only for a trunk window: the snapshot of the window
* behind a prompt's tail is what a prefix hit resumes from. A drafter's own window is recomputed
* by draft refill, so it takes no checkpoint and leaves the hit at any block. */
* behind a prompt's tail is what a prefix hit resumes from. A drafter's own window alone takes no
* checkpoint and leaves the hit at any block: draft refill recomputes it. */
TEST(chunk_geometry_snapshots_a_trunk_window_and_not_a_drafters) {
for (int drafter = 0; drafter < 2; ++drafter) {
Program prog;
@@ -343,6 +343,12 @@ TEST(chunk_geometry_snapshots_a_trunk_window_and_not_a_drafters) {
CHECK_OK(chunk_geometry_resolve(prog, cfg, &g));
CHECK_EQ(g.checkpoint_interval, drafter ? 0ll : 256ll);
CHECK(g.window_ckpt == !drafter);
/* Bring-up asks the same before the geometry is resolved (window_snapshots), and puts a
* block drafter's window in the snapshot only where it answers yes: a full-attention
* trunk takes no snapshot for its drafter's window alone. */
CHECK(window_snapshots(prog, cfg) == g.window_ckpt);
cfg.prefix_cache = false;
CHECK(!window_snapshots(prog, cfg));
}
}
@@ -379,7 +385,9 @@ TEST(window_prefill_writes_interval_snapshots_before_the_tail) {
REQUIRE(n > 0);
pos += n;
if (ckpt > 0) {
CHECK_EQ(ckpt, pos);
/* An interval snapshot ends its chunk; the tail's rides inside the last one. */
CHECK(ckpt == pos || pos == 1100);
CHECK(ckpt > pos - n);
snapshots.push_back(ckpt);
}
}
@@ -387,9 +395,10 @@ TEST(window_prefill_writes_interval_snapshots_before_the_tail) {
CHECK(snapshots == expected);
/* An aligned prompt must still snapshot before its last block: that block's
* generation marker changes when the client replays the assistant reply. */
* generation marker changes when the client replays the assistant reply. The snapshot
* is taken inside the chunk, which is not split for it. */
int64_t ckpt = -1;
CHECK_EQ(f.sch.plan_chunk(768, 1024, 512, &ckpt), 240ll);
CHECK_EQ(f.sch.plan_chunk(768, 1024, 512, &ckpt), 256ll);
CHECK_EQ(ckpt, 1008ll);
/* A shared step may end before the boundary; the next chunk must reach it. */
CHECK_EQ(f.sch.plan_chunk(0, 1100, 160, &ckpt), 160ll);
@@ -419,12 +428,12 @@ TEST(tip_only_window_prefill_writes_only_the_tail_snapshot) {
CHECK_EQ(ckpt, -1ll);
CHECK_EQ(f.sch.plan_chunk(512, 1100, 512, &ckpt), 512ll);
CHECK_EQ(ckpt, -1ll);
CHECK_EQ(f.sch.plan_chunk(1024, 1100, 512, &ckpt), 48ll);
CHECK_EQ(f.sch.plan_chunk(1024, 1100, 512, &ckpt), 76ll);
CHECK_EQ(ckpt, 1072ll);
CHECK_EQ(f.sch.plan_chunk(1072, 1100, 512, &ckpt), 28ll);
CHECK_EQ(ckpt, -1ll);
CHECK_EQ(f.sch.plan_chunk(768, 1024, 512, &ckpt), 240ll);
CHECK_EQ(f.sch.plan_chunk(768, 1024, 512, &ckpt), 256ll);
CHECK_EQ(ckpt, 1008ll);
CHECK_EQ(f.sch.plan_chunk(0, 256, 512, &ckpt), 256ll);
CHECK_EQ(ckpt, -1ll);
@@ -799,6 +808,105 @@ TEST(a_span_needs_an_interval_grid) {
CHECK_EQ((int64_t)f.sch.plan().e.size(), 2ll);
}
/* A Gemma-like model (a sliding window over a full-attention trunk, no linear state) resumes a
* prefix hit only from a window snapshot at an earlier prompt's tail. One is taken wherever that
* position, a block short of the prompt's end, is kWindowSnapshotMin or more, at the default
* 2048-token interval too, so a short conversation's next turn resumes: the shortest prompt takes
* its snapshot at the floor and one token less takes none, and a prompt past an interval takes the
* one it always did. An interval under the floor is the floor. A 1000-token prompt runs whole, its
* snapshot taken inside the chunk: the window's rows are still held when it ends, so unlike linear
* state nothing makes the prompt split there. */
TEST(a_window_snapshot_is_taken_at_the_tail_of_a_short_prompt_too) {
Fixture f;
f.build(4096, 64, /*max_tok=*/2048, 4096, /*windowed=*/true, /*linear=*/false);
f.cfg.checkpoint_interval = 2048;
CHECK_OK(f.start());
CHECK(f.sch.geometry().window_ckpt);
const int64_t Q = f.sch.geometry().quantum, back = std::max<int64_t>(Q, 16);
const int64_t floor = Scheduler::kWindowSnapshotMin, shortest = floor + back;
CHECK_EQ(floor % Q, (int64_t)0);
CHECK_EQ(f.sch.tail_checkpoint(shortest), floor);
CHECK_EQ(f.sch.tail_checkpoint(shortest - 1), (int64_t)-1);
CHECK_EQ(f.sch.tail_checkpoint(400), (int64_t)-1);
CHECK_EQ(f.sch.tail_checkpoint(3000), (3000 - back) / Q * Q);
const int64_t t = (1000 - back) / Q * Q;
CHECK_EQ(f.sch.tail_checkpoint(1000), t);
f.submit(1000, 8);
const RadBatch* b = f.sch.step();
CHECK(b != nullptr);
CHECK_EQ(b->n_tok, 1000);
CHECK_EQ(b->n_checkpoints, 1);
CHECK_EQ(b->checkpoint_tok[0], t - 1);
Fixture g;
g.build(4096, 64, /*max_tok=*/2048, 4096, /*windowed=*/true, /*linear=*/false);
g.cfg.checkpoint_interval = 256;
CHECK_OK(g.start());
const int64_t I = g.sch.geometry().checkpoint_interval;
CHECK_EQ(I, (int64_t)256);
CHECK_EQ(g.sch.tail_checkpoint(I + back), I);
CHECK_EQ(g.sch.tail_checkpoint(I + back - 1), (int64_t)-1);
}
/* A prompt longer than the step budget takes its window snapshot inside its last chunk: the chunks
* before it are the budget's, and the last runs to the prompt's end with the snapshot at its tail
* row. */
TEST(a_long_prompt_takes_its_window_snapshot_inside_its_last_chunk) {
Fixture f;
f.build(4096, 64, /*max_tok=*/512, 4096, /*windowed=*/true, /*linear=*/false);
f.cfg.checkpoint_interval = 2048;
CHECK_OK(f.start());
const int64_t Q = f.sch.geometry().quantum, back = std::max<int64_t>(Q, 16);
const int64_t t = (1000 - back) / Q * Q;
f.submit(1000, 8);
const RadBatch* b = f.sch.step();
CHECK(b != nullptr);
CHECK_EQ(b->n_tok, 512);
CHECK_EQ(b->n_checkpoints, 0);
f.commit_plain();
b = f.sch.step();
CHECK(b != nullptr);
CHECK_EQ(b->n_tok, 1000 - 512);
CHECK_EQ(b->n_checkpoints, 1);
CHECK_EQ(b->checkpoint_tok[0], t - 512 - 1);
}
/* Under load a prompt's chunks are held back for the speculating decode rows behind it. Every prompt
* takes its window snapshot once, at its tail row, in whichever chunk carries that row: the final
* one, or a held-back one cut short of the prompt's end on a quantum. */
TEST(a_window_snapshot_under_load_lands_at_the_tail_whatever_chunk_carries_it) {
for (int64_t n = 600; n <= 1000; n += 24) {
Fixture f;
f.build(4096, 64, /*max_tok=*/256, 8192, /*windowed=*/true, /*linear=*/false);
f.cfg.checkpoint_interval = 2048;
f.cfg.n_spec = 7;
f.cfg.busy_prefill_chunk = -1;
CHECK_OK(f.start());
const int64_t Q = f.sch.geometry().quantum, back = std::max<int64_t>(Q, 16);
const int64_t t = (n - back) / Q * Q;
for (int d = 0; d < 4; ++d) f.submit(40, 4000);
for (int k = 0; k < 2; ++k) { CHECK(f.sch.step() != nullptr); f.commit_plain(11); }
const uint64_t p = f.submit(n, 8);
int snaps = 0;
for (int k = 0; k < 64 && f.sch.find(p) && f.sch.find(p)->n_computed < n; ++k) {
CHECK(f.sch.step() != nullptr);
for (const StepEntry& e : f.sch.plan().e) {
if (e.seq != p || e.ckpt_slot < 0) continue;
++snaps;
if (!(e.ctx_len < t && e.ctx_len + e.n_tokens >= t && e.ctx_len + e.ckpt_tok + 1 == t))
fprintf(stderr, " n %lld: chunk [%d, %d), snapshot at %d, tail %lld\n",
(long long)n, (int)e.ctx_len, (int)(e.ctx_len + e.n_tokens),
(int)(e.ctx_len + e.ckpt_tok + 1), (long long)t);
CHECK((int64_t)e.ctx_len < t && (int64_t)e.ctx_len + e.n_tokens >= t);
CHECK_EQ((int64_t)e.ctx_len + e.ckpt_tok + 1, t);
}
f.commit_plain(11);
}
if (snaps != 1) fprintf(stderr, " n %lld: %d snapshots\n", (long long)n, snaps);
CHECK_EQ(snaps, 1);
}
}
/* ================================================================== exact resume */
/* --prefix-resume exact (the default): a hit resumes only where an idle server's cold prefill of
* the same prompt starts a chunk, and a prompt's tail snapshot is where its last chunk starts. A
@@ -925,7 +1033,7 @@ TEST(an_exact_tail_snapshot_is_where_the_last_chunk_starts) {
/* One ending on the grid: the last chunk is [1536, 2048), and its end is an interval. */
c = cut_from(f.sch, 0, 2048, 512);
CHECK((c.ckpts == std::vector<int64_t>{ 1024, 1536, 2048 }));
/* Inside the first interval nothing (as before, cheap to prefill again). */
/* Inside the first interval nothing (as under nearest: cheap to prefill again). */
c = cut_from(f.sch, 0, 900, 512);
CHECK(c.ckpts.empty());
/* A step sharing its budget may straddle the tail: split there, the snapshot written. */
@@ -1366,8 +1474,7 @@ TEST(a_hit_on_a_model_with_a_windowed_group_reuses_nothing) {
/* The same model with the trunk's window in the checkpoint slot (KVGroupPlan::win_snap beside
* linear state, as DeepSeek-V4.1's sliding layers beside its compressor state): the hit resumes at
* the snapshot, which restores the linear state and the window together, and the cached group's
* blocks are adopted. Before, a model with linear state never put its window in the slot, so this
* clamp refused every hit on it. */
* blocks are adopted. */
TEST(a_hit_on_a_hybrid_whose_slot_carries_the_window_resumes_at_the_snapshot) {
Fixture f;
f.build(4096, 64, 512, 4096, /*windowed=*/true);
@@ -1405,8 +1512,7 @@ TEST(a_hit_on_a_hybrid_whose_slot_carries_the_window_resumes_at_the_snapshot) {
}
/* A trunk group the cache does not index and no slot carries is a hole no snapshot fills: a full
* group left out (as a group at another block size was before the cache took every block size)
* refuses the hit even where the window is in the slot. */
* group left out refuses the hit even where the window is in the slot. */
TEST(a_trunk_group_neither_cached_nor_in_the_slot_refuses_the_hit) {
Fixture f;
f.build(4096, 64, 512, 4096, /*windowed=*/true);
@@ -1958,6 +2064,28 @@ RefillRun refill_run(int n_prompt, int32_t seeded, int64_t ckpt_lo = 0) {
}
} /* namespace */
TEST(the_refill_window_is_the_retention_policys_drafter_floor) {
/* tip-only keeps a snapshot this deep below the tip, or a refill-capped hit has nothing to end
* on and the request decodes without drafts (KeepTipOnly). Without a refill the floor is 0. */
for (int spec : { 7, 0 }) {
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/8192);
f.cfg.n_spec = spec;
f.prog.drafter.kind = RAD_DRAFT_BLOCK;
f.prog.drafter.window = 512;
KVGroupInfo w;
w.name = "draft";
w.decl.kind = RAD_KV_WINDOW;
w.decl.window = 512;
w.block_size = 16;
f.prog.kv_groups.push_back(w);
f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64);
f.pc.groups = { 0 };
CHECK_OK(f.start());
CHECK_EQ(f.pc.drafter_floor, spec ? (int64_t)512 : (int64_t)0);
}
}
TEST(a_prefix_hit_ends_a_drafter_window_before_the_prompt_and_the_drafter_drafts_at_once) {
const RefillRun r = refill_run(/*prompt=*/1100, /*seeded=*/1024);
/* The cap is 1100 - 512 = 588: attention 576, and the checkpoint under it 512. */
@@ -1985,6 +2113,51 @@ TEST(a_prefix_hit_with_no_checkpoint_near_the_cap_is_kept_whole) {
CHECK_EQ(r.rows, 0);
}
/* A Gemma-like model: a full-attention trunk with a sliding window and no linear state, so a hit
* resumes from the window snapshot taken at an earlier prompt's tail (ChunkGeometry::window_ckpt),
* and a windowed block drafter. When that snapshot carries the trunk's window only, draft refill
* cannot cut the hit (no snapshot a window back), the whole hit stands and the drafter waits for
* its window; when it carries the drafter's window too (a block drafter on the card's driver,
* KVManager::set_drafter_window_snapshot), there is no hole, no refill, and the drafter drafts from
* the first decode. */
TEST(a_prefix_hit_whose_window_snapshot_carries_the_drafters_window_drafts_at_once) {
for (int with_drafter = 0; with_drafter < 2; ++with_drafter) {
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/8192,
/*windowed=*/true, /*linear=*/false);
f.cfg.n_spec = 7;
f.prog.drafter.kind = RAD_DRAFT_BLOCK;
f.prog.drafter.window = 512;
KVGroupInfo w;
w.name = "draft";
w.decl.kind = RAD_KV_WINDOW;
w.decl.window = 512;
w.block_size = 16;
f.prog.kv_groups.push_back(w);
f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64);
const int32_t swa = 1, draft = 2;
f.kv.snap = with_drafter ? std::vector<int32_t>{ swa, draft } : std::vector<int32_t>{ swa };
f.pc.groups = { 0 };
f.pc.ckpt_lo = 2048; /* the earlier prompt's tail snapshot, none below it */
CHECK_OK(f.start());
CHECK(f.sch.geometry().window_ckpt);
f.pc.seed(2048); f.pc.lin = 2048; f.pc.src = 3;
const uint64_t a = f.submit(2200, 64);
Scheduler::BlockRow rows[4];
int n_rows = -1;
for (int st = 0; st < 40; ++st) {
CHECK(f.sch.step() != nullptr);
if (st == 0) CHECK_EQ(f.sch.find(a)->n_computed, (int64_t)2048);
f.commit_plain(11);
const int n = f.sch.block_begin(8, 7, 512, 99, rows, 4);
f.sch.block_end();
if (!f.sch.find(a)->output.empty()) { n_rows = n; break; }
}
CHECK_EQ(f.sch.metrics().draft_refills, (int64_t)0);
CHECK_EQ(n_rows, with_drafter ? 1 : 0);
}
}
/* z-lab's DFlash on the Gemma 4 31B: a full-attention block drafter (no window), whose own group the
* prefix cache indexes like the trunk's full layers. A hit resumes the trunk's window from the
* window snapshot, so no paged group is left with a hole and the drafter drafts from the first
@@ -2028,6 +2201,23 @@ TEST(a_full_attention_drafter_drafts_at_once_after_a_hit_the_window_snapshot_res
}
}
/* The short block's switch (--draft-short-from): on from the threshold, off again two below, and
* off at one decoding sequence whatever the threshold, where the long block pays. From 2 (a tree's
* auto) a load of 2, 1, 1 runs it, then not; from 8, 8 then 7 keeps it and 6 drops it. */
TEST(the_short_block_switches_off_at_one_sequence) {
bool on = false;
on = Scheduler::short_block_on(on, 2, 2); CHECK(on);
on = Scheduler::short_block_on(on, 1, 2); CHECK(!on);
on = Scheduler::short_block_on(on, 1, 2); CHECK(!on);
on = Scheduler::short_block_on(on, 0, 2); CHECK(!on);
on = Scheduler::short_block_on(false, 8, 8); CHECK(on);
on = Scheduler::short_block_on(on, 7, 8); CHECK(on);
on = Scheduler::short_block_on(on, 6, 8); CHECK(!on);
on = Scheduler::short_block_on(on, 7, 8); CHECK(!on);
CHECK(Scheduler::short_block_on(false, 1, 1)); /* from 1: every sequence runs it */
CHECK(!Scheduler::short_block_on(true, 0, 1));
}
TEST(no_prefix_hit_gives_nothing_back) {
const RefillRun r = refill_run(1100, 0);
CHECK_EQ(r.m.draft_refills, (int64_t)0);
+3 -1
View File
@@ -2848,6 +2848,7 @@ TEST(the_live_view_prints_ordinary_lines_when_it_is_not_a_terminal) {
* GEMM streaming across the link. */
s.experts.routed = 200; s.experts.routed_resident = 150;
s.link.stream_bytes = 700;
s.link.kv_streaming = true; s.link.kv_stream_bytes = 600;
/* A pipe is not a terminal, so the constructor picks the line renderer and the frame must
* contain no escape sequence: a log full of cursor-home codes is ungreppable, and the breakage
@@ -2871,11 +2872,12 @@ TEST(the_live_view_prints_ordinary_lines_when_it_is_not_a_terminal) {
/* Hit rate is not residency: 37.50% of the units are in VRAM and 75% of the routing found one
* there, which is the placement working. Both numbers, since either alone misleads. */
CHECK(line.find("hit=75.00%") != std::string::npos);
/* The link, cumulative, with all three of the things that share it. */
/* The link, cumulative, with all four of the things that share it. */
CHECK(line.find("link ar=5000") != std::string::npos);
CHECK(line.find("h2d=900") != std::string::npos);
CHECK(line.find("d2h=800") != std::string::npos);
CHECK(line.find("stream=700") != std::string::npos);
CHECK(line.find("kv=600") != std::string::npos);
CHECK(line.back() == '\n');
/* The terminal renderer is the one that may use escapes, and it colours by tier. */
+3 -3
View File
@@ -2242,9 +2242,9 @@ TEST(the_normal_forms_agree_with_an_independent_implementation) {
CHECK(rows > 2500);
}
/* A release that ships no chat template (DeepSeek's) is why --chat-template exists: the file is
* read, trailing newlines stripped exactly as the checkpoint's own file is, and an unreadable or
* empty file is refused rather than skipped. */
/* --chat-template serves a release that ships no chat template (DeepSeek's): the file is read,
* trailing newlines stripped exactly as the checkpoint's own file is, and an unreadable or empty
* file is refused rather than skipped. */
TEST(read_chat_template_path_strips_newlines_and_refuses_empty) {
VocabBuild vb;
const std::string p = radtest::tmp_path("chat_template.jinja");
+105
View File
@@ -480,6 +480,111 @@ inline bool write_gemma4(const std::string& dir, const Gemma4& s) {
return write_checkpoint(dir, c, ts);
}
/* ------------------------------------------------------------------ dflash2: a block drafter */
/* A DFlash2 drafter in vLLM's speculators layout, RedHatAI/gemma-4-31B-it-speculator.dflash2's at
* toy sizes, for a write_gemma4 target of the same `hidden` and `vocab`: Qwen3-shaped layers on a
* non-causal sliding window, an fc over the target's residual stream after the `taps` layers, a
* grouped dynamic convolution around each sublayer (a prepare and a finish half, `conv_kernel`
* taps a group of `conv_group` channels) and a candidate selector. It ships no embedding or head:
* it reads the target's. rad-convert merges it (--draft-model) into a container the 31B's plugin
* serves (gemma4_bf16, under the w4a8 DFlash2 recipe). */
struct DFlash2 {
int64_t layers = 2, hidden = 256, heads = 4, kv_heads = 2, head_dim = 64, ffn = 512;
int64_t window = 64, block = 8, conv_group = 16, conv_kernel = 2, rank = 16, top_k = 16;
int64_t vocab = 320, ctx = 4096, mask_id = 4;
std::vector<int64_t> taps = { 1, 3, 5 };
/* The gain of o_proj and down_proj, and the q/k norms' centre. A random drafter's residual is
* otherwise its input embedding, which its head (the target's table) answers with the mask
* token at every position whatever the context: sharp attention and strong branches make
* what it proposes follow the context it attends to. */
float branch = 4.0f, qk = 3.0f;
uint64_t seed = 6;
};
inline bool write_dflash2(const std::string& dir, const DFlash2& s) {
Rng r(s.seed);
const int64_t H = s.hidden, q = s.heads * s.head_dim, kv = s.kv_heads * s.head_dim;
nlohmann::ordered_json types = nlohmann::ordered_json::array();
for (int64_t l = 0; l < s.layers; ++l) types.push_back("sliding_attention");
nlohmann::ordered_json t;
t["attention_bias"] = false;
t["head_dim"] = s.head_dim;
t["hidden_act"] = "silu";
t["hidden_size"] = H;
t["intermediate_size"] = s.ffn;
t["layer_types"] = types;
t["max_position_embeddings"] = s.ctx;
t["model_type"] = "qwen3";
t["num_attention_heads"] = s.heads;
t["num_hidden_layers"] = s.layers;
t["num_key_value_heads"] = s.kv_heads;
t["rms_norm_eps"] = 1e-6;
t["rope_parameters"] = { { "rope_theta", 10000.0 }, { "rope_type", "default" } };
t["sliding_window"] = s.window;
t["use_sliding_window"] = true;
t["vocab_size"] = s.vocab;
nlohmann::ordered_json greedy;
greedy["proposal_type"] = "greedy";
greedy["speculative_tokens"] = s.block - 1;
nlohmann::ordered_json verifier;
verifier["architectures"] = { "Gemma4ForConditionalGeneration" };
verifier["name_or_path"] = "tiny";
nlohmann::ordered_json spec;
spec["algorithm"] = "dflash2";
spec["default_proposal_method"] = "greedy";
spec["proposal_methods"] = nlohmann::ordered_json::array({ greedy });
spec["verifier"] = verifier;
nlohmann::ordered_json c;
c["architectures"] = { "DFlash2DraftModel" };
c["aux_hidden_state_layer_ids"] = s.taps;
c["block_size"] = s.block;
c["conv_group_size"] = s.conv_group;
c["conv_kernel_size"] = s.conv_kernel;
c["draft_vocab_size"] = s.vocab;
c["dtype"] = "bfloat16";
c["mask_token_id"] = s.mask_id;
c["sample_from_anchor"] = false;
c["selector_rank"] = s.rank;
c["selector_top_k"] = s.top_k;
c["sliding_window_non_causal"] = true;
c["speculators_config"] = spec;
c["speculators_model_type"] = "dflash2";
c["tie_word_embeddings"] = false;
c["transformer_layer_config"] = t;
/* The convolution's coefficients: a prepare and a finish half, each conv_kernel taps for every
* group of conv_group channels. */
const int64_t coef = 2 * s.conv_kernel * (H / s.conv_group);
std::vector<Tensor> ts;
ts.push_back(linear("candidate_selector.hidden_projection.weight", s.rank, H, r));
ts.push_back(noise("candidate_selector.predecessor_codebook", { s.vocab, s.rank }, r, 0.5f));
ts.push_back(noise("candidate_selector.successor_codebook", { s.vocab, s.rank }, r, 0.5f));
ts.push_back(linear("fc.weight", H, (int64_t)s.taps.size() * H, r));
ts.push_back(noise("hidden_norm.weight", { H }, r, 0.1f, 1.0f));
for (int64_t l = 0; l < s.layers; ++l) {
const std::string p = "layers." + std::to_string(l) + ".";
for (const char* conv : { "attention_conv.", "mlp_conv." }) {
ts.push_back(noise(p + conv + "base_kernel", { 2, s.conv_kernel, H }, r, 0.3f));
ts.push_back(linear(p + conv + "kernel_projection.weight", coef, H, r, 0.3f));
}
ts.push_back(noise(p + "input_layernorm.weight", { H }, r, 0.1f, 1.0f));
ts.push_back(noise(p + "post_attention_layernorm.weight", { H }, r, 0.1f, 1.0f));
ts.push_back(linear(p + "self_attn.q_proj.weight", q, H, r));
ts.push_back(linear(p + "self_attn.k_proj.weight", kv, H, r));
ts.push_back(linear(p + "self_attn.v_proj.weight", kv, H, r));
ts.push_back(linear(p + "self_attn.o_proj.weight", H, q, r, s.branch));
ts.push_back(noise(p + "self_attn.q_norm.weight", { s.head_dim }, r, 0.1f, s.qk));
ts.push_back(noise(p + "self_attn.k_norm.weight", { s.head_dim }, r, 0.1f, s.qk));
ts.push_back(linear(p + "mlp.gate_proj.weight", s.ffn, H, r));
ts.push_back(linear(p + "mlp.up_proj.weight", s.ffn, H, r));
ts.push_back(linear(p + "mlp.down_proj.weight", H, s.ffn, r, s.branch));
}
ts.push_back(noise("norm.weight", { H }, r, 0.1f, 1.0f));
return write_text(dir + "/config.json", c.dump(2)) &&
write_safetensors(dir + "/model.safetensors", ts);
}
/* ------------------------------------------------------------------ llama: dense attention */
/* LLaMA (`llama`, served by llama_dense_fp8 once rad-convert has made its linears block fp8):