Merge main into laya-arch-plugin

This commit is contained in:
Brandon Bertelsen committed 2026-10-29 13:45:18 -04:00
commit ec243c2a7d
189 files changed
+11212 -7060

No files matched your search

+3 -3
View File
@@ -612,9 +612,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
+3
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)
@@ -83,6 +84,7 @@ ABI_FIELD(RadBatch, vgen_b)
ABI_FIELD(RadBatch, control_vector)
ABI_FIELD(RadBatch, enc_seg_h)
ABI_FIELD(RadBatch, enc_seg_w)
ABI_FIELD(RadBatch, score_only)
ABI_FIELD(RadBatch, n_plugin_words)
ABI_FIELD(RadBatch, plugin_words)
ABI_FIELD(RadBatch, plugin_cu)
@@ -122,6 +124,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)
+7 -6
View File
@@ -29,7 +29,7 @@
{ "RadArgs", "instance", 48, 8 },
{ "RadArgs", "rank", 56, 4 },
{ "RadArgs", "world_size", 60, 4 },
{ "RadBatch", "", 0, 400 },
{ "RadBatch", "", 0, 408 },
{ "RadBatch", "phase", 0, 4 },
{ "RadBatch", "step", 4, 4 },
{ "RadBatch", "n_tok", 8, 8 },
@@ -80,11 +80,12 @@
{ "RadBatch", "control_vector", 336, 4 },
{ "RadBatch", "enc_seg_h", 344, 8 },
{ "RadBatch", "enc_seg_w", 352, 8 },
{ "RadBatch", "n_plugin_words", 360, 8 },
{ "RadBatch", "plugin_words", 368, 8 },
{ "RadBatch", "plugin_cu", 376, 8 },
{ "RadBatch", "plugin_words_h", 384, 8 },
{ "RadBatch", "plugin_cu_h", 392, 8 },
{ "RadBatch", "score_only", 360, 4 },
{ "RadBatch", "n_plugin_words", 368, 8 },
{ "RadBatch", "plugin_words", 376, 8 },
{ "RadBatch", "plugin_cu", 384, 8 },
{ "RadBatch", "plugin_words_h", 392, 8 },
{ "RadBatch", "plugin_cu_h", 400, 8 },
{ "RadBufDecl", "", 0, 80 },
{ "RadBufDecl", "dtype", 0, 4 },
{ "RadBufDecl", "rank", 4, 4 },
+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
+20 -1
View File
@@ -86,6 +86,8 @@ struct RecJoin { size_t at = 0; int from = 0, to = 0; };
using namespace rad_fake;
struct RadBuilder {
rad_buf score_hidden = 0; /* rad_declare_scores */
rad_weight score_table = 0;
std::vector<RecWeight> weights;
std::vector<RecBuf> bufs;
std::vector<RecOp> ops;
@@ -121,6 +123,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;
@@ -289,6 +293,14 @@ extern "C" int rad_declare_logits(RadBuilder* b, rad_buf logits) {
return RAD_OK;
}
/* Scored steps' hidden rows and head table, recorded for the tests. */
extern "C" int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table) {
if (!b || !hidden || !table) return RAD_E_INVAL;
b->score_hidden = hidden;
b->score_table = table;
return RAD_OK;
}
/* An embedding program names its pooled output instead of logits; a program declares one. */
extern "C" int rad_declare_pooled(RadBuilder* b, rad_buf pooled) {
if (!b || !pooled || b->logits) return RAD_E_INVAL;
@@ -408,6 +420,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;
@@ -420,7 +437,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;
}
+233 -11
View File
@@ -4007,8 +4007,8 @@ RadModelMeta lfm2_meta(int n_kv = 4) {
std::vector<std::string> lfm2_layer_ops(bool attention) {
std::vector<std::string> v = { "rmsnorm" };
if (attention) {
for (const char* s : { "gemm_nt", "gemm_nt", "gemm_nt", "rmsnorm", "rmsnorm", "rope",
"rope", "attn_paged", "kv_store", "gemm_nt" })
for (const char* s : { "gemm_nt", "gemm_nt", "gemm_nt", "rmsnorm_rows", "rmsnorm_rows",
"rope_rows", "rope_rows", "attn_paged", "kv_store", "gemm_nt" })
v.push_back(s);
} else {
for (const char* s : { "gemm_nt", "mul", "causal_conv1d", "mul", "gemm_nt" })
@@ -4043,12 +4043,14 @@ TEST(lfm2_declares_the_checkpoints_own_schedule) {
for (const auto& bd : b.binds)
CHECK_EQ(bd.second, bd.first == 2 ? (rad_kvgroup)1 : (rad_kvgroup)2);
/* A plain RMSNorm at the checkpoint's epsilon, NeoX over the whole head. */
/* A plain RMSNorm at the checkpoint's epsilon, NeoX over the whole head; the head norms and
* rope ask for the rows forms (their prefill row counts are what those forms are for). */
const RecOp* norm = find_op(b, "rmsnorm");
CHECK_NEAR(pflt(norm, "eps"), 1e-5, 1e-9);
CHECK_EQ(param(norm, "wadd") ? pflt(norm, "wadd") : 0.0, 0.0);
CHECK_EQ(pstr(find_op(b, "rope"), "mode"), "neox");
CHECK_EQ(pint(find_op(b, "rope"), "rotary_dim"), 16);
REQUIRE(find_op(b, "rmsnorm_rows") != nullptr);
CHECK_EQ(pstr(find_op(b, "rope_rows"), "mode"), "neox");
CHECK_EQ(pint(find_op(b, "rope_rows"), "rotary_dim"), 16);
CHECK_EQ(pint(find_op(b, "attn_paged"), "gqa"), 4);
CHECK_EQ(pint(find_op(b, "causal_conv1d"), "width"), 3);
@@ -4165,6 +4167,85 @@ TEST(lfm2_issues_the_convolution_once_per_half_of_a_mixed_step) {
CHECK_EQ(convs, 6); /* three conv layers, two halves each */
}
TEST(lfm2_fp8_fuses_the_conv_gate_into_the_quantiser) {
/* A block-fp8 LFM2 whose linears are all whole 128-blocks: 128 hidden, 128 query/key/value,
* 256 ffn. The convolution gate's multiply and the quantiser the out projection reads become
* one op where gate_quant_fp8 is served; without it, the pair is unchanged. */
RadModelMeta meta = lfm2_meta();
meta.n_embd = 128; meta.n_head = 4; meta.n_head_kv = 4; meta.head_dim = 32;
meta.n_ff = 256;
const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
auto encs = [&](RadBuilder& b) {
for (const char* s : { "conv_in.", "conv_out.", "attn_q.", "attn_k.", "attn_v.",
"attn_output.", "ffn_gate_up.", "ffn_down." })
b.encs.push_back({ s, fp8 });
};
/* A bf16 model keeps the plain mul: the candidate is a block-fp8 producer only. */
{
RadBuilder b;
RadBuildCtx ctx = build_ctx();
CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx));
CHECK_EQ(count_op(b, "gate_quant_fp8"), 0);
}
for (int how = 0; how < 2; ++how) {
RadBuilder b;
encs(b);
if (how == 0) b.undeclared.insert("gate_quant_fp8");
else b.refuse.insert("gate_quant_fp8");
RadBuildCtx ctx = build_ctx();
REQUIRE_EQ(lfm2_bf16::declare(&b, &meta, &ctx), RAD_OK);
int resolved = 0;
for (const auto& o : b.ops)
if (o.op == "gate_quant_fp8" && o.resolved) ++resolved;
CHECK_EQ(resolved, 0);
CHECK_EQ(count_op(b, "quant_act_fp8"), 4); /* three conv mixers + the attention output */
CHECK_EQ(count_op(b, "mul"), 6); /* gate_in and gate_out per conv layer */
}
RadBuilder b;
encs(b);
RadBuildCtx ctx = build_ctx();
REQUIRE_EQ(lfm2_bf16::declare(&b, &meta, &ctx), RAD_OK);
CHECK_EQ(count_op(b, "gate_quant_fp8"), 3); /* the three convolution layers */
CHECK_EQ(count_op(b, "quant_act_fp8"), 1); /* only the attention output remains */
CHECK_EQ(count_op(b, "mul"), 3); /* gate_in alone */
const RecOp* gq = find_op(b, "gate_quant_fp8");
REQUIRE(gq != nullptr);
CHECK_EQ(pstr(gq, "act"), std::string("none"));
CHECK_EQ(pint(gq, "n"), 128);
CHECK_EQ((int)gq->reads.size(), 2);
CHECK_EQ((int)gq->writes.size(), 2); /* codes and scales; no bf16 product */
/* Decode (one row) and a 32-row chunk: the fused op carries both, and its gate is the C
* third of the [B|C|x] row while the value it scales is the convolution output. */
auto buf_id = [&](const char* name) -> rad_buf {
for (size_t j = 0; j < b.bufs.size(); ++j)
if (b.bufs[j].name == name) return (rad_buf)(j + 1);
return 0;
};
for (const auto& k : { kit(b, { 1 }, {}), kit(b, {}, { 32 }) }) {
const auto v = run_passes(b, lfm2_bf16::step, { k.get() });
CHECK_PASSES(b, v);
const std::vector<std::string> ops = issued_ops(b, *v[0]);
CHECK_EQ(count_issued(ops, "gate_quant_fp8"), 3);
CHECK_EQ(count_issued(ops, "quant_act_fp8"), 1);
int seen = 0;
for (const RecIssue& i : v[0]->issues) {
const RecOp* o = b.op_of(i.op);
if (!o || o->op != "gate_quant_fp8" || seen++) continue;
REQUIRE(i.opd.size() == 5); /* Optional BF16 output still occupies its schema slot. */
CHECK_EQ(i.opd[0].offset, (int64_t)128); /* C in [B|C|x] */
CHECK_EQ(i.opd[0].cols, (int64_t)128);
CHECK_EQ(i.opd[1].handle, buf_id("conv_out"));
CHECK_EQ(i.opd[2].handle, buf_id("conv_out.q"));
CHECK_EQ(i.opd[3].handle, buf_id("conv_out.s"));
}
CHECK_EQ(seen, 3);
}
}
/* ==================================================================== LFM2-VL's tower */
namespace {
@@ -4705,8 +4786,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 +7201,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
@@ -7703,11 +7830,106 @@ TEST(qwen35_fp8_declares_fp8_linears_and_the_fused_output_gate) {
if (o.resolved) CHECK(o.uses_declared);
for (const auto& w : b.weights)
if (!w.d.source) CHECK(find_map(b, w.name) != nullptr);
/* The lfm2-only rows are that model's own declarations: nothing here names one, so every op
* resolves to the row it always did (gemm_nt keeps its band, rmsnorm and rope their launches). */
for (const auto& o : b.ops) {
CHECK(o.op != "gemm_nt_q_short");
CHECK(o.op != "gemm_nt_q_gated_wide");
CHECK(o.op != "rmsnorm_rows");
CHECK(o.op != "rope_rows");
}
/* No speculation: no head, no drafter. */
CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_NONE);
CHECK(find_b(b, "mtp_x") == nullptr);
}
/* On an MXFP4 trunk the feed-forward's gated fold (gate_up, silu_mul and down's quantiser in one
* launch) is declared over 1..16 rows, libr4d's gated_gemv (1..8) and part of gated_gemv_wide's
* (9..64) band: a verify step of one or two sequences at speculation 7 (8 or 16 rows) issues it
* once a layer at the step's height and no gated_quant_fp8; a taller one (24..64 rows) the unfused
* gate_up and gated_quant_fp8. */
TEST(qwen35_fp8_mxfp4_feed_forward_folds_verify_steps_up_to_16_rows) {
MetaKV mk = with_dflash2(q35fp8_meta());
const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, rad::arch::RAD_MX_GROUP);
const int L = 8;
for (int rank = 0; rank < 2; ++rank) {
RadBuilder b;
b.encs = { { "blk.", mx } };
RadBuildCtx ctx = spec_ctx(rank, 2, 7);
ctx.max_tok = 2048;
REQUIRE_EQ(stderr_of_rc([&] { return qwen35_fp8::declare(&b, mk.meta(), &ctx); }), RAD_OK);
int folds = 0;
for (const auto& o : b.ops)
if (o.op == "gemm_nt_q_gated_mx" && !o.w.empty() &&
b.weights[o.w[0] - 1].name.rfind("blk.", 0) == 0) {
++folds;
CHECK_EQ(pstr(&o, "act"), std::string("silu"));
CHECK_EQ(param(&o, "M")->ihi, 16);
}
CHECK_EQ(folds, L);
for (int n = 1; n <= 8; ++n) {
const auto k = kit(b, std::vector<int>((size_t)n, 8), {});
const auto v = run_passes(b, qwen35_fp8::step, { k.get() }, rank, 2);
CHECK_PASSES(b, v);
const std::vector<std::string> ops = issued_ops(b, *v[0]);
const bool fold = 8 * n <= 16;
int gated = 0;
for (size_t i = 0; i < ops.size(); ++i)
if (ops[i] == "gemm_nt_q_gated_mx") {
++gated;
CHECK_EQ(v[0]->issues[i].n, 8 * n);
}
CHECK_EQ(gated, fold ? L : 0);
CHECK_EQ(count_issued(ops, "gated_quant_fp8"), fold ? 0 : L);
}
}
}
/* At two ranks each delta-net layer reads its out-projection into the on-die cache beside the decode
* recurrent update (GdnFP8::op_pf_out): a `prefetch` of the whole projection, issued right before
* the update on steps of up to four decode sequences and 32 rows, none on a step of five or more
* sequences, on a prompt's rows or at one rank. */
TEST(qwen35_fp8_reads_the_delta_net_out_projection_beside_its_decode_update) {
MetaKV mk = with_dflash2(q35fp8_meta());
const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, rad::arch::RAD_MX_GROUP);
const int n_gdn = 6;
for (int world : { 1, 2 }) {
RadBuilder b;
b.encs = { { "blk.", mx } };
RadBuildCtx ctx = spec_ctx(0, world, 7);
ctx.max_tok = 2048;
REQUIRE_EQ(stderr_of_rc([&] { return qwen35_fp8::declare(&b, mk.meta(), &ctx); }), RAD_OK);
int declared = 0;
for (const auto& o : b.ops)
if (o.op == "prefetch" && o.w.size() == 1 &&
b.weights[o.w[0] - 1].name.find("ssm_out") != std::string::npos) {
++declared;
CHECK_EQ(pint(&o, "bytes"), (int64_t)8 << 20);
}
CHECK_EQ(declared, world > 1 ? n_gdn : 0);
/* (decode sequences, rows each, prompt rows) -> whether the reads go */
struct Case { int seqs, rows, prompt; bool reads; };
for (const Case& cs : { Case{ 1, 8, 0, true }, Case{ 2, 8, 0, true }, Case{ 4, 8, 0, true },
Case{ 4, 1, 0, true }, Case{ 5, 4, 0, false }, Case{ 8, 4, 0, false },
Case{ 0, 0, 64, false }, Case{ 2, 8, 64, false } }) {
const auto k = kit(b, std::vector<int>((size_t)cs.seqs, cs.rows),
cs.prompt ? std::vector<int>{ cs.prompt } : std::vector<int>{});
const auto v = run_passes(b, qwen35_fp8::step, { k.get() }, 0, world);
CHECK_PASSES(b, v);
const std::vector<std::string> ops = issued_ops(b, *v[0]);
int updates = 0, beside = 0;
for (size_t i = 0; i < ops.size(); ++i)
if (ops[i] == "gdn_conv_recurrent_update" || ops[i] == "gdn_recurrent_update") {
++updates;
if (i > 0 && ops[i - 1] == "prefetch") ++beside;
}
CHECK_EQ(updates, cs.seqs ? n_gdn : 0);
CHECK_EQ(beside, cs.reads && world > 1 ? n_gdn : 0);
}
}
}
/* Every engine step the dense fp8 model runs lints clean at one and two ranks, the MTP head's
* history pass and rounds included. */
TEST(qwen35_fp8_steps_lint_clean_with_its_mtp_head) {
@@ -10467,7 +10689,7 @@ struct ArchCases {
qwen35_fp8::step, 3, {}, 0x20ab9ed24e409329ull);
add("qwen35_fp8 + MTP, two ranks", [this, sc](RadBuilder* b) {
auto c = sc(2, 3); return qwen35_fp8::declare(b, q35.meta(), &c); },
nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0xd12381e7e3ede24dull);
nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x5b52afb1706a954eull);
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, {}, 0x365e4cbb415ac284ull);
@@ -10476,7 +10698,7 @@ struct ArchCases {
qwen35_w8a8::step, 7, {}, 0x742a596708bbda1dull);
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" }, 0x7b7a1b301de20c1eull);
nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0x93b6390d30e59953ull);
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, {}, 0x4c7e42e71f167042ull);
@@ -10507,7 +10729,7 @@ struct ArchCases {
llama_fp8::step, 7, {}, 0xdcf36a1d31aba73cull);
add("lfm2_bf16", [this, sc](RadBuilder* b) {
auto c = sc(1, 0); return lfm2_bf16::declare(b, &lfm, &c); },
lfm2_bf16::step, 0, {}, 0x1775b188dc4a5120ull);
lfm2_bf16::step, 0, {}, 0x5bce917918dbd478ull);
add("gemma4_bf16", [this, sc](RadBuilder* b) {
auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); },
gemma4_bf16::step, 0, {}, 0x2ba2f4943031468full);
@@ -11223,7 +11445,7 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) {
{ "qwen4exp_fp8", 4, 0, 0x780814049d36bebcull, 0xfbe74f2b9d7020bfull },
{ "qwen4exp_fp8", 4, 3, 0x0723ed824fef82d4ull, 0x36df57cac613c6cfull },
{ "qwen35_fp8", 1, 0, 0xc56a518087e3f4b4ull, 0xa7ec3cf6252cd441ull },
{ "qwen35_fp8", 2, 1, 0x61d309383f96b1acull, 0xbf359de7b8a6322cull },
{ "qwen35_fp8", 2, 1, 0x6e644b3d13bac619ull, 0xdd5d65ef158c4136ull },
{ "qwen35moe_fp8", 1, 0, 0x7a9330e0da08f97cull, 0x2b5989b2a6dbc7dfull },
{ "qwen35moe_fp8", 2, 0, 0x3a2761e9546797f1ull, 0x4a597c66b5868eeeull },
};
+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) {
@@ -1839,8 +1870,9 @@ TEST(the_plugin_words_bound_is_recorded_and_checked) {
CHECK_EQ(b.program().plugin_words, (int64_t)4096);
}
/* 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());
@@ -2221,7 +2253,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");
@@ -2279,6 +2313,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; }
+122 -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;
@@ -3416,6 +3503,39 @@ TEST(a_sessions_standing_share_is_what_retention_keeps) {
CHECK_EQ((int64_t)most, 9ll);
}
/* The reserve --host-headroom-mib charges a store's floor: it gives back exactly what the floor is
* short, never below a gigabyte, never above what was asked for, and stays put when the floor
* already fits. A byte rule, so a wider slot (any hybrid model's linear state) or a wider mirror
* (any KV encoding) needs no second case. */
TEST(the_host_reserve_gives_way_to_a_stores_floor_and_no_further) {
const int64_t gib = (int64_t)1 << 30, mib = (int64_t)1 << 20;
const int64_t slot = 113 * mib, floor8 = 8 * slot, reserve = 4 * gib;
/* The floor fits: the reserve never moves, so a host with room to spare sees nothing. */
CHECK_EQ(host_reserve_for_floor(floor8, 20 * floor8, reserve), reserve);
CHECK_EQ(host_reserve_for_floor(floor8, floor8, reserve), reserve);
/* Short: the shortfall comes back in whole MiB, rounded up so the store is never a byte
* short of its floor, and the rest of the reserve stays. */
CHECK_EQ(host_reserve_for_floor(floor8, slot / 2, reserve), reserve - 848 * mib);
CHECK_EQ(host_reserve_for_floor(floor8, floor8 - 1, reserve), reserve - 1 * mib);
CHECK_EQ(host_reserve_for_floor(floor8, floor8 - mib, reserve), reserve - 1 * mib);
CHECK_EQ(host_reserve_for_floor(floor8, floor8 - mib - 1, reserve), reserve - 2 * mib);
/* A floor beyond both the spare memory and the reserve: down to the floor, never below. */
CHECK_EQ(host_reserve_for_floor(64 * gib, 0, reserve), gib);
/* Never above the margin asked for, so a small --host-headroom-mib is still a real bound. */
CHECK_EQ(host_reserve_for_floor(floor8, 0, 512 * mib), 512 * mib);
/* Nothing to protect. */
CHECK_EQ(host_reserve_for_floor(0, 0, reserve), reserve);
CHECK_EQ(host_reserve_for_floor(floor8, 0, 0), 0);
/* The count a floor is taken from: the policy's hold plus a running turn, per sequence. */
const GeometricBackoff g(2048);
CHECK_EQ(checkpoint_slots_want(g, 8, 200000, 2048), 80ll);
CHECK_EQ(checkpoint_slots_want(g, 1, 200000, 2048), 10ll);
CHECK_EQ(checkpoint_slots_want(g, 0, 200000, 2048), 10ll);
CHECK_EQ(checkpoint_slots_want(KeepTipOnly(), 1, 200000, 2048), 2ll);
}
/* --checkpoint-slots auto: the policy's share plus one for each sequence, held to the share of
* memory but not below the floor, and to the room the host has. */
TEST(the_auto_store_gives_every_sequence_its_sessions_share) {
+12 -2
View File
@@ -983,6 +983,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",
@@ -1065,15 +1067,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
@@ -9687,6 +9691,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")),
@@ -9698,6 +9704,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. */
+20
View File
@@ -262,6 +262,24 @@ struct FakeKV : IKVManager {
if (geom.g[i].paged && rows_for((int)i, n) > total[i]) return false;
return true;
}
bool can_grow(uint64_t id, int64_t n) const override {
auto it = seqs.find(id);
if (it == seqs.end()) return false;
const Seq& q = it->second;
if (n <= q.n) return true;
for (size_t i = 0; i < gs.size(); ++i) {
if (geom.g[i].paged) {
int64_t need = rows_for((int)i, n) - (int64_t)q.blocks[i].size();
if (need > 0 && need > (int64_t)freelist[i].size()) return false;
} else if (!geom.g[i].paged && q.state[i] < 0 && state_free[i].empty()) {
return false;
}
}
return true;
}
int64_t available_blocks(int32_t g) const override {
return g >= 0 && g < (int32_t)freelist.size() ? (int64_t)freelist[(size_t)g].size() : 0;
}
const std::vector<int32_t>& block_table(uint64_t id, int32_t g) const override {
auto it = seqs.find(id);
@@ -363,6 +381,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 +446,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
+325 -16
View File
@@ -11,6 +11,7 @@
#include "server/sink.h"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <new>
@@ -97,7 +98,9 @@ struct Fixture {
g_gdn_row = KernelRow{ &g_gdn_ki, "fake", 0, 0 };
prog.meta.n_ctx_train = 4096;
prog.meta.n_vocab = 512;
/* Above the 1000 + i the requests below spell: admission refuses ids past the
* vocabulary, and these prompts must be admissible. */
prog.meta.n_vocab = 65536;
/* index 0 is the sentinel every handle table in Program carries */
prog.ops.emplace_back();
@@ -166,9 +169,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 +317,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 +346,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 +388,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 +398,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 +431,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 +811,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 +1036,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. */
@@ -1172,6 +1283,30 @@ TEST(a_scored_request_names_real_vocabulary_rows) {
CHECK(!kept->may_speculate);
}
/* The prompt itself names real vocabulary rows too: raw id arrays arrive verbatim from the
* request body, and an id past the embedding table must die at admission, never staged into a
* pass — the embedding gather would fail the step, a failed step is a device fault, and a
* device fault stops the engine (spec §17). One bad number must not be a server kill. */
TEST(a_prompt_names_real_vocabulary_rows) {
Fixture f;
f.build(/*blocks=*/20, /*states=*/64);
CHECK_OK(f.start());
const int32_t n_vocab = (int32_t)f.prog.meta.n_vocab;
std::unique_ptr<Request> rs[5];
const std::vector<std::vector<int32_t>> ids = { { 1, 2, n_vocab - 1 }, { n_vocab }, { -1 },
{ 7, INT32_MAX }, { 0, 1, 2, n_vocab + 9 } };
int rc[5] = { -1, -1, -1, -1, -1 };
for (int i = 0; i < 5; ++i) {
rs[i] = std::make_unique<Request>();
rs[i]->id = f.next_id++;
rs[i]->max_tokens = 1;
rs[i]->prompt = ids[(size_t)i];
}
f.sch.add_all(rs, 5, rc);
CHECK_EQ(rc[0], RAD_OK);
for (int i = 1; i < 5; ++i) CHECK_EQ(rc[i], RAD_E_INVAL);
}
TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) {
Fixture f;
f.build();
@@ -1366,8 +1501,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 +1539,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);
@@ -1565,6 +1698,58 @@ TEST(preemption_takes_the_lowest_priority_victim_and_requeues_it_to_the_front) {
}
/* ================================================================== the step batch */
/* A PREEMPTED PREFILL WAITS FOR ROOM FOR THE WHOLE RECOMPUTE plus one block per running
* sequence. Admitting it on a shortfall is what makes the prefill loop: the next decode takes
* the block it just reserved, its next chunk is refused, and preempt_back() resets it again. */
TEST(a_preempted_prefill_waits_for_the_whole_prompt_and_running_headroom) {
Fixture f;
f.build(/*blocks=*/26, /*states=*/64); /* 26 x 16 = 416 tokens */
CHECK_OK(f.start());
uint64_t a = f.submit(287, 64, /*priority=*/5);
uint64_t b = f.submit(128, 64, /*priority=*/0);
/* A takes 287 tokens (18 blocks), B 128 (8): the pool is full. */
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().e.size(), 2);
f.commit_plain();
/* B's next token needs a new block; it is the lowest-priority victim and is reset. */
CHECK(f.sch.step() != nullptr);
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Preempted);
CHECK_EQ(f.sch.find(b)->n_computed, 0);
CHECK_EQ(f.sch.metrics().preemptions, 1);
f.commit_plain();
/* One block the fake pool has free and no sequence holds: the victim's own blocks plus one.
* The gate still wants one block of headroom beside the running A. */
f.kv.total[0] += 1;
f.kv.refcnt[0].push_back(0);
f.kv.freelist[0].push_back(26);
/* B stays in the queue while A runs; it must not be admitted into a pool that has no room
* for its whole prompt plus A's next block. */
uint64_t q[8];
CHECK_EQ(f.sch.queue_snapshot(q, 8), 1);
CHECK_EQ(q[0], b);
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Preempted);
for (int i = 0; i < 80 && f.sch.find(a)->state != ReqState::Finished; ++i) {
CHECK(f.sch.step() != nullptr);
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Preempted);
CHECK_EQ(f.sch.find(b)->n_computed, 0);
f.commit_plain();
}
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Finished);
/* A's blocks are back; B can now prefill its whole prompt. */
CHECK(f.sch.step() != nullptr);
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Running);
CHECK_EQ(f.sch.find(b)->n_computed, 0);
CHECK_EQ(f.sch.metrics().preemptions, 1);
f.commit_plain();
}
TEST(a_mixed_step_has_the_right_boundaries_and_slot_mapping) {
Fixture f;
f.build();
@@ -1958,6 +2143,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 +2192,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 +2280,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);
@@ -5650,6 +5919,46 @@ TEST(a_request_finishing_under_a_step_issued_ahead_keeps_its_blocks_for_that_ste
CHECK_EQ((int)f.sch.find(a)->output.size(), 2); /* the step ahead emitted nothing */
}
/* A SCORED row (Request::token_scores) the step in flight brings to max_tokens gets no step issued
* ahead: it would be a forward pass for a request that finishes at the commit. The step after the
* commit is planned as usual, and a decode that is not scored keeps its step of overlap. */
TEST(no_step_is_issued_ahead_for_a_scored_request_the_step_in_flight_finishes) {
Fixture f;
f.build(/*blocks=*/20, /*states=*/64);
CHECK_OK(f.start());
const int64_t before = f.kv.free_blocks(0);
auto r = f.request(40, /*max_tokens=*/2);
r->speculation_fixed = true;
r->token_scores = std::make_shared<TokenScores>();
r->token_scores->tokens = { 1, 2 };
const uint64_t a = f.add(std::move(r));
REQUIRE(f.sch.step() != nullptr);
f.commit_plain();
REQUIRE(f.sch.step() != nullptr);
CHECK(f.sch.step_next() == nullptr);
f.commit_plain(); /* the second token: finished */
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Finished);
CHECK_EQ(f.kv.free_blocks(0), before);
CHECK_EQ((int)f.sch.find(a)->output.size(), 2);
CHECK(f.sch.step() == nullptr);
}
/* The same row without token_scores is an ordinary decode: the step ahead is issued, as upstream. */
TEST(a_non_scored_row_keeps_the_step_issued_ahead) {
Fixture f;
f.build(/*blocks=*/20, /*states=*/64);
CHECK_OK(f.start());
auto r = f.request(40, /*max_tokens=*/2);
r->speculation_fixed = true;
const uint64_t a = f.add(std::move(r));
REQUIRE(f.sch.step() != nullptr);
f.commit_plain();
REQUIRE(f.sch.step() != nullptr);
CHECK(f.sch.step_next() != nullptr);
f.commit_plain();
CHECK_EQ((int)f.sch.find(a)->output.size(), 2);
}
/* ================================================================== terminal paths */
/* A lone request that outgrows the whole pool fails with the reason the client sees and gives its
* blocks back; nothing is preempted, since there is nobody to preempt and preempting itself would
+22 -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. */
@@ -4745,6 +4747,10 @@ TEST(the_control_vector_field_overrides_the_default_or_is_refused) {
CHECK(!def);
/* Refuses a body that names no boolean rather than guessing. */
CHECK_EQ(f.post("/admin/control-vector", R"({"enabled":"yes"})").status, 400);
/* And a body that is brackets alone: valid JSON, nested deeper than any stack wants to
* tear down, parsed bounded and refused. */
CHECK_EQ(f.post("/admin/control-vector",
std::string(20000, '[') + std::string(20000, ']')).status, 400);
/* Without --api-key a change comes from loopback only; reading it is not restricted. */
HttpRequest q;
q.method = "POST";
@@ -4756,6 +4762,21 @@ TEST(the_control_vector_field_overrides_the_default_or_is_refused) {
q.peer = "127.0.0.1:50122";
CHECK_EQ(f.srv->router().dispatch(q).status, 200);
CHECK(def);
/* A browser page on another origin is not a loopback client, even though its own
* browser makes the request arrive loopback: defeating the guard that way is exactly
* what the drive-by would do. Same-origin browser traffic still passes. */
HttpRequest x;
x.method = "POST";
x.path = "/admin/control-vector";
x.body = R"({"enabled":false})";
x.peer = "127.0.0.1:50122";
x.headers["Origin"] = "http://evil.test";
x.headers["Host"] = "127.0.0.1:8080";
CHECK_EQ(f.srv->router().dispatch(x).status, 403);
CHECK(def);
x.headers["Origin"] = "http://127.0.0.1:8080";
CHECK_EQ(f.srv->router().dispatch(x).status, 200);
CHECK(!def);
HttpRequest g2;
g2.path = "/admin/control-vector";
g2.peer = "192.168.1.20:50122";
+20
View File
@@ -299,6 +299,26 @@ TEST(a_speech_session_refuses_what_it_cannot_take_and_goes_on) {
CHECK(!s.conn.closed);
}
/* A frame that is brackets alone, nested tens of thousands deep, is still valid JSON: parsing it
* into a tree and tearing that tree down both recurse once per level, so the session parses it
* bounded — the tree never outgrows the stack — answers its invalid-message error, and goes on.
*/
TEST(a_deeply_nested_frame_is_refused_not_fatal) {
Stream s;
const std::string deep = std::string(20000, '[') + std::string(20000, ']');
{
std::lock_guard<std::mutex> lk(s.conn.m);
s.conn.in.push_back(deep);
s.conn.cv.notify_all();
}
CHECK(!s.conn.wait_for("error").is_null());
CHECK(!s.conn.closed);
s.config();
s.text("Still here.");
s.done();
REQUIRE(!s.conn.wait_for("session.done").is_null());
}
/* A sentence the generator refuses or fails is an error and an audio.done saying so; the next
* sentence is spoken as usual. */
TEST(a_failed_sentence_says_so_and_the_next_is_spoken) {
+1
View File
@@ -326,6 +326,7 @@ TEST(the_endpoint_answers_only_for_a_declared_d1) {
if (!*type) { CHECK_EQ(res.status, 501); continue; }
REQUIRE(res.status == 200);
const json j = json::parse(res.body);
CHECK_EQ(j["model"].get<std::string>(), "d1");
CHECK_NEAR(j["answers"]["q"]["noul"].get<double>(), 0.75, 1e-6);
CHECK_EQ(j["answers"]["c"]["choice"].get<std::string>(), "one");
CHECK_EQ(j["usage"]["output_tokens"].get<int>(), 0);
+3 -3
View File
@@ -2298,9 +2298,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):
+26 -1
View File
@@ -261,7 +261,9 @@ TEST(the_api_key_gate_holds_every_route_but_the_probes) {
REQUIRE(s.srv->port() > 0);
s.sched.hang = false;
s.sched.reply = "ok";
auto ask = [&](const std::string& req) { return ::ask(s, req); };
auto ask = [&](const std::string& req, bool head_only = false) {
return ::ask(s, req, head_only);
};
for (const char* h : { "", "Authorization: Bearer wrong\r\n", "X-Api-Key: wrong\r\n",
"Authorization: k\r\n", "Authorization: Basic k\r\n" }) {
const Reply r = ask(get("/v1/models", h));
@@ -279,6 +281,16 @@ TEST(the_api_key_gate_holds_every_route_but_the_probes) {
}
for (const char* p : { "/health", "/v1/health", "/ping", "/", "/dashboard" })
CHECK_EQ(ask(get(p)).status, 200);
/* The page says what bounds it: a CSP that lets its own script talk only to this origin and
* keeps it out of a frame, and a type no browser may second-guess — the last on every
* response, refusals included. */
const Reply page = ask(get("/"));
CHECK(has(page.header("Content-Security-Policy"), "frame-ancestors 'none'"));
CHECK(has(page.header("Content-Security-Policy"), "connect-src 'self'"));
CHECK_EQ(page.header("X-Frame-Options"), std::string("DENY"));
CHECK_EQ(page.header("X-Content-Type-Options"), std::string("nosniff"));
CHECK_EQ(ask(get("/stats", "Authorization: Bearer k\r\n")).header("X-Content-Type-Options"),
std::string("nosniff"));
CHECK_EQ(ask(get("/metrics")).status, 401);
CHECK_EQ(ask(get("/stats")).status, 401);
CHECK_EQ(ask(post("/tokenize", R"({"prompt":"a"})")).status, 401);
@@ -298,6 +310,19 @@ TEST(the_api_key_gate_holds_every_route_but_the_probes) {
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");
CHECK_EQ(big.status, 401);
/* The exemption is a closed set of decoded paths and methods. Paths that only reach a
* guarded route after the router's own matching (empty segments collapse there, dot segments
* resolve nowhere) pay the key; and so does any method on an exempt path that no route
* answers, so the exemption can never ride a future mutating route. */
for (const char* p : { "//stats", "/%2Fstats", "/dashboard/../sessions", "/stats/", "/Stats",
"/stats;x", "/health//", "//health", "/HEALTH" })
CHECK_EQ(ask(get(p)).status, 401);
CHECK_EQ(ask("POST / HTTP/1.1\r\nHost: t\r\nContent-Length: 0\r\n\r\n").status, 401);
CHECK_EQ(ask("DELETE /health HTTP/1.1\r\nHost: t\r\n\r\n").status, 401);
/* POST /ping is the health-check convention and stays exempt, as every read on an exempt
* path does. */
CHECK_EQ(ask("POST /ping HTTP/1.1\r\nHost: t\r\nContent-Length: 0\r\n\r\n").status, 200);
CHECK_EQ(ask("HEAD / HTTP/1.1\r\nHost: t\r\n\r\n", /*head_only=*/true).status, 200);
}
/* A refusal the transport writes itself on an Anthropic path (the key gate's 401, a body over