radiance 1.1.0

- The VRAM split has no ratio: --expert-vs-cache-ratio is gone (now an unknown option). The
  experts keep what the pinned host pool cannot hold, the KV cache takes the rest and lends idle
  blocks to the experts. Flash-Next at tp2: 7.9 GiB of KV a card, up from 4.7. Startup, /stats,
  /metrics and the dashboard report the most the cache can hold.
- Linear-state snapshots live in pinned host memory, not VRAM (--checkpoint-slots sizes the
  store). Prefix-cache misses on agent sessions fixed; a published conversation is no longer
  trimmed away.
- Any world size from the shipped container (baKon): --tp 3 on Flash-Next with no padded
  checkpoint -- the attention world, uneven delta-net heads, the fill op.
- Kernels (keptn42): moe_gemm_q decode loads and one-trip run search, hc_read's prefill form
  (+3.7% prefill at 18K), hc_up row groups up to eight, the fused router launch. Each is the rule
  where it was measured faster; no environment switches.
- Tool calls: a typed argument is always JSON (Python True/None no longer leak into arguments --
  Codeberg #21); nine further reply-parser fixes; the reply path inside a call is ~12x cheaper on
  the host.
- The kernel changes: prefill +2-3% and decode -2% a step on 2x R9700 at tp2, identical text.
This commit is contained in:
Deadcode committed 2026-10-06 14:04:49 +02:00
1 parent 9f5feb24ee
commit 82b5835c02
101 files changed
+5105 -3767

No files matched your search

+33 -27
View File
@@ -45,11 +45,10 @@ struct RecWeight {
* checked. A weight with no span -- every even shard -- has `span_set` false. */
bool span_set = false;
int64_t span_lo = 0, span_hi = 0;
/* rad_weight_shard_span_parts and rad_weight_shard_zero, recorded the same way. */
/* rad_weight_shard_span_parts, recorded the same way. */
int n_part_spans = 0;
int64_t part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0};
int64_t part_total[RAD_MAX_ROW_PARTS] = {0};
bool zero = false;
};
struct RecBuf { std::string name; RadBufDecl d{}; };
struct RecOp {
@@ -238,13 +237,6 @@ extern "C" int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const in
rw.n_part_spans = n;
return RAD_OK;
}
extern "C" int rad_weight_shard_zero(RadBuilder* b, rad_weight w) {
if (!b || w == 0 || w > b->weights.size()) return RAD_E_INVAL;
RecWeight& rw = b->weights[w - 1];
if (rw.d.shard != RAD_SHARD_ROW && rw.d.shard != RAD_SHARD_COL) return RAD_E_INVAL;
rw.zero = true;
return RAD_OK;
}
extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) {
if (!b || g == 0 || g > b->kv_groups.size()) return RAD_E_INVAL;
b->kv_groups[g - 1].zero = true;
@@ -2243,17 +2235,28 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) {
}
}
/* A WORLD THAT CANNOT REPLICATE -- not a multiple of the KV head count -- is no longer
* refused: it serves attention on the largest multiple under it and the rest of the ranks
* carry zero attention (the tp3 case below holds the shapes). Nothing is rounded into a
* half head: the replication rule itself is unchanged and still refuses an attention world
* that is not a multiple, which cannot arise from geom_from's construction. */
/* A WORLD THAT CANNOT REPLICATE -- not a multiple of the KV head count -- declares: qwen4exp
* asks for the attention world (geom_from's `attn_world_ok`), so attention is served on the
* largest multiple under it and the rest of the ranks compute none (the tp3 case below holds
* the shapes). Nothing is rounded into a half head: the replication rule refuses an attention
* world that is not a multiple, which geom_from's construction cannot produce. A plugin that
* does not ask is refused at this world, by geom_from itself. */
{
RadBuilder b3;
RadBuildCtx c3 = build_ctx(0, 3);
c3.max_tok = 2048; c3.max_seqs = 8; c3.max_spec = 3; c3.max_ctx = 200000;
CHECK_EQ(qwen4exp_fp8::declare(&b3, &meta, &c3), RAD_OK);
}
{
rad::arch::Geom g3{};
RadBuildCtx c3 = build_ctx(0, 3);
c3.max_tok = 2048; c3.max_seqs = 8; c3.max_spec = 3; c3.max_ctx = 200000;
CHECK_EQ(rad::arch::geom_from(g3, &meta, &c3, "bf16", RAD_BF16, /*arch_splits_ff=*/true), RAD_E_INVAL);
CHECK_EQ(rad::arch::geom_from(g3, &meta, &c3, "bf16", RAD_BF16, /*arch_splits_ff=*/true,
/*attn_world_ok=*/true), RAD_OK);
CHECK(g3.attn_zero == false);
CHECK_EQ(g3.attn_world, 2);
}
/* ---- A LAYER THAT KEEPS EXPERTS PLAIN STAYS AT FOUR CLASSES. Two plain experts leave 510
* quantised ones, four leave 508; either way the layer is served by `moe_gemm_q_mod4`, the
@@ -2478,11 +2481,10 @@ const RecIssue* issue_of(const RadBuilder& b, const RadCtx& c, const std::string
} /* namespace */
/* THREE RANKS OVER TWO KV HEADS: the attention world is 2 (rad_arch.h), rank 2 declares the same
* attention as its peers and reads zeros for it, and the delta net's 16 K heads go 6, 5, 5 with
* the V heads at the same multiple -- declared as spans of the container, nothing padded. On the
* tree before this, geom_from refuses world 3 ("cannot replicate n_head_kv = 2") and nothing
* below runs. */
/* THREE RANKS OVER TWO KV HEADS: the attention world is 2 (rad_arch.h), rank 2 computes no
* attention -- a `fill` of its output wire and a zero KV group -- and the delta net's 16 K heads
* go 5, 5, 6 with the V heads at the same multiple, the extra head on the rank without attention
* -- declared as spans of the container, nothing padded. */
TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenly) {
RadModelMeta meta = qwen4exp_meta();
const int world = 3;
@@ -2529,6 +2531,7 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl
}
}
std::vector<std::pair<int64_t, int64_t>> k_span((size_t)world); /* each rank's K heads, [lo, hi) */
for (int r = 0; r < world; ++r) {
const bool zero = r >= attn_world;
CHECK_EQ(b[r].kv_groups[0].d.n_head_kv, 1);
@@ -2566,7 +2569,6 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl
const int ar = zero ? attn_world - 1 : r;
CHECK_EQ(w->span_lo, (int64_t)ar * head_dim);
CHECK_EQ(w->span_hi, w->span_lo + head_dim);
CHECK_EQ(w->zero, zero);
}
if (!zero) {
const RecWeight* w = find_w(b[r], qg);
@@ -2576,13 +2578,11 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl
CHECK_EQ(w->d.shape[0], qg_rows);
CHECK(w->span_set);
CHECK_EQ(w->span_lo, (int64_t)ar * qg_rows);
CHECK_EQ(w->zero, zero);
const RecWeight* o = find_w(b[r], oo);
REQUIRE(o != nullptr);
CHECK_EQ(o->d.shard, RAD_SHARD_COL);
CHECK(o->span_set);
CHECK_EQ(o->span_lo, (int64_t)ar * (n_head / attn_world) * head_dim);
CHECK_EQ(o->zero, zero);
}
/* (3) THE DELTA NET: 5, 5, 6 K heads and 15, 15, 18 V heads, real on every rank, as
* per-part spans of [q|k|v|z] and of the conv channels, a one-span of A_log. */
@@ -2605,7 +2605,7 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl
CHECK_EQ(in->part_lo[3], v0 * hv);
CHECK_EQ(in->part_total[0], nk * hk);
CHECK_EQ(in->part_total[2], nv * hv);
CHECK(!in->zero);
k_span[(size_t)r] = { in->part_lo[0] / hk, in->part_hi[0] / hk };
const RecWeight* cv = find_w(b[r], "blk.0.ssm_conv1d.weight");
REQUIRE(cv != nullptr);
REQUIRE_EQ(cv->n_part_spans, 3);
@@ -2629,11 +2629,17 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl
if (g.name == "kv_gdn_state") { seen = true; CHECK_EQ(g.d.n_head_kv, (int)my_v); }
CHECK(seen);
}
/* The three ranks' K heads are the container's 16, once each. */
/* The three ranks' K heads, read back from the declared spans, are the container's 16, each
* exactly once. */
{
int64_t sum = 0;
for (int r = 0; r < world; ++r) sum += nk / world + (r < nk % world ? 1 : 0); /* a permutation of the same counts */
CHECK_EQ(sum, nk);
std::vector<int> owner((size_t)nk, -1);
for (int r = 0; r < world; ++r)
for (int64_t h = k_span[(size_t)r].first; h < k_span[(size_t)r].second; ++h) {
REQUIRE(h >= 0 && h < nk);
CHECK_EQ(owner[(size_t)h], -1);
owner[(size_t)h] = r;
}
for (int64_t h = 0; h < nk; ++h) CHECK(owner[(size_t)h] >= 0);
}
}
+6 -10
View File
@@ -1349,14 +1349,14 @@ TEST(the_gate_names_its_caller) {
CHECK(has(msg, "the container's layout"));
}
/* A span, per-part spans and a zero share have to SURVIVE THE WEIGHT LIST GROWING: WeightInfo's
* copy is hand-written (the atomic), so a field the copy leaves out is reset on every weight
* declared before the vector's last reallocation -- which is what the loader saw on rank 0 of a
* three-rank Flash-Next: layer 0's [a|b] with its per-part spans gone, refused as an even share. */
TEST(shard_spans_and_zero_survive_the_weight_list_reallocating) {
/* A span and per-part spans have to SURVIVE THE WEIGHT LIST GROWING: WeightInfo's copy is
* hand-written (the atomic), so a field the copy leaves out is reset on every weight declared
* before the vector's last reallocation, and the loader then sees an uneven share as an even one
* and refuses it. */
TEST(shard_spans_survive_the_weight_list_reallocating) {
NEED_PLUGIN(reg)
Builder b(reg, make_meta(), make_ctx());
/* Three weights declared first and marked, then enough declared after them to grow the
/* Two weights declared first and marked, then enough declared after them to grow the
* list several times over. */
RadWeightDecl d{};
d.dtype = RAD_BF16; d.rank = 2; d.shape[0] = 36; d.shape[1] = 64;
@@ -1370,8 +1370,6 @@ TEST(shard_spans_and_zero_survive_the_weight_list_reallocating) {
const rad_weight sp = decl_w(b, "span", 18, 64);
CHECK_EQ(b.weight_shard_span(sp, 6, 24), RAD_OK);
const rad_weight z = decl_w(b, "zero", 18, 64);
CHECK_EQ(b.weight_shard_zero(z), RAD_OK);
for (int i = 0; i < 300; ++i) {
char n[32]; snprintf(n, sizeof n, "w%d", i);
@@ -1387,8 +1385,6 @@ TEST(shard_spans_and_zero_survive_the_weight_list_reallocating) {
w = b.program().weight(sp);
CHECK_EQ((long long)w->shard_lo, 6LL);
CHECK_EQ((long long)w->shard_hi, 24LL);
w = b.program().weight(z);
CHECK(w->shard_zero);
CHECK_EQ((int)b.errors().size(), 0);
}
+184 -10
View File
@@ -160,16 +160,16 @@ static Verdict run(Bench* b, const std::string& text, const char* what, size_t s
* grammar, and the calls must come back as the message had them. */
/* What the template wrote for an argument, read back: a string argument is its text and any
* other one is JSON. Two exceptions, both the template's rendering rather than the parser's
* reading: a boolean or null, which Jinja renders the Python way (`True`, `None`), and -- in
* MiniCPM's template, which prints a value with a bare `{{ param_value }}` -- a list or an object,
* which this Jinja engine prints without its brackets. Those are compared by what the reply says,
* which the differential check already covers, rather than by what the message held. */
* other one is JSON -- a boolean or null included, which Jinja renders the Python way (`True`,
* `None`) and the parser reads back as JSON's. One exception, the template's rendering rather than
* the parser's reading: MiniCPM's template prints a value with a bare `{{ param_value }}`, and a
* list or an object comes out of this Jinja engine without its brackets. Those are compared by
* what the reply says, which the differential check already covers, rather than by what the
* message held. */
static bool round_trips(const json& want, const json& got, bool containers) {
if (!got.is_object() || want.size() != got.size()) return false;
for (auto it = want.begin(); it != want.end(); ++it) {
if (!got.contains(it.key())) return false;
if (it.value().is_boolean() || it.value().is_null()) continue;
if (!containers && it.value().is_structured()) continue;
if (got.at(it.key()) != it.value()) return false;
}
@@ -295,6 +295,71 @@ TEST(the_decided_shapes_read_as_decided) {
if (!r.calls.empty())
CHECK_EQ(r.calls[0].arguments, std::string("{\"command\":\"sleep\",\"timeout\":\"30 seconds\"}"));
/* A typed argument always reads as JSON: Python's literals as JSON's, inside a container
* too, an empty value as null, and text that spells no JSON value as a string of it.
* Qwen's format reads non-string arguments as JSON; MiniCPM's reads every one as text. */
if (q) {
r = read_adv(m, "Python literals");
CHECK_EQ(r.calls.size(), (size_t)1);
if (!r.calls.empty())
CHECK_EQ(r.calls[0].arguments, std::string("{\"verbose\":true,\"nothing\":null}"));
r = read_adv(m, "a Python dict with literals");
if (!r.calls.empty()) {
const json a = json::parse(r.calls[0].arguments, nullptr, false);
CHECK(!a.is_discarded());
if (!a.is_discarded()) {
CHECK(a["extra"]["a"] == json(true));
CHECK(a["extra"]["b"].is_null());
CHECK(a["extra"]["c"] == json("False"));
}
}
r = read_adv(m, "an empty typed value");
if (!r.calls.empty())
CHECK_EQ(r.calls[0].arguments, std::string("{\"level\":null}"));
r = read_adv(m, "a typed value that is no JSON");
if (!r.calls.empty())
CHECK_EQ(r.calls[0].arguments, std::string("{\"verbose\":\"yes please\"}"));
r = read_adv(m, "a number that is not one");
if (!r.calls.empty())
CHECK_EQ(r.calls[0].arguments, std::string("{\"path\":\"/a\",\"limit\":\"01\"}"));
/* A raw line break or tab inside a string is the escape JSON spells it as: a client's
* JSON parser refuses the raw character. */
r = read_adv(m, "JSON strings holding a raw line break and tab");
CHECK_EQ(r.calls.size(), (size_t)1);
if (!r.calls.empty()) {
const json a = json::parse(r.calls[0].arguments, nullptr, false);
CHECK(!a.is_discarded());
if (!a.is_discarded()) {
CHECK(a["extra"]["a"] == json("line1\nline2"));
CHECK(a["extra"]["b"] == json("\tx"));
}
}
/* A container is JSON once normalised, or the string of its text: a trailing comma,
* a bare word or a missing bracket is no JSON, and the arguments must stay JSON. */
r = read_adv(m, "Python containers that are no JSON");
CHECK_EQ(r.calls.size(), (size_t)1);
if (!r.calls.empty())
CHECK_EQ(r.calls[0].arguments, std::string("{\"extra\":\"{'a': 1, 'b': [2, 3],}\","
"\"tags\":\"['x', nan]\"}"));
r = read_adv(m, "a container missing its close");
if (!r.calls.empty())
CHECK_EQ(r.calls[0].arguments, std::string("{\"extra\":\"{'a': [1, 2}\"}"));
r = read_adv(m, "an escaped quote in a double-quoted string");
if (!r.calls.empty())
CHECK_EQ(r.calls[0].arguments, std::string("{\"tags\":[\"it's\", \"x\"]}"));
/* The grammar's JSON admits a number past a double's range and an unpaired surrogate
* escape, which a client's JSON parser refuses: such a value is its text. */
r = read_adv(m, "JSON a client cannot read");
if (!r.calls.empty()) {
const json a = json::parse(r.calls[0].arguments, nullptr, false);
CHECK(!a.is_discarded());
if (!a.is_discarded()) {
CHECK(a["level"] == json("1e400"));
CHECK(a["extra"] == json(R"({"a": "\ud800"})"));
}
}
}
/* A Python-quoted array is normalised to JSON. */
r = read_adv(m, "a Python-quoted array");
if (!r.calls.empty()) {
@@ -331,6 +396,18 @@ TEST(the_decided_shapes_read_as_decided) {
CHECK_EQ(r.calls[0].arguments, std::string("{\"command\":\"ls\"}"));
}
CHECK(r.content.empty());
/* A call whose own close is missing is ended by its wrapper's, and the next call is
* a call of its own rather than more arguments for this one. */
r = read_adv(m, "a call closed by its wrapper alone");
CHECK_EQ(r.calls.size(), (size_t)2);
if (r.calls.size() == 2) {
CHECK(r.calls[0].closed);
CHECK_EQ(r.calls[0].arguments, std::string("{\"command\":\"ls\"}"));
CHECK_EQ(r.calls[1].name, std::string("read"));
CHECK_EQ(r.calls[1].arguments, std::string("{\"path\":\"/a\"}"));
}
CHECK(r.content.empty());
}
/* The terminator is not the answer, nor is trailing whitespace. */
@@ -339,6 +416,81 @@ TEST(the_decided_shapes_read_as_decided) {
}
}
/* AN ARGUMENT NAME THAT REPEATS ITS OWN TAG'S OPENING -- `<parameter=parameter=command>`, which
* models write and the grammar's undeclared arm admits -- is the argument it names, read
* leniently: as the undeclared `parameter=command` the call reaches the tool without its command.
* A name the repetition does not make a declared one stays as written. */
TEST(an_argument_name_repeating_its_tag_is_the_argument_it_names) {
for (const Model& m : models()) {
Bench* b = bench(m, ChatRequest{});
if (!b) continue;
const std::string T = "Thinking it over.\n</think>\n\n";
const bool q = is_qwen(m);
const std::string rep = q ? "parameter=" : "param name=\"";
const std::string text = T + C(m, "bash", { { rep + "command", "ls -la" },
{ rep + rep + "timeout", "30" },
{ rep + "nope", "x" } });
bool strict = true;
const ReplyMessage r = b->new_parse(text, &strict);
CHECK(!strict);
REQUIRE(r.calls.size() == 1);
const bool typed = b->format().other_value == ChatValue::Json;
CHECK_EQ(r.calls[0].arguments, "{\"command\":\"ls -la\",\"timeout\":" +
std::string(typed ? "30" : "\"30\"") + "," +
json(rep + "nope").dump() + ":\"x\"}");
const std::string s = stream_all(b->parser(), text);
CHECK(s.empty());
if (!s.empty()) fprintf(stderr, " %s\n", s.c_str());
}
}
/* A CALL THE REPLY ENDED INSIDE reads back, as content, as the text it was written as: the content
* before it, then the call's own bytes -- never the reasoning, never a call that closed before it.
* What a buffered response answers with when that call cannot be reported as a call. */
TEST(a_call_the_reply_ended_inside_reads_back_as_its_text) {
auto trimmed = [](std::string s) {
while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) s.pop_back();
return s;
};
for (const Model& m : models()) {
Bench* b = bench(m, ChatRequest{});
if (!b) continue;
const std::string T = "Thinking it over.\n</think>\n\n";
const std::string done = C(m, "bash", { { "command", "ls" } });
const std::string call = C(m, "write", { { "path", "/a" }, { "content", "partial fi" } });
for (const size_t cut : { call.find("partial") + 3, call.find("</function>") + 3 }) {
const std::string open = call.substr(0, cut);
struct Case { std::string text, content; size_t calls; };
std::vector<Case> cases = {
{ T + "Writing.\n" + open, "Writing.\n" + trimmed(open), 1 },
{ T + "Writing.\n" + done + "\n" + open, "Writing.\n" + trimmed(open), 2 },
{ T + open, trimmed(open), 1 },
};
/* Qwen's reasoning block ends where a call starts. */
if (is_qwen(m)) cases.push_back({ "I will write it.\n" + open, trimmed(open), 1 });
for (const Case& k : cases) {
std::unique_ptr<ReplyStream> s = b->parser().open();
for (size_t i = 0; i < k.text.size(); ++i)
s->feed(std::string_view(k.text).substr(i, 1), nullptr);
s->finish(nullptr);
const ReplyMessage& r = s->message();
CHECK_EQ(r.calls.size(), k.calls);
if (r.calls.size() != k.calls) continue;
CHECK(!r.calls.back().closed);
if (k.calls == 2) CHECK(r.calls[0].closed);
CHECK_EQ(s->content_with_open_call(k.text), k.content);
CHECK(stream_all(b->parser(), k.text).empty());
}
}
/* With no open call the content is the content. */
const std::string whole = T + "Writing.\n" + done;
std::unique_ptr<ReplyStream> s = b->parser().open();
s->feed(whole, nullptr);
s->finish(nullptr);
CHECK_EQ(s->content_with_open_call(whole), std::string("Writing."));
}
}
/* ================================================================== calls without the wrapper
*
* Qwen's grammar opens a call at `<tool_call>\n`, and the lazy grammar engages only there -- so a
@@ -378,6 +530,11 @@ static std::vector<Shape> bare_shapes() {
{ "two bare calls", T + ls + "\n" + rd, 2, false },
{ "two bare calls with a sentence between", T + ls + "\nNow the file.\n" + rd, 2, false },
{ "a bare call with no arguments", T + "<function=which gcc cc>\n</function>", 1, false },
/* The first argument's name is what makes the opener a call, and it is held while it is
* read: a tag name, not a delimiter, however long. */
{ "a bare call whose first argument name is long",
T + "<function=bash>\n<parameter=" + std::string(200, 'x') + ">\nls\n</parameter>\n</function>",
1, false },
/* Unconstrained, the model need not write the newlines the template puts around each
* tag; a loose call's tags are read with that whitespace optional. */
{ "a bare call written without newlines",
@@ -400,6 +557,9 @@ static std::vector<Shape> bare_shapes() {
/* An argument name that runs into a tag is no argument: the opener was text. */
{ "a bare opener whose argument name runs into a tag",
T + "<function=bash>\n<parameter=com\nls\n</parameter>\n</function>", 0, true },
{ "a bare opener whose long argument name runs into a tag",
T + "<function=bash>\n<parameter=" + std::string(200, 'x') + "\nls\n</parameter>\n</function>",
0, true },
{ "a mangled bare opener before a wrapped call",
T + "<function=bash>\n<parameter=com\nls\n</parameter>\n</function>\n<tool_call>\n" + rd +
"\n</tool_call>", 1, true },
@@ -950,6 +1110,16 @@ TEST(an_argument_no_value_satisfies_has_no_arm_in_either_grammar) {
gq.generation_prompt = b->prompt().generation_prompt;
CHECK_OK(chat_format_grammar(declared, gq, &g, &why));
CHECK_EQ(g.text, b->prompt().grammar);
/* And the parser reads such an argument as the grammar does, by the undeclared arm: text,
* though its value spells JSON. */
const std::string reply = "Thinking it over.\n</think>\n\n" +
C(models()[0], "task", { { "context", "c" }, { "tasks", "[]" }, { "model", "123" } });
const Verdict v = run(b, reply, "an argument no value satisfies");
CHECK(v.strict);
const ReplyMessage r = b->new_parse(reply);
REQUIRE(r.calls.size() == 1);
CHECK_EQ(r.calls[0].arguments, std::string("{\"context\":\"c\",\"tasks\":[],\"model\":\"123\"}"));
}
/* OH-MY-PI 18.6.0's TOOLS AS AN UNMODIFIED CLIENT SENDS THEM (tests/data/chat), descriptions aside.
@@ -1059,7 +1229,9 @@ TEST(a_tool_name_holding_the_format_delimiter_is_refused_at_admission) {
/* ================================================================== the wire
*
* What a streaming client assembles from the SSE chunks -- content, reasoning, each call's id,
* name and arguments -- is the buffered answer, for every reply, cut a byte at a time. */
* name and arguments -- is the buffered answer, for every reply, cut a byte at a time. Every
* chunk is the bytes nlohmann writes for the value it carries: the delta chunks are written
* directly rather than through a tree, and are held to it here. */
TEST(what_a_streaming_client_assembles_is_the_buffered_answer) {
for (const Model& m : models()) {
Bench* b = bench(m, ChatRequest{});
@@ -1096,7 +1268,9 @@ TEST(what_a_streaming_client_assembles_is_the_buffered_answer) {
size_t at = 0;
while ((at = sse.find("data: ", at)) != std::string::npos) {
const size_t end = sse.find("\n\n", at);
const json j = json::parse(sse.substr(at + 6, end - at - 6));
const std::string payload = sse.substr(at + 6, end - at - 6);
const json j = json::parse(payload);
CHECK_EQ(j.dump(), payload);
at = end;
const json& c = j["choices"][0];
if (!c["finish_reason"].is_null()) finish = c["finish_reason"].get<std::string>();
@@ -1126,8 +1300,8 @@ TEST(what_a_streaming_client_assembles_is_the_buffered_answer) {
CHECK_EQ(args[k], want.calls[k].arguments);
CHECK_EQ(p.tool_calls[k].id, ids[k]);
}
/* A call is reported as one only when its arguments parse. */
bool complete = !want.calls.empty();
/* A call is reported as one only when it closed and its arguments parse. */
bool complete = !want.calls.empty() && want.calls.back().closed;
for (const ReplyCall& c : want.calls) complete = complete && server::json_complete(c.arguments);
CHECK_EQ(finish, std::string(complete ? "tool_calls" : "stop"));
}
+1 -26
View File
@@ -117,7 +117,6 @@ TEST(a_flag_missing_its_argument_is_refused_rather_than_read_past) {
CHECK_EQ(parse({ "--tp" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--port" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--kv-cache-dtype" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio" }, &c), RAD_E_INVAL);
Args a{ "--model" };
CHECK_EQ(config_parse(a.argc(), a.argv.data(), &c), RAD_E_INVAL);
}
@@ -347,30 +346,6 @@ TEST(the_table_placements_are_auto_vram_ram_or_disk) {
CHECK_EQ(parse({ "--ngram-placement" }, &c), RAD_E_INVAL);
}
/* THE FLAG THAT DECIDES WHETHER MULTI-TURN WORKS. It is the WEIGHTS share, strictly inside
* (0, 1): either endpoint gives one side of the split nothing at all, and the server would come
* up and then fail to place either the experts or the cache. */
TEST(the_expert_cache_ratio_is_strictly_between_zero_and_one) {
Config c;
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "0.82" }, &c), RAD_OK);
CHECK_NEAR(c.expert_cache_ratio, 0.82, 1e-9);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "0.5" }, &c), RAD_OK);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "0" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "1" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "1.5" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "-0.5" }, &c), RAD_E_INVAL);
/* A PERCENTAGE IS THE OBVIOUS MISREADING of a flag documented as a ratio, and 82 is outside
* the range rather than clamped to it -- which is the difference between a server that says
* what is wrong and one that quietly serves a different split. */
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "82" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "high" }, &c), RAD_E_INVAL);
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK_NEAR(d.expert_cache_ratio, 0.75, 1e-9);
}
/* A POLICY NAME THIS BUILD DOES NOT KNOW WOULD FALL THROUGH TO THE DEFAULT, and a measurement
* comparing the default against itself is the failure that costs the most to notice. */
TEST(the_checkpoint_policy_is_one_of_the_three_that_exist) {
@@ -814,7 +789,7 @@ TEST(usage_names_every_flag_it_documents) {
fclose(f);
CHECK(text.find("--model") != std::string::npos);
CHECK(text.find("--expert-vs-cache-ratio") != std::string::npos);
CHECK(text.find("--host-pool-mib") != std::string::npos);
CHECK(text.find("--kv-cache-dtype") != std::string::npos);
CHECK(text.find("--num-speculative-tokens") != std::string::npos);
CHECK(text.find("--checkpoint-policy") != std::string::npos);
+59
View File
@@ -150,8 +150,67 @@ int oracle_impl(const GbnfGrammar& g, uint32_t* bitmask, int64_t n_words, uint64
return RAD_E_STATE;
}
void accept_chr(const GbnfRuleSet& rules, const GbnfStack& stack, uint32_t chr,
GbnfStacks& out, SetBuild& build) {
if (stack.empty()) return;
const GbnfElement* pos = stack.back();
if (is_token_elem(pos)) return;
auto m = match_char(pos, chr);
build.work.add((size_t)(m.second - pos));
if (!m.first) return;
GbnfStack next(stack.begin(), stack.end() - 1);
if (!is_end_of_sequence(m.second)) next.push_back(m.second);
advance_stack(rules, next, out, build);
}
int accept_impl(const GbnfGrammar& g, int32_t token, GbnfStacks* out, PartialUtf8* partial) {
const GbnfRuleSet& rules = program_rules(g.program());
const auto decoded = decode_utf8(g.vocab()->token_piece(token), g.partial());
const auto& cps = decoded.first;
OpWork work;
GbnfStacks new_stacks;
SetBuild new_set(work);
GbnfStacks current;
for (const auto& stack : g.stacks()) {
if (stack.empty()) continue;
const GbnfElement* pos = stack.back();
if (is_token_elem(pos)) {
if (!match_token(pos, token)) continue;
GbnfStack next(stack.begin(), stack.end() - 1);
if (!is_end_of_sequence(pos + 1)) next.push_back(pos + 1);
advance_stack(rules, next, new_stacks, new_set);
} else {
current.push_back(stack);
}
}
for (auto it = cps.begin(), end = cps.end() - 1; it != end && !current.empty(); ++it) {
GbnfStacks next;
SetBuild next_set(work);
for (const auto& cs : current) accept_chr(rules, cs, *it, next, next_set);
current = std::move(next);
}
for (auto& s : current) new_set.insert(new_stacks, std::move(s));
std::sort(new_stacks.begin(), new_stacks.end());
*out = std::move(new_stacks);
*partial = decoded.second;
return out->empty() ? RAD_E_STATE : RAD_OK;
}
} /* namespace */
int gbnf_oracle_accept(const GbnfGrammar& g, int32_t token, GbnfStacks* out,
PartialUtf8* partial) {
if (!out || !partial || !g.vocab()) return RAD_E_INVAL;
try {
return accept_impl(g, token, out, partial);
} catch (const gbnf::GbnfLimit&) {
return RAD_E_FULL;
} catch (const std::bad_alloc&) {
return RAD_E_NOMEM;
}
}
int gbnf_oracle_mask(const GbnfGrammar& g, uint32_t* bitmask, int64_t n_words,
uint64_t work_limit) {
if (!bitmask || !g.vocab()) return RAD_E_INVAL;
+11
View File
@@ -26,4 +26,15 @@ namespace rad {
int gbnf_oracle_mask(const GbnfGrammar& g, uint32_t* bitmask, int64_t n_words,
uint64_t work_limit = 0);
/* THE STATE ACCEPTING `token` LEAVES, the way the stack machinery builds it: every stack advanced
* one code point at a time through accept_chr and the epsilon closure, as upstream's
* llama_grammar_accept_impl does. The engine steps the stacks that match code points through the
* mask plan's automaton instead, and the two must leave the same stack set and the same carried
* partial character. `*out` comes back sorted. Returns RAD_OK, RAD_E_STATE when no stack
* survives, or RAD_E_FULL / RAD_E_NOMEM past the engine's bounds. For a grammar not waiting on
* its trigger, and a token that is not end-of-generation -- accept_token answers those without
* the stacks. */
int gbnf_oracle_accept(const GbnfGrammar& g, int32_t token, GbnfStacks* out,
PartialUtf8* partial);
} /* namespace rad */
+38 -8
View File
@@ -4,7 +4,9 @@
* (core/sample/gbnf_mask.cpp); tests/gbnf_oracle.cpp computes the same mask the way llama.cpp
* does, by rescanning the vocabulary. They are two implementations of one pure function of the
* grammar's state, so every case here is the same assertion: at every state a walk reaches, the
* two agree bit for bit and status for status.
* two agree bit for bit and status for status. Accepting is held the same way: the engine steps a
* state through the mask plan's automaton, the oracle through the stack machinery one stack and
* one code point at a time, and every token a walk accepts must leave both in the same state.
*
* WHAT MAKES A STATE WORTH COMPARING is that the engine reached it the way the sampler does. The
* walks below drive a grammar exactly as Sampler::build_step drives a constrained sequence under
@@ -243,6 +245,7 @@ struct Tally {
* rescanning one stack at a time, could still answer */
int64_t grammars = 0;
int64_t mismatches = 0;
int64_t accepts = 0; /* accepted tokens whose new state was compared with the oracle's */
};
std::string show_piece(const std::string& s) {
@@ -306,6 +309,32 @@ bool has(const std::vector<uint32_t>& m, int32_t id) {
return id >= 0 && ((m[(size_t)id >> 5] >> (id & 31)) & 1u);
}
/* Accept `id`, holding the state it leaves to the oracle's: the same status, the same stack set
* and the same carried partial character. Returns the engine's status. A side that ran past its
* bounds is not compared, for the reason compare() gives. */
int accept(GbnfGrammar& g, int32_t id, Tally& t) {
const bool cmp = !g.awaiting_trigger() && !g.vocab()->is_eog(id);
GbnfStacks ref;
PartialUtf8 rp;
const int rs = cmp ? gbnf_oracle_accept(g, id, &ref, &rp) : RAD_OK;
const int as = g.accept_token(id);
if (!cmp || rs == RAD_E_FULL || rs == RAD_E_NOMEM || as == RAD_E_FULL || as == RAD_E_NOMEM)
return as;
++t.accepts;
bool same = (as >= 0) == (rs >= 0);
if (same && as >= 0) {
GbnfStacks got = g.stacks();
std::sort(got.begin(), got.end());
same = got == ref && g.partial().value == rp.value && g.partial().n_remain == rp.n_remain;
}
CHECK(same);
if (!same && ++t.mismatches <= 4)
std::fprintf(stderr, " accept %d '%s': engine status %d with %zu stacks, oracle %d "
"with %zu\n", id, show_piece(g.vocab()->token_piece(id)).c_str(), as,
g.stacks().size(), rs, ref.size());
return as;
}
/* MAY THE MASK ADMIT A TOKEN THAT ACCEPTING THEN REFUSES? Upstream's mask and upstream's accept
* read a piece differently in two places, and the engine reproduces the mask exactly, so an
* admitted token can kill the parse:
@@ -364,7 +393,7 @@ void walk_and_compare(const std::string& gbnf, const BpeVocab& bv, uint64_t seed
g->push_state();
int live = 0;
for (int k = 0; k < n_pos; ++k) {
if (k > 0 && g->accept_token(d[(size_t)k - 1]) < 0) {
if (k > 0 && accept(*g, d[(size_t)k - 1], t) < 0) {
/* A draft the grammar refuses leaves no parse; the mask there must say so. */
compare(*g, v, m[(size_t)k], ref, t, name + " after a refused draft");
break;
@@ -388,7 +417,7 @@ void walk_and_compare(const std::string& gbnf, const BpeVocab& bv, uint64_t seed
bool ok = true;
for (size_t k = 0; k < j && ok; ++k) {
const bool quirk = accept_may_refuse(*g, gbnf, v, d[k]);
const int as = g->accept_token(d[k]);
const int as = accept(*g, d[k], t);
ok = as >= 0;
CHECK(ok || quirk || as == RAD_E_FULL || as == RAD_E_NOMEM);
}
@@ -396,7 +425,7 @@ void walk_and_compare(const std::string& gbnf, const BpeVocab& bv, uint64_t seed
const int32_t bonus = pick_admitted(m[j], bv, rng);
if (bonus < 0) break;
const bool quirk = accept_may_refuse(*g, gbnf, v, bonus);
const int as = g->accept_token(bonus);
const int as = accept(*g, bonus, t);
if (as == RAD_E_FULL || as == RAD_E_NOMEM) break; /* the parse outgrew its bounds */
CHECK(as >= 0 || quirk);
if (as < 0) break;
@@ -421,14 +450,14 @@ void replay_and_compare(const std::string& gbnf, const BpeVocab& bv,
const int n_pos = (int)std::min<size_t>(4, toks.size() - i);
g->push_state();
for (int k = 0; k < n_pos; ++k) {
if (k > 0 && g->accept_token(toks[i + (size_t)k - 1]) < 0) { CHECK(false); break; }
if (k > 0 && accept(*g, toks[i + (size_t)k - 1], t) < 0) { CHECK(false); break; }
const std::string where = name + " token " + std::to_string(i + (size_t)k);
if (compare(*g, v, m, ref, t, where) < 0) break;
CHECK(has(m, toks[i + (size_t)k]));
}
CHECK_OK(g->rollback());
const size_t n_acc = std::min<size_t>(3, toks.size() - i);
for (size_t k = 0; k < n_acc; ++k) REQUIRE(g->accept_token(toks[i + k]) >= 0);
for (size_t k = 0; k < n_acc; ++k) REQUIRE(accept(*g, toks[i + k], t) >= 0);
i += n_acc;
}
++t.grammars;
@@ -436,9 +465,10 @@ void replay_and_compare(const std::string& gbnf, const BpeVocab& bv,
void report(const char* what, const Tally& t) {
std::fprintf(stderr, " %s: %lld grammars, %lld masks compared (%lld at a split character, "
"%lld dead); %lld beyond the oracle's bound, %lld beyond the engine's\n", what,
"%lld dead), %lld accepts; %lld beyond the oracle's bound, %lld beyond the "
"engine's\n", what,
(long long)t.grammars, (long long)t.masks, (long long)t.partial, (long long)t.dead,
(long long)t.skipped, (long long)t.bounded);
(long long)t.accepts, (long long)t.skipped, (long long)t.bounded);
}
/* ================================================================== grammars */
+69 -3
View File
@@ -186,20 +186,50 @@ Verdict compare(const Bench& b, const std::string& text) {
o.content.find(f.call_open.substr(a, e - a)) != std::string::npos;
}
v.same = o.content == m.content && o.reasoning == m.reasoning && o.calls.size() == m.calls.size();
/* ARGUMENTS THE OLD READER LEFT AS NO JSON AT ALL are not a reading to agree with: it passed a
* typed value's text through bare (`"verbose":True`, `"extra":}`), which no client can parse,
* and the new reader makes every complete such value JSON (chatparse.cpp, ValueOut). So the
* arguments are compared only where the old object is JSON, and there byte for byte; the new
* reader's own reading of the rest is held by the decided shapes and the streaming checks. */
auto args_agree = [](const std::string& old_a, const std::string& new_a) {
if (old_a == new_a || !nlohmann::json::accept(old_a)) return true;
/* NOR IS A NEWLINE THE OLD READER TOOK OFF A VALUE'S FRONT that the tag before it had
* already ended with -- Qwen's `<parameter=NAME>\n` -- the newline the template writes
* when the value itself starts with one. Every other byte must agree. */
const ojson o = ojson::parse(old_a, nullptr, false);
const ojson n = ojson::parse(new_a, nullptr, false);
if (!o.is_object() || !n.is_object() || o.size() != n.size()) return false;
for (auto it = o.begin(); it != o.end(); ++it) {
if (!n.contains(it.key())) return false;
const ojson& nv = n.at(it.key());
if (nv == it.value()) continue;
if (!nv.is_string() || !it.value().is_string()) return false;
const std::string& ns = nv.get_ref<const std::string&>();
if (ns.empty() || ns[0] != '\n' || ns.compare(1, std::string::npos,
it.value().get_ref<const std::string&>()) != 0)
return false;
}
return true;
};
for (size_t i = 0; v.same && i < o.calls.size(); ++i)
v.same = o.calls[i].name == m.calls[i].name && o.calls[i].arguments == m.calls[i].arguments;
v.same = o.calls[i].name == m.calls[i].name &&
args_agree(o.calls[i].arguments, m.calls[i].arguments);
for (const legacy::ToolCall& c : o.calls)
for (char ch : c.arguments)
if ((unsigned char)ch < 0x20) v.old_raw_control = true;
if (!v.same) v.detail = " old: " + show(o) + "\n new: " + show(m);
return v;
}
std::string judge(const Verdict& v) {
if (v.strict) {
if (v.old_clean && !v.same) return "both read the reply within the grammar and disagree";
if (v.old_clean && !v.same && !v.old_raw_control)
return "both read the reply within the grammar and disagree";
if (!v.old_clean && !v.bare_lift)
return "the new parser read within the grammar a reply the old grammar rejected";
return std::string();
}
if (v.old_clean && !v.old_call_syntax)
if (v.old_clean && !v.old_call_syntax && !v.old_raw_control)
return "the new parser left the grammar on a reply the old grammar accepted";
return std::string();
}
@@ -274,6 +304,24 @@ std::string check_stream(const ReplyParser& p, const std::string& text,
if (!err.empty()) return err;
if (!same(got, expect)) return "the deltas add up to\n " + show(got);
if (!same(s->message(), expect)) return "the message is\n " + show(s->message());
/* Where each call begins in the reply, which an open call's text is read back from, is a
* fact of the reply, not of how it was cut. */
for (size_t i = 0; i < expect.calls.size(); ++i) {
const ReplyCall& a = s->message().calls[i];
const ReplyCall& b = expect.calls[i];
if (a.at != b.at || a.content_at != b.content_at || a.content_held != b.content_held)
return "call " + std::to_string(i) + " begins at " + std::to_string(a.at) + " cut this way, " +
std::to_string(b.at) + " read whole";
if (b.at >= text.size() || (i > 0 && b.at <= expect.calls[i - 1].at))
return "call " + std::to_string(i) + " begins at " + std::to_string(b.at) + ", outside the reply";
}
/* A closed call is one a client is handed to run: its arguments are JSON, whatever the
* model wrote into them -- in a reply that is UTF-8, as every reply is once the decoder has
* sanitised it. */
if (sanitize(text) == text)
for (const ReplyCall& c : expect.calls)
if (c.closed && !nlohmann::json::accept(c.arguments))
return "a closed call's arguments are no JSON: " + q(c.arguments);
return std::string();
}
@@ -343,6 +391,7 @@ std::vector<ojson> rendered_corpus() {
v.push_back(message("", "", { call("write", { { "path", "/work/x.xml" },
{ "content", "<param name=\"k\">v</param>\n</param\n</parameter\n</function>x" } }) }));
v.push_back(message("", "", { call("write", { { "path", "" }, { "content", "" } }) }));
v.push_back(message("", "", { call("write", { { "path", "/a" }, { "content", "\n\nx\n\n" } }) }));
v.push_back(message("", "", { call("ping", ojson::object()) }));
return v;
}
@@ -400,6 +449,20 @@ std::vector<Adversarial> adversarial(const Model& m) {
add("JSON then a stray character", T + C(m, "configure", { { "extra", "{\"a\": 1}x" } }));
add("an unterminated JSON string", T + C(m, "configure", { { "extra", "\"abc" } }));
add("a number that is not one", T + C(m, "read", { { "path", "/a" }, { "limit", "01" } }));
add("Python literals", T + C(m, "configure", { { "verbose", "True" }, { "nothing", "None" } }));
add("a Python dict with literals", T + C(m, "configure",
{ { "extra", "{'a': True, 'b': None, 'c': 'False'}" } }));
add("an empty typed value", T + C(m, "configure", { { "level", "" } }));
add("a typed value that is no JSON", T + C(m, "configure", { { "verbose", "yes please" } }));
add("JSON strings holding a raw line break and tab", T + C(m, "configure",
{ { "extra", "{\"a\": \"line1\nline2\",\n \"b\": \"\tx\"}" } }));
add("Python containers that are no JSON", T + C(m, "configure",
{ { "extra", "{'a': 1, 'b': [2, 3],}" }, { "tags", "['x', nan]" } }));
add("a container missing its close", T + C(m, "configure", { { "extra", "{'a': [1, 2}" } }));
add("JSON a client cannot read", T + C(m, "configure",
{ { "level", "1e400" }, { "extra", R"({"a": "\ud800"})" } }));
add("an escaped quote in a double-quoted string", T + C(m, "configure",
{ { "tags", " [\"it\\'s\", 'x']" } }));
add("unicode", T + "Größe 大小 🚀 " + C(m, "write", { { "path", "/中.txt" }, { "content", "こんにちは 🌍" } }));
add("CDATA with brackets and tags", T + C(m, "write", { { "path", "/a" },
{ "content", "<![CDATA[if (a[b[0]]) { x = \"]]\"; }\n <tag>\n indented\n]]>" } }));
@@ -450,6 +513,9 @@ std::vector<Adversarial> adversarial(const Model& m) {
add("a call with no closing wrapper",
T + "<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n</function>\n"
"<tool_call>\n<function=read>\n<parameter=path>\n/a\n</parameter>\n</function>\n</tool_call>");
add("a call closed by its wrapper alone",
T + "<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n</tool_call>\n" +
C(m, "read", { { "path", "/a" } }));
add("an argument with no newline after its name",
T + "<tool_call>\n<function=bash>\n<parameter=command>ls</parameter>\n</function>\n</tool_call>");
} else {
+6
View File
@@ -92,6 +92,12 @@ struct Verdict {
* without its wrapper, which the legacy lifter takes only when nothing else in the reply
* parses as a call, and which the streaming parser always reads as one. */
bool old_call_syntax = false;
/* A call in the legacy answer has a raw control character in its arguments: its JSON reader
* took a string holding one, which the schema grammar refuses -- the reply goes on in the
* grammar's text arm, and ends the value at its suffix, where the legacy reader kept reading
* -- or it passed a typed value's text through bare. Neither is JSON, and neither is a
* reading to hold the streaming parser to. */
bool old_raw_control = false;
std::string detail; /* both answers, when they differ */
};
Verdict compare(const Bench& b, const std::string& text);
+764 -746
View File
File diff suppressed because it is too large. Load diff
+52
View File
@@ -97,6 +97,7 @@ const char* rad_dev_last_error(void) { return ""; }
namespace {
constexpr int64_t MiB = 1024 * 1024;
constexpr int64_t KiB = 1024;
/* Two kernel rows, one per domain. The planner reads Band::dom[] to learn whether a host site
* exists at all, so a fixture that wants to exercise that has to resolve real rows. */
@@ -409,6 +410,57 @@ TEST(planner_spills_experts_before_dense_weights) {
CHECK_EQ(zero_copy, 6);
}
/* THE BUDGET'S EXPERT FLOOR PLACES EVERY EXPERT. A lending cache leaves the expert slab exactly
* expert_vram_floor, so a floor short of what the planner spends -- the residents, the slab's
* spare slots beside them, and the slack each first-fit pass can strand -- is experts with no
* tier, and a server that refuses to start. Two strides make two slab classes, each with its own
* shadow slots, which is the shape a mixed-precision container has. */
TEST(the_expert_floor_places_every_expert) {
Fixture f;
const rad_weight m = f.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1);
f.op("embed", {m}, false);
for (int l = 0; l < 8; ++l) {
const int64_t gu = l < 4 ? 600 * KiB : 1 * MiB, dn = l < 4 ? 300 * KiB : 500 * KiB;
std::vector<rad_weight> g, d;
for (int e = 0; e < 16; ++e) {
const std::string b = "blk." + std::to_string(l) + ".";
g.push_back(f.weight(b + "ffn_gate_up_exps." + std::to_string(e) + ".weight", gu,
RAD_ACCESS_CONDITIONAL, l, e));
d.push_back(f.weight(b + "ffn_down_exps." + std::to_string(e) + ".weight", dn,
RAD_ACCESS_CONDITIONAL, l, e));
}
f.op("moe_gemm", g, false);
f.op("moe_gemm", d, false);
}
WeightFootprint wf;
weight_footprint(f.prog, &wf, TablePlacement::Vram, TablePlacement::Disk);
CHECK(wf.expert_spare > 0);
const int64_t host = 100 * MiB;
auto plan_with = [&](int64_t floor, Plan* p) {
Config c = base_config();
c.placement = "expert_tiered";
c.vram_weights_mib = (wf.statics + floor + MiB - 1) / MiB;
c.host_pool_mib = host / MiB;
PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0};
return Planner(in).plan(p);
};
const int64_t floor = expert_vram_floor(wf, host);
CHECK(floor > 0 && floor < wf.experts);
Plan p;
CHECK_OK(plan_with(floor, &p));
CHECK(p.unfit.empty());
CHECK_EQ(count_tier(f.prog, p, Tier::SSD), 0);
CHECK(p.totals.bytes[(int)Tier::VRAM] + p.slab_overhead <= p.vram_budget);
/* AND THE SPARE SLOTS ARE WHY: a floor that counts only the experts the pool cannot hold and
* one unit of slack strands some. */
Plan q;
CHECK(plan_with(wf.experts - host + wf.expert_unit_max, &q) == RAD_E_NOMEM);
CHECK(!q.unfit.empty());
}
TEST(planner_warm_starts_from_the_container_profile) {
Fixture f;
std::vector<rad_weight> ex;
+1 -1
View File
@@ -256,7 +256,7 @@ TEST(op_vocabulary) {
static const char* kOps[] = {
"rmsnorm", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter",
"layernorm", "add", "mul", "silu_mul", "gelu", "silu",
"sigmoid", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv",
"sigmoid", "fill", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv",
"embed_lookup_q", "cast",
"scale_rows",
"softmax",
+115 -4
View File
@@ -388,10 +388,30 @@ struct FakePC : IPrefixCache {
++evict_calls;
if (evict_grant <= 0) return 0;
int64_t took = n < evict_grant ? n : evict_grant;
if (evict_frees) {
/* An entry is one block in every cached group: give that many back to the pool. */
int64_t have = seeded.empty() ? 0 : (int64_t)seeded[0].size();
took = std::min(took, have);
for (size_t i = 0; i < groups.size() && i < seeded.size(); ++i)
for (int64_t k = 0; k < took; ++k) {
kv->release(groups[i], seeded[i].back());
seeded[i].pop_back();
}
}
evict_grant -= took;
evicted += took;
return took;
}
bool evict_frees = false; /* evict() returns the seeded blocks to the pool */
std::vector<uint64_t> holds, releases;
void hold(const Request& r) override { holds.push_back(r.id); }
void release(const Request& r) override { releases.push_back(r.id); }
/* What the reserve asked for, call by call. */
std::vector<int64_t> trims;
int64_t trim(int64_t n) override {
trims.push_back(n);
return 0;
}
/* Cumulative, like the real cache's: the scheduler publishes it as a counter and the
* server takes deltas, so a fake that reported per-call would read as a cache that
* never evicts. */
@@ -402,7 +422,11 @@ struct FakePC : IPrefixCache {
return ((pos / interval) + 1) * interval;
}
std::vector<int64_t> committed;
void commit_checkpoint(const Request&, int64_t pos) override { committed.push_back(pos); }
std::vector<int64_t> resumed; /* the commits marked as resume points */
void commit_checkpoint(const Request&, int64_t pos, bool resume) override {
committed.push_back(pos);
if (resume) resumed.push_back(pos);
}
int reserve_checkpoint(const Request&, int64_t, int32_t* slot_out) override {
++reserved;
*slot_out = next_slot++;
@@ -618,10 +642,23 @@ TEST(prefill_chunks_split_at_the_checkpoint_interval) {
CHECK_EQ(f.sch.plan_chunk(256, 1000, 512, &ck), 256);
CHECK_EQ(ck, 512);
/* The final chunk is allowed to be short -- that is the accepted cost of owning the
* boundaries -- and writes no checkpoint because it does not reach one. */
CHECK_EQ(f.sch.plan_chunk(768, 1000, 512, &ck), 232);
/* The final chunk ends at the prompt's last quantum boundary and writes a checkpoint there:
* the next turn of a conversation resumes from it instead of from 768. The remainder, under a
* quantum, is the chunk after it and writes none -- that is the accepted cost of owning the
* boundaries. */
CHECK_EQ(f.sch.plan_chunk(768, 1000, 512, &ck), 192);
CHECK_EQ(ck, 960);
CHECK_EQ(f.sch.plan_chunk(960, 1000, 512, &ck), 40);
CHECK_EQ(ck, -1);
/* A prompt that ends less than a quantum past where the chunk starts has no boundary to
* split at, and one inside the first interval is cheap enough to prefill again. */
CHECK_EQ(f.sch.plan_chunk(768, 830, 512, &ck), 62);
CHECK_EQ(ck, -1);
CHECK_EQ(f.sch.plan_chunk(0, 200, 512, &ck), 200);
CHECK_EQ(ck, -1);
/* And a prompt ending on a quantum boundary takes its checkpoint at the end, unsplit. */
CHECK_EQ(f.sch.plan_chunk(768, 960, 512, &ck), 192);
CHECK_EQ(ck, 960);
/* A budget short of the interval still ends on a quantum, never in the middle of a tile. */
CHECK_EQ(f.sch.plan_chunk(0, 1000, 100, &ck), 64);
@@ -784,6 +821,23 @@ TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) {
CHECK_EQ(f.pc.committed[0], 512); /* ctx_len 256 + ckpt_tok 255 + 1 */
}
/* THE DEEPEST CHECKPOINT A PROMPT GETS IS ITS RESUME POINT, and it alone is committed as one: it is
* the state the next turn resumes from, and the tiers copy it off the card at once rather than
* with the rest of the conversation at its publish. */
TEST(only_a_prompt_s_deepest_checkpoint_is_its_resume_point) {
Fixture f;
f.build();
CHECK_OK(f.start());
const uint64_t a = f.submit(1000, 8);
for (int i = 0; i < 64 && f.sch.find(a)->n_computed < 1000; ++i) {
REQUIRE(f.sch.step() != nullptr);
f.commit_plain();
}
REQUIRE(f.pc.committed.size() >= 2u);
REQUIRE_EQ(f.pc.resumed.size(), 1u);
CHECK_EQ(f.pc.resumed[0], f.pc.committed.back());
}
/* A hit that skipped tokens with no snapshot to resume from is the corruption this whole mechanism
* exists to prevent, so it is refused outright rather than served with a zeroed state. */
TEST(a_hit_with_no_checkpoint_slot_reuses_nothing) {
@@ -2031,6 +2085,63 @@ TEST(the_cache_trim_does_not_mistake_released_vram_for_occupancy) {
f.commit_plain(); /* finishes and publishes */
CHECK_EQ((int)f.pc.published.size(), 1);
CHECK_EQ(f.pc.evict_calls, 0);
CHECK(f.pc.trims.empty());
}
/* WHEN LIVE SEQUENCES HOLD MORE THAN THE RESERVE ALLOWS, THE TRIM ASKS FOR THE SHORTFALL ONCE.
* Nothing the cache can give closes it entirely, and a loop that kept evicting until it did would
* take the conversation this close has just published along with everything else on the list. */
TEST(the_cache_trim_asks_for_the_shortfall_and_not_for_the_whole_cache) {
Fixture f;
f.build(/*blocks=*/40, /*states=*/64);
CHECK_OK(f.start());
f.pc.evict_grant = 1 << 20;
f.submit(160, /*max_tokens=*/1); /* 10 blocks, finishes on the first commit */
f.submit(176, /*max_tokens=*/64); /* 11 blocks each, still running after it */
f.submit(176, /*max_tokens=*/64);
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.kv.held_blocks(0), 32ll); /* 8 free against a reserve of 10 */
f.commit_plain();
CHECK_EQ((int)f.pc.published.size(), 1);
REQUIRE(f.pc.trims.size() == 1u);
CHECK_EQ(f.pc.trims[0], 2ll);
CHECK_EQ(f.pc.evict_calls, 0);
}
/* THE CACHE GIVES WAY TO A NEW REQUEST AS IT DOES TO A RUNNING ONE. With nothing running, no
* other path takes blocks back from the cache, and a pool full of finished conversations would
* keep the request waiting for good. */
TEST(an_admission_short_of_blocks_takes_them_from_the_cache) {
Fixture f;
f.build(/*blocks=*/20, /*states=*/64);
CHECK_OK(f.start());
f.pc.seed(240); /* 15 of 20 held by finished conversations */
f.pc.attn = 0; /* and none of them is this prompt */
f.pc.evict_frees = true;
f.pc.evict_grant = 1 << 20;
const uint64_t a = f.submit(160, 8); /* 10 blocks, 5 free */
CHECK(f.sch.step() != nullptr);
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running);
CHECK(f.pc.evict_calls >= 1);
CHECK(f.pc.holds.empty());
}
/* A REFUSED ADMISSION HOLDS WHAT ITS RESTORE BROUGHT BACK, and lets go once the request is gone,
* so the next attempt finds the chain on the card instead of copying it again. */
TEST(a_refused_admission_holds_its_chain_until_the_request_goes) {
Fixture f;
f.build(/*blocks=*/20, /*states=*/64);
CHECK_OK(f.start());
f.pc.seed(240);
f.pc.attn = 0;
const uint64_t a = f.submit(160, 8); /* the cache gives nothing back */
CHECK(f.sch.step() == nullptr);
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Waiting);
REQUIRE_EQ(f.pc.holds.size(), 1u);
CHECK_EQ(f.pc.holds[0], a);
CHECK_OK(f.sch.cancel(a));
CHECK(std::find(f.pc.releases.begin(), f.pc.releases.end(), a) != f.pc.releases.end());
}
/* AN ENGINE THAT HAS STOPPED ANSWERS EVERY REQUEST IT HELD AND REFUSES NEW ONES, rather than
+139 -6
View File
@@ -10,6 +10,7 @@
#include "mm/processor.h"
#include "rad_test.h"
#include "server/adapters.h"
#include "server/http.h"
#include "server/json_partial.h"
#include "server/liveview.h"
@@ -17,6 +18,8 @@
#include "server/oai.h"
#include "server/server.h"
#include "server/sink.h"
#include "text/chatfmt.h"
#include "text/chatparse.h"
#include <nlohmann/json.hpp>
@@ -33,6 +36,7 @@
#include <map>
#include <memory>
#include <mutex>
#include <random>
#include <string>
#include <thread>
#include <vector>
@@ -123,7 +127,8 @@ struct FakeChatTemplate : IChatTemplate {
}
/* The parser is built per render and reads calls only for a request that sent tools --
* the contract the real bridge keeps (IReplyParser). */
if (with_parser) out->parser = std::make_shared<FakeReplyParser>(!tools.empty());
if (real_parser) out->parser = real_parser;
else if (with_parser) out->parser = std::make_shared<FakeReplyParser>(!tools.empty());
out->think_open = think_open;
out->think_close = think_close;
out->think_starts_open = think_starts_open;
@@ -134,6 +139,8 @@ struct FakeChatTemplate : IChatTemplate {
std::string tool_refusal() const override { return refusal; }
bool with_parser = false;
/* A real reply parser to hand out instead of the fake one. */
std::shared_ptr<IReplyParser> real_parser;
std::string refusal;
std::string refuse_kwarg;
/* The reasoning block a render reports. FakeTokenizer makes a one-byte marker one token. */
@@ -142,15 +149,22 @@ struct FakeChatTemplate : IChatTemplate {
/* Reads "TOOL:<name>:<json...>" -- everything after the second colon is the arguments,
* however incomplete, and it arrives a piece at a time. That is exactly the shape the
* streaming path has to cope with. With calls off every byte is content. */
* streaming path has to cope with. With calls off every byte is content. The call is open
* when the reply ends before its arguments are whole, and its text is then the reply. */
struct FakeReplyReader : IReplyReader {
explicit FakeReplyReader(bool calls) : calls_(calls) {}
void feed(std::string_view t, std::vector<ReplyDelta>* out) override {
text_.append(t);
step(out, false);
}
void finish(std::vector<ReplyDelta>* out) override { step(out, true); }
void finish(std::vector<ReplyDelta>* out) override {
step(out, true);
msg_.open_call = !msg_.tool_calls.empty() && !json_complete(msg_.tool_calls[0].arguments);
}
ParsedMessage message() const override { return msg_; }
std::string content_with_open_call(std::string_view reply) const override {
return msg_.open_call ? std::string(reply) : msg_.content;
}
private:
void emit(std::vector<ReplyDelta>* out, ReplyDelta::Kind k, std::string s) {
if (out) out->push_back({ k, 0, std::move(s) });
@@ -239,7 +253,7 @@ struct FakeScheduler : IScheduler {
/* Nonzero: every token after the first is a verify step that proposed this many drafts and
* accepted one, as a speculating engine reports them. */
int32_t drafts = 0;
SchedMetrics m;
server::SchedMetrics m;
std::mutex mu;
std::vector<uint64_t> submitted;
@@ -302,7 +316,7 @@ struct FakeScheduler : IScheduler {
cancelled.push_back(id);
}
SchedMetrics metrics() const override { return m; }
server::SchedMetrics metrics() const override { return m; }
bool saw_cancel() {
std::lock_guard<std::mutex> lk(mu);
@@ -1511,6 +1525,88 @@ TEST(a_request_the_engine_failed_says_what_failed) {
std::string("the engine failed this request: unsupported"));
}
/* A REPLY THAT ENDS INSIDE ITS LAST CALL, read by the real parser in Qwen's format: that call is
* the text the model wrote, after the content before it, and nothing else moves -- the reasoning
* stays reasoning, a call that closed before it stays a call, and the finish reason is "stop",
* streamed or not. The stream has sent the open call's deltas already and cannot take them back;
* its finish reason is what says not to run it, and it is the buffered one. */
static std::shared_ptr<IReplyParser> qwen_reply_parser(const json& tools) {
ChatFormat f;
f.reasoning_open = "<think>\n";
f.reasoning_close = "\n</think>\n\n";
f.reasoning_breaks = { "<tool_call>\n" };
f.call_open = "<tool_call>\n";
f.call_close = "</tool_call>";
f.name_prefix = "<function=";
f.name_suffix = ">\n";
f.call_end = "</function>\n";
f.arg_prefix = "<parameter=";
f.arg_name_suffix = ">\n";
f.arg_value_suffix = "</parameter>\n";
f.triggers = { "<tool_call>\n" };
std::shared_ptr<const ReplyFormat> rf;
std::string why;
if (ReplyFormat::compile(f, &rf, &why) < 0) return nullptr;
ReplyOptions ro;
ro.generation_prompt = "<|im_start|>assistant\n<think>\n";
ro.tools = &tools;
std::shared_ptr<const ReplyParser> rp;
if (ReplyParser::create(rf, ro, &rp, &why) < 0) return nullptr;
return std::make_shared<ReplyParserBridge>(rp);
}
TEST(a_reply_ending_inside_a_call_keeps_its_reasoning_and_earlier_calls) {
const json tools = json::parse(R"([{"type":"function","function":{"name":"bash",
"parameters":{"type":"object","properties":{"command":{"type":"string"}},
"required":["command"]}}}])");
const std::string call1 = "<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n"
"</function>\n</tool_call>\n";
const std::string open = "<tool_call>\n<function=bash>\n<parameter=command>\ncat /a";
const std::string reply = "Look first.\n</think>\n\nChecking.\n" + call1 + open;
const std::string body = R"({"messages":[{"role":"user","content":"hi"}],"max_tokens":1000,
"tools":)" + tools.dump();
Fixture f;
f.tmpl.real_parser = qwen_reply_parser(tools);
REQUIRE(f.tmpl.real_parser != nullptr);
f.sched.reply = reply;
HttpResponse r = f.post("/v1/chat/completions", body + "}");
CHECK_EQ(r.status, 200);
const json c = json::parse(r.body)["choices"][0];
CHECK_EQ(c["finish_reason"].get<std::string>(), std::string("stop"));
CHECK_EQ(c["message"]["reasoning_content"].get<std::string>(), std::string("Look first.\n"));
CHECK_EQ(c["message"]["content"].get<std::string>(), "Checking.\n" + open);
REQUIRE(c["message"].contains("tool_calls") && c["message"]["tool_calls"].size() == 1);
CHECK_EQ(c["message"]["tool_calls"][0]["function"]["arguments"].get<std::string>(),
std::string("{\"command\":\"ls\"}"));
/* Streamed: the same reasoning, the closed call, the same finish reason. */
HttpResponse s = f.post("/v1/chat/completions", body + R"(,"stream":true})");
CHECK_EQ(s.status, 200);
int bad = 0;
std::string reasoning, finish;
std::vector<std::string> args;
for (const std::string& p : sse_payloads(drain(s), &bad)) {
if (p == "[DONE]") continue;
const json j = json::parse(p);
if (j["choices"].empty()) continue;
const json& ch = j["choices"][0];
if (!ch["finish_reason"].is_null()) finish = ch["finish_reason"].get<std::string>();
const json& d = ch["delta"];
if (d.contains("reasoning_content")) reasoning += d["reasoning_content"].get<std::string>();
if (!d.contains("tool_calls")) continue;
const size_t k = d["tool_calls"][0]["index"].get<size_t>();
if (k >= args.size()) args.resize(k + 1);
if (d["tool_calls"][0]["function"].contains("arguments"))
args[k] += d["tool_calls"][0]["function"]["arguments"].get<std::string>();
}
CHECK_EQ(bad, 0);
CHECK_EQ(finish, std::string("stop"));
CHECK_EQ(reasoning, std::string("Look first.\n"));
REQUIRE(!args.empty());
CHECK_EQ(args[0], std::string("{\"command\":\"ls\"}"));
}
TEST(a_streamed_tool_call_is_named_before_its_arguments_flow) {
Fixture f;
f.sched.reply = "TOOL:lookup:{\"q\":\"x\"}";
@@ -2153,7 +2249,7 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) {
* each total once: however many of them run, the counter ends at the total. */
TEST(concurrent_scrapes_count_each_total_once) {
Metrics m("m", 1024);
SchedMetrics s;
server::SchedMetrics s;
s.steps = 1000;
s.prefill_tokens = 5000;
s.draft_depth_seen = 3;
@@ -2231,6 +2327,43 @@ TEST(a_stable_prefix_never_cuts_a_code_point_or_an_escape) {
CHECK_EQ((long long)json_stable_prefix("x\\u0041"), 7LL);
}
/* A string literal is written exactly as nlohmann writes it, and refused exactly where nlohmann
* refuses: every byte value alone and after each lead byte, and random strings drawn from the
* bytes that decide -- controls, the quote and backslash, DEL, continuation and lead bytes. */
TEST(a_quoted_string_is_what_nlohmann_writes) {
auto agree = [](const std::string& s) {
std::string got = "x";
const bool ok = json_quote_append(got, s);
std::string want;
bool refused = false;
try {
want = "x" + json(s).dump();
} catch (const nlohmann::json::type_error&) {
refused = true;
}
CHECK_EQ(ok, !refused);
if (ok) CHECK_EQ(got, want);
else CHECK_EQ(got, std::string("x"));
return ok == !refused && (!ok || got == want);
};
for (int a = 0; a < 256; ++a) {
agree(std::string(1, (char)a));
for (int b = 0; b < 256; ++b) agree(std::string{ (char)a, (char)b, 'z' });
}
const unsigned char pool[] = { 0x00, 0x01, 0x08, 0x09, 0x0a, 0x0c, 0x0d, 0x1f, 0x20, '"',
'\\', '/', 'a', 0x7f, 0x80, 0x8f, 0x90, 0x9f, 0xa0, 0xbf,
0xc0, 0xc1, 0xc2, 0xdf, 0xe0, 0xed, 0xee, 0xef, 0xf0, 0xf4,
0xf5, 0xff };
std::mt19937 rng(7);
int bad = 0;
for (int i = 0; i < 200000 && bad < 4; ++i) {
std::string s(rng() % 12, '\0');
for (char& c : s) c = (char)pool[rng() % sizeof pool];
if (!agree(s)) ++bad;
}
CHECK_EQ(bad, 0);
}
/* ================================================================== the live view */
TEST(the_live_view_prints_ordinary_lines_when_it_is_not_a_terminal) {
-22
View File
@@ -192,28 +192,6 @@ TEST(per_part_spans_cut_each_stacked_part_by_its_own_rows) {
CHECK(why.find("stated rows") != std::string::npos);
}
/* A ZERO SHARE has the declaration's extents and no rectangles: the loader writes zeros and reads
* nothing. At one rank there is nothing to zero. */
TEST(a_zero_share_is_the_declared_extent_and_no_rectangles) {
const RadEncoding e = fp8_block();
WeightInfo w = decl(e, { 0, 1 }, 1536, 128, RAD_SHARD_ROW, 3);
w.shard_zero = true;
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(share(w, 1536, 128, 3, 2, s), RAD_OK);
CHECK(s[0].zero);
CHECK_EQ(s[0].rects.size(), (size_t)0);
CHECK_EQ(s[0].rows, (int64_t)512);
CHECK_EQ(s[0].cols, (int64_t)128);
CHECK_EQ(s[0].dense_bytes(), (int64_t)(512 * 128));
CHECK(s[1].zero);
CHECK_EQ(s[1].rows, (int64_t)4);
WeightInfo one = decl(e, { 0, 1 }, 1536, 128, RAD_SHARD_ROW, 1);
one.shard_zero = true;
REQUIRE_EQ(share(one, 1536, 128, 1, 0, s), RAD_OK);
CHECK(!s[0].zero);
CHECK_EQ(s[0].rows, (int64_t)1536);
}
/* A per-tensor scale is one value every rank carries whole, once, whatever the codes' cut. */
TEST(a_per_tensor_scale_is_carried_whole_by_every_rank) {
RadEncoding e;