Archived
The gemma4_bf16 architecture (sliding and global attention, the proportional RoPE ladder, the assistant head as a drafter that reads the trunk's cache, the vision tower), its w4a8 decode junctions, the h512/gqa8 and h256/gqa2 attention kernels, compressed-tensors int4 import, multi-EOS from generation_config, the call/reasoning reply format, a window group that keeps the keys a prefill chunk still reads, and window snapshots in checkpoint slots so a prefix hit on a sliding-window trunk resumes. Fixes on top: the investigation switches and diagnostic blocks out of the served paths; int4 import through the checkpoint import framework; attention_k_eq_v from the config; the fused junctions only where every reader takes their pair; a shared-KV head binds no group of its own; the compose file without HSA_ENABLE_IPC_MODE_LEGACY (TP2 fails with it on ROCm 10.1); a checkpoint carries a window only where a hit resumes from it; the README says the linked container is keptn42's calibrated GPTQ build and what the in-tree recipe gives.
This commit is contained in:
commit
7c7f755931
84 files changed
+10292
-230
No files matched your search
@@ -41,7 +41,7 @@ add_library(rad_legacy_toolparse STATIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy/toolp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/legacy/chatdiff.cpp)
|
||||
target_link_libraries(rad_legacy_toolparse PUBLIC rad_core)
|
||||
target_include_directories(rad_legacy_toolparse PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy)
|
||||
set(RAD_TESTS_WITH_LEGACY chatparse_test)
|
||||
set(RAD_TESTS_WITH_LEGACY chatparse_test chatparse_gemma4_test)
|
||||
|
||||
# relayout_parity_test holds each kernel library's relayout of libquant's planes to the recorded
|
||||
# hash of the bytes that library stores. libr4d needs a HIP toolchain to build and its layouts do
|
||||
|
||||
+694
-1
@@ -19,6 +19,7 @@
|
||||
#include "rad_runtime.h"
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <set>
|
||||
@@ -90,6 +91,13 @@ struct RadBuilder {
|
||||
/* The buffer the plugin named as this step's logits (rad_declare_logits). */
|
||||
rad_buf logits = 0;
|
||||
|
||||
/* The draft head's declaration (rad_declare_drafter), and whether it said it keeps no cache
|
||||
* of its own (rad_drafter_shared_kv) and at which rotary offset. */
|
||||
RadDrafterDecl drafter{};
|
||||
std::string drafter_name;
|
||||
bool drafter_shared = false;
|
||||
int drafter_pos = -1;
|
||||
|
||||
/* The vision tower's declaration (rad_declare_encoder), when the plugin made one, and the
|
||||
* audio encoder's. */
|
||||
RadEncoderDecl encoder{};
|
||||
@@ -246,7 +254,16 @@ extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) {
|
||||
return RAD_OK;
|
||||
}
|
||||
extern "C" int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) {
|
||||
(void)b; (void)d;
|
||||
if (!b || !d) return RAD_E_INVAL;
|
||||
b->drafter = *d;
|
||||
b->drafter_name = d->name ? d->name : "";
|
||||
return RAD_OK;
|
||||
}
|
||||
extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) {
|
||||
if (!b || b->drafter.kind != RAD_DRAFT_SERIAL || (pos_offset != 0 && pos_offset != 1))
|
||||
return RAD_E_STATE;
|
||||
b->drafter_shared = true;
|
||||
b->drafter_pos = pos_offset;
|
||||
return RAD_OK;
|
||||
}
|
||||
extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
|
||||
@@ -296,6 +313,7 @@ extern "C" const RadBatch* rad_batch(RadCtx* c) { return c->batch; }
|
||||
extern "C" int rad_rank(RadCtx* c) { return c->rank; }
|
||||
extern "C" int rad_world_size(RadCtx* c) { return c->world; }
|
||||
extern "C" RadStream rad_stream(RadCtx* c) { (void)c; return nullptr; }
|
||||
extern "C" int rad_stream_sync(RadStream s) { (void)s; return RAD_OK; }
|
||||
extern "C" int rad_route_report(RadCtx* c, int layer, const RadRouting* r) {
|
||||
(void)r;
|
||||
c->routed_layers.push_back(layer);
|
||||
@@ -326,6 +344,8 @@ extern "C" void* rad_buf_ptr (RadCtx* c, rad_buf b) { (void)c; return (void
|
||||
#include "../arch/llama_fp8/llama_fp8.cpp"
|
||||
/* And LFM2, whose layer schedule and short convolution are its own. */
|
||||
#include "../arch/lfm2_bf16/lfm2_bf16.cpp"
|
||||
/* Gemma 4 dense: two attention classes (sliding-window + proportional-RoPE global) on one stream. */
|
||||
#include "../arch/gemma4_bf16/gemma4_bf16.cpp"
|
||||
/* The PLE block on its own: no architecture in this file declares it, and what its step() hands
|
||||
* the two windowed ops is a contract of its own (rad_block_ple.h). */
|
||||
#include <arch/rad_block_ple.h>
|
||||
@@ -373,6 +393,87 @@ RadModelMeta qwen35_meta() {
|
||||
return m;
|
||||
}
|
||||
|
||||
/* Gemma 4 31B's text geometry, cut to TWELVE layers so a failure names a real shape. Twelve is the
|
||||
* smallest count that lands two global layers at (l + 1) % 6 == 0 -- layers 5 and 11 -- over the ten
|
||||
* sliding ones, the 5:1 ratio the model card carries. head_dim 256 here is the SLIDING width; the
|
||||
* global class' 512 width and 4 heads are free-form header keys the plugin must read, not fields on
|
||||
* RadModelMeta. */
|
||||
const char* k_gem4_keys[] = {
|
||||
"sliding_window",
|
||||
"global_head_dim",
|
||||
"num_global_key_value_heads",
|
||||
"rope_parameters.sliding_attention.rope_theta",
|
||||
"rope_parameters.full_attention.rope_theta",
|
||||
"rope_parameters.full_attention.partial_rotary_factor",
|
||||
"num_kv_shared_layers",
|
||||
"final_logit_softcapping",
|
||||
"full_attention_interval",
|
||||
"attention_k_eq_v",
|
||||
};
|
||||
const char* k_gem4_vals[] = { "1024", "512", "4", "10000", "1000000", "0.25", "0", "30", "6", "1" };
|
||||
|
||||
RadModelMeta gemma4_meta() {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "gemma4";
|
||||
m.name = "test-gemma4-31b";
|
||||
m.quant = "bf16";
|
||||
m.n_layers = 12;
|
||||
m.n_embd = 5376;
|
||||
m.n_head = 32;
|
||||
m.n_head_kv = 16;
|
||||
m.head_dim = 256;
|
||||
m.n_ff = 21504;
|
||||
m.n_vocab = 262144;
|
||||
m.n_ctx_train = 262144;
|
||||
m.rms_eps = 1e-6f;
|
||||
m.rope_theta = 1e6f;
|
||||
m.rope_scale = 1.0f;
|
||||
m.n_kv = (int)(sizeof(k_gem4_keys) / sizeof(k_gem4_keys[0]));
|
||||
m.kv_key = k_gem4_keys;
|
||||
m.kv_val = k_gem4_vals;
|
||||
return m;
|
||||
}
|
||||
|
||||
/* The same twelve layers with Gemma's assistant head merged under `draft.`, the way
|
||||
* `rad-convert --draft-model` writes it: the head's own config flattened, its text config nested
|
||||
* under `draft.text_config.`. The 31B's head: width 1024, four layers (three sliding, one full),
|
||||
* the trunk's head geometry and window, its own 262144-row tied table. */
|
||||
const char* k_gem4d_keys[] = {
|
||||
"sliding_window", "global_head_dim", "num_global_key_value_heads",
|
||||
"rope_parameters.sliding_attention.rope_theta", "rope_parameters.full_attention.rope_theta",
|
||||
"rope_parameters.full_attention.partial_rotary_factor", "num_kv_shared_layers",
|
||||
"final_logit_softcapping", "full_attention_interval", "attention_k_eq_v",
|
||||
"draft.architectures", "draft.backbone_hidden_size", "draft.use_ordered_embeddings",
|
||||
"draft.text_config.hidden_size", "draft.text_config.num_hidden_layers",
|
||||
"draft.text_config.layer_types", "draft.text_config.num_attention_heads",
|
||||
"draft.text_config.num_key_value_heads", "draft.text_config.num_global_key_value_heads",
|
||||
"draft.text_config.head_dim", "draft.text_config.global_head_dim",
|
||||
"draft.text_config.intermediate_size", "draft.text_config.sliding_window",
|
||||
"draft.text_config.vocab_size", "draft.text_config.rms_norm_eps",
|
||||
"draft.text_config.rope_parameters.sliding_attention.rope_theta",
|
||||
"draft.text_config.rope_parameters.full_attention.rope_theta",
|
||||
"draft.text_config.rope_parameters.full_attention.partial_rotary_factor",
|
||||
};
|
||||
const char* k_gem4d_vals[] = {
|
||||
"1024", "512", "4", "10000", "1000000", "0.25", "0", "30", "6", "1",
|
||||
"Gemma4AssistantForCausalLM", "5376", "0",
|
||||
"1024", "4",
|
||||
"sliding_attention sliding_attention sliding_attention full_attention", "32",
|
||||
"16", "4",
|
||||
"256", "512",
|
||||
"8192", "1024",
|
||||
"262144", "1e-06",
|
||||
"10000", "1000000", "0.25",
|
||||
};
|
||||
|
||||
RadModelMeta gemma4_draft_meta() {
|
||||
RadModelMeta m = gemma4_meta();
|
||||
m.n_kv = (int)(sizeof(k_gem4d_keys) / sizeof(k_gem4d_keys[0]));
|
||||
m.kv_key = k_gem4d_keys;
|
||||
m.kv_val = k_gem4d_vals;
|
||||
return m;
|
||||
}
|
||||
|
||||
RadBuildCtx build_ctx(int rank = 0, int world = 1) {
|
||||
RadBuildCtx c{};
|
||||
c.rank = rank;
|
||||
@@ -3439,3 +3540,595 @@ TEST(lfm2_vl_encoder_pass_and_the_rows_it_scatters) {
|
||||
CHECK_EQ(ops[0], std::string("embed_lookup"));
|
||||
CHECK_EQ(ops[1], std::string("scatter_rows"));
|
||||
}
|
||||
|
||||
/* =============================== gemma4 dense: two attention classes =========================== */
|
||||
|
||||
TEST(declare_is_a_gemma4_trunk) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
/* 12 layers: 10 sliding + 2 global (layers 5 and 11). */
|
||||
CHECK_EQ(count_op(b, "attn_paged"), 12);
|
||||
CHECK_EQ(count_op(b, "kv_store"), 12);
|
||||
CHECK_EQ(count_op(b, "rmsnorm_p"), 12); /* the weightless value normalisation, one per layer */
|
||||
CHECK_EQ(count_op(b, "rope"), 24); /* q + k */
|
||||
CHECK_EQ(count_op(b, "gelu_mul"), 12); /* Gemma's FFN activation, not SwiGLU */
|
||||
CHECK_EQ(count_op(b, "silu_mul"), 0);
|
||||
CHECK_EQ(count_op(b, "gemm_nt"), 70); /* 10x6 sliding (q,k,v,o,gu,down) + 2x5 global (no v) */
|
||||
CHECK_EQ(count_op(b, "rmsnorm"), 73); /* 4 attn + 2 ffn per layer, plus the final norm */
|
||||
CHECK_EQ(count_op(b, "add"), 24); /* the two GemmaRMSNorm residuals per layer */
|
||||
CHECK_EQ(count_op(b, "embed_lookup"), 1);
|
||||
CHECK_EQ(count_op(b, "gather_rows"), 1);
|
||||
CHECK_EQ(count_op(b, "logits_gemm"), 1);
|
||||
CHECK_EQ(count_op(b, "logit_softcap"), 1);
|
||||
CHECK_EQ(count_op(b, "all_reduce"), 0); /* world 1 */
|
||||
}
|
||||
|
||||
/* The reply format is the plugin's to state: Gemma 4's template is one the template analysis
|
||||
* cannot read. Its calls are the object family -- a name and one object in Gemma's dialect --
|
||||
* and its thought channel may open again after the answer. The parser's reading of it is
|
||||
* chatparse_gemma4_test's; this holds the export to what the header declares. */
|
||||
TEST(gemma4_declares_its_reply_format) {
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
const RadChatFormat* f = gemma4_bf16::chat_format(&meta);
|
||||
REQUIRE(f != nullptr);
|
||||
CHECK_EQ(f->struct_size, (uint32_t)sizeof(RadChatFormat));
|
||||
CHECK_EQ(f->args_form, (uint32_t)RAD_CHAT_ARGS_OBJECT);
|
||||
CHECK_EQ(std::string(f->call_open), std::string("<|tool_call>"));
|
||||
CHECK_EQ(std::string(f->call_close), std::string("<tool_call|>"));
|
||||
CHECK_EQ(std::string(f->name_prefix), std::string("call:"));
|
||||
CHECK_EQ(std::string(f->name_suffix), std::string(""));
|
||||
CHECK_EQ(std::string(f->object_string_open), std::string("<|\"|>"));
|
||||
CHECK_EQ(std::string(f->object_string_close), std::string("<|\"|>"));
|
||||
CHECK(f->object_bare_keys != 0);
|
||||
CHECK_EQ(std::string(f->reasoning_open), std::string("<|channel>thought\n"));
|
||||
CHECK_EQ(std::string(f->reasoning_close), std::string("<channel|>"));
|
||||
CHECK(f->reasoning_anywhere != 0);
|
||||
REQUIRE(f->n_triggers == 1);
|
||||
CHECK_EQ(std::string(f->triggers[0]), std::string("<|tool_call>"));
|
||||
CHECK(f->arg_prefix == nullptr && f->arg_value_suffix == nullptr);
|
||||
}
|
||||
|
||||
TEST(gemma4_declares_two_kv_groups_and_binds_the_schedule) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
CHECK_EQ((int)b.kv_groups.size(), 2);
|
||||
CHECK_EQ((int)b.kv_groups[0].d.kind, RAD_KV_WINDOW); /* sliding, declared first */
|
||||
CHECK_EQ(b.kv_groups[0].d.window, 1024);
|
||||
CHECK_EQ(b.kv_groups[0].d.n_head_kv, 16);
|
||||
CHECK_EQ(b.kv_groups[0].d.head_dim, 256);
|
||||
CHECK_EQ((int)b.kv_groups[1].d.kind, RAD_KV_FULL); /* global */
|
||||
CHECK_EQ(b.kv_groups[1].d.window, 0);
|
||||
CHECK_EQ(b.kv_groups[1].d.n_head_kv, 4);
|
||||
CHECK_EQ(b.kv_groups[1].d.head_dim, 512);
|
||||
|
||||
/* (l + 1) % 6 == 0 -> global layers 5 and 11; the fake hands group #1 to sliding (declared
|
||||
* first) and #2 to global. */
|
||||
CHECK_EQ((int)b.binds.size(), 12);
|
||||
for (int l = 0; l < 12; ++l) {
|
||||
const bool want_global = ((l + 1) % 6 == 0);
|
||||
CHECK_EQ((int)b.binds[(size_t)l].first, l);
|
||||
CHECK_EQ((int)b.binds[(size_t)l].second, want_global ? 2 : 1);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(gemma4_attention_shapes_for_both_classes) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
/* layer 0 (sliding): q 32x256, k/v 16x256, windowed. */
|
||||
{
|
||||
const RecOp* at = find_op(b, "attn_paged", 0);
|
||||
CHECK(at != nullptr);
|
||||
CHECK_EQ(pint(at, "head_dim"), 256);
|
||||
CHECK_EQ(pint(at, "gqa"), 2);
|
||||
CHECK_EQ(pint(at, "window"), 1024);
|
||||
CHECK_EQ(pint(at, "n_head"), 32);
|
||||
CHECK_EQ(pint(at, "block_size"), 16);
|
||||
CHECK_EQ(pstr(at, "q_dtype"), std::string("bf16"));
|
||||
}
|
||||
/* layer 5 (the first global, (5+1)%6==0): q 32x512, k 4x512, windowless. */
|
||||
{
|
||||
const RecOp* at = find_op(b, "attn_paged", 5);
|
||||
CHECK(at != nullptr);
|
||||
CHECK_EQ(pint(at, "head_dim"), 512);
|
||||
CHECK_EQ(pint(at, "gqa"), 8);
|
||||
CHECK_EQ(pint(at, "window"), 0);
|
||||
CHECK_EQ(pint(at, "n_head"), 32);
|
||||
}
|
||||
|
||||
/* rope: the sliding call is standard over the full 256 (theta 1e4); the global call is
|
||||
* proportional over 128 of 512 (the "head" ladder, theta 1e6). rope ops are declared q, k per
|
||||
* layer, so global index = 2*layer + (q ? 0 : 1). */
|
||||
{
|
||||
const RecOp* r = find_op(b, "rope", 0); /* layer 0, q */
|
||||
CHECK(r != nullptr);
|
||||
CHECK_EQ(pint(r, "head_dim"), 256);
|
||||
CHECK_EQ(pint(r, "rotary_dim"), 256);
|
||||
CHECK_NEAR(pflt(r, "theta"), 1e4, 1.0);
|
||||
CHECK_EQ(pstr(r, "ladder"), std::string("rotary"));
|
||||
CHECK_EQ(pint(r, "n_head"), 32);
|
||||
|
||||
const RecOp* rg = find_op(b, "rope", 10); /* layer 5, q */
|
||||
CHECK(rg != nullptr);
|
||||
CHECK_EQ(pint(rg, "head_dim"), 512);
|
||||
CHECK_EQ(pint(rg, "rotary_dim"), 128);
|
||||
CHECK_NEAR(pflt(rg, "theta"), 1e6, 1.0);
|
||||
CHECK_EQ(pstr(rg, "ladder"), std::string("head"));
|
||||
CHECK_EQ(pint(rg, "n_head"), 32);
|
||||
|
||||
/* the k rope is a separate buffer, served by the fused-row kernel as a q-only form over
|
||||
* the k heads: n_head is the head count to rotate (here n_head_kv = 4) and n_head_kv is 0. */
|
||||
const RecOp* rkg = find_op(b, "rope", 11); /* layer 5, k */
|
||||
CHECK(rkg != nullptr);
|
||||
CHECK_EQ(pint(rkg, "n_head"), 4);
|
||||
CHECK_EQ(pint(rkg, "n_head_kv"), 0);
|
||||
}
|
||||
|
||||
/* the weightless value normalisation reads 256 dims on a sliding layer, 512 on a global one;
|
||||
* and the global layer has no v_proj weight at all -- v is k. */
|
||||
{
|
||||
const RecOp* vn = find_op(b, "rmsnorm_p", 0); /* layer 0 */
|
||||
CHECK(vn != nullptr);
|
||||
CHECK_EQ(pint(vn, "n"), 256);
|
||||
const RecOp* vng = find_op(b, "rmsnorm_p", 5); /* layer 5 */
|
||||
CHECK(vng != nullptr);
|
||||
CHECK_EQ(pint(vng, "n"), 512);
|
||||
}
|
||||
CHECK(find_w(b, "blk.0.attn_v.weight") != nullptr); /* sliding has a v projection */
|
||||
CHECK(find_w(b, "blk.5.attn_v.weight") == nullptr); /* global: k == v */
|
||||
CHECK(find_w(b, "blk.5.attn_q.weight") != nullptr);
|
||||
CHECK(find_w(b, "blk.5.attn_o.weight") != nullptr);
|
||||
}
|
||||
|
||||
TEST(gemma4_final_norm_softcap_and_vocab) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
const RecOp* cap = find_op(b, "logit_softcap", 0);
|
||||
CHECK(cap != nullptr);
|
||||
CHECK_EQ(pint(cap, "n"), 262144);
|
||||
CHECK_NEAR(pflt(cap, "cap"), 30.0, 1e-9);
|
||||
CHECK_EQ(pstr(cap, "dtype"), std::string("f32"));
|
||||
|
||||
const RecOp* lg = find_op(b, "logits_gemm", 0);
|
||||
CHECK(lg != nullptr);
|
||||
CHECK_EQ(pint(lg, "n_vocab"), 262144);
|
||||
CHECK_EQ(pint(lg, "n_embd"), 5376);
|
||||
|
||||
const RecWeight* emb = find_w(b, "token_embd.weight");
|
||||
CHECK(emb != nullptr);
|
||||
CHECK_EQ(emb->d.shape[0], 262144);
|
||||
CHECK_EQ(emb->d.shape[1], 5376);
|
||||
CHECK_EQ(emb->d.shard, RAD_SHARD_ROW);
|
||||
|
||||
/* lm_head is tied to the embedding. */
|
||||
CHECK(find_map(b, "output.weight") != nullptr);
|
||||
|
||||
/* The embedding is scaled by sqrt(n_embd) at the LOOKUP, not baked into the table (the
|
||||
* reference's build_inp_embd and HF's ScaledWordEmbedding both do it there), so the table
|
||||
* stays tied to the head's. The scale rides the op. */
|
||||
const RecOp* el = find_op(b, "embed_lookup", 0);
|
||||
CHECK(el != nullptr);
|
||||
CHECK_NEAR(pflt(el, "mult"), std::sqrt(5376.0), 1e-9);
|
||||
}
|
||||
|
||||
TEST(gemma4_every_op_declares_the_buffers_it_touches) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
for (const auto& o : b.ops)
|
||||
if (o.resolved) CHECK(o.uses_declared);
|
||||
}
|
||||
|
||||
/* attention_k_eq_v decides whether the global layers have a v_proj: 31B's read V from K and have
|
||||
* none, a checkpoint that says 0 declares one, and one that says nothing is refused. */
|
||||
TEST(gemma4_global_v_follows_attention_k_eq_v) {
|
||||
for (const char* v : { "1", "0", "" }) {
|
||||
std::vector<const char*> keys(std::begin(k_gem4_keys), std::end(k_gem4_keys));
|
||||
std::vector<const char*> vals(std::begin(k_gem4_vals), std::end(k_gem4_vals));
|
||||
if (*v) vals.back() = v;
|
||||
else { keys.pop_back(); vals.pop_back(); }
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
meta.n_kv = (int)keys.size(); meta.kv_key = keys.data(); meta.kv_val = vals.data();
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
const int rc = gemma4_bf16::declare(&b, &meta, &ctx);
|
||||
if (!*v) { CHECK(rc != RAD_OK); continue; }
|
||||
CHECK_OK(rc);
|
||||
CHECK(find_w(b, "blk.0.attn_v.weight") != nullptr); /* sliding: always */
|
||||
CHECK_EQ(find_w(b, "blk.5.attn_v.weight") != nullptr, *v == '0'); /* global */
|
||||
}
|
||||
}
|
||||
|
||||
TEST(gemma4_every_weight_has_a_name_map) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
for (const auto& w : b.weights)
|
||||
CHECK(find_map(b, w.name) != nullptr);
|
||||
}
|
||||
|
||||
TEST(a_gemma4_decode_step_runs_both_classes_in_order) {
|
||||
RadBuilder b;
|
||||
b.refuse.insert("qkv_norm_rope"); /* the unfused prologue; the fused one is checked below */
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4_bf16::step(&c, &batch);
|
||||
|
||||
std::vector<std::string> want = { "embed_lookup" };
|
||||
for (int l = 0; l < 12; ++l) {
|
||||
if ((l + 1) % 6 == 0) {
|
||||
/* global: k == v, so no v gemm -- the weightless v norm derives from k instead. */
|
||||
for (const char* s : { "rmsnorm", "gemm_nt", "gemm_nt",
|
||||
"rmsnorm_p", "rmsnorm", "rmsnorm", "rope", "rope",
|
||||
"kv_store", "attn_paged", "gemm_nt", "rmsnorm", "add" })
|
||||
want.push_back(s);
|
||||
} else {
|
||||
/* sliding: a v gemm feeds the weightless v norm. */
|
||||
for (const char* s : { "rmsnorm", "gemm_nt", "gemm_nt", "gemm_nt",
|
||||
"rmsnorm_p", "rmsnorm", "rmsnorm", "rope", "rope",
|
||||
"kv_store", "attn_paged", "gemm_nt", "rmsnorm", "add" })
|
||||
want.push_back(s);
|
||||
}
|
||||
for (const char* s : { "rmsnorm", "gemm_nt", "gelu_mul", "gemm_nt", "rmsnorm", "add" })
|
||||
want.push_back(s);
|
||||
want.push_back("scale"); /* the per-layer scalar over the residual stream */
|
||||
}
|
||||
for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" })
|
||||
want.push_back(s);
|
||||
CHECK_EQ(join(issued_ops(b, c)), join(want));
|
||||
|
||||
/* The sampled-row ops band on n_out; the attention bands on q_len. */
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (!o) continue;
|
||||
if (o->op == "attn_paged")
|
||||
CHECK_EQ(i.n, (int64_t)batch.max_q_len);
|
||||
else if (o->op == "gather_rows" || o->op == "logits_gemm" || o->op == "logit_softcap")
|
||||
CHECK_EQ(i.n, (int64_t)batch.n_out);
|
||||
}
|
||||
}
|
||||
|
||||
/* THE w4a8 TRUNK FUSES ITS RESIDUAL JUNCTIONS: the first block's entry, every attention -> feed-forward
|
||||
* and every feed-forward -> next attention is one `rmsnorm_quant_i8` (post-norm, add, layer scalar,
|
||||
* norm and quantiser), and q, k and v read one quantised pair. The last layer's stream goes to the
|
||||
* final norm unfused, and a kernel set that does not resolve the op keeps the whole unfused chain
|
||||
* -- with the shared q/k/v pair, which needs nothing new. */
|
||||
static std::vector<std::string> gemma4_w4_step(const std::set<std::string>& refuse, int world = 1) {
|
||||
RadBuilder b;
|
||||
const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128);
|
||||
b.encs = { { "attn_q.", w4 }, { "attn_k.", w4 }, { "attn_v.", w4 }, { "attn_o.", w4 },
|
||||
{ "ffn_gate_up.", w4 }, { "ffn_down.", w4 } };
|
||||
for (const auto& r : refuse) b.refuse.insert(r);
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
RadBuildCtx ctx = build_ctx(0, world);
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = world;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4_bf16::step(&c, &batch);
|
||||
return issued_ops(b, c);
|
||||
}
|
||||
|
||||
/* At two ranks the all-reduce in front of every junction is folded into it: the only standalone
|
||||
* collectives left are the embedding's and the last layer's feed-forward, whose stream goes to the
|
||||
* final norm rather than a quantiser. Without the fused collective the junctions keep their
|
||||
* all-reduces in front of them. */
|
||||
TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) {
|
||||
std::vector<std::string> want = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" };
|
||||
for (int l = 0; l < 12; ++l) {
|
||||
const bool global = (l + 1) % 6 == 0;
|
||||
for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q");
|
||||
for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q",
|
||||
"ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" })
|
||||
want.push_back(s);
|
||||
if (l < 11) want.push_back("ar_rmsnorm_quant_i8");
|
||||
else for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) want.push_back(s);
|
||||
}
|
||||
for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" })
|
||||
want.push_back(s);
|
||||
CHECK_EQ(join(gemma4_w4_step({}, 2)), join(want));
|
||||
|
||||
std::vector<std::string> plain = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" };
|
||||
for (int l = 0; l < 12; ++l) {
|
||||
const bool global = (l + 1) % 6 == 0;
|
||||
for (int i = 0; i < (global ? 2 : 3); ++i) plain.push_back("gemm_nt_q");
|
||||
for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q",
|
||||
"all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8",
|
||||
"gemm_nt_q", "all_reduce" })
|
||||
plain.push_back(s);
|
||||
if (l < 11) plain.push_back("rmsnorm_quant_i8");
|
||||
else for (const char* s : { "rmsnorm", "add", "scale" }) plain.push_back(s);
|
||||
}
|
||||
for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" })
|
||||
plain.push_back(s);
|
||||
CHECK_EQ(join(gemma4_w4_step({ "ar_rmsnorm_quant_i8" }, 2)), join(plain));
|
||||
}
|
||||
|
||||
TEST(a_gemma4_w4a8_step_fuses_its_residual_junctions) {
|
||||
std::vector<std::string> want = { "embed_lookup", "rmsnorm_quant_i8" };
|
||||
for (int l = 0; l < 12; ++l) {
|
||||
const bool global = (l + 1) % 6 == 0;
|
||||
for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q");
|
||||
for (const char* s : { "qkv_norm_rope", "kv_store",
|
||||
"attn_paged", "quant_act_i8", "gemm_nt_q", "rmsnorm_quant_i8",
|
||||
"gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" })
|
||||
want.push_back(s);
|
||||
if (l < 11) want.push_back("rmsnorm_quant_i8");
|
||||
else for (const char* s : { "rmsnorm", "add", "scale" }) want.push_back(s);
|
||||
}
|
||||
for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" })
|
||||
want.push_back(s);
|
||||
CHECK_EQ(join(gemma4_w4_step({})), join(want));
|
||||
}
|
||||
|
||||
TEST(a_gemma4_w4a8_step_without_the_fused_ops_keeps_the_chain_and_one_qkv_quantiser) {
|
||||
std::vector<std::string> want = { "embed_lookup" };
|
||||
for (int l = 0; l < 12; ++l) {
|
||||
const bool global = (l + 1) % 6 == 0;
|
||||
want.push_back("rmsnorm");
|
||||
want.push_back("quant_act_i8");
|
||||
for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q");
|
||||
for (const char* s : { "rmsnorm_p", "rmsnorm", "rmsnorm", "rope", "rope", "kv_store",
|
||||
"attn_paged", "quant_act_i8", "gemm_nt_q", "rmsnorm", "add",
|
||||
"rmsnorm", "quant_act_i8", "gemm_nt_q", "gelu_mul", "quant_act_i8",
|
||||
"gemm_nt_q", "rmsnorm", "add", "scale" })
|
||||
want.push_back(s);
|
||||
}
|
||||
for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" })
|
||||
want.push_back(s);
|
||||
CHECK_EQ(join(gemma4_w4_step({ "rmsnorm_quant_i8", "qkv_norm_rope", "gelu_mul_quant_i8" })), join(want));
|
||||
}
|
||||
|
||||
/* =============================== gemma4: the assistant (MTP) head =============================== */
|
||||
|
||||
namespace {
|
||||
/* The draft passes the core stages for a head with no cache of its own: one row a drafting
|
||||
* sequence. Four sequences; the history pass names every row as a draft row. */
|
||||
static const int32_t kHeadRows[] = { 0, 1, 2, 3 };
|
||||
RadBatch head_batch(int pass) {
|
||||
RadBatch b{};
|
||||
b.phase = RAD_PHASE_DECODE;
|
||||
b.n_tok = 4;
|
||||
b.n_seq = 4;
|
||||
b.max_q_len = 1;
|
||||
b.max_ctx_len = 100;
|
||||
b.draft_pass = pass;
|
||||
if (pass < 0) {
|
||||
b.n_out = 4;
|
||||
b.out_ids = kHeadRows;
|
||||
b.n_draft_out = 4;
|
||||
b.draft_out_ids = kHeadRows;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
TEST(gemma4_declares_no_head_without_one_or_without_speculation) {
|
||||
{
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.max_spec = 3;
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_NONE);
|
||||
CHECK(find_w(b, "mtp.pre_proj.weight") == nullptr);
|
||||
}
|
||||
{
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_draft_meta();
|
||||
RadBuildCtx ctx = build_ctx(); /* max_spec 0 */
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_NONE);
|
||||
CHECK(find_w(b, "mtp.pre_proj.weight") == nullptr);
|
||||
CHECK_EQ(count_op(b, "attn_paged"), 12);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(gemma4_assistant_is_a_serial_head_with_no_cache_of_its_own) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_draft_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.max_spec = 3;
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_SERIAL);
|
||||
CHECK_EQ(b.drafter.depth, 3);
|
||||
CHECK_EQ(b.drafter_name, std::string("mtp"));
|
||||
CHECK_EQ((int)b.drafter.proposal, 0); /* through the sampler chain */
|
||||
CHECK(b.drafter_shared);
|
||||
CHECK_EQ(b.drafter_pos, gemma4_bf16::kHeadPosOffset);
|
||||
|
||||
/* It binds no layer: it writes no K and V. The trunk's twelve bindings are all there are. */
|
||||
CHECK_EQ((int)b.binds.size(), 12);
|
||||
CHECK_EQ((int)b.kv_groups.size(), 2);
|
||||
|
||||
/* Four head layers' worth of attention beside the trunk's twelve, none of them storing. */
|
||||
CHECK_EQ(count_op(b, "attn_paged"), 16);
|
||||
CHECK_EQ(count_op(b, "kv_store"), 12);
|
||||
CHECK_EQ(count_op(b, "logit_softcap"), 1); /* the trunk's; the head's logits are not capped */
|
||||
CHECK_EQ(count_op(b, "logits_gemm"), 2);
|
||||
|
||||
for (int l = 0; l < 4; ++l) {
|
||||
const RecOp* at = find_op(b, "attn_paged", 12 + l);
|
||||
REQUIRE(at != nullptr);
|
||||
const bool full = (l == 3);
|
||||
CHECK_EQ(pint(at, "head_dim"), full ? 512 : 256);
|
||||
CHECK_EQ(pint(at, "gqa"), full ? 8 : 2);
|
||||
CHECK_EQ(pint(at, "window"), full ? 0 : 1024);
|
||||
CHECK_EQ(pint(at, "causal"), 1);
|
||||
CHECK_NEAR(pflt(at, "scale"), 1.0, 1e-12);
|
||||
const RecParam* ql = param(at, "q_len");
|
||||
REQUIRE(ql != nullptr);
|
||||
CHECK_EQ(ql->ival, 1); /* one row a sequence, the decode band only */
|
||||
CHECK_EQ(ql->ihi, 1);
|
||||
}
|
||||
|
||||
/* The weights: q-only attention, the two projections and the head's own tied table. */
|
||||
const RecWeight* wq0 = find_w(b, "mtp.blk.0.attn_q.weight");
|
||||
const RecWeight* wq3 = find_w(b, "mtp.blk.3.attn_q.weight");
|
||||
REQUIRE(wq0 != nullptr); REQUIRE(wq3 != nullptr);
|
||||
CHECK_EQ(wq0->d.shape[0], 32 * 256); CHECK_EQ(wq0->d.shape[1], 1024);
|
||||
CHECK_EQ(wq3->d.shape[0], 32 * 512); CHECK_EQ(wq3->d.shape[1], 1024);
|
||||
const RecWeight* wo3 = find_w(b, "mtp.blk.3.attn_o.weight");
|
||||
REQUIRE(wo3 != nullptr);
|
||||
CHECK_EQ(wo3->d.shape[0], 1024); CHECK_EQ(wo3->d.shape[1], 32 * 512);
|
||||
CHECK(find_w(b, "mtp.blk.0.attn_k.weight") == nullptr);
|
||||
CHECK(find_w(b, "mtp.blk.0.attn_v.weight") == nullptr);
|
||||
const RecWeight* gu = find_w(b, "mtp.blk.1.ffn_gate_up.weight");
|
||||
REQUIRE(gu != nullptr);
|
||||
CHECK_EQ(gu->d.shape[0], 2 * 8192); CHECK_EQ(gu->d.shape[1], 1024);
|
||||
const RecWeight* pre = find_w(b, "mtp.pre_proj.weight");
|
||||
const RecWeight* post = find_w(b, "mtp.post_proj.weight");
|
||||
REQUIRE(pre != nullptr); REQUIRE(post != nullptr);
|
||||
CHECK_EQ(pre->d.shape[0], 1024); CHECK_EQ(pre->d.shape[1], 2 * 5376);
|
||||
CHECK_EQ(post->d.shape[0], 5376); CHECK_EQ(post->d.shape[1], 1024);
|
||||
CHECK_EQ(pre->d.shard, RAD_SHARD_NONE);
|
||||
const RecWeight* lm = find_w(b, "mtp.output.weight");
|
||||
REQUIRE(lm != nullptr);
|
||||
CHECK_EQ(lm->d.shape[0], 262144); CHECK_EQ(lm->d.shape[1], 1024);
|
||||
CHECK_EQ(lm->d.shard, RAD_SHARD_ROW);
|
||||
CHECK_EQ(lm->d.access, RAD_ACCESS_VOCAB);
|
||||
|
||||
/* The checkpoint's names, merged under `draft.`: the head's table is its lm_head and nothing
|
||||
* else, and gate and up are fused like the trunk's. */
|
||||
const RecMap* mlm = find_map(b, "mtp.output.weight");
|
||||
REQUIRE(mlm != nullptr);
|
||||
CHECK_EQ(mlm->src[0], std::string("draft.model.embed_tokens.weight"));
|
||||
const RecMap* mgu = find_map(b, "mtp.blk.1.ffn_gate_up.weight");
|
||||
REQUIRE(mgu != nullptr);
|
||||
CHECK_EQ(mgu->mode, RAD_MAP_CONCAT);
|
||||
CHECK_EQ(mgu->src[0], std::string("draft.model.layers.1.mlp.gate_proj.weight"));
|
||||
CHECK_EQ(mgu->src[1], std::string("draft.model.layers.1.mlp.up_proj.weight"));
|
||||
const RecMap* mpre = find_map(b, "mtp.pre_proj.weight");
|
||||
REQUIRE(mpre != nullptr);
|
||||
CHECK_EQ(mpre->src[0], std::string("draft.pre_projection.weight"));
|
||||
|
||||
/* The entry embeds through the TRUNK's table, scaled as the trunk scales it. */
|
||||
const RecOp* el = find_op(b, "embed_lookup", 1);
|
||||
REQUIRE(el != nullptr);
|
||||
CHECK_EQ(pint(el, "n_embd"), 5376);
|
||||
CHECK_NEAR(pflt(el, "mult"), std::sqrt(5376.0), 1e-9);
|
||||
CHECK(el->w.size() == 1 && find_op(b, "embed_lookup", 0)->w == el->w);
|
||||
|
||||
for (const auto& o : b.ops)
|
||||
if (o.resolved) CHECK(o.uses_declared);
|
||||
for (const auto& w : b.weights)
|
||||
CHECK(find_map(b, w.name) != nullptr);
|
||||
}
|
||||
|
||||
TEST(gemma4_head_passes_read_the_last_trunk_layer_of_their_class) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_draft_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.max_spec = 3;
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
for (int pass : { -1, 2 }) {
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = head_batch(pass);
|
||||
c.batch = &batch;
|
||||
gemma4_bf16::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
|
||||
std::vector<std::string> want;
|
||||
want.push_back(pass < 0 ? "gather_rows" : "cast"); /* the trunk's h, or the head's h' */
|
||||
for (const char* s : { "embed_lookup", "cast", "gemm_nt" }) want.push_back(s);
|
||||
for (int l = 0; l < 4; ++l)
|
||||
for (const char* s : { "rmsnorm", "gemm_nt", "rmsnorm", "rope", "attn_paged", "gemm_nt",
|
||||
"rmsnorm", "add", "rmsnorm", "gemm_nt", "gelu_mul", "gemm_nt",
|
||||
"rmsnorm", "add", "scale" })
|
||||
want.push_back(s);
|
||||
for (const char* s : { "rmsnorm", "logits_gemm", "gemm_nt" }) want.push_back(s);
|
||||
CHECK_EQ(join(issued_ops(b, c)), join(want));
|
||||
|
||||
/* The attention reads the trunk's cache: layers 0..2 the last sliding trunk layer (10 of
|
||||
* the twelve), layer 3 the last full one (11). Groups by declaration: 1 sliding, 2 full. */
|
||||
int seen = 0;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (!o || o->op != "attn_paged") continue;
|
||||
REQUIRE(i.opd.size() > 1);
|
||||
CHECK_EQ((int)i.opd[1].kind, (int)RAD_OPK_KV);
|
||||
CHECK_EQ((int)i.opd[1].handle, seen < 3 ? 1 : 2);
|
||||
CHECK_EQ((long long)i.opd[1].offset, seen < 3 ? 10LL : 11LL);
|
||||
CHECK_EQ(i.n, 1);
|
||||
++seen;
|
||||
}
|
||||
CHECK_EQ(seen, 4);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(gemma4_head_at_two_ranks_reduces_before_each_post_norm) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_draft_meta();
|
||||
RadBuildCtx ctx = build_ctx(0, 2);
|
||||
ctx.max_spec = 3;
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
const RecWeight* wq0 = find_w(b, "mtp.blk.0.attn_q.weight");
|
||||
REQUIRE(wq0 != nullptr);
|
||||
CHECK_EQ(wq0->d.shape[0], 16 * 256);
|
||||
const RecWeight* lm = find_w(b, "mtp.output.weight");
|
||||
REQUIRE(lm != nullptr);
|
||||
CHECK_EQ(lm->d.shape[0], 131072);
|
||||
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 2;
|
||||
RadBatch batch = head_batch(-1);
|
||||
c.batch = &batch;
|
||||
gemma4_bf16::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
const std::vector<std::string> got = issued_ops(b, c);
|
||||
std::vector<std::string> want = { "gather_rows", "embed_lookup", "all_reduce", "cast", "gemm_nt" };
|
||||
for (int l = 0; l < 4; ++l)
|
||||
for (const char* s : { "rmsnorm", "gemm_nt", "rmsnorm", "rope", "attn_paged", "gemm_nt",
|
||||
"all_reduce", "rmsnorm", "add", "rmsnorm", "gemm_nt", "gelu_mul",
|
||||
"gemm_nt", "all_reduce", "rmsnorm", "add", "scale" })
|
||||
want.push_back(s);
|
||||
for (const char* s : { "rmsnorm", "logits_gemm", "gemm_nt" }) want.push_back(s);
|
||||
CHECK_EQ(join(got), join(want));
|
||||
}
|
||||
|
||||
TEST(gemma4_head_refuses_a_history_pass_shaped_for_a_cache_of_its_own) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_draft_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.max_spec = 3;
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = head_batch(-1);
|
||||
batch.n_draft_out = 1; /* a history run with rows that do not draft */
|
||||
c.batch = &batch;
|
||||
gemma4_bf16::step(&c, &batch);
|
||||
CHECK(!c.step_fail.empty());
|
||||
CHECK(c.issues.empty());
|
||||
}
|
||||
|
||||
TEST(gemma4_probe_names_the_heads_operating_depth) {
|
||||
RadArchProbe p{};
|
||||
RadModelMeta with = gemma4_draft_meta();
|
||||
CHECK_OK(gemma4_bf16::probe(&with, &p));
|
||||
CHECK_EQ(p.draft_depth, gemma4_bf16::kHeadDepth);
|
||||
CHECK_EQ(p.draft_depth_fixed, 0);
|
||||
RadArchProbe q{};
|
||||
RadModelMeta without = gemma4_meta();
|
||||
CHECK_OK(gemma4_bf16::probe(&without, &q));
|
||||
CHECK_EQ(q.draft_depth, 0);
|
||||
}
|
||||
@@ -706,6 +706,38 @@ TEST(tune_requests_are_one_per_kernel_and_shape) {
|
||||
}
|
||||
|
||||
/* ================================================================== KV groups */
|
||||
/* A HEAD THAT KEEPS NO CACHE OF ITS OWN BINDS NONE: it is given no history pass, so a group bound at
|
||||
* one of its layers (meta.n_layers and above) would be read and never written. The same head
|
||||
* borrowing only the trunk's layers finishes. */
|
||||
TEST(a_head_with_no_cache_of_its_own_binds_no_group_of_its_own) {
|
||||
NEED_PLUGIN(reg)
|
||||
for (bool own : { false, true }) {
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL; kd.dtype = RAD_BF16; kd.n_head_kv = 8; kd.head_dim = 128;
|
||||
const rad_kvgroup g = b.decl_kv_group("kv_full", &kd);
|
||||
const RadParam p[] = { RAD_RANGE("q_len", 1, 16), RAD_INT("head_dim", 128),
|
||||
RAD_INT("window", 0), RAD_INT("block_size", 16),
|
||||
RAD_INT("causal", 1), RAD_INT("n_head", 8),
|
||||
RAD_STR("kv_dtype", "bf16") };
|
||||
b.decl_op("t_attn", p, 7, nullptr, 0);
|
||||
CHECK_OK(b.bind_layer_kv(0, g));
|
||||
CHECK_OK(b.bind_layer_kv(1, g));
|
||||
if (own) CHECK_OK(b.bind_layer_kv(2, g)); /* make_meta: two trunk layers, so 2 is the head's */
|
||||
RadDrafterDecl d{};
|
||||
d.kind = RAD_DRAFT_SERIAL; d.name = "mtp"; d.depth = 3;
|
||||
CHECK_OK(rad_declare_drafter(&b, &d));
|
||||
CHECK_OK(rad_drafter_shared_kv(&b, 0));
|
||||
b.finish();
|
||||
if (own) {
|
||||
CHECK_EQ(b.status(), RAD_E_STATE);
|
||||
CHECK(has(b.errors().back(), "keeps no cache of its own"));
|
||||
} else {
|
||||
CHECK_OK(b.status());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(kv_block_size_comes_off_the_kernel) {
|
||||
NEED_PLUGIN(reg)
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
@@ -1005,6 +1037,49 @@ TEST(the_drafter_name_survives_the_program_leaving_the_builder) {
|
||||
CHECK_EQ(p.drafter.depth, 3);
|
||||
}
|
||||
|
||||
/* A HEAD THAT KEEPS NO CACHE OF ITS OWN (rad_drafter_shared_kv) is a property of a declared SERIAL
|
||||
* drafter. With none declared, with a block drafter, or at a position no head sits at, the call is
|
||||
* refused at declare -- a head staged the wrong way round costs acceptance and says nothing. */
|
||||
TEST(a_head_that_keeps_no_cache_of_its_own_is_a_serial_one) {
|
||||
Registry reg;
|
||||
{
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
CHECK_EQ(rad_drafter_shared_kv(&b, 0), RAD_E_STATE); /* nothing declared */
|
||||
}
|
||||
{
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
RadBufDecl bd{};
|
||||
bd.dtype = RAD_I32; bd.rank = 2; bd.shape[0] = 256; bd.shape[1] = 4;
|
||||
const rad_buf prop = rad_decl_buffer(&b, "prop", &bd);
|
||||
RadDrafterDecl d{};
|
||||
d.kind = RAD_DRAFT_BLOCK; d.name = "df"; d.depth = 4; d.mask_token = 5;
|
||||
d.proposal = prop; d.proposal_pitch = 4;
|
||||
CHECK_OK(rad_declare_drafter(&b, &d));
|
||||
CHECK_EQ(rad_drafter_shared_kv(&b, 0), RAD_E_STATE); /* a block drafter */
|
||||
CHECK(!b.program().drafter_shared_kv);
|
||||
}
|
||||
{
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
RadDrafterDecl d{};
|
||||
d.kind = RAD_DRAFT_SERIAL; d.name = "mtp"; d.depth = 4;
|
||||
CHECK_OK(rad_declare_drafter(&b, &d));
|
||||
CHECK_EQ(rad_drafter_shared_kv(&b, 2), RAD_E_INVAL); /* no position a head sits at */
|
||||
CHECK(!b.program().drafter_shared_kv);
|
||||
CHECK_OK(rad_drafter_shared_kv(&b, 1));
|
||||
CHECK(b.program().drafter_shared_kv);
|
||||
CHECK_EQ(b.program().drafter_pos_offset, 1);
|
||||
}
|
||||
{
|
||||
/* Every drafter that does not ask keeps the old shape. */
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
RadDrafterDecl d{};
|
||||
d.kind = RAD_DRAFT_SERIAL; d.name = "mtp"; d.depth = 4;
|
||||
CHECK_OK(rad_declare_drafter(&b, &d));
|
||||
CHECK(!b.program().drafter_shared_kv);
|
||||
CHECK_EQ(b.program().drafter_pos_offset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ================================================================== the enum name tables
|
||||
*
|
||||
|
||||
@@ -0,0 +1,897 @@
|
||||
/* chatparse_gemma4_test.cpp -- Gemma 4's reply format: a reasoning channel, and calls written as a
|
||||
* name and ONE object in a dialect of JSON.
|
||||
*
|
||||
* Gemma 4's template is one llama.cpp reads with a hand-written handler, so the template analysis
|
||||
* finds no format in it and the plugin declares one (arch/gemma4_bf16/gemma4_chat_format.h):
|
||||
*
|
||||
* <|channel>thought\n ... <channel|> reasoning
|
||||
* <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3}<tool_call|> a call, repeated for more
|
||||
*
|
||||
* Every case reads a reply under a request rendered through the model's REAL template
|
||||
* (tests/data/chat/gemma4), and where the reply is within the format the answer is held, byte for
|
||||
* byte, to llama.cpp's own Gemma 4 parser -- the PEG grammar and value mapper its handler builds
|
||||
* (tests/legacy, the `old` side). Every reply is also streamed cut every way (chatdiff.h
|
||||
* check_stream): each delta a prefix of the finished value, the deltas adding up to it, the bytes
|
||||
* held under the format's bound, and a closed call's arguments JSON.
|
||||
*
|
||||
* The object family itself -- JSON behind a name tag or a function tag -- is chatparse_test's.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "chatdiff.h"
|
||||
#include "rad_builder.h"
|
||||
#include "sample/gbnf.h"
|
||||
#include "sample/vocab_view.h"
|
||||
#include "server/adapters.h"
|
||||
#include "text/chat.h"
|
||||
#include "text/chatfmt.h"
|
||||
#include "text/chatparse.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
#include "../arch/gemma4_bf16/gemma4_chat_format.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
using namespace rad::chatdiff;
|
||||
using json = nlohmann::ordered_json;
|
||||
|
||||
/* ================================================================== fixtures */
|
||||
|
||||
static std::string fixture() {
|
||||
std::ifstream f(std::string(RAD_CHAT_FIXTURES) + "/gemma4/chat_template.jinja");
|
||||
std::ostringstream ss;
|
||||
ss << f.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
/* The vocabulary's spellings: generation_config.json ends a turn on <eos>, <turn|> and
|
||||
* <|tool_response>. */
|
||||
static const Model& gemma() {
|
||||
static const Model m = { "gemma4", "gemma4", "<bos>", "<eos>",
|
||||
{ "<eos>", "<turn|>", "<|tool_response>" },
|
||||
gemma4_bf16::chat_format_decl() };
|
||||
return m;
|
||||
}
|
||||
|
||||
static Bench* bench(const ChatRequest& rq, const json& tools = agent_tools()) {
|
||||
static std::map<std::string, std::unique_ptr<Bench>> cache;
|
||||
const std::string key = describe(rq) + "|" + tools.dump();
|
||||
auto it = cache.find(key);
|
||||
if (it != cache.end()) return it->second.get();
|
||||
auto b = std::make_unique<Bench>();
|
||||
std::string why;
|
||||
if (b->load(gemma(), fixture(), &why) < 0 || b->bind(rq, tools, &why) < 0) {
|
||||
::radtest::fail(__FILE__, __LINE__, "gemma4 (" + describe(rq) + "): " + why);
|
||||
return nullptr;
|
||||
}
|
||||
return (cache[key] = std::move(b)).get();
|
||||
}
|
||||
|
||||
static ChatRequest thinking(bool on) {
|
||||
ChatRequest r;
|
||||
r.thinking = on;
|
||||
return r;
|
||||
}
|
||||
|
||||
static std::string quote(const std::string& s) {
|
||||
return json(s).dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
}
|
||||
|
||||
/* One call as the model writes it. `args` is the object's inside. */
|
||||
static std::string G(const std::string& name, const std::string& args) {
|
||||
return "<|tool_call>call:" + name + "{" + args + "}<tool_call|>";
|
||||
}
|
||||
static const std::string Q = "<|\"|>";
|
||||
static std::string S(const std::string& text) { return Q + text + Q; }
|
||||
|
||||
/* ================================================================== the streaming checks */
|
||||
|
||||
static std::vector<size_t> every(size_t n, size_t step) {
|
||||
std::vector<size_t> c;
|
||||
for (size_t i = step; i < n; i += step) c.push_back(i);
|
||||
return c;
|
||||
}
|
||||
|
||||
/* Every cut of the reply against its one-shot parse: one piece, byte by byte, token-sized pieces,
|
||||
* and every two-way split. */
|
||||
static std::string stream_all(const ReplyParser& p, const std::string& text) {
|
||||
const ReplyMessage expect = reply_parse(p, text);
|
||||
std::string err = check_stream(p, text, {}, expect);
|
||||
if (err.empty()) err = check_stream(p, text, every(text.size(), 1), expect);
|
||||
std::mt19937 rng(11);
|
||||
for (int k = 0; err.empty() && k < 3; ++k) {
|
||||
std::vector<size_t> c;
|
||||
for (size_t at = 1 + rng() % 5; at < text.size(); at += 1 + rng() % 7) c.push_back(at);
|
||||
err = check_stream(p, text, c, expect);
|
||||
}
|
||||
for (size_t k = 1; err.empty() && k < text.size() && text.size() <= 2048; ++k)
|
||||
err = check_stream(p, text, { k }, expect);
|
||||
return err;
|
||||
}
|
||||
|
||||
static void streams(const ReplyParser& p, const std::string& text, const std::string& what) {
|
||||
const std::string err = stream_all(p, text);
|
||||
if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, what + ": " + err + "\n reply: " + quote(text));
|
||||
++::radtest::checks();
|
||||
}
|
||||
|
||||
static ReplyMessage parse(const ReplyParser& p, const std::string& text, bool* strict = nullptr) {
|
||||
return reply_parse(p, text, strict);
|
||||
}
|
||||
|
||||
static std::shared_ptr<const ReplyParser> parser(const std::string& gp, bool tools = true,
|
||||
bool reasoning = true, bool parallel = true) {
|
||||
static std::shared_ptr<const ReplyFormat> rf = [] {
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
std::shared_ptr<const ReplyFormat> r;
|
||||
if (chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why) < 0 ||
|
||||
ReplyFormat::compile(f, &r, &why) < 0)
|
||||
::radtest::fail(__FILE__, __LINE__, "gemma4 format: " + why);
|
||||
return r;
|
||||
}();
|
||||
ReplyOptions ro;
|
||||
ro.generation_prompt = gp;
|
||||
ro.extract_reasoning = reasoning;
|
||||
ro.tools = tools ? &agent_tools() : nullptr;
|
||||
ro.parallel_tool_calls = parallel;
|
||||
ro.terminators = gemma().terminators;
|
||||
std::shared_ptr<const ReplyParser> p;
|
||||
std::string why;
|
||||
if (ReplyParser::create(rf, ro, &p, &why) < 0)
|
||||
::radtest::fail(__FILE__, __LINE__, "gemma4 parser: " + why);
|
||||
return p;
|
||||
}
|
||||
|
||||
/* The three generation prompts a reply follows: a turn with thinking off (the template closes an
|
||||
* empty channel), a turn with thinking on (the model opens its own), and the continuation after a
|
||||
* tool response with thinking on (the template has opened the channel). With thinking off a
|
||||
* continuation has no generation prompt at all. */
|
||||
static const std::string kOff = "<|turn>model\n<|channel>thought\n<channel|>";
|
||||
static const std::string kOn = "<|turn>model\n";
|
||||
static const std::string kAfter = "<|channel>thought\n";
|
||||
|
||||
/* ================================================================== the declaration */
|
||||
|
||||
TEST(the_declaration_is_a_format_the_parser_runs) {
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why));
|
||||
CHECK_OK(chat_format_check(f, &why));
|
||||
CHECK(f.object_args());
|
||||
CHECK(f.reasoning_anywhere);
|
||||
CHECK_EQ(f.object_string_open, Q);
|
||||
CHECK_EQ(chat_format_describe(f),
|
||||
std::string("plugin:gemma4: reasoning \"<|channel>thought\\n\"..\"<channel|>\" "
|
||||
"anywhere; calls \"<|tool_call>\"\"call:\"NAME\"\" {OBJECT, strings "
|
||||
"\"<|\\\"|>\"..\"<|\\\"|>\", bare keys} \"\"\"<tool_call|>\"; grammar on "
|
||||
"\"<|tool_call>\""));
|
||||
/* What the decoder must render as text: every delimiter, the string's included -- without it
|
||||
* a string argument reaches the parser with its quotes gone. */
|
||||
const std::vector<std::string> m = chat_format_markers(f);
|
||||
for (const char* want : { "<|channel>thought", "<channel|>", "<|tool_call>", "<tool_call|>",
|
||||
"call:", "<|\"|>" })
|
||||
CHECK(std::find(m.begin(), m.end(), std::string(want)) != m.end());
|
||||
}
|
||||
|
||||
/* A plugin compiled against the header before the object family reads its new fields as zero:
|
||||
* the tagged family, no dialect, reasoning at the start only -- and Gemma's declaration read that
|
||||
* way is refused by name rather than run wrongly. */
|
||||
TEST(an_older_struct_reads_the_object_fields_as_zero) {
|
||||
RadChatFormat c = *gemma4_bf16::chat_format_decl();
|
||||
c.struct_size = (uint32_t)offsetof(RadChatFormat, args_form);
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(&c, &f, &why));
|
||||
CHECK(!f.object_args());
|
||||
CHECK(f.object_string_open.empty());
|
||||
CHECK(!f.object_bare_keys);
|
||||
CHECK(!f.reasoning_anywhere);
|
||||
CHECK(chat_format_check(f, &why) == RAD_E_UNSUPPORTED);
|
||||
CHECK(why.find("name_suffix") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(an_object_format_the_parser_cannot_read_is_refused_by_name) {
|
||||
auto refused = [](void (*edit)(RadChatFormat&), const char* word) {
|
||||
RadChatFormat c = *gemma4_bf16::chat_format_decl();
|
||||
edit(c);
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
if (chat_format_from_abi(&c, &f, &why) < 0) return false;
|
||||
const bool no = chat_format_check(f, &why) == RAD_E_UNSUPPORTED;
|
||||
if (!no || why.find(word) == std::string::npos)
|
||||
::radtest::fail(__FILE__, __LINE__, std::string("expected a refusal naming '") +
|
||||
word + "', got: " + (no ? why : "accepted"));
|
||||
return no;
|
||||
};
|
||||
CHECK(refused([](RadChatFormat& c) { c.arg_prefix = "<arg>"; }, "arg_*"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.object_string_close = nullptr; }, "together"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.object_string_open = c.object_string_close = " <q>"; },
|
||||
"whitespace"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.object_string_open = "q"; }, "bare word"));
|
||||
CHECK(refused([](RadChatFormat& c) {
|
||||
c.object_string_open = c.object_string_close = "<q>"; c.call_close = "<q>"; }, "closes the call"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.call_close = "<tc,>"; }, "punctuation"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.call_close = "<|"; }, "told apart"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.args_form = 7; }, "RAD_CHAT_ARGS"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.reasoning_open = ""; }, "reasoning_anywhere"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.call_open = "<|channel>thought"; c.reasoning_breaks = nullptr;
|
||||
c.n_reasoning_breaks = 0; }, "content"));
|
||||
/* The tagged family is untouched: a dialect field there is refused, not ignored. */
|
||||
CHECK(refused([](RadChatFormat& c) {
|
||||
c.args_form = RAD_CHAT_ARGS_TAGGED;
|
||||
c.name_suffix = ">"; c.call_end = "</f>"; c.arg_prefix = "<a="; c.arg_name_suffix = ">";
|
||||
c.arg_value_suffix = "</a>"; }, "object_*"));
|
||||
}
|
||||
|
||||
/* ================================================================== the template's own replies
|
||||
*
|
||||
* An assistant message rendered through the template is what the model is trained to write. With
|
||||
* thinking on the reply is exactly what the template writes after the generation prompt; with it
|
||||
* off the template renders a past turn without the empty channel its generation prompt holds, so
|
||||
* those replies are read by the hand-written cases below instead. */
|
||||
TEST(rendered_replies_read_back_as_the_template_wrote_them) {
|
||||
Bench* b = bench(thinking(true));
|
||||
REQUIRE(b != nullptr);
|
||||
int read = 0;
|
||||
for (const json& msg : rendered_corpus()) {
|
||||
const std::string reply = b->render_reply(msg);
|
||||
REQUIRE(!reply.empty());
|
||||
bool strict = false;
|
||||
const ReplyMessage m = b->new_parse(reply, &strict);
|
||||
const legacy::Answer o = b->old_parse(reply);
|
||||
|
||||
/* The calls come back as the message had them, arguments as JSON values. */
|
||||
const size_t ncalls = msg.contains("tool_calls") ? msg["tool_calls"].size() : 0;
|
||||
REQUIRE_EQ(m.calls.size(), ncalls);
|
||||
for (size_t i = 0; i < ncalls; ++i) {
|
||||
const json& want = msg["tool_calls"][i]["function"];
|
||||
CHECK_EQ(m.calls[i].name, want["name"].get<std::string>());
|
||||
CHECK(m.calls[i].closed);
|
||||
/* Compared as values: the template writes keys in sorted order. */
|
||||
CHECK(nlohmann::json::parse(m.calls[i].arguments) ==
|
||||
nlohmann::json::parse(want["arguments"].get<std::string>()));
|
||||
}
|
||||
const std::string r = msg.contains("reasoning_content") ? msg["reasoning_content"].get<std::string>() : "";
|
||||
CHECK_EQ(m.reasoning, r.empty() ? r : r + "\n");
|
||||
CHECK_EQ(m.content, msg["content"].get<std::string>());
|
||||
|
||||
/* llama.cpp's parser reads the same calls and reasoning, byte for byte. Where the template
|
||||
* wrote content AFTER the calls -- its order for a past turn, not the model's -- the old
|
||||
* parser drops that content and the new one keeps it, leniently. */
|
||||
CHECK_EQ(o.calls.size(), m.calls.size());
|
||||
for (size_t i = 0; i < std::min(o.calls.size(), m.calls.size()); ++i) {
|
||||
CHECK_EQ(o.calls[i].name, m.calls[i].name);
|
||||
CHECK_EQ(o.calls[i].arguments, m.calls[i].arguments);
|
||||
}
|
||||
CHECK_EQ(o.reasoning, m.reasoning);
|
||||
const bool after = ncalls > 0 && !msg["content"].get<std::string>().empty();
|
||||
CHECK_EQ(strict, !after);
|
||||
if (!after) CHECK_EQ(o.content, m.content);
|
||||
streams(b->parser(), reply, "rendered reply");
|
||||
++read;
|
||||
}
|
||||
CHECK(read > 10);
|
||||
}
|
||||
|
||||
/* Every prefix of a rendered reply -- a reply the decoder stopped anywhere -- streams to its own
|
||||
* one-shot parse, and a call the reply ended inside reads back as its text. */
|
||||
TEST(every_truncation_of_a_rendered_reply_keeps_the_contract) {
|
||||
Bench* b = bench(thinking(true));
|
||||
REQUIRE(b != nullptr);
|
||||
for (const json& msg : rendered_corpus()) {
|
||||
const std::string reply = b->render_reply(msg);
|
||||
for (size_t n = 1; n <= reply.size(); n += 1 + n / 64) {
|
||||
const std::string cut = sanitize(reply.substr(0, n));
|
||||
const std::string err = check_stream(b->parser(), cut, every(cut.size(), 3),
|
||||
reply_parse(b->parser(), cut));
|
||||
if (!err.empty())
|
||||
::radtest::fail(__FILE__, __LINE__, err + "\n reply: " + quote(cut));
|
||||
std::unique_ptr<ReplyStream> s = b->parser().open();
|
||||
s->feed(cut, nullptr);
|
||||
s->finish(nullptr);
|
||||
const ReplyMessage& m = s->message();
|
||||
if (!m.calls.empty() && !m.calls.back().closed) {
|
||||
const std::string text = s->content_with_open_call(cut);
|
||||
CHECK(text.find("<|tool_call>call:") != std::string::npos);
|
||||
}
|
||||
}
|
||||
++::radtest::checks();
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the decided shapes
|
||||
*
|
||||
* Replies written the way the model writes them, and the ways it leaves its format. Each reads as
|
||||
* stated, streams under the contract, and -- where `oracle` says so -- agrees with llama.cpp's
|
||||
* parser byte for byte. */
|
||||
|
||||
struct Call { std::string name, args; bool closed = true; };
|
||||
struct Shape {
|
||||
const char* what;
|
||||
std::string gp;
|
||||
std::string reply;
|
||||
std::string content, reasoning;
|
||||
std::vector<Call> calls;
|
||||
bool strict;
|
||||
bool oracle; /* llama.cpp's parser reads it the same */
|
||||
};
|
||||
|
||||
static std::vector<Shape> shapes() {
|
||||
const std::string ls = G("bash", "command:" + S("ls"));
|
||||
const std::string LS = "{\"command\":\"ls\"}";
|
||||
std::vector<Shape> v = {
|
||||
{ "an answer", kOff, "The answer is 4.", "The answer is 4.", "", {}, true, true },
|
||||
{ "a call", kOff, ls, "", "", { { "bash", LS } }, true, true },
|
||||
{ "a sentence, then a call", kOff, "Let me look.\n" + ls, "Let me look.", "",
|
||||
{ { "bash", LS } }, true, true },
|
||||
{ "two calls", kOff, ls + G("read", "limit:40,path:" + S("/a")), "", "",
|
||||
{ { "bash", LS }, { "read", "{\"limit\":40,\"path\":\"/a\"}" } }, true, true },
|
||||
{ "two calls on two lines", kOff, ls + "\n" + G("read", "path:" + S("/a")), "", "",
|
||||
{ { "bash", LS }, { "read", "{\"path\":\"/a\"}" } }, true, false },
|
||||
{ "every kind of value", kOff,
|
||||
G("configure", "extra:{a:[1,2,[]],b:{c:null},d:{}},label:" + S("") +
|
||||
",level:-1.5e3,mode:" + S("fast") + ",tags:[" + S("x") + "," + S("y") +
|
||||
"],verbose:false"),
|
||||
"", "", { { "configure", "{\"extra\":{\"a\":[1,2,[]],\"b\":{\"c\":null},\"d\":{}},"
|
||||
"\"label\":\"\",\"level\":-1.5e3,\"mode\":\"fast\","
|
||||
"\"tags\":[\"x\",\"y\"],\"verbose\":false}" } }, true, true },
|
||||
{ "a call that takes no arguments", kOff, G("ping", ""), "", "", { { "ping", "{}" } },
|
||||
true, true },
|
||||
{ "a string holding what JSON escapes", kOff,
|
||||
G("write", "content:" + S("a \"q\" \\ b\n\tc\x01 é 🚀") + ",path:" + S("/x")), "", "",
|
||||
{ { "write", "{\"content\":\"a \\\"q\\\" \\\\ b\\n\\tc\\u0001 é 🚀\",\"path\":\"/x\"}" } },
|
||||
true, true },
|
||||
{ "a string holding the format's own punctuation", kOff,
|
||||
G("write", "content:" + S("{a:1,} [<|tool_call>call:x()<tool_call|>] <channel|> <|\" .") +
|
||||
",path:" + S("/x")), "", "",
|
||||
{ { "write", "{\"content\":\"{a:1,} [<|tool_call>call:x()<tool_call|>] <channel|> <|\\\" .\","
|
||||
"\"path\":\"/x\"}" } }, true, true },
|
||||
/* Text ending in the start of the delimiter reads as written. (No grammar of this shape
|
||||
* can write it -- llama.cpp's cannot either.) */
|
||||
{ "a string ending in the start of its own delimiter", kOff,
|
||||
G("write", "content:" + S("a <|\"") + ",path:" + S("/x")), "", "",
|
||||
{ { "write", "{\"content\":\"a <|\\\"\",\"path\":\"/x\"}" } }, true, true },
|
||||
/* llama.cpp's key rule takes everything up to the colon, delimiters included, and
|
||||
* hands the client a key `<|"|>path<|"|>`. */
|
||||
{ "a key written as a string", kOff, G("read", S("path") + ":" + S("/a")), "", "",
|
||||
{ { "read", "{\"path\":\"/a\"}" } }, true, false },
|
||||
/* And keeps the blank after a number, `"limit":3 }`, which is no JSON. */
|
||||
{ "whitespace inside the object", kOff, G("read", " path: " + S("/a") + ",\n limit: 3 "),
|
||||
"", "", { { "read", "{\"path\":\"/a\",\"limit\":3}" } }, true, false },
|
||||
|
||||
/* reasoning */
|
||||
{ "thinking on: a thought, then an answer", kOn,
|
||||
"<|channel>thought\nIt is two plus two.\n<channel|>The answer is 4.", "The answer is 4.",
|
||||
"It is two plus two.\n", {}, true, true },
|
||||
{ "thinking on: no thought at all", kOn, "The answer is 4.", "The answer is 4.", "", {},
|
||||
true, true },
|
||||
{ "thinking on: a thought, then a call", kOn,
|
||||
"<|channel>thought\nList it.\n<channel|>" + ls, "", "List it.\n", { { "bash", LS } }, true,
|
||||
true },
|
||||
{ "a thought never closed before a call", kOn, "<|channel>thought\nList it.\n" + ls, "",
|
||||
"List it.\n", { { "bash", LS } }, true, false },
|
||||
{ "after a tool response, thinking on", kAfter,
|
||||
"The tool says 18.\n<channel|>It is 18 degrees.", "It is 18 degrees.",
|
||||
"The tool says 18.\n", {}, true, false },
|
||||
{ "after a tool response, thinking off", "", "It is 18 degrees.", "It is 18 degrees.", "",
|
||||
{}, true, false },
|
||||
{ "an empty thought after the answer", kOff, "The answer is 4.<|channel>thought\n<channel|>",
|
||||
"The answer is 4.", "", {}, true, true },
|
||||
{ "a thought in the middle of the answer", kOff,
|
||||
"First.\n<|channel>thought\nhm\n<channel|>Second.", "First.\nSecond.", "hm\n", {}, true,
|
||||
true },
|
||||
{ "a close with no thought open", kOff, "The answer is 4.<channel|>", "The answer is 4.", "",
|
||||
{}, false, false },
|
||||
{ "the turn's terminator left on", kOff, "The answer is 4.<turn|>", "The answer is 4.", "",
|
||||
{}, true, false },
|
||||
|
||||
/* leaving the object */
|
||||
{ "a JSON string", kOff, G("bash", "command:\"ls -la\""), "", "",
|
||||
{ { "bash", "{\"command\":\"ls -la\"}" } }, false, false },
|
||||
/* Gemma's plain-quoted values are its own strings with, at most, the quotes escaped
|
||||
* (measured: `code: "const s = \"a\nb\";"` for the JS `const s = "a\nb";`): an
|
||||
* escaped quote is a quote, every other backslash is text. */
|
||||
{ "a plain-quoted value with its quotes escaped", kOff,
|
||||
G("bash", "command:\"a\\\"b\\\\c\\u00e9\\n\\q\""), "", "",
|
||||
{ { "bash", "{\"command\":\"a\\\"b\\\\\\\\c\\\\u00e9\\\\n\\\\q\"}" } }, false,
|
||||
false },
|
||||
{ "a plain-quoted value written verbatim", kOff,
|
||||
G("write", "content:\"const s = \"a\\nb\"; f(\"x\", {y: 1});\",path:" + S("/x")), "", "",
|
||||
{ { "write", "{\"content\":\"const s = \\\"a\\\\nb\\\"; f(\\\"x\\\", {y: 1});\",\"path\":\"/x\"}" } },
|
||||
false, false },
|
||||
/* Measured: asked for nested arguments, the model writes Python's quotes. */
|
||||
{ "single-quoted values, as served", kOff,
|
||||
G("configure", "label: 'prod \"eu\"', extra: {note: 'x: {y}', tags: ['a,b', 'c}']}, mode: 'it\\'s'"),
|
||||
"", "", { { "configure", "{\"label\":\"prod \\\"eu\\\"\",\"extra\":{\"note\":\"x: {y}\",\"tags\":[\"a,b\",\"c}\"]},"
|
||||
"\"mode\":\"it's\"}" } }, false, false },
|
||||
{ "a plain quote closed by the dialect's delimiter", kOff, G("bash", "command:\"ls" + Q), "",
|
||||
"", { { "bash", "{\"command\":\"ls\"}" } }, false, false },
|
||||
/* The model leaves a string unclosed and writes the object's `}` and the call's close
|
||||
* (measured: the close delimiter at p=0.86, `}` at p=0.08). The close ends the string and
|
||||
* the call; the closers before it are the object's. */
|
||||
{ "a string the model left open, as served", kOff,
|
||||
"<|tool_call>call:execute{code:" + Q + "const s = \"line1\\nline2\"; console.log(...);}"
|
||||
"<tool_call|><tool_call|><|channel>thought\n<channel|><channel|>"
|
||||
"<|tool_call>call:execute{code:" + Q + "const s = \"line1\\nline2\"; console.log(...);" + Q +
|
||||
"}<tool_call|>", "", "",
|
||||
{ { "execute", "{\"code\":\"const s = \\\"line1\\\\nline2\\\"; console.log(...);\"}" },
|
||||
{ "execute", "{\"code\":\"const s = \\\"line1\\\\nline2\\\"; console.log(...);\"}" } },
|
||||
false, false },
|
||||
{ "a string left open whose code ends in a brace", kOff,
|
||||
"<|tool_call>call:bash{command:" + Q + "f() { return 1; }}<tool_call|>", "", "",
|
||||
{ { "bash", "{\"command\":\"f() { return 1; }\"}" } }, false, false },
|
||||
{ "a nested string left open", kOff,
|
||||
"<|tool_call>call:configure{extra:{a:[" + Q + "x]}\n}<tool_call|>" + G("bash", "command:" + S("ls")),
|
||||
"", "", { { "configure", "{\"extra\":{\"a\":[\"x\"]}}" }, { "bash", "{\"command\":\"ls\"}" } },
|
||||
false, false },
|
||||
/* Thinking on, measured: the close spelled as a plain quote, and text after the call. */
|
||||
{ "a string closed by a stray quote, text after the call", kOn,
|
||||
"<|tool_call>call:bash{command:" + Q + "f(\"a\");\n\"}<tool_call|>end", "end", "",
|
||||
{ { "bash", "{\"command\":\"f(\\\"a\\\");\\n\"}" } }, false, false },
|
||||
{ "a string left open that ends in its own quote", kOff,
|
||||
"<|tool_call>call:bash{command:" + Q + "say \"hi\"}<tool_call|>", "", "",
|
||||
{ { "bash", "{\"command\":\"say \\\"hi\\\"\"}" } }, false, false },
|
||||
{ "a string left open at the end of the reply", kOff,
|
||||
"<|tool_call>call:bash{command:" + Q + "ls}<tool_call|>", "", "",
|
||||
{ { "bash", "{\"command\":\"ls\"}" } }, false, false },
|
||||
{ "code with quotes, backticks, a regex and braces", kOff,
|
||||
G("bash", "command:" + S("const r = /\\d+\"}/g; `${a}` <b> '{'") + ",x:1"), "", "",
|
||||
{ { "bash", "{\"command\":\"const r = /\\\\d+\\\"}/g; `${a}` <b> '{'\",\"x\":1}" } }, true, true },
|
||||
{ "Python literals", kOff, G("configure", "verbose:True,nothing:None"), "", "",
|
||||
{ { "configure", "{\"verbose\":true,\"nothing\":null}" } }, false, false },
|
||||
{ "a bare word", kOff, G("configure", "mode:fast,level:01"), "", "",
|
||||
{ { "configure", "{\"mode\":\"fast\",\"level\":\"01\"}" } }, false, false },
|
||||
{ "a trailing comma", kOff, G("read", "path:" + S("/a") + ","), "", "",
|
||||
{ { "read", "{\"path\":\"/a\"}" } }, false, false },
|
||||
{ "a missing comma", kOff, G("read", "path:" + S("/a") + " limit:3"), "", "",
|
||||
{ { "read", "{\"path\":\"/a\",\"limit\":3}" } }, false, false },
|
||||
{ "a key with no value", kOff, G("read", "path:,limit"), "", "",
|
||||
{ { "read", "{\"path\":null,\"limit\":null}" } }, false, false },
|
||||
{ "the wrong closing bracket", kOff, G("configure", "tags:[" + S("x") + "}"), "", "",
|
||||
{ { "configure", "{\"tags\":[\"x\"]}" } }, false, false },
|
||||
{ "an object the call's close cuts off", kOff,
|
||||
"<|tool_call>call:configure{extra:{a:[1,{b:" + S("c") + "<tool_call|>" + ls, "", "",
|
||||
{ { "configure", "{\"extra\":{\"a\":[1,{\"b\":\"c\"}]}}" }, { "bash", LS } }, false, false },
|
||||
/* llama.cpp's grammar has no arm for it and reads no call at all. */
|
||||
{ "a call to a function that is not a tool", kOff, G("frobnicate", "x:1"), "", "",
|
||||
{ { "frobnicate", "{\"x\":1}" } }, false, false },
|
||||
{ "a call written without its wrapper", kOff, "call:bash{command:" + S("ls") + "}", "", "",
|
||||
{ { "bash", LS } }, false, false },
|
||||
{ "the name prefix in prose", kOff, "This is what I call: a plan, and call:me{ maybe.",
|
||||
"This is what I call: a plan, and call:me{ maybe.", "", {}, true, true },
|
||||
{ "a reply that ends inside a call", kOff,
|
||||
"<|tool_call>call:write{path:" + S("/a") + ",content:" + Q + "half", "", "",
|
||||
{ { "write", "{\"path\":\"/a\",\"content\":\"half", false } }, true, false },
|
||||
};
|
||||
return v;
|
||||
}
|
||||
|
||||
TEST(what_gemma_writes_reads_as_decided) {
|
||||
for (const Shape& s : shapes()) {
|
||||
std::shared_ptr<const ReplyParser> p = parser(s.gp);
|
||||
bool strict = false;
|
||||
const ReplyMessage m = parse(*p, s.reply, &strict);
|
||||
const std::string tag = std::string(s.what) + ": " + quote(s.reply) + "\n got " + show(m);
|
||||
if (m.content != s.content || m.reasoning != s.reasoning || m.calls.size() != s.calls.size() ||
|
||||
strict != s.strict)
|
||||
::radtest::fail(__FILE__, __LINE__, tag + (strict ? " (strict)" : " (lenient)"));
|
||||
for (size_t i = 0; i < std::min(m.calls.size(), s.calls.size()); ++i)
|
||||
if (m.calls[i].name != s.calls[i].name || m.calls[i].arguments != s.calls[i].args ||
|
||||
m.calls[i].closed != s.calls[i].closed)
|
||||
::radtest::fail(__FILE__, __LINE__, tag);
|
||||
for (const ReplyCall& c : m.calls)
|
||||
if (c.closed && !json::accept(c.arguments))
|
||||
::radtest::fail(__FILE__, __LINE__, tag + "\n arguments are no JSON");
|
||||
streams(*p, s.reply, s.what);
|
||||
}
|
||||
}
|
||||
|
||||
/* Where the reply is within the format, llama.cpp's own Gemma 4 parser -- run on the generation
|
||||
* prompt and the reply, as its handler runs it -- reads exactly what this one reads. */
|
||||
TEST(the_shapes_in_the_format_read_as_llama_cpp_reads_them) {
|
||||
int compared = 0;
|
||||
for (const Shape& s : shapes()) {
|
||||
if (!s.oracle) continue;
|
||||
const bool on = s.gp == kOn;
|
||||
Bench* b = bench(thinking(on));
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->prompt().generation_prompt, s.gp);
|
||||
const legacy::Answer o = b->old_parse(s.reply);
|
||||
const ReplyMessage m = b->new_parse(s.reply);
|
||||
bool same = !o.strict_failed && o.content == m.content && o.reasoning == m.reasoning &&
|
||||
o.calls.size() == m.calls.size();
|
||||
for (size_t i = 0; same && i < o.calls.size(); ++i)
|
||||
same = o.calls[i].name == m.calls[i].name && o.calls[i].arguments == m.calls[i].arguments;
|
||||
if (!same)
|
||||
::radtest::fail(__FILE__, __LINE__, std::string(s.what) + ": " + quote(s.reply) +
|
||||
"\n old: " + show(o) + "\n new: " + show(m));
|
||||
++compared;
|
||||
}
|
||||
CHECK(compared >= 15);
|
||||
}
|
||||
|
||||
/* ================================================================== the request switches */
|
||||
|
||||
TEST(thinking_off_starts_the_reply_after_the_closed_channel) {
|
||||
Bench* b = bench(thinking(false));
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->prompt().generation_prompt, kOff);
|
||||
const ReasoningMarkers rm = b->parser().reasoning();
|
||||
CHECK_EQ(rm.open, std::string("<|channel>thought"));
|
||||
CHECK_EQ(rm.close, std::string("<channel|>"));
|
||||
CHECK(!rm.starts_open);
|
||||
|
||||
Bench* on = bench(thinking(true));
|
||||
REQUIRE(on != nullptr);
|
||||
CHECK_EQ(on->prompt().generation_prompt, kOn);
|
||||
CHECK(!on->parser().reasoning().starts_open);
|
||||
/* The system turn carries the thinking switch. */
|
||||
CHECK(on->prompt().prompt.find("<|turn>system\n<|think|>\n") != std::string::npos);
|
||||
CHECK(b->prompt().prompt.find("<|think|>") == std::string::npos);
|
||||
|
||||
CHECK(parser(kAfter)->reasoning().starts_open);
|
||||
CHECK(!parser("")->reasoning().starts_open);
|
||||
}
|
||||
|
||||
/* reasoning_format "none": the channel stays in the content as the model wrote it, and with it
|
||||
* the call grammar's break -- a call still ends the text before it. */
|
||||
TEST(reasoning_format_none_keeps_the_channel_in_the_content) {
|
||||
std::shared_ptr<const ReplyParser> p = parser(kOn, true, /*reasoning=*/false);
|
||||
const std::string reply = "<|channel>thought\nhm\n<channel|>Yes." +
|
||||
G("bash", "command:" + S("ls"));
|
||||
const ReplyMessage m = parse(*p, reply);
|
||||
CHECK_EQ(m.content, std::string("<|channel>thought\nhm\n<channel|>Yes."));
|
||||
CHECK(m.reasoning.empty());
|
||||
REQUIRE_EQ(m.calls.size(), (size_t)1);
|
||||
streams(*p, reply, "reasoning none");
|
||||
}
|
||||
|
||||
/* A request that sent no tools reads call syntax as the text it is -- but the thought channel is
|
||||
* still the model's reasoning, wherever it opens. */
|
||||
TEST(without_tools_a_call_is_text_and_a_late_channel_is_still_reasoning) {
|
||||
std::shared_ptr<const ReplyParser> p = parser(kOff, /*tools=*/false);
|
||||
const std::string reply = "Use <|tool_call>call:bash{} to run it.<|channel>thought\nx\n<channel|>";
|
||||
const ReplyMessage m = parse(*p, reply);
|
||||
CHECK_EQ(m.content, std::string("Use <|tool_call>call:bash{} to run it."));
|
||||
CHECK_EQ(m.reasoning, std::string("x\n"));
|
||||
CHECK(m.calls.empty());
|
||||
streams(*p, reply, "no tools");
|
||||
}
|
||||
|
||||
TEST(parallel_tool_calls_false_still_reads_a_second_call) {
|
||||
std::shared_ptr<const ReplyParser> p = parser(kOff, true, true, /*parallel=*/false);
|
||||
bool strict = true;
|
||||
const ReplyMessage m = parse(*p, G("bash", "command:" + S("ls")) + G("bash", "command:" + S("pwd")), &strict);
|
||||
CHECK_EQ(m.calls.size(), (size_t)2);
|
||||
CHECK(!strict);
|
||||
}
|
||||
|
||||
/* ================================================================== a conversation
|
||||
*
|
||||
* The turn after a call: the assistant message carries the call, a `role: tool` message its
|
||||
* result, and the template writes both into the model's own turn -- the call in the model's
|
||||
* spelling, the result as a response block -- and leaves the turn open for the model to go on. */
|
||||
static json conversation(bool two_calls) {
|
||||
json calls = json::array();
|
||||
calls.push_back({ { "id", "c1" }, { "type", "function" },
|
||||
{ "function", { { "name", "read" }, { "arguments", "{\"path\":\"/a\",\"limit\":3}" } } } });
|
||||
if (two_calls)
|
||||
calls.push_back({ { "id", "c2" }, { "type", "function" },
|
||||
{ "function", { { "name", "bash" }, { "arguments", "{\"command\":\"ls\"}" } } } });
|
||||
json msgs = json::array({ { { "role", "user" }, { "content", "Read /a." } },
|
||||
{ { "role", "assistant" }, { "content", "" }, { "tool_calls", calls } },
|
||||
{ { "role", "tool" }, { "tool_call_id", "c1" }, { "content", "line one" } } });
|
||||
if (two_calls)
|
||||
msgs.push_back({ { "role", "tool" }, { "tool_call_id", "c2" }, { "content", "a.txt" } });
|
||||
return msgs;
|
||||
}
|
||||
|
||||
TEST(a_tool_result_renders_into_the_open_turn_and_the_reply_goes_on) {
|
||||
for (bool on : { false, true }) {
|
||||
for (bool two : { false, true }) {
|
||||
ChatTemplate t;
|
||||
CHECK_OK(t.load(fixture(), "<bos>", "<eos>"));
|
||||
ChatOptions opt;
|
||||
opt.enable_thinking = on;
|
||||
ChatPrompt p;
|
||||
REQUIRE_EQ(t.apply(conversation(two), agent_tools(), opt, &p), RAD_OK);
|
||||
const std::string want =
|
||||
"<|turn>model\n<|tool_call>call:read{limit:3,path:<|\"|>/a<|\"|>}<tool_call|>" +
|
||||
std::string(two ? "<|tool_call>call:bash{command:<|\"|>ls<|\"|>}<tool_call|>" : "") +
|
||||
"<|tool_response>response:read{value:<|\"|>line one<|\"|>}<tool_response|>" +
|
||||
std::string(two ? "<|tool_response>response:bash{value:<|\"|>a.txt<|\"|>}<tool_response|>"
|
||||
: "");
|
||||
if (p.prompt.find(want) == std::string::npos)
|
||||
::radtest::fail(__FILE__, __LINE__, "the turn is not rendered as " + quote(want) +
|
||||
"\n prompt: " + quote(p.prompt));
|
||||
/* The model goes on in the same turn: thinking off with nothing written for it,
|
||||
* thinking on inside a channel the template opened. */
|
||||
CHECK_EQ(p.generation_prompt, std::string(on ? kAfter : ""));
|
||||
CHECK(p.prompt.size() >= want.size() &&
|
||||
p.prompt.compare(p.prompt.size() - p.generation_prompt.size() - 0,
|
||||
p.generation_prompt.size(), p.generation_prompt) == 0);
|
||||
|
||||
std::shared_ptr<const ReplyParser> rp = parser(p.generation_prompt);
|
||||
const std::string reply = on ? "The file has one line.\n<channel|>It reads \"line one\"."
|
||||
: "It reads \"line one\".";
|
||||
const ReplyMessage m = parse(*rp, reply);
|
||||
CHECK_EQ(m.content, std::string("It reads \"line one\"."));
|
||||
CHECK_EQ(m.reasoning, std::string(on ? "The file has one line.\n" : ""));
|
||||
streams(*rp, reply, "after a tool result");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== fuzz */
|
||||
|
||||
static std::vector<std::string> fragments() {
|
||||
return { "<|tool_call>", "<tool_call|>", "call:", "call:bash", "call:read", "{", "}", "[", "]",
|
||||
",", ":", Q, "<|\"", "<|", "|>", "<|channel>thought\n", "<channel|>", "<|channel>",
|
||||
"\"", "\\", "\\u", "\\ud83d", "true", "None", "-1.5e3", "path", "command", "x", "\n",
|
||||
" ", "中", "🚀", "<turn|>", "<eos>", "<|tool_response>" };
|
||||
}
|
||||
|
||||
TEST(fuzzed_replies_keep_the_contract) {
|
||||
std::mt19937 rng(3);
|
||||
const std::vector<std::string> frag = fragments();
|
||||
const std::vector<std::string> seeds = {
|
||||
G("configure", "extra:{a:[1,{b:" + S("c") + "}]},tags:[" + S("x") + "]"),
|
||||
"Sure.\n" + G("bash", "command:" + S("ls -la")) + G("read", "path:" + S("/a") + ",limit:3"),
|
||||
"<|channel>thought\nPlan.\n<channel|>Done.<|channel>thought\n<channel|>",
|
||||
G("write", "content:\"a\\nb\\u00e9\",path:" + S("/x")),
|
||||
};
|
||||
int n = 0;
|
||||
for (const std::string& gp : { kOff, kOn, kAfter }) {
|
||||
std::shared_ptr<const ReplyParser> p = parser(gp);
|
||||
for (const std::string& seed : seeds)
|
||||
for (int k = 0; k < 60; ++k) {
|
||||
const std::string text = sanitize(mutate(rng, seed, frag));
|
||||
const std::string err = check_stream(*p, text, every(text.size(), 1),
|
||||
reply_parse(*p, text));
|
||||
if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err + "\n reply: " + quote(text));
|
||||
++n;
|
||||
}
|
||||
}
|
||||
CHECK(n > 0);
|
||||
}
|
||||
|
||||
/* A long reply holds a bounded number of bytes, whatever it holds: a file written into a string
|
||||
* streams as it arrives. */
|
||||
TEST(a_long_string_streams_and_holds_a_bounded_number_of_bytes) {
|
||||
std::string file;
|
||||
while (file.size() < 200000) file += " x = compute(a, b) # <tag> & \"quoted\" <| ]] \\n\n";
|
||||
const std::string reply = "<|channel>thought\nWriting it.\n<channel|>" +
|
||||
G("write", "content:" + S(file) + ",path:" + S("/big.py"));
|
||||
std::shared_ptr<const ReplyParser> p = parser(kOn);
|
||||
const std::string err = check_stream(*p, reply, every(reply.size(), 7), reply_parse(*p, reply));
|
||||
if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err);
|
||||
const ReplyMessage m = parse(*p, reply);
|
||||
REQUIRE_EQ(m.calls.size(), (size_t)1);
|
||||
CHECK(json::parse(m.calls[0].arguments)["content"] == file);
|
||||
}
|
||||
|
||||
/* ================================================================== the grammar */
|
||||
|
||||
static const SimpleVocab& printable() {
|
||||
static const SimpleVocab v = [] {
|
||||
SimpleVocab s;
|
||||
for (int c = 32; c < 127; ++c) s.add(std::string(1, (char)c));
|
||||
s.add("\n");
|
||||
s.add("\t");
|
||||
return s;
|
||||
}();
|
||||
return v;
|
||||
}
|
||||
|
||||
/* 1 complete, 0 admitted but unfinished or refused, -1 does not compile. */
|
||||
static int admits(const std::string& gbnf, const std::string& prefix, const std::string& text) {
|
||||
std::unique_ptr<GbnfGrammar> gr;
|
||||
std::string err;
|
||||
if (GbnfGrammar::create(gbnf, "root", &printable(), false, {}, {}, &gr, &err) < 0) return -1;
|
||||
if (gr->accept_str(prefix) < 0 || gr->accept_str(text) < 0) return 0;
|
||||
return gr->complete() ? 1 : 0;
|
||||
}
|
||||
|
||||
static std::string grammar_for(const ChatGrammarRequest& gq) {
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why));
|
||||
ChatGrammar g;
|
||||
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
|
||||
return g.text;
|
||||
}
|
||||
|
||||
/* The lazy call grammar admits every call the template writes and every strict call above, as
|
||||
* llama.cpp's own Gemma 4 grammar does; it refuses what leaves the dialect. */
|
||||
TEST(the_call_grammar_admits_what_the_model_writes_and_refuses_the_rest) {
|
||||
Bench* b = bench(thinking(true));
|
||||
REQUIRE(b != nullptr);
|
||||
ChatGrammarRequest gq;
|
||||
gq.tools = &agent_tools();
|
||||
gq.generation_prompt = b->prompt().generation_prompt;
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why));
|
||||
ChatGrammar g;
|
||||
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
|
||||
CHECK(g.lazy);
|
||||
CHECK(g.trigger_words == std::vector<std::string>{ "<|tool_call>" });
|
||||
const std::string& vendored = b->prompt().grammar;
|
||||
|
||||
int seen = 0;
|
||||
for (const json& msg : rendered_corpus()) {
|
||||
std::string reply = b->render_reply(msg);
|
||||
const size_t at = reply.find("<|tool_call>");
|
||||
if (at == std::string::npos) continue;
|
||||
reply = reply.substr(at, reply.rfind("<tool_call|>") + 12 - at);
|
||||
if (reply.find_first_of("\x01") != std::string::npos) continue;
|
||||
CHECK_EQ(admits(g.text, "", reply), 1);
|
||||
CHECK_EQ(admits(vendored, "", reply), 1);
|
||||
++seen;
|
||||
}
|
||||
CHECK(seen > 8);
|
||||
for (const Shape& s : shapes()) {
|
||||
if (!s.strict || s.calls.empty() || s.reply.find("\x01") != std::string::npos) continue;
|
||||
const size_t at = s.reply.find("<|tool_call>");
|
||||
if (at == std::string::npos || !s.calls.back().closed) continue;
|
||||
const std::string calls = s.reply.substr(at, s.reply.rfind("<tool_call|>") + 12 - at);
|
||||
if (s.reply.find("\n<|tool_call>") != std::string::npos) continue; /* a line between calls */
|
||||
if (std::string(s.what) == "whitespace inside the object" ||
|
||||
std::string(s.what) == "a string ending in the start of its own delimiter")
|
||||
continue;
|
||||
if (admits(g.text, "", calls) != 1)
|
||||
::radtest::fail(__FILE__, __LINE__, std::string("refused: ") + s.what + " " + quote(calls));
|
||||
}
|
||||
/* Python's quotes, as the model writes arguments it was handed as JSON. */
|
||||
CHECK_EQ(admits(g.text, "", G("bash", "command:'echo \"hi\" \\' {x}'")), 1);
|
||||
CHECK_EQ(admits(g.text, "", G("configure", "extra:{tags:['a,b', 'c}']}")), 1);
|
||||
for (const std::string& bad : {
|
||||
G("bash", "command:ls"), /* a bare word */
|
||||
G("bash", "command:\"ls\""), /* a JSON string */
|
||||
G("bash", "command:" + S("ls") + ","), /* a trailing comma */
|
||||
"<|tool_call>call:bash{command:" + S("ls") + "<tool_call|>", /* the object unclosed */
|
||||
G("frobnicate", "x:1"), /* not a tool */
|
||||
"<|tool_call>call:bash {command:" + S("ls") + "}<tool_call|>", /* a space after the name */
|
||||
G("bash", "command:True"),
|
||||
})
|
||||
CHECK_EQ(admits(g.text, "", bad), 0);
|
||||
}
|
||||
|
||||
/* tool_choice "required" makes the grammar the whole reply: from the generation prompt, an
|
||||
* optional thought, then the calls and nothing after them; a named function admits that one, and
|
||||
* parallel_tool_calls false one call. */
|
||||
TEST(a_required_call_is_the_whole_reply) {
|
||||
for (const std::string& gp : { kOff, kOn }) {
|
||||
ChatGrammarRequest gq;
|
||||
gq.tools = &agent_tools();
|
||||
gq.generation_prompt = gp;
|
||||
gq.require_call = true;
|
||||
const std::string any = grammar_for(gq);
|
||||
gq.parallel_tool_calls = false;
|
||||
const std::string one = grammar_for(gq);
|
||||
gq.parallel_tool_calls = true;
|
||||
gq.only_tool = "read";
|
||||
const std::string rd = grammar_for(gq);
|
||||
const std::string ls = G("bash", "command:" + S("ls")), ra = G("read", "path:" + S("/a"));
|
||||
const std::string T = gp == kOn ? "<|channel>thought\nPlan.\n<channel|>" : "";
|
||||
CHECK_EQ(admits(any, gp, T + ls), 1);
|
||||
CHECK_EQ(admits(any, gp, T + ls + ra), 1);
|
||||
CHECK_EQ(admits(any, gp, T + "The answer."), 0);
|
||||
CHECK_EQ(admits(any, gp, T + ls + "Done."), 0);
|
||||
CHECK_EQ(admits(one, gp, T + ls), 1);
|
||||
CHECK_EQ(admits(one, gp, T + ls + ra), 0);
|
||||
CHECK_EQ(admits(rd, gp, T + ra), 1);
|
||||
CHECK_EQ(admits(rd, gp, T + ls), 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_response_format_is_the_whole_reply) {
|
||||
const json schema = json::parse(R"({"type":"object","properties":{"n":{"type":"integer"}},"required":["n"]})");
|
||||
ChatGrammarRequest gq;
|
||||
gq.json_schema = &schema;
|
||||
gq.generation_prompt = kOff;
|
||||
const std::string g = grammar_for(gq);
|
||||
CHECK_EQ(admits(g, kOff, "{\"n\": 3}"), 1);
|
||||
CHECK_EQ(admits(g, kOff, "```json\n{\"n\": 3}\n```"), 1);
|
||||
CHECK_EQ(admits(g, kOff, "{\"n\": \"x\"}"), 0);
|
||||
}
|
||||
|
||||
/* ================================================================== the server's view
|
||||
*
|
||||
* The chat bridge serves the model from the plugin's declaration: tool requests are no longer
|
||||
* refused, the grammar comes from the format, and the decoder renders the dialect's string
|
||||
* delimiter -- a control token like the format's tags -- so the parser sees it. */
|
||||
static std::shared_ptr<Vocab> gemma_vocab() {
|
||||
VocabBuild vb;
|
||||
vb.tokens = { "<pad>", "<eos>", "<bos>", "a", "<|tool_call>", "<tool_call|>", "<|tool_response>",
|
||||
"<tool_response|>", "<|\"|>", "<|channel>", "<channel|>", "<|turn>", "<turn|>",
|
||||
"thought", "call:" };
|
||||
vb.types.assign(vb.tokens.size(), RAD_TT_CONTROL);
|
||||
vb.types[3] = vb.types[13] = vb.types[14] = RAD_TT_NORMAL;
|
||||
/* The letters the markers' text is spelled with, so a marker tokenises whole. */
|
||||
for (const char* c : { "t", "h", "o", "u", "g", "c", "l", ":" }) {
|
||||
vb.tokens.push_back(c);
|
||||
vb.types.push_back(RAD_TT_NORMAL);
|
||||
}
|
||||
vb.bos = 2;
|
||||
vb.eos = 1;
|
||||
vb.chat_template = fixture();
|
||||
/* generation_config.json: eos_token_id [1, 106, 50] -- here <eos>, <turn|>, <|tool_response>. */
|
||||
vb.eos_ids = { 1, 12, 6 };
|
||||
auto v = std::make_shared<Vocab>();
|
||||
return v->load(std::move(vb)) >= 0 ? v : nullptr;
|
||||
}
|
||||
|
||||
TEST(the_chat_bridge_serves_gemma_from_its_declaration) {
|
||||
std::shared_ptr<Vocab> v = gemma_vocab();
|
||||
REQUIRE(v != nullptr);
|
||||
CHECK(v->is_eog(6)); /* <|tool_response>: after its calls the model stops there */
|
||||
server::ChatTemplateBridge br;
|
||||
CHECK_OK(br.init(*v, gemma4_bf16::chat_format_decl(), "gemma4_bf16"));
|
||||
CHECK(br.supports_tools());
|
||||
CHECK(br.tool_refusal().empty());
|
||||
|
||||
server::ChatRenderOptions opt;
|
||||
opt.enable_thinking = false;
|
||||
server::ChatRender r;
|
||||
std::string why;
|
||||
const json msgs = json::array({ { { "role", "user" }, { "content", "List /work." } } });
|
||||
REQUIRE_EQ(br.apply(msgs, agent_tools(), opt, &r, &why), RAD_OK);
|
||||
CHECK_EQ(r.generation_prompt, kOff);
|
||||
CHECK(r.grammar_lazy);
|
||||
REQUIRE_EQ(r.grammar_triggers.size(), (size_t)1);
|
||||
CHECK_EQ(r.grammar_triggers[0].value, std::string("<|tool_call>"));
|
||||
CHECK(std::find(r.preserved_tokens.begin(), r.preserved_tokens.end(), Q) != r.preserved_tokens.end());
|
||||
CHECK(!r.think_starts_open);
|
||||
REQUIRE(r.parser != nullptr);
|
||||
|
||||
/* The decoder renders every control token the markers are made of, the string's among them;
|
||||
* the turn's terminators it does not. */
|
||||
Detokenizer d(v, {}, false, r.preserved_tokens);
|
||||
std::string text;
|
||||
for (int32_t id : { 9, 13, 3, 10, 4, 14, 3, 8, 3, 8, 5 }) text += d.push(id);
|
||||
text += d.flush();
|
||||
CHECK_EQ(text, std::string("<|channel>thoughta<channel|><|tool_call>call:a<|\"|>a<|\"|><tool_call|>"));
|
||||
|
||||
std::unique_ptr<server::IReplyReader> rd = r.parser->open();
|
||||
std::vector<server::ReplyDelta> deltas;
|
||||
const std::string reply = "On it." + G("bash", "command:" + S("ls"));
|
||||
for (char c : reply) rd->feed(std::string(1, c), &deltas);
|
||||
rd->finish(&deltas);
|
||||
const server::ParsedMessage pm = rd->message();
|
||||
CHECK_EQ(pm.content, std::string("On it."));
|
||||
REQUIRE_EQ(pm.tool_calls.size(), (size_t)1);
|
||||
CHECK_EQ(pm.tool_calls[0].name, std::string("bash"));
|
||||
CHECK_EQ(pm.tool_calls[0].arguments, std::string("{\"command\":\"ls\"}"));
|
||||
CHECK(!pm.open_call);
|
||||
std::string args;
|
||||
int begins = 0, ends = 0;
|
||||
for (const server::ReplyDelta& dl : deltas) {
|
||||
if (dl.kind == server::ReplyDelta::CallBegin) ++begins;
|
||||
if (dl.kind == server::ReplyDelta::CallArgs) args += dl.text;
|
||||
if (dl.kind == server::ReplyDelta::CallEnd) ++ends;
|
||||
}
|
||||
CHECK_EQ(begins, 1);
|
||||
CHECK_EQ(ends, 1);
|
||||
CHECK_EQ(args, pm.tool_calls[0].arguments);
|
||||
|
||||
/* A tool whose name the object's opening would end is refused at admission, by name. */
|
||||
const json bad = json::parse(R"([{"type":"function","function":{"name":"a{b"}}])");
|
||||
server::ChatRender rb;
|
||||
CHECK(br.apply(msgs, bad, opt, &rb, &why) < 0);
|
||||
CHECK(why.find("a{b") != std::string::npos);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -1492,6 +1492,187 @@ TEST(a_template_whose_calls_cannot_be_described_refuses_tools_and_still_chats) {
|
||||
CHECK(!why.empty());
|
||||
}
|
||||
|
||||
/* ================================================================== the object family
|
||||
*
|
||||
* A call written as its name and ONE object holding the arguments (ChatArgs::Object): JSON behind
|
||||
* a name tag with neither an end nor a wrapper -- Mistral's `[TOOL_CALLS]NAME[ARGS]{...}` -- and
|
||||
* behind a function tag that has its own close. The dialect fields (Gemma 4's strings and bare
|
||||
* keys) are held in chatparse_gemma4_test, against the model's own template and llama.cpp's
|
||||
* parser for it. */
|
||||
|
||||
static std::shared_ptr<const ReplyParser> object_format(bool tagged_end, ChatFormat* out = nullptr) {
|
||||
static const char* const kT1[] = { "[TOOL_CALLS]" };
|
||||
static const char* const kT2[] = { "<tool_call>" };
|
||||
RadChatFormat c{};
|
||||
c.struct_size = sizeof(RadChatFormat);
|
||||
c.args_form = RAD_CHAT_ARGS_OBJECT;
|
||||
if (!tagged_end) {
|
||||
c.name = "test:name-tag";
|
||||
c.name_prefix = "[TOOL_CALLS]";
|
||||
c.name_suffix = "[ARGS]";
|
||||
c.triggers = kT1;
|
||||
} else {
|
||||
c.name = "test:function-tag";
|
||||
c.call_open = "<tool_call>\n";
|
||||
c.call_close = "</tool_call>";
|
||||
c.name_prefix = "<function=";
|
||||
c.name_suffix = ">";
|
||||
c.call_end = "</function>\n";
|
||||
c.triggers = kT2;
|
||||
}
|
||||
c.n_triggers = 1;
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
std::shared_ptr<const ReplyFormat> rf;
|
||||
std::shared_ptr<const ReplyParser> p;
|
||||
if (chat_format_from_abi(&c, &f, &why) < 0 || ReplyFormat::compile(f, &rf, &why) < 0) {
|
||||
::radtest::fail(__FILE__, __LINE__, why);
|
||||
return nullptr;
|
||||
}
|
||||
if (out) *out = f;
|
||||
ReplyOptions ro;
|
||||
ro.tools = &agent_tools();
|
||||
if (ReplyParser::create(rf, ro, &p, &why) < 0) ::radtest::fail(__FILE__, __LINE__, why);
|
||||
return p;
|
||||
}
|
||||
|
||||
static int object_admits(const std::string& gbnf, const std::string& text) {
|
||||
static const SimpleVocab vocab = [] {
|
||||
SimpleVocab v;
|
||||
for (int c = 32; c < 127; ++c) v.add(std::string(1, (char)c));
|
||||
v.add("\n");
|
||||
return v;
|
||||
}();
|
||||
std::unique_ptr<GbnfGrammar> gr;
|
||||
std::string err;
|
||||
if (GbnfGrammar::create(gbnf, "root", &vocab, false, {}, {}, &gr, &err) < 0) return -1;
|
||||
if (gr->accept_str(text) < 0) return 0;
|
||||
return gr->complete() ? 1 : 0;
|
||||
}
|
||||
|
||||
TEST(json_arguments_behind_a_name_tag_read_as_one_object) {
|
||||
std::shared_ptr<const ReplyParser> p = object_format(false);
|
||||
REQUIRE(p != nullptr);
|
||||
bool strict = false;
|
||||
const std::string reply = "Sure.[TOOL_CALLS]bash[ARGS]{\"command\": \"ls -la\", \"timeout\": 30}"
|
||||
"[TOOL_CALLS]read[ARGS]{\"path\": \"/a\", \"limit\": [1, {\"x\": null}]}";
|
||||
const ReplyMessage m = reply_parse(*p, reply, &strict);
|
||||
CHECK(strict);
|
||||
CHECK_EQ(m.content, std::string("Sure."));
|
||||
REQUIRE(m.calls.size() == 2);
|
||||
CHECK_EQ(m.calls[0].arguments, std::string("{\"command\":\"ls -la\",\"timeout\":30}"));
|
||||
CHECK_EQ(m.calls[1].arguments, std::string("{\"path\":\"/a\",\"limit\":[1,{\"x\":null}]}"));
|
||||
const std::string err = stream_all(*p, reply);
|
||||
if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err);
|
||||
/* A bare key is outside JSON: read, and said so. */
|
||||
const ReplyMessage b = reply_parse(*p, "[TOOL_CALLS]read[ARGS]{path: \"/a\"}", &strict);
|
||||
CHECK(!strict);
|
||||
REQUIRE(b.calls.size() == 1);
|
||||
CHECK_EQ(b.calls[0].arguments, std::string("{\"path\":\"/a\"}"));
|
||||
/* No object after the tag: a call with none, and what stood there is content. */
|
||||
const ReplyMessage n = reply_parse(*p, "[TOOL_CALLS]ping[ARGS] and then", &strict);
|
||||
CHECK(!strict);
|
||||
REQUIRE(n.calls.size() == 1);
|
||||
CHECK_EQ(n.calls[0].arguments, std::string("{}"));
|
||||
CHECK_EQ(n.content, std::string("and then"));
|
||||
}
|
||||
|
||||
TEST(json_arguments_behind_a_function_tag_end_at_its_close) {
|
||||
ChatFormat f;
|
||||
std::shared_ptr<const ReplyParser> p = object_format(true, &f);
|
||||
REQUIRE(p != nullptr);
|
||||
bool strict = false;
|
||||
const std::string reply = "<tool_call>\n<function=bash>{\"command\": \"ls\"}</function>\n</tool_call>"
|
||||
"<tool_call>\n<function=read>{\"path\": \"/a\"}\n</function>\n</tool_call>";
|
||||
const ReplyMessage m = reply_parse(*p, reply, &strict);
|
||||
CHECK(strict);
|
||||
REQUIRE(m.calls.size() == 2);
|
||||
CHECK_EQ(m.calls[0].arguments, std::string("{\"command\":\"ls\"}"));
|
||||
CHECK_EQ(m.calls[1].arguments, std::string("{\"path\":\"/a\"}"));
|
||||
const std::string err = stream_all(*p, reply);
|
||||
if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err);
|
||||
/* The function's close where the object was still open closes it. */
|
||||
const ReplyMessage c = reply_parse(
|
||||
*p, "<tool_call>\n<function=read>{\"path\": \"/a\"</function>\n</tool_call>", &strict);
|
||||
CHECK(!strict);
|
||||
REQUIRE(c.calls.size() == 1);
|
||||
CHECK(c.calls[0].closed);
|
||||
CHECK_EQ(c.calls[0].arguments, std::string("{\"path\":\"/a\"}"));
|
||||
|
||||
/* The grammar: a JSON object between the tags, and the tags as written. */
|
||||
ChatGrammarRequest gq;
|
||||
gq.tools = &agent_tools();
|
||||
ChatGrammar g;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
|
||||
CHECK(g.lazy);
|
||||
log_set_level(Log::Error);
|
||||
CHECK_EQ(object_admits(g.text, "<tool_call>\n<function=bash>{\"command\": \"ls\", \"n\": [1, {\"a\": null}]}"
|
||||
"</function>\n</tool_call>"), 1);
|
||||
CHECK_EQ(object_admits(g.text, "<tool_call>\n<function=bash>{command: \"ls\"}</function>\n</tool_call>"), 0);
|
||||
CHECK_EQ(object_admits(g.text, "<tool_call>\n<function=nope>{}</function>\n</tool_call>"), 0);
|
||||
log_set_level(Log::Warn);
|
||||
}
|
||||
|
||||
/* reasoning_anywhere: a block that opens after the answer is reasoning there too, and a close
|
||||
* with no block open is not part of the answer. Without it, both are content. */
|
||||
TEST(a_reasoning_block_may_open_again_later_when_the_format_says_so) {
|
||||
for (bool anywhere : { false, true }) {
|
||||
RadChatFormat c = qwen_abi();
|
||||
c.reasoning_anywhere = anywhere ? 1 : 0;
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
std::shared_ptr<const ReplyFormat> rf;
|
||||
std::shared_ptr<const ReplyParser> p;
|
||||
CHECK_OK(chat_format_from_abi(&c, &f, &why));
|
||||
CHECK_OK(ReplyFormat::compile(f, &rf, &why));
|
||||
ReplyOptions ro;
|
||||
ro.generation_prompt = "<|im_start|>assistant\n<think>\n";
|
||||
ro.tools = &agent_tools();
|
||||
CHECK_OK(ReplyParser::create(rf, ro, &p, &why));
|
||||
const std::string reply = "Plan.\n</think>\n\nAnswer.<think>\nmore\n</think>\n\nTail.</think>";
|
||||
bool strict = false;
|
||||
const ReplyMessage m = reply_parse(*p, reply, &strict);
|
||||
if (anywhere) {
|
||||
CHECK_EQ(m.reasoning, std::string("Plan.\nmore\n"));
|
||||
CHECK_EQ(m.content, std::string("Answer.Tail."));
|
||||
CHECK(!strict); /* the last </think> closed nothing */
|
||||
} else {
|
||||
CHECK_EQ(m.reasoning, std::string("Plan.\n"));
|
||||
CHECK_EQ(m.content, std::string("Answer.<think>\nmore\n</think>\n\nTail.</think>"));
|
||||
}
|
||||
const std::string err = stream_all(*p, reply);
|
||||
if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(an_object_format_the_parser_cannot_read_is_refused) {
|
||||
auto refused = [](void (*edit)(RadChatFormat&), const char* word) {
|
||||
static const char* const kT[] = { "[TOOL_CALLS]" };
|
||||
RadChatFormat c{};
|
||||
c.struct_size = sizeof(RadChatFormat);
|
||||
c.args_form = RAD_CHAT_ARGS_OBJECT;
|
||||
c.name_prefix = "[TOOL_CALLS]";
|
||||
c.name_suffix = "[ARGS]";
|
||||
c.triggers = kT;
|
||||
c.n_triggers = 1;
|
||||
edit(c);
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
if (chat_format_from_abi(&c, &f, &why) < 0) return false;
|
||||
return chat_format_check(f, &why) == RAD_E_UNSUPPORTED && why.find(word) != std::string::npos;
|
||||
};
|
||||
CHECK(refused([](RadChatFormat&) {}, "") == false); /* the base is a format */
|
||||
CHECK(refused([](RadChatFormat& c) { c.arg_value_suffix = "</a>"; }, "arg_*"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.object_string_open = "<s>"; }, "together"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.object_string_open = c.object_string_close = "'"; },
|
||||
"bare word"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.call_end = "<,>"; }, "punctuation"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.call_end = " \n"; }, "only whitespace"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.name_prefix = ""; c.triggers = nullptr; c.n_triggers = 0; },
|
||||
"name_prefix is empty"));
|
||||
}
|
||||
|
||||
/* ================================================================== cost
|
||||
*
|
||||
* The legacy path re-parses the whole reply on every chunk, so a reply of n bytes costs O(n^2). The
|
||||
|
||||
@@ -684,3 +684,164 @@ TEST(the_index_decides_which_shard_a_tensor_is_read_from) {
|
||||
std::remove((dir + "/" + f).c_str());
|
||||
::rmdir(dir.c_str());
|
||||
}
|
||||
|
||||
/* ================================================================== CT-INT4 */
|
||||
namespace {
|
||||
|
||||
/* A compressed-tensors pack-quantized int4 weight as llm-compressor writes it: code (row n, column
|
||||
* k) is the signed value q[n][k], stored unsigned about 8 as nibble k % 8 of int32 word [n, k / 8];
|
||||
* `X.weight_scale` is bf16 [N, K / group]. */
|
||||
struct Ct {
|
||||
std::vector<std::vector<int>> q; /* [N][K] signed codes, -8..7 */
|
||||
std::vector<float> scale; /* [N * K / group] */
|
||||
int64_t N = 0, K = 0, group = 0;
|
||||
};
|
||||
|
||||
Ct make_ct(int64_t N, int64_t K, int64_t group, int seed) {
|
||||
Ct c;
|
||||
c.N = N; c.K = K; c.group = group;
|
||||
c.q.assign((size_t)N, std::vector<int>((size_t)K));
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
c.q[(size_t)n][(size_t)k] = (int)((n * 7 + k * 3 + seed * 5 + (k * k) % 11) % 16) - 8;
|
||||
for (int64_t i = 0; i < N * (K / group); ++i)
|
||||
c.scale.push_back(rad_load_f32(std::vector<uint16_t>{ rad_f32_to_bf16(
|
||||
0.01f * (float)(1 + (i * 13 + seed) % 29)) }.data(), RAD_BF16, 0));
|
||||
return c;
|
||||
}
|
||||
|
||||
void add_ct(std::vector<T>* ts, const std::string& base, const Ct& c) {
|
||||
T p{ base + ".weight_packed", "I32", { c.N, c.K / 8 }, {} };
|
||||
p.bytes.assign((size_t)(c.N * c.K / 2), 0);
|
||||
for (int64_t n = 0; n < c.N; ++n)
|
||||
for (int64_t k = 0; k < c.K; ++k) {
|
||||
const uint32_t u = (uint32_t)(c.q[(size_t)n][(size_t)k] + 8);
|
||||
uint32_t w;
|
||||
std::memcpy(&w, p.bytes.data() + (n * (c.K / 8) + k / 8) * 4, 4);
|
||||
w |= u << (4 * (k % 8));
|
||||
std::memcpy(p.bytes.data() + (n * (c.K / 8) + k / 8) * 4, &w, 4);
|
||||
}
|
||||
T s{ base + ".weight_scale", "BF16", { c.N, c.K / c.group }, {} };
|
||||
s.bytes.resize((size_t)(c.N * (c.K / c.group) * 2));
|
||||
for (size_t i = 0; i < c.scale.size(); ++i) rad_store_f32(s.bytes.data(), RAD_BF16, (int64_t)i, c.scale[i]);
|
||||
ts->push_back(p);
|
||||
ts->push_back(s);
|
||||
}
|
||||
|
||||
std::string ct_config(const char* symmetric, int group) {
|
||||
return std::string("{\"model_type\":\"qwen4_exp\",\"quantization_config\":{\"quant_method\":"
|
||||
"\"compressed-tensors\",\"format\":\"pack-quantized\",\"config_groups\":"
|
||||
"{\"group_0\":{\"format\":\"pack-quantized\",\"targets\":[\"Linear\"],"
|
||||
"\"weights\":{\"num_bits\":4,\"type\":\"int\",\"symmetric\":") + symmetric +
|
||||
",\"strategy\":\"group\",\"group_size\":" + std::to_string(group) +
|
||||
",\"dynamic\":false,\"actorder\":null}}}}}";
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* CT-INT4 IS IMPORTED: gate and up, each its own packed weight, become one `i4*bf16[1x32]` weight
|
||||
* whose codes are the shipped ones made signed and whose scales are the shipped ones. Read as f32
|
||||
* it is the shipped value, the code less eight times its group's scale -- a code below eight is a
|
||||
* negative weight, which an unsigned `code - 8` once turned into four billion. */
|
||||
TEST(a_ct_int4_weight_is_imported_as_its_signed_codes_and_scales) {
|
||||
const Ct gate = make_ct(4, 64, 32, 1), up = make_ct(6, 64, 32, 2);
|
||||
std::vector<T> ts;
|
||||
add_ct(&ts, "e.0.gate_proj", gate);
|
||||
add_ct(&ts, "e.0.up_proj", up);
|
||||
T plain = bf16("e.0.norm.weight", { 64 }, 1.0f); /* an ignored layer is an ordinary tensor */
|
||||
ts.push_back(plain);
|
||||
const std::string dir = write_checkpoint(ts, ct_config("true", 32).c_str());
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() == Checkpoint::Import::CtInt4);
|
||||
CHECK(ck.import_refusal().empty());
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "e.0.gate_proj.weight", "e.0.up_proj.weight" }));
|
||||
prog.name_map.push_back(map("norm", RAD_MAP_COPY, { "e.0.norm.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
|
||||
REQUIRE(w.imported);
|
||||
CHECK_EQ(w.rows, (int64_t)10);
|
||||
CHECK_EQ(w.cols, (int64_t)64);
|
||||
REQUIRE_EQ(w.enc.n_planes, 2);
|
||||
CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_I4);
|
||||
CHECK_EQ(w.enc.plane[0].block[1], (int64_t)1);
|
||||
CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_BF16);
|
||||
CHECK_EQ(w.enc.plane[1].block[1], (int64_t)32);
|
||||
CHECK(rad_enc_valid(&w.enc));
|
||||
|
||||
std::vector<uint8_t> codes((size_t)(10 * 32)), scales((size_t)(10 * 2 * 2));
|
||||
REQUIRE_EQ(ckpt_plane_rows(w, 0, 0, 10, codes.data(), &why), RAD_OK);
|
||||
REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 10, scales.data(), &why), RAD_OK);
|
||||
std::vector<float> f((size_t)(10 * 64));
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 10, f.data(), &why), RAD_OK);
|
||||
int bad_code = 0, bad_scale = 0, bad_f = 0, negative = 0;
|
||||
for (int64_t r = 0; r < 10; ++r) {
|
||||
const Ct& c = r < 4 ? gate : up;
|
||||
const int64_t n = r < 4 ? r : r - 4;
|
||||
for (int64_t k = 0; k < 64; ++k) {
|
||||
const int q = c.q[(size_t)n][(size_t)k];
|
||||
negative += q < 0;
|
||||
if ((int)rad_load_f32(codes.data(), RAD_I4, r * 64 + k) != q) ++bad_code;
|
||||
if (f[(size_t)(r * 64 + k)] != (float)q * c.scale[(size_t)(n * 2 + k / 32)]) ++bad_f;
|
||||
}
|
||||
for (int64_t g = 0; g < 2; ++g)
|
||||
if (rad_load_f32(scales.data(), RAD_BF16, r * 2 + g) != c.scale[(size_t)(n * 2 + g)])
|
||||
++bad_scale;
|
||||
}
|
||||
CHECK(negative > 0);
|
||||
CHECK_EQ(bad_code, 0);
|
||||
CHECK_EQ(bad_scale, 0);
|
||||
CHECK_EQ(bad_f, 0);
|
||||
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "norm", false, &w, &why), RAD_OK);
|
||||
CHECK(w.trivial);
|
||||
CHECK(!w.imported);
|
||||
remove_checkpoint(dir);
|
||||
}
|
||||
|
||||
/* WHAT IS NOT READ IS REFUSED, NOT MISREAD: an asymmetric config, a zero point beside a weight a
|
||||
* symmetric config describes, and a scale plane that is not one a group. */
|
||||
TEST(a_ct_int4_checkpoint_this_does_not_read_is_refused) {
|
||||
const Ct c = make_ct(4, 64, 32, 3);
|
||||
{
|
||||
std::vector<T> ts;
|
||||
add_ct(&ts, "p", c);
|
||||
const std::string dir = write_checkpoint(ts, ct_config("false", 32).c_str());
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() == Checkpoint::Import::None);
|
||||
CHECK(ck.import_refusal().find("symmetric") != std::string::npos);
|
||||
remove_checkpoint(dir);
|
||||
}
|
||||
{
|
||||
std::vector<T> ts;
|
||||
add_ct(&ts, "p", c);
|
||||
ts.push_back(T{ "p.weight_zero_point", "I32", { 4, 1 }, std::vector<uint8_t>(16, 0) });
|
||||
const std::string dir = write_checkpoint(ts, ct_config("true", 32).c_str());
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
CHECK(ckpt_resolve(ck, prog, "p", false, &w, &why) != RAD_OK);
|
||||
CHECK(why.find("zero point") != std::string::npos);
|
||||
remove_checkpoint(dir);
|
||||
}
|
||||
{
|
||||
std::vector<T> ts;
|
||||
add_ct(&ts, "p", c); /* scales a 32, the config says 16 */
|
||||
const std::string dir = write_checkpoint(ts, ct_config("true", 16).c_str());
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
CHECK(ckpt_resolve(ck, prog, "p", false, &w, &why) != RAD_OK);
|
||||
CHECK(why.find("weight_scale") != std::string::npos);
|
||||
remove_checkpoint(dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
{#
|
||||
Template: Google Gemma 4 Canonical Chat Template
|
||||
Author: Google Gemma Engineering Team
|
||||
Published: 2026-07-09
|
||||
Context: Fixed tool-calling loops, turn closures, and thinking content-ordering.
|
||||
#}
|
||||
{%- macro format_parameters(properties, required, filter_keys=false) -%}
|
||||
{%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%}
|
||||
{%- set ns = namespace(found_first=false) -%}
|
||||
{%- for key, value in properties | dictsort -%}
|
||||
{%- set add_comma = false -%}
|
||||
{%- if not filter_keys or key not in standard_keys -%}
|
||||
{%- if ns.found_first %},{% endif -%}
|
||||
{%- set ns.found_first = true -%}
|
||||
{{ key }}:{
|
||||
{%- if value['description'] -%}
|
||||
description:<|"|>{{ value['description'] }}<|"|>
|
||||
{%- set add_comma = true -%}
|
||||
{%- endif -%}
|
||||
{%- if value['type'] | upper == 'STRING' -%}
|
||||
{%- if value['enum'] -%}
|
||||
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
||||
enum:{{ format_argument(value['enum']) }}
|
||||
{%- endif -%}
|
||||
{%- elif value['type'] | upper == 'ARRAY' -%}
|
||||
{%- if value['items'] is mapping and value['items'] -%}
|
||||
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
||||
items:{
|
||||
{%- set ns_items = namespace(found_first=false) -%}
|
||||
{%- for item_key, item_value in value['items'] | dictsort -%}
|
||||
{%- if item_value is not none -%}
|
||||
{%- if ns_items.found_first %},{% endif -%}
|
||||
{%- set ns_items.found_first = true -%}
|
||||
{%- if item_key == 'properties' -%}
|
||||
properties:{
|
||||
{%- if item_value is mapping -%}
|
||||
{{- format_parameters(item_value, value['items']['required'] | default([])) -}}
|
||||
{%- endif -%}
|
||||
}
|
||||
{%- elif item_key == 'required' -%}
|
||||
required:[
|
||||
{%- for req_item in item_value -%}
|
||||
<|"|>{{- req_item -}}<|"|>
|
||||
{%- if not loop.last %},{% endif -%}
|
||||
{%- endfor -%}
|
||||
]
|
||||
{%- elif item_key == 'type' -%}
|
||||
{%- if item_value is string -%}
|
||||
type:{{ format_argument(item_value | upper) }}
|
||||
{%- else -%}
|
||||
type:{{ format_argument(item_value | map('upper') | list) }}
|
||||
{%- endif -%}
|
||||
{%- else -%}
|
||||
{{ item_key }}:{{ format_argument(item_value) }}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- if value['nullable'] %}
|
||||
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
||||
nullable:true
|
||||
{%- endif -%}
|
||||
{%- if value['type'] | upper == 'OBJECT' -%}
|
||||
{%- if value['properties'] is defined and value['properties'] is mapping -%}
|
||||
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
||||
properties:{
|
||||
{{- format_parameters(value['properties'], value['required'] | default([])) -}}
|
||||
}
|
||||
{%- elif value is mapping -%}
|
||||
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
||||
properties:{
|
||||
{{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}}
|
||||
}
|
||||
{%- endif -%}
|
||||
{%- if value['required'] -%}
|
||||
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
||||
required:[
|
||||
{%- for item in value['required'] | default([]) -%}
|
||||
<|"|>{{- item -}}<|"|>
|
||||
{%- if not loop.last %},{% endif -%}
|
||||
{%- endfor -%}
|
||||
]
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
||||
type:<|"|>{{ value['type'] | upper }}<|"|>}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endmacro -%}
|
||||
{%- macro format_function_declaration(tool_data) -%}
|
||||
declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|>
|
||||
{%- set params = tool_data['function']['parameters'] -%}
|
||||
{%- if params -%}
|
||||
,parameters:{
|
||||
{%- if params['properties'] -%}
|
||||
properties:{ {{- format_parameters(params['properties'], params['required']) -}} },
|
||||
{%- endif -%}
|
||||
{%- if params['required'] -%}
|
||||
required:[
|
||||
{%- for item in params['required'] -%}
|
||||
<|"|>{{- item -}}<|"|>
|
||||
{{- ',' if not loop.last -}}
|
||||
{%- endfor -%}
|
||||
],
|
||||
{%- endif -%}
|
||||
{%- if params['type'] -%}
|
||||
type:<|"|>{{- params['type'] | upper -}}<|"|>}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- if 'response' in tool_data['function'] -%}
|
||||
{%- set response_declaration = tool_data['function']['response'] -%}
|
||||
,response:{
|
||||
{%- if response_declaration['description'] -%}
|
||||
description:<|"|>{{- response_declaration['description'] -}}<|"|>,
|
||||
{%- endif -%}
|
||||
{%- if response_declaration['type'] | upper == 'OBJECT' -%}
|
||||
type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
}
|
||||
{%- endmacro -%}
|
||||
{%- macro format_argument(argument, escape_keys=True) -%}
|
||||
{%- if argument is none -%}
|
||||
{{- 'null' -}}
|
||||
{%- elif argument is string -%}
|
||||
{{- '<|"|>' + argument + '<|"|>' -}}
|
||||
{%- elif argument is boolean -%}
|
||||
{{- 'true' if argument else 'false' -}}
|
||||
{%- elif argument is mapping -%}
|
||||
{{- '{' -}}
|
||||
{%- set ns = namespace(found_first=false) -%}
|
||||
{%- for key, value in argument | dictsort -%}
|
||||
{%- if ns.found_first %},{% endif -%}
|
||||
{%- set ns.found_first = true -%}
|
||||
{%- if escape_keys -%}
|
||||
{{- '<|"|>' + key + '<|"|>' -}}
|
||||
{%- else -%}
|
||||
{{- key -}}
|
||||
{%- endif -%}
|
||||
:{{- format_argument(value, escape_keys=escape_keys) -}}
|
||||
{%- endfor -%}
|
||||
{{- '}' -}}
|
||||
{%- elif argument is sequence -%}
|
||||
{{- '[' -}}
|
||||
{%- for item in argument -%}
|
||||
{{- format_argument(item, escape_keys=escape_keys) -}}
|
||||
{%- if not loop.last %},{% endif -%}
|
||||
{%- endfor -%}
|
||||
{{- ']' -}}
|
||||
{%- else -%}
|
||||
{{- argument -}}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- macro strip_thinking(text) -%}
|
||||
{%- set ns = namespace(result='') -%}
|
||||
{%- for part in text.split('<channel|>') -%}
|
||||
{%- if '<|channel>' in part -%}
|
||||
{%- set ns.result = ns.result + part.split('<|channel>')[0] -%}
|
||||
{%- else -%}
|
||||
{%- set ns.result = ns.result + part -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{{- ns.result | trim -}}
|
||||
{%- endmacro -%}
|
||||
|
||||
{%- macro format_tool_response_block(tool_name, response) -%}
|
||||
{{- '<|tool_response>' -}}
|
||||
{%- if response is mapping -%}
|
||||
{{- 'response:' + tool_name + '{' -}}
|
||||
{%- for key, value in response | dictsort -%}
|
||||
{{- key -}}:{{- format_argument(value, escape_keys=False) -}}
|
||||
{%- if not loop.last %},{% endif -%}
|
||||
{%- endfor -%}
|
||||
{{- '}' -}}
|
||||
{%- else -%}
|
||||
{{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}}
|
||||
{%- endif -%}
|
||||
{{- '<tool_response|>' -}}
|
||||
{%- endmacro -%}
|
||||
|
||||
{#- ===== SETUP ===== -#}
|
||||
{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%}
|
||||
{%- set loop_messages = messages -%}
|
||||
{%- set enable_thinking = enable_thinking | default(false) -%}
|
||||
{%- set preserve_thinking = preserve_thinking | default(false) -%}
|
||||
{{- bos_token -}}
|
||||
{#- Handle System/Tool Definitions Block -#}
|
||||
{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%}
|
||||
{{- '<|turn>system\n' -}}
|
||||
{#- Inject Thinking token at the very top of the FIRST system turn -#}
|
||||
{%- if enable_thinking -%}
|
||||
{{- '<|think|>\n' -}}
|
||||
{%- set ns.prev_message_type = 'think' -%}
|
||||
{%- endif -%}
|
||||
{%- if messages and messages[0]['role'] in ['system', 'developer'] -%}
|
||||
{%- if messages[0]['content'] is string -%}
|
||||
{{- messages[0]['content'] | trim -}}
|
||||
{%- elif messages[0]['content'] is sequence -%}
|
||||
{%- for item in messages[0]['content'] -%}
|
||||
{{- item['text'] | trim + ' '-}}
|
||||
{%- endfor -%}
|
||||
{%- endif -%}
|
||||
{%- set loop_messages = messages[1:] -%}
|
||||
{%- endif -%}
|
||||
{%- if tools -%}
|
||||
{%- for tool in tools %}
|
||||
{{- '<|tool>' -}}
|
||||
{{- format_function_declaration(tool) | trim -}}
|
||||
{{- '<tool|>' -}}
|
||||
{%- endfor %}
|
||||
{%- set ns.prev_message_type = 'tool' -%}
|
||||
{%- endif -%}
|
||||
{{- '<turn|>\n' -}}
|
||||
{%- endif %}
|
||||
|
||||
{#- Pre-scan: find last user message index for reasoning guard -#}
|
||||
{%- set ns_turn = namespace(last_user_idx=-1) -%}
|
||||
{%- for i in range(loop_messages | length) -%}
|
||||
{%- if loop_messages[i]['role'] == 'user' -%}
|
||||
{%- set ns_turn.last_user_idx = i -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
|
||||
{#- Loop through messages -#}
|
||||
{%- for message in loop_messages -%}
|
||||
{%- if message['role'] != 'tool' -%}
|
||||
{%- set ns.prev_message_type = None -%}
|
||||
{%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}
|
||||
{#- Detect continuation using tracked state — O(1) instead of O(n) backward scan -#}
|
||||
{%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%}
|
||||
{%- if not continue_same_model_turn -%}
|
||||
{{- '<|turn>' + role + '\n' }}
|
||||
|
||||
{%- endif -%}
|
||||
|
||||
{#- Render reasoning/reasoning_content as thinking channel -#}
|
||||
{%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%}
|
||||
{%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%}
|
||||
{%- if thinking_text and thinking_gate -%}
|
||||
{{- '<|channel>thought\n' + thinking_text + '\n<channel|>' -}}
|
||||
{%- endif -%}
|
||||
|
||||
{%- if message.get('tool_calls') -%}
|
||||
{%- for tool_call in message.get('tool_calls') -%}
|
||||
{%- set function = tool_call['function'] -%}
|
||||
{{- '<|tool_call>call:' + function['name'] + '{' -}}
|
||||
{%- if function['arguments'] is mapping -%}
|
||||
{%- set ns_args = namespace(found_first=false) -%}
|
||||
{%- for key, value in function['arguments'] | dictsort -%}
|
||||
{%- if ns_args.found_first %},{% endif -%}
|
||||
{%- set ns_args.found_first = true -%}
|
||||
{{- key -}}:{{- format_argument(value, escape_keys=False) -}}
|
||||
{%- endfor -%}
|
||||
{%- elif function['arguments'] is none -%}
|
||||
{%- else -%}
|
||||
{{- raise_exception(
|
||||
"chat_template: tool_calls[].function.arguments must be a "
|
||||
"JSON object (mapping), not a string. Deserialize arguments "
|
||||
"before passing to the template."
|
||||
) -}}
|
||||
{%- endif -%}
|
||||
{{- '}<tool_call|>' -}}
|
||||
{%- endfor -%}
|
||||
{%- set ns.prev_message_type = 'tool_call' -%}
|
||||
{%- endif -%}
|
||||
|
||||
{%- set ns_tr_out = namespace(flag=false) -%}
|
||||
{%- if message.get('tool_responses') -%}
|
||||
{#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#}
|
||||
{%- for tool_response in message.get('tool_responses') -%}
|
||||
{{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}}
|
||||
{%- set ns_tr_out.flag = true -%}
|
||||
{%- set ns.prev_message_type = 'tool_response' -%}
|
||||
{%- endfor -%}
|
||||
{%- elif message.get('tool_calls') -%}
|
||||
{#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#}
|
||||
{%- set ns_tool_scan = namespace(stopped=false) -%}
|
||||
{%- for k in range(loop.index0 + 1, loop_messages | length) -%}
|
||||
{%- if ns_tool_scan.stopped -%}
|
||||
{%- elif loop_messages[k]['role'] != 'tool' -%}
|
||||
{%- set ns_tool_scan.stopped = true -%}
|
||||
{%- else -%}
|
||||
{%- set follow = loop_messages[k] -%}
|
||||
{#- Resolve tool_call_id to function name -#}
|
||||
{%- set ns_tname = namespace(name=follow.get('name') or 'unknown') -%}
|
||||
{%- for tc in message.get('tool_calls') -%}
|
||||
{%- if tc.get('id') == follow.get('tool_call_id') -%}
|
||||
{%- set ns_tname.name = tc['function']['name'] -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{#- Handle content as string or content-parts array -#}
|
||||
{%- set tool_body = follow.get('content') -%}
|
||||
{%- if tool_body is string -%}
|
||||
{{- format_tool_response_block(ns_tname.name, tool_body) -}}
|
||||
{%- elif tool_body is sequence and tool_body is not string -%}
|
||||
{%- set ns_txt = namespace(s='') -%}
|
||||
{%- for part in tool_body -%}
|
||||
{%- if part.get('type') == 'text' -%}
|
||||
{%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{{- format_tool_response_block(ns_tname.name, ns_txt.s) -}}
|
||||
{%- for part in tool_body -%}
|
||||
{%- if part.get('type') in ['image', 'image_url'] -%}
|
||||
{{- '<|image|>' -}}
|
||||
{%- elif part.get('type') in ['audio', 'input_audio'] -%}
|
||||
{{- '<|audio|>' -}}
|
||||
{%- elif part.get('type') == 'video' -%}
|
||||
{{- '<|video|>' -}}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- else -%}
|
||||
{{- format_tool_response_block(ns_tname.name, tool_body) -}}
|
||||
{%- endif -%}
|
||||
{%- set ns_tr_out.flag = true -%}
|
||||
{%- set ns.prev_message_type = 'tool_response' -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endif -%}
|
||||
|
||||
{%- set captured_content -%}
|
||||
{%- if message.get('content') is string -%}
|
||||
{%- if role == 'model' -%}
|
||||
{{- strip_thinking(message['content']) -}}
|
||||
{%- else -%}
|
||||
{{- message['content'] | trim -}}
|
||||
{%- endif -%}
|
||||
{%- elif message.get('content') is sequence -%}
|
||||
{%- for item in message['content'] -%}
|
||||
{%- if item.get('type') == 'text' -%}
|
||||
{%- if role == 'model' -%}
|
||||
{{- strip_thinking(item['text']) -}}
|
||||
{%- else -%}
|
||||
{{- item['text'] | trim -}}
|
||||
{%- endif -%}
|
||||
{%- elif item.get('type') in ['image', 'image_url'] -%}
|
||||
{{- '<|image|>' -}}
|
||||
{%- elif item.get('type') in ['audio', 'input_audio'] -%}
|
||||
{{- '<|audio|>' -}}
|
||||
{%- elif item.get('type') == 'video' -%}
|
||||
{{- '<|video|>' -}}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endif -%}
|
||||
{%- endset -%}
|
||||
|
||||
{{- captured_content -}}
|
||||
{%- set has_content = captured_content | trim | length > 0 -%}
|
||||
|
||||
{#- Forward-scan: find next non-tool message role for continuation detection -#}
|
||||
{%- set next_nt = namespace(role=None, found=false) -%}
|
||||
{%- for j in range(loop.index0 + 1, loop_messages | length) -%}
|
||||
{%- if not next_nt.found -%}
|
||||
{%- if loop_messages[j]['role'] != 'tool' -%}
|
||||
{%- set next_nt.role = loop_messages[j]['role'] -%}
|
||||
{%- set next_nt.found = true -%}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
|
||||
{%- set continues_into_next = (
|
||||
role == 'model'
|
||||
and next_nt.role == 'assistant'
|
||||
and (not message.get('tool_calls') or ns_tr_out.flag)
|
||||
) -%}
|
||||
|
||||
{%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%}
|
||||
{{- '<|tool_response>' -}}
|
||||
{%- elif continues_into_next -%}
|
||||
{%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%}
|
||||
{{- '<turn|>\n' -}}
|
||||
{%- endif -%}
|
||||
|
||||
{#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#}
|
||||
{%- set ns.prev_non_tool_role = message['role'] -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
|
||||
{%- if add_generation_prompt -%}
|
||||
{%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}
|
||||
{{- '<|turn>model\n' -}}
|
||||
{%- if not enable_thinking -%}
|
||||
{{- '<|channel>thought\n<channel|>' -}}
|
||||
{%- endif -%}
|
||||
{%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%}
|
||||
{{- '<|channel>thought\n' -}}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
@@ -65,6 +65,11 @@ int Bench::load(const Model& m, const std::string& jinja, std::string* why) {
|
||||
*why = "the template did not compile";
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (m.declared) {
|
||||
const int st = chat_format_from_abi(m.declared, &fmt_, why);
|
||||
if (st < 0) return st;
|
||||
return ReplyFormat::compile(fmt_, &rf_, why);
|
||||
}
|
||||
std::string refused;
|
||||
int st = chat_format_from_template(jinja, m.bos, m.eos, &fmt_, &refused, why);
|
||||
if (st < 0) return st;
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
#include "text/chatparse.h"
|
||||
#include "toolparse_legacy.h"
|
||||
|
||||
struct RadChatFormat;
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <memory>
|
||||
@@ -31,6 +33,9 @@ struct Model {
|
||||
std::string dir; /* under the fixture root */
|
||||
std::string bos, eos;
|
||||
std::vector<std::string> terminators; /* its end-of-generation spellings */
|
||||
/* The architecture plugin's reply format, when it declares one; null derives the format from
|
||||
* the template, as the engine does. */
|
||||
const RadChatFormat* declared = nullptr;
|
||||
};
|
||||
const std::vector<Model>& models();
|
||||
|
||||
|
||||
+146
-5
@@ -943,6 +943,106 @@ TEST(kv_preemption_by_recompute_and_the_undeadlockable_request) {
|
||||
CHECK_OK(f.kv.ensure(newcomer, per));
|
||||
}
|
||||
|
||||
/* THE WINDOW BEHIND A PREFIX HIT: a checkpoint slot carries window_blocks pages a WINDOW group,
|
||||
* window_rows() names the pages a query at P reads from the table that wrote them, seed_window()
|
||||
* gives a resumed sequence fresh pages at the same floor -- and a table whose floor moved past it
|
||||
* answers false, which is the fallback (no snapshot, a full re-prefill). */
|
||||
TEST(kv_window_snapshot_rows_and_seed) {
|
||||
std::vector<KVGroupInfo> g;
|
||||
g.push_back(null_group());
|
||||
KVGroupInfo k;
|
||||
k.name = "swa";
|
||||
k.decl.kind = RAD_KV_WINDOW;
|
||||
k.decl.dtype = RAD_BF16;
|
||||
k.decl.n_head_kv = 2;
|
||||
k.decl.head_dim = 8;
|
||||
k.decl.window = 64;
|
||||
k.block_size = 16;
|
||||
k.layers = { 0 };
|
||||
g.push_back(k);
|
||||
Config cfg = small_config();
|
||||
Pools p;
|
||||
CHECK_OK(p.configure(cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator()));
|
||||
KVManager kv;
|
||||
CHECK_OK(kv.configure(g, cfg, p.kv()));
|
||||
CHECK(kv.has_window_snapshot());
|
||||
CHECK_EQ(kv.checkpoint_bytes(), 5 * kv.plan(G_FULL)->bytes_per_block);
|
||||
|
||||
CHECK_OK(kv.add_sequence(1));
|
||||
CHECK_OK(kv.ensure(1, 400)); /* a prompt of 400 in one chunk */
|
||||
std::vector<int32_t> rows;
|
||||
CHECK(kv.window_rows(1, 400, &rows));
|
||||
CHECK_EQ((long long)rows.size(), 5ll); /* padded to window_blocks */
|
||||
/* A query at 400 reads back to 337: blocks 21..24, the floor recycle_window keeps. */
|
||||
for (int j = 0; j < 4; ++j) CHECK_EQ(rows[(size_t)j], kv.block_table(1, G_FULL)[(size_t)(21 + j)]);
|
||||
CHECK_EQ(rows[4], -1);
|
||||
/* A short prefix: the window starts at zero and the rest is padding. */
|
||||
CHECK(kv.window_rows(1, 32, &rows));
|
||||
CHECK_EQ(rows[0], kv.block_table(1, G_FULL)[0]);
|
||||
CHECK_EQ(rows[2], -1);
|
||||
/* Not on a block: no rows. */
|
||||
CHECK(!kv.window_rows(1, 40, &rows));
|
||||
/* The floor moved past it (a decode step slid the window): the fallback. */
|
||||
CHECK_OK(kv.ensure(1, 401));
|
||||
CHECK(!kv.window_rows(1, 64, &rows));
|
||||
CHECK(kv.window_rows(1, 400, &rows));
|
||||
|
||||
/* A resumed sequence: seeded at the floor, extended from there, and its rows are its own. */
|
||||
CHECK_OK(kv.add_sequence(2));
|
||||
CHECK_OK(kv.seed_window(2, 400));
|
||||
CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll);
|
||||
CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 4ll);
|
||||
CHECK_EQ(kv.seq_tokens(2), 400ll);
|
||||
CHECK_OK(kv.ensure(2, 432, 400));
|
||||
CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll);
|
||||
CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 6ll);
|
||||
std::vector<int32_t> rows2;
|
||||
CHECK(kv.window_rows(2, 400, &rows2));
|
||||
for (int j = 0; j < 4; ++j) CHECK_EQ(rows2[(size_t)j], kv.block_table(2, G_FULL)[(size_t)j]);
|
||||
/* A table already holding window pages is not seeded twice. */
|
||||
CHECK_EQ(kv.seed_window(2, 400), RAD_E_STATE);
|
||||
kv.free_sequence(1);
|
||||
kv.free_sequence(2);
|
||||
}
|
||||
|
||||
/* A SNAPSHOT ONLY WHERE A HIT RESUMES FROM IT: the trunk's window in a model with no linear state.
|
||||
* A model with linear state re-prefills a hit on a windowed trunk, and a drafter's window is
|
||||
* recomputed by draft refill, so a window section in either slot would be copied at every
|
||||
* checkpoint and never read. */
|
||||
TEST(kv_window_snapshot_only_where_a_hit_resumes_from_it) {
|
||||
KVGroupInfo w;
|
||||
w.name = "swa";
|
||||
w.decl.kind = RAD_KV_WINDOW;
|
||||
w.decl.dtype = RAD_BF16;
|
||||
w.decl.n_head_kv = 2;
|
||||
w.decl.head_dim = 8;
|
||||
w.decl.window = 64;
|
||||
w.block_size = 16;
|
||||
w.layers = { 6 };
|
||||
const Config cfg = small_config();
|
||||
{ /* beside linear state: the slot holds the state and nothing more */
|
||||
std::vector<KVGroupInfo> g = hybrid_groups();
|
||||
g.push_back(w);
|
||||
Pools p;
|
||||
CHECK_OK(p.configure(cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator()));
|
||||
KVManager kv;
|
||||
CHECK_OK(kv.configure(g, cfg, p.kv()));
|
||||
CHECK(!kv.has_window_snapshot());
|
||||
CHECK_EQ(kv.checkpoint_bytes(), 16384ll);
|
||||
}
|
||||
{ /* a drafter's own window over a full-attention trunk */
|
||||
std::vector<KVGroupInfo> g = hybrid_groups(/*with_linear=*/false);
|
||||
w.drafter = true;
|
||||
g.push_back(w);
|
||||
Pools p;
|
||||
CHECK_OK(p.configure(cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator()));
|
||||
KVManager kv;
|
||||
CHECK_OK(kv.configure(g, cfg, p.kv()));
|
||||
CHECK(!kv.has_window_snapshot());
|
||||
CHECK_EQ(kv.checkpoint_bytes(), 0ll);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(kv_window_group_recycles_below_the_window) {
|
||||
std::vector<KVGroupInfo> g;
|
||||
g.push_back(null_group());
|
||||
@@ -965,19 +1065,60 @@ TEST(kv_window_group_recycles_below_the_window) {
|
||||
CHECK_OK(kv.configure(g, cfg, p.kv()));
|
||||
/* window 64 at block 16 is 4 blocks plus one for the straddle. */
|
||||
CHECK_EQ(kv.plan(G_FULL)->window_blocks, 5ll);
|
||||
/* Sized against the cap, not against the whole budget: blocks past the window are memory
|
||||
* nobody will ever address. */
|
||||
CHECK_EQ(kv.total_blocks(G_FULL), cfg.max_seqs * 5);
|
||||
/* Sized against the cap, not against the whole budget: a window a sequence plus one step's
|
||||
* worth of tokens (max_tok) and a straddle block a sequence -- a chunk's own blocks are held
|
||||
* beside the window behind its first query. Past that is memory nobody will ever address. */
|
||||
CHECK_EQ(kv.total_blocks(G_FULL), cfg.max_seqs * 5 + (cfg.max_tok + 15) / 16 + cfg.max_seqs);
|
||||
|
||||
const int64_t n0 = kv.free_blocks(G_FULL);
|
||||
CHECK_OK(kv.add_sequence(1));
|
||||
CHECK_OK(kv.ensure(1, 80));
|
||||
CHECK_OK(kv.ensure(1, 80)); /* a chunk from 0: all of it held */
|
||||
CHECK_EQ(kv.first_block_pos(1, G_FULL), 0ll);
|
||||
CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 5ll);
|
||||
/* A chunk from 80 to 400: its first query (80) reads back to 17, so block 1 stays and only
|
||||
* block 0 goes -- NOT the window behind 400, which left rows 80..335 with no keys. */
|
||||
CHECK_OK(kv.ensure(1, 400));
|
||||
CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 5ll); /* recycled, not grown */
|
||||
CHECK_EQ(kv.first_block_pos(1, G_FULL), 16ll);
|
||||
CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 24ll);
|
||||
/* A decode step from 400: back to the window, recycled rather than grown. */
|
||||
CHECK_OK(kv.ensure(1, 401));
|
||||
CHECK_EQ(kv.first_block_pos(1, G_FULL), 336ll);
|
||||
CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 5ll);
|
||||
CHECK_EQ(kv.free_blocks(G_FULL), n0 - 5);
|
||||
kv.free_sequence(1);
|
||||
CHECK_EQ(kv.free_blocks(G_FULL), n0);
|
||||
|
||||
/* THE PROMPT LONGER THAN THE WINDOW, in one chunk from 0: every position keeps its slot. The
|
||||
* old rule rebased this table at ceil(400/16) - 5 = 20 blocks, and a sliding layer read no
|
||||
* keys at all for positions 0..319. */
|
||||
CHECK_OK(kv.add_sequence(2));
|
||||
CHECK_OK(kv.ensure(2, 400));
|
||||
CHECK_EQ(kv.first_block_pos(2, G_FULL), 0ll);
|
||||
CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 25ll);
|
||||
/* And the scheduler's form names the step's first query itself: a chunk grown in the same
|
||||
* step (ensure called twice) keeps what the first call's first query reads. */
|
||||
CHECK_OK(kv.ensure(2, 432, 400));
|
||||
CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll);
|
||||
CHECK_OK(kv.ensure(2, 464, 400));
|
||||
CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll);
|
||||
CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 8ll);
|
||||
kv.free_sequence(2);
|
||||
CHECK_EQ(kv.free_blocks(G_FULL), n0);
|
||||
|
||||
/* A COMMITTED CHUNK GIVES ITS BLOCKS BACK at once: trim_window to the new end keeps the window
|
||||
* behind it and nothing else, so a prefill that waits a step for its next chunk holds a window
|
||||
* and not a chunk. */
|
||||
CHECK_OK(kv.add_sequence(3));
|
||||
CHECK_OK(kv.ensure(3, 400));
|
||||
CHECK_EQ((long long)kv.block_table(3, G_FULL).size(), 25ll);
|
||||
kv.trim_window(3, 400);
|
||||
CHECK_EQ(kv.first_block_pos(3, G_FULL), 336ll);
|
||||
CHECK_EQ((long long)kv.block_table(3, G_FULL).size(), 4ll);
|
||||
CHECK_EQ(kv.free_blocks(G_FULL), n0 - 4);
|
||||
CHECK_OK(kv.ensure(3, 401));
|
||||
CHECK_EQ((long long)kv.block_table(3, G_FULL).size(), 5ll);
|
||||
kv.free_sequence(3);
|
||||
CHECK_EQ(kv.free_blocks(G_FULL), n0);
|
||||
}
|
||||
|
||||
TEST(kv_conv_slot_is_a_rolling_window) {
|
||||
|
||||
+142
-5
@@ -254,11 +254,11 @@ TEST(plugin_surface) {
|
||||
* which is a decision and not an oversight (docs/OPS.md). */
|
||||
TEST(op_vocabulary) {
|
||||
static const char* kOps[] = {
|
||||
"rmsnorm", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter",
|
||||
"layernorm", "add", "mul", "mul_weight", "silu_mul", "act_mul", "seg_mean", "pool_rows",
|
||||
"relu", "clamp", "conv2d", "conv1d_dw", "rel_sinusoid", "attn_local_rel", "gelu", "silu",
|
||||
"sigmoid", "fill", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv",
|
||||
"causal_conv1d",
|
||||
"rmsnorm", "rmsnorm_p", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter",
|
||||
"layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean",
|
||||
"pool_rows", "relu", "clamp", "conv2d", "conv1d_dw", "rel_sinusoid", "attn_local_rel",
|
||||
"gelu", "silu", "sigmoid", "logit_softcap", "scale", "fill",
|
||||
"gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", "causal_conv1d",
|
||||
"embed_lookup_q", "cast",
|
||||
"scale_rows",
|
||||
"softmax",
|
||||
@@ -450,6 +450,24 @@ TEST(op_rmsnorm) {
|
||||
CHECK_NEAR(y2.at(3), 4 * s, 1e-6);
|
||||
}
|
||||
|
||||
/* The weightless rmsnorm: same normalisation as rmsnorm with no gain, so the row divides by its
|
||||
* rms and stops. The literals are exactly op_rmsnorm's, because a plain norm IS rmsnorm whose gain
|
||||
* is one. */
|
||||
TEST(op_rmsnorm_p) {
|
||||
T x(RAD_F32, {1, 4}); x.f({1, 2, 3, 4});
|
||||
T y(RAD_F32, {1, 4});
|
||||
A a; a.t(x).t(y).i("M", 1).i("n", 4).d("eps", 0).s("dtype", "f32");
|
||||
CHECK_OK(run("rmsnorm_p", a));
|
||||
/* rms = sqrt((1+4+9+16)/4) = sqrt(7.5) = 2.7386128 */
|
||||
const float s = 1.0f / 2.7386128f;
|
||||
CHECK_NEAR(y.at(0), 1 * s, 1e-6);
|
||||
CHECK_NEAR(y.at(3), 4 * s, 1e-6);
|
||||
|
||||
/* A non-positive n is not a normalisation, so it is refused rather than answered. */
|
||||
A bb; bb.t(x).t(y).i("M", 1).i("n", 0).d("eps", 0).s("dtype", "f32");
|
||||
CHECK(run("rmsnorm_p", bb) != RAD_OK);
|
||||
}
|
||||
|
||||
TEST(op_rmsnorm_add) {
|
||||
T x(RAD_F32, {1, 2}); x.f({1, 3});
|
||||
T res(RAD_F32, {1, 2}); res.f({1, 1});
|
||||
@@ -523,6 +541,70 @@ TEST(op_silu_mul_and_unary) {
|
||||
CHECK_NEAR(s.at(1), 0.73105858f, 1e-6);
|
||||
}
|
||||
|
||||
/* Gemma's gated FFN, on paper: same fused layout as silu_mul (gate the first half, up the second)
|
||||
* but the gate runs the tanh GELU, not silu. gelu_tanh matches the gemm_nt_bias tanh epilogue and
|
||||
* differs from the unary `gelu` (exact erf) -- the check at 1.0 pins that difference: erf gelu(1) is
|
||||
* 0.84134..., the tanh form is 0.84119.... */
|
||||
TEST(op_gelu_mul) {
|
||||
T gu(RAD_F32, {1, 4}); gu.f({1, 2, 3, 4}); /* gate [1,2], up [3,4] */
|
||||
T y(RAD_F32, {1, 2});
|
||||
A a; a.t(gu).t(y).i("M", 1).i("n", 2).s("dtype", "f32");
|
||||
CHECK_OK(run("gelu_mul", a));
|
||||
CHECK_NEAR(y.at(0), 0.84119199f * 3.0f, 1e-6); /* gelu_tanh(1) * up */
|
||||
CHECK_NEAR(y.at(1), 1.95459769f * 4.0f, 1e-6); /* gelu_tanh(2) * up */
|
||||
/* And the negative side, where tanh gelu and erf gelu drift furthest. */
|
||||
T gx(RAD_F32, {1, 4}); gx.f({-2, -1, 3, 4}); /* gate [-2,-1], up [3,4] */
|
||||
T gy(RAD_F32, {1, 2});
|
||||
A b; b.t(gx).t(gy).i("M", 1).i("n", 2).s("dtype", "f32");
|
||||
CHECK_OK(run("gelu_mul", b));
|
||||
CHECK_NEAR(gy.at(0), -0.04540231f * 3.0f, 1e-6); /* gelu_tanh(-2) * up */
|
||||
CHECK_NEAR(gy.at(1), -0.15880801f * 4.0f, 1e-6); /* gelu_tanh(-1) * up */
|
||||
}
|
||||
|
||||
/* The final-logit softcap, on paper. `cap` at 30 -- Gemma's value -- and the input the kernel
|
||||
* actually sees after a logits_gemm, reduced to the five ratios the formula can take: 0, cap/2,
|
||||
* both signs of cap, and 2 cap. Every ratio is exact in f32, so the literals below are tanh of a
|
||||
* small integer, and the check is the f32 rounding of the product and nothing else. */
|
||||
TEST(op_logit_softcap) {
|
||||
T x(RAD_F32, {5}); x.f({ 0.0f, 15.0f, 30.0f, -30.0f, 60.0f });
|
||||
T y(RAD_F32, {5});
|
||||
A a; a.t(x).t(y).i("M", 1).i("n", 5).d("cap", 30.0).s("dtype", "f32");
|
||||
CHECK_OK(run("logit_softcap", a));
|
||||
CHECK_EQ(y.at(0), 0.0f);
|
||||
CHECK_NEAR(y.at(1), 30.0f * 0.4621171573f, 1e-5); /* tanh(1/2) */
|
||||
CHECK_NEAR(y.at(2), 30.0f * 0.7615941560f, 1e-5); /* tanh(1) */
|
||||
CHECK_NEAR(y.at(3), -30.0f * 0.7615941560f, 1e-5); /* tanh(-1) */
|
||||
CHECK_NEAR(y.at(4), 30.0f * 0.9640275801f, 1e-5); /* tanh(2) */
|
||||
|
||||
/* A non-positive cap is a division by zero in every lane, so it is refused, not answered. */
|
||||
T y2(RAD_F32, {5});
|
||||
A b; b.t(x).t(y2).i("M", 1).i("n", 5).d("cap", 0.0).s("dtype", "f32");
|
||||
CHECK(run("logit_softcap", b) != RAD_OK);
|
||||
}
|
||||
|
||||
/* The per-tensor scalar scale. `s` is a [1] weight broadcast over every element, so the answer is
|
||||
* a literal times the literal -- not a second call into the same multiply. The negative case is a
|
||||
* scalar with no element: that is a shape error, not a broadcast of zero (a zero scalar would be a
|
||||
* plausible number, which is the thing this file's rule exists to rule out). */
|
||||
TEST(op_scale) {
|
||||
T x(RAD_F32, {5}); x.f({ 0.0f, 2.0f, 4.0f, -6.0f, 8.0f });
|
||||
T s(RAD_F32, {1}); s.f({ 3.0f });
|
||||
T y(RAD_F32, {5});
|
||||
A a; a.t(x).t(s).t(y).i("M", 1).i("n", 5).s("dtype", "f32");
|
||||
CHECK_OK(run("scale", a));
|
||||
CHECK_EQ(y.at(0), 0.0f);
|
||||
CHECK_EQ(y.at(1), 6.0f);
|
||||
CHECK_EQ(y.at(2), 12.0f);
|
||||
CHECK_EQ(y.at(3), -18.0f);
|
||||
CHECK_EQ(y.at(4), 24.0f);
|
||||
|
||||
/* A scalar with no element is a shape error, not a broadcast of zero. */
|
||||
T s0(RAD_F32, {0});
|
||||
T y2(RAD_F32, {5});
|
||||
A b; b.t(x).t(s0).t(y2).i("M", 1).i("n", 5).s("dtype", "f32");
|
||||
CHECK(run("scale", b) != RAD_OK);
|
||||
}
|
||||
|
||||
/* The quantised gather. Three things, and the scale is the least interesting of them.
|
||||
*
|
||||
* The E4M3 codes are chosen so their VALUES are exact and writable as literals: 0x38 is 1.0,
|
||||
@@ -1704,6 +1786,16 @@ TEST(op_vocab_edges) {
|
||||
CHECK_EQ(x.at(2), 1.0f); CHECK_EQ(x.at(3), 2.0f);
|
||||
CHECK_EQ(x.at(4), 0.0f); CHECK_EQ(x.at(5), 0.0f); /* a negative id is padding */
|
||||
|
||||
/* A runtime gather scale multiplies the rows that are found; a missed row stays zero, not
|
||||
* zero times the scale. Absent it, the lookup is the plain gather (the first block). */
|
||||
T xs(RAD_F32, {3, 2});
|
||||
A as; as.t(tok).t(wte).t(xs).i("M", 3).i("n_embd", 2).i("n_vocab", 3)
|
||||
.s("dtype", "f32").d("mult", 2.0);
|
||||
CHECK_OK(run("embed_lookup", as));
|
||||
CHECK_EQ(xs.at(0), 10.0f); CHECK_EQ(xs.at(1), 12.0f);
|
||||
CHECK_EQ(xs.at(2), 2.0f); CHECK_EQ(xs.at(3), 4.0f);
|
||||
CHECK_EQ(xs.at(4), 0.0f); CHECK_EQ(xs.at(5), 0.0f);
|
||||
|
||||
/* An id at or above n_vocab fails the launch rather than returning a plausible row. */
|
||||
T bad(RAD_I32, {1}); bad.n({7});
|
||||
T x2(RAD_F32, {1, 2});
|
||||
@@ -2453,6 +2545,51 @@ TEST(op_rope_multi_component) {
|
||||
}
|
||||
}
|
||||
|
||||
/* THE PROPORTIONAL LADDER. With head_dim wider than rotary_dim, the two ladders give frequency 1 a
|
||||
* different angle: `rotary` divides by rotary_dim, `head` by head_dim. And they pair different
|
||||
* channels: `rotary` is a complete rotary of rotary_dim's own width, pair i = (i, i + rot/2) with
|
||||
* the tail past rot untouched, while `head` is HF's proportional RoPE
|
||||
* (_compute_proportional_rope_parameters + rotate_half over the WHOLE head): pair i is
|
||||
* (i, i + head_dim/2) and every frequency past rot/2 is zero, so only those rot/2 pairs turn.
|
||||
* Frequency 0 is theta^0 under both; frequency 1 pins the ladder, the partner index the pairing. */
|
||||
TEST(op_rope_ladder) {
|
||||
const int64_t hd = 8, rot = 4; /* two frequencies, a partial rotary (hd > rot) */
|
||||
const float pos = 7.0f;
|
||||
for (const char* lad : { "rotary", "head" }) {
|
||||
const bool head = lad[0] == 'h';
|
||||
const int64_t den = head ? hd : rot;
|
||||
const int64_t poff = head ? hd / 2 : rot / 2; /* where pair i's partner sits */
|
||||
T got(RAD_F32, { 1, hd });
|
||||
got.f(std::vector<float>(hd, 1.0f));
|
||||
T p1(RAD_I32, { 1 }); p1.n({ 7 });
|
||||
A a; a.t(got).t(p1).i("M", 1).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 0)
|
||||
.d("theta", 100).d("scale", 1).s("mode", "neox").i("rotary_dim", rot)
|
||||
.s("ladder", lad);
|
||||
CHECK_OK(run("rope", a));
|
||||
std::vector<bool> turned(hd, false);
|
||||
for (int i = 0; i < rot / 2; ++i) {
|
||||
const float inv = 1.0f / std::pow(100.0f, (float)(2 * i) / (float)den);
|
||||
const float ang = pos * inv;
|
||||
CHECK_NEAR(got.at(i), std::cos(ang) - std::sin(ang), 1e-5);
|
||||
CHECK_NEAR(got.at(i + poff), std::sin(ang) + std::cos(ang), 1e-5);
|
||||
turned[i] = turned[i + poff] = true;
|
||||
}
|
||||
for (int d = 0; d < hd; ++d)
|
||||
if (!turned[d]) CHECK_EQ(got.at(d), 1.0f); /* every other channel untouched */
|
||||
}
|
||||
/* absent ladder == rotary: the models that never set it keep the old angles bit-for-bit */
|
||||
{
|
||||
T got(RAD_F32, { 1, hd });
|
||||
got.f(std::vector<float>(hd, 1.0f));
|
||||
T p1(RAD_I32, { 1 }); p1.n({ 7 });
|
||||
A a; a.t(got).t(p1).i("M", 1).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 0)
|
||||
.d("theta", 100).d("scale", 1).s("mode", "neox").i("rotary_dim", rot);
|
||||
CHECK_OK(run("rope", a));
|
||||
const float ang = pos * (1.0f / std::pow(100.0f, (float)(2 * 1) / (float)rot));
|
||||
CHECK_NEAR(got.at(1), std::cos(ang) - std::sin(ang), 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
/* ALIGNED CORNERS: a grid's first and last rows and columns sit exactly on the table's, so a
|
||||
* corner patch reads one table row whole; an interior one blends four. */
|
||||
TEST(op_grid_embed) {
|
||||
|
||||
+299
-2
@@ -9,6 +9,7 @@
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "sched/scheduler.h"
|
||||
#include "sched/advance_impl.h"
|
||||
#include "sched/derive.h"
|
||||
#include "server/sink.h"
|
||||
|
||||
@@ -499,7 +500,7 @@ struct Fixture {
|
||||
~Fixture() { sch.fini(); for (void* p : owned) std::free(p); }
|
||||
|
||||
void build(int64_t blocks = 4096, int64_t states = 64, int64_t max_tok = 512,
|
||||
int64_t max_ctx = 4096) {
|
||||
int64_t max_ctx = 4096, bool windowed = false) {
|
||||
g_gdn_ki = RadKernelInfo{};
|
||||
g_gdn_ki.name = "gdn_fake";
|
||||
g_gdn_ki.op = "gdn_chunked";
|
||||
@@ -532,6 +533,25 @@ struct Fixture {
|
||||
conv.decl.conv_width = 4;
|
||||
prog.kv_groups.push_back(conv);
|
||||
|
||||
/* A WINDOWED paged group — the second half of the pair a sliding-window model declares
|
||||
* (windowed layers + a full group; qwen35/llama windowed checkpoints declare these).
|
||||
* Paged, block-aligned, and deliberately NOT prefix-cached: prefix.cpp indexes only the
|
||||
* groups whose blocks below the window stay put. Tests that want a prefix cache over a
|
||||
* WINDOW+FULL pair trim pc.groups to the cached ones. */
|
||||
if (windowed) {
|
||||
KVGroupInfo win;
|
||||
win.name = "swa";
|
||||
win.decl.kind = RAD_KV_WINDOW;
|
||||
win.decl.window = 64;
|
||||
win.block_size = 16;
|
||||
win.layers = { 2 }; /* bound to a TRUNK layer — the group a trunk attention reads;
|
||||
* a drafter's own group is bound at the trunk's layer count and
|
||||
* above (rad_bind_layer_kv at the drafter declare) */
|
||||
prog.kv_groups.push_back(win);
|
||||
prog.meta.n_layers = 16; /* trunk layers 0..15; the drafter tests' appended group
|
||||
* stays unbound, and unbound is not trunk-owned */
|
||||
}
|
||||
|
||||
OpInfo op;
|
||||
op.op = "gdn_chunk_scan";
|
||||
op.schema = &g_gdn_schema;
|
||||
@@ -659,6 +679,39 @@ TEST(chunk_geometry_rounds_the_checkpoint_interval_up_to_a_legal_chunk) {
|
||||
CHECK_EQ(f.sch.geometry().checkpoint_interval, 256);
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
TEST(chunk_geometry_snapshots_a_trunk_window_and_not_a_drafters) {
|
||||
for (int drafter = 0; drafter < 2; ++drafter) {
|
||||
Program prog;
|
||||
prog.meta.n_layers = 16;
|
||||
prog.kv_groups.emplace_back();
|
||||
KVGroupInfo attn;
|
||||
attn.name = "attn";
|
||||
attn.decl.kind = RAD_KV_FULL;
|
||||
attn.block_size = 16;
|
||||
attn.layers = { 0 };
|
||||
prog.kv_groups.push_back(attn);
|
||||
KVGroupInfo win;
|
||||
win.name = "swa";
|
||||
win.decl.kind = RAD_KV_WINDOW;
|
||||
win.decl.window = 64;
|
||||
win.block_size = 16;
|
||||
win.layers = { drafter ? 16 : 1 };
|
||||
win.drafter = drafter != 0;
|
||||
prog.kv_groups.push_back(win);
|
||||
Config cfg;
|
||||
cfg.max_tok = 512;
|
||||
cfg.checkpoint_interval = 256;
|
||||
cfg.prefix_cache = true;
|
||||
ChunkGeometry g;
|
||||
CHECK_OK(chunk_geometry_resolve(prog, cfg, &g));
|
||||
CHECK_EQ(g.checkpoint_interval, drafter ? 0ll : 256ll);
|
||||
CHECK(g.window_ckpt == !drafter);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(chunk_geometry_refuses_a_budget_it_cannot_serve) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
@@ -993,6 +1046,50 @@ TEST(a_hit_that_no_checkpoint_covers_replays_from_zero) {
|
||||
CHECK_EQ(f.sch.metrics().linear_cached_tokens, 0);
|
||||
}
|
||||
|
||||
/* THE PREFIX CACHE CANNOT COVER A MODEL WITH A PAGED GROUP IT DOES NOT INDEX. The fixture's
|
||||
* groups are FULL, LINEAR, CONV, WINDOW — the windowed group is paged, bound to a trunk layer,
|
||||
* and a real cache skips it (prefix.cpp: its blocks below the window are recycled, so no block
|
||||
* list describes them), which is what pc.groups = {0} reproduces: three paged groups, one
|
||||
* cached. The cache below is seeded to a DEEP, checkpoint-covered hit — 304 attention blocks,
|
||||
* the linear state at 256, a slot to restore from — the most legitimate hit there is: every
|
||||
* clamp above the trunk one lets it through untouched. The adopted blocks cover group 0 ONLY,
|
||||
* while used = ctx_len + n_tok makes the windowed trunk layers read the positions below ctx_len
|
||||
* this sequence never wrote — and the pool hands out the most recently freed blocks, i.e. the
|
||||
* previous tenant's. That is reading ANOTHER REQUEST'S KV AS YOUR OWN PREFIX: fluent text
|
||||
* carrying the last request's content. No tail-recompute repairs a trunk hole (a drafter's own
|
||||
* hole is another matter, and the refill tests above keep theirs); the hit is refused. */
|
||||
TEST(a_hit_on_a_model_with_a_windowed_group_reuses_nothing) {
|
||||
Fixture f;
|
||||
f.build(4096, 64, 512, 4096, /*windowed=*/true);
|
||||
f.pc.groups = {0}; /* a cache that indexes the FULL group only — windowed groups are not
|
||||
* prefix-cacheable; must precede start(), which reads it once */
|
||||
CHECK_OK(f.start());
|
||||
f.pc.seed(304); /* a deep, block-aligned attention hit: 19 blocks */
|
||||
f.pc.lin = 256; /* its linear state checkpoints at 256 — the resume point exists */
|
||||
f.pc.src = 3; /* and names a snapshot, so no checkpoint clamp applies */
|
||||
|
||||
uint64_t a = f.submit(300, 8);
|
||||
const RadBatch* b = f.sch.step();
|
||||
REQUIRE(b != nullptr);
|
||||
|
||||
/* The whole hit is refused, not trimmed: the request runs from zero. */
|
||||
CHECK_EQ(f.sch.find(a)->n_computed, 0);
|
||||
CHECK_EQ(f.sch.find(a)->n_cached, 0);
|
||||
CHECK_EQ(b->ctx_lens[0], 0);
|
||||
CHECK_EQ(f.sch.plan().e[0].ckpt_restore, -1);
|
||||
|
||||
/* NOTHING IS ADOPTED — the 16 blocks covering the 256-token chunk are all freshly grabbed. */
|
||||
CHECK_EQ((int)f.kv.block_table(a, 0).size(), 16);
|
||||
CHECK(std::find(f.pc.seeded[0].begin(), f.pc.seeded[0].end(),
|
||||
f.kv.block_table(a, 0)[0]) == f.pc.seeded[0].end());
|
||||
|
||||
/* THE CACHE STILL REPORTED THE MATCH, and the metrics say so: this is a real hit the
|
||||
* scheduler refused, not a lookup that found nothing. */
|
||||
SchedMetrics m = f.sch.metrics();
|
||||
CHECK_EQ(m.attn_cached_tokens, 304);
|
||||
CHECK_EQ(m.linear_cached_tokens, 0);
|
||||
}
|
||||
|
||||
/* ================================================================== preemption */
|
||||
/* A REQUEST WHOSE CONTEXT IS STILL BEING READ OFF DISK WAITS, AND ONLY IT DOES. It is not admitted
|
||||
* short -- the hit length is what its prefill is shaped by -- and it does not hold up the queue:
|
||||
@@ -1358,7 +1455,11 @@ RefillRun refill_run(int n_prompt, int32_t seeded, int64_t ckpt_lo = 0) {
|
||||
f.cfg.n_spec = 7;
|
||||
f.prog.drafter.kind = RAD_DRAFT_BLOCK;
|
||||
f.prog.drafter.window = 512;
|
||||
KVGroupInfo w; /* the drafter's own group: paged, windowed, not prefix-cached */
|
||||
KVGroupInfo w; /* the drafter's own group: paged, windowed, not prefix-cached.
|
||||
* UNBOUND, and a drafter group bound at the trunk's layer count
|
||||
* and above is the same — the trunk clamp reads bound TRUNK
|
||||
* layers (scheduler.h, hit_holes_trunk_) and does not fire on a
|
||||
* drafter hole: the refill below is exactly its repair. */
|
||||
w.name = "draft";
|
||||
w.decl.kind = RAD_KV_WINDOW;
|
||||
w.decl.window = 512;
|
||||
@@ -3014,6 +3115,202 @@ TEST(the_history_pass_carries_draft_round_one) {
|
||||
f.sch.serial_end(2);
|
||||
}
|
||||
|
||||
/* THE SERIAL DRIVER'S TWO SHAPES, side by side over one verify step. A head with a cache of its own
|
||||
* (every drafter but one) owes the history of every verified position and steps one position a
|
||||
* round; a head that reads the trunk's cache and keeps none (rad_drafter_shared_kv) owes nothing,
|
||||
* runs one row a drafting sequence, and does not step. The first half of this is the old path and
|
||||
* must not move: it is what Qwen's MTP head is staged with. */
|
||||
namespace {
|
||||
struct SerialShape {
|
||||
int hist_tok = 0, hist_out = 0, hist_dout = 0;
|
||||
int32_t hist_ctx = 0, hist_row = 0;
|
||||
int32_t round_ctx[4] = {0, 0, 0, 0};
|
||||
};
|
||||
|
||||
void serial_shape(bool shared, SerialShape& r) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/4096, /*states=*/64);
|
||||
f.cfg.n_spec = 4;
|
||||
f.prog.drafter.kind = RAD_DRAFT_SERIAL;
|
||||
f.prog.drafter.depth = 4;
|
||||
f.prog.drafter_shared_kv = shared;
|
||||
CHECK_OK(f.start());
|
||||
|
||||
const uint64_t a = f.submit(160, 64);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain(11);
|
||||
int32_t draft[4] = { 21, 22, 23, 24 };
|
||||
CHECK_OK(f.sch.set_draft(a, draft, 4));
|
||||
const RadBatch* b = f.sch.step();
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->n_spec, 4);
|
||||
|
||||
int rounds = 4;
|
||||
Scheduler::SerialRow rows[4];
|
||||
CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 1);
|
||||
const RadBatch* hb = f.sch.serial_batch(0, 1);
|
||||
REQUIRE(hb != nullptr);
|
||||
CHECK(hb->draft_pass < 0);
|
||||
r.hist_tok = (int)hb->n_tok;
|
||||
r.hist_out = (int)hb->n_out;
|
||||
r.hist_dout = (int)hb->n_draft_out;
|
||||
r.hist_ctx = hb->ctx_lens[0];
|
||||
r.hist_row = hb->out_ids[0];
|
||||
for (int rd = 2; rd <= 3; ++rd) {
|
||||
const RadBatch* rb = f.sch.serial_batch(rd, 1);
|
||||
REQUIRE(rb != nullptr);
|
||||
CHECK_EQ(rb->n_tok, 1);
|
||||
r.round_ctx[rd] = rb->ctx_lens[0];
|
||||
}
|
||||
f.sch.serial_end(3);
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
TEST(a_head_with_a_cache_of_its_own_is_staged_as_it_always_was) {
|
||||
SerialShape o;
|
||||
serial_shape(false, o);
|
||||
CHECK_EQ(o.hist_tok, 5); /* every verified position */
|
||||
CHECK_EQ(o.hist_out, 5); /* one trunk row each */
|
||||
CHECK_EQ(o.hist_dout, 1);
|
||||
CHECK_EQ(o.hist_ctx, 160); /* the history starts at the first verified one */
|
||||
CHECK_EQ(o.hist_row, 0); /* the verify step's first row */
|
||||
CHECK_EQ(o.round_ctx[2], 165); /* the furthest round 2 can sit: one past the last */
|
||||
CHECK_EQ(o.round_ctx[3], 166); /* ...and the head steps one position a round */
|
||||
}
|
||||
|
||||
TEST(a_head_with_no_cache_of_its_own_runs_one_row_and_stays_put) {
|
||||
SerialShape s;
|
||||
serial_shape(true, s);
|
||||
CHECK_EQ(s.hist_tok, 1); /* round 1 alone */
|
||||
CHECK_EQ(s.hist_out, 1);
|
||||
CHECK_EQ(s.hist_dout, 1);
|
||||
CHECK_EQ(s.hist_ctx, 164); /* the furthest the committed position can be */
|
||||
CHECK_EQ(s.hist_row, 0); /* the run's first trunk row; the card adds acc */
|
||||
CHECK_EQ(s.round_ctx[2], 164); /* and every round stays there */
|
||||
CHECK_EQ(s.round_ctx[3], 164);
|
||||
}
|
||||
|
||||
/* A HEAD WITH NO CACHE OF ITS OWN IS OWED NO HISTORY: a prefill chunk that drafts nothing runs no
|
||||
* pass for it at all, where a head with its own cache is given the whole chunk. */
|
||||
TEST(a_head_with_no_cache_of_its_own_runs_no_pass_when_nothing_drafts) {
|
||||
for (int shared = 0; shared < 2; ++shared) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/10, /*states=*/64); /* exactly the prompt: nothing to look ahead into */
|
||||
f.cfg.n_spec = 4;
|
||||
f.prog.drafter.kind = RAD_DRAFT_SERIAL;
|
||||
f.prog.drafter.depth = 4;
|
||||
f.prog.drafter_shared_kv = shared != 0;
|
||||
CHECK_OK(f.start());
|
||||
f.submit(160, 64);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
int rounds = 4;
|
||||
Scheduler::SerialRow rows[4];
|
||||
CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 0);
|
||||
const RadBatch* hb = f.sch.serial_batch(0, 1);
|
||||
if (shared) {
|
||||
CHECK(hb == nullptr);
|
||||
} else {
|
||||
REQUIRE(hb != nullptr);
|
||||
CHECK_EQ(hb->n_tok, 160);
|
||||
}
|
||||
f.sch.serial_end(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* WHAT THE CARD WRITES INTO A DRAFT PASS, row by row (advance_impl.h), for both shapes. One verify
|
||||
* step at positions 101..105 accepted two drafts, so the committed position is 103 and the trunk
|
||||
* chose token 7003 there; the block table maps position p to slot p. A head with a cache of its own
|
||||
* gets the verified run with its tail repeated and a context that runs to its end; a head with no
|
||||
* cache of its own gets the committed position and a context that ends there, in every round. */
|
||||
namespace {
|
||||
struct AdvSlab {
|
||||
alignas(16) int32_t w[512] = {};
|
||||
rad::StepSlot st{};
|
||||
int32_t src[8] = { 7001, 7002, 7003, 7004, 7005, 0, 0, 0 };
|
||||
rad::AdvanceArgs a;
|
||||
|
||||
/* word offsets */
|
||||
enum { ROWS = 0, TOK = 8, POS = 16, CTX = 24, ACC = 28, OUT = 32, SID = 40, CU = 44, Q = 48,
|
||||
GRP = 64, SLOT = 96, USED = 104, BT = 112, FIRST = 128 };
|
||||
|
||||
AdvSlab(int mode, int n_rows, int round, bool shared, int shift) {
|
||||
a.mode = mode;
|
||||
a.round = round;
|
||||
a.n_seq = 1;
|
||||
a.n_groups = 1;
|
||||
a.slab = reinterpret_cast<char*>(w);
|
||||
a.row_off = ROWS * 4; a.row_pitch = 1;
|
||||
a.tok_off = TOK * 4; a.pos_off = POS * 4; a.ctx_off = CTX * 4; a.acc_off = ACC * 4;
|
||||
a.out_off = OUT * 4; a.sid_off = SID * 4; a.cu_off = CU * 4; a.q_off = Q * 4;
|
||||
a.grp_off = GRP * 4;
|
||||
a.st = &st;
|
||||
a.src = src;
|
||||
a.shared_kv = shared ? 1 : 0;
|
||||
a.rot_shift = shift;
|
||||
w[ROWS + 0] = 1; /* a device row */
|
||||
w[ROWS + 1] = 0; /* its first verified token row */
|
||||
w[ROWS + 2] = 0; /* its first sampled row */
|
||||
w[ROWS + 3] = 0; /* no history before the verified positions */
|
||||
w[SID] = 0; w[CU] = 0; w[Q] = n_rows;
|
||||
w[OUT] = 40; /* the host staged the run's first trunk row */
|
||||
rad::AdvGroup g{};
|
||||
g.block_size = 16; g.paged = 1; g.pitch = 16;
|
||||
g.slot_off = SLOT * 4; g.used_off = USED * 4; g.bt_off = BT * 4; g.first_off = FIRST * 4;
|
||||
std::memcpy(&w[GRP], &g, sizeof g);
|
||||
for (int i = 0; i < 16; ++i) w[BT + i] = i; /* block i holds positions 16i.. */
|
||||
w[FIRST] = 0;
|
||||
st.head = 103; st.acc = 2; st.ctx = 104; st.n_acc = 3; st.tok[0] = 7003;
|
||||
}
|
||||
};
|
||||
} /* namespace */
|
||||
|
||||
TEST(the_card_stages_a_cacheless_head_at_the_committed_position) {
|
||||
/* The history pass. */
|
||||
{
|
||||
AdvSlab o(rad::ADV_HIST, 5, 0, false, 0);
|
||||
rad::adv_row(o.a, 0);
|
||||
const int32_t pos[5] = { 101, 102, 103, 103, 103 }, tok[5] = { 7001, 7002, 7003, 7003, 7003 };
|
||||
for (int j = 0; j < 5; ++j) {
|
||||
CHECK_EQ(o.w[AdvSlab::POS + j], pos[j]);
|
||||
CHECK_EQ(o.w[AdvSlab::TOK + j], tok[j]);
|
||||
CHECK_EQ(o.w[AdvSlab::OUT + j], 40 + (j < 2 ? j : 2));
|
||||
CHECK_EQ(o.w[AdvSlab::SLOT + j], pos[j]);
|
||||
}
|
||||
CHECK_EQ(o.w[AdvSlab::USED], 106); /* the verify step's whole run */
|
||||
CHECK_EQ(o.w[AdvSlab::CTX], 101);
|
||||
}
|
||||
for (int shift = 0; shift < 2; ++shift) {
|
||||
AdvSlab s(rad::ADV_HIST, 1, 0, true, shift);
|
||||
rad::adv_row(s.a, 0);
|
||||
CHECK_EQ(s.w[AdvSlab::POS], 103 + shift);
|
||||
CHECK_EQ(s.w[AdvSlab::TOK], 7003);
|
||||
CHECK_EQ(s.w[AdvSlab::OUT], 42);
|
||||
CHECK_EQ(s.w[AdvSlab::USED], 104); /* the committed positions and no more */
|
||||
CHECK_EQ(s.w[AdvSlab::CTX], 103);
|
||||
}
|
||||
/* Round 3: the old head two positions on, the cacheless one where it was. */
|
||||
{
|
||||
AdvSlab o(rad::ADV_ROUND, 1, 3, false, 0);
|
||||
o.src[0] = 9001;
|
||||
rad::adv_row(o.a, 0);
|
||||
CHECK_EQ(o.w[AdvSlab::POS], 105);
|
||||
CHECK_EQ(o.w[AdvSlab::USED], 106);
|
||||
CHECK_EQ(o.w[AdvSlab::TOK], 9001);
|
||||
CHECK_EQ(o.st.tok[2], 9001);
|
||||
}
|
||||
for (int shift = 0; shift < 2; ++shift) {
|
||||
AdvSlab s(rad::ADV_ROUND, 1, 3, true, shift);
|
||||
s.src[0] = 9001;
|
||||
rad::adv_row(s.a, 0);
|
||||
CHECK_EQ(s.w[AdvSlab::POS], 103 + shift);
|
||||
CHECK_EQ(s.w[AdvSlab::USED], 104);
|
||||
CHECK_EQ(s.w[AdvSlab::CTX], 103);
|
||||
CHECK_EQ(s.w[AdvSlab::TOK], 9001);
|
||||
CHECK_EQ(s.st.tok[2], 9001);
|
||||
}
|
||||
}
|
||||
|
||||
/* A STEP IS ISSUED AHEAD OF A COMMIT ONLY FOR A REQUEST WHOSE SPECULATION THAT COMMIT CANNOT
|
||||
* CHANGE. The ahead step is sized before the commit in front of it, so a request the sampler has
|
||||
* not started yet -- whose grammar, if any, nobody has asked -- is not issued ahead; one whose
|
||||
|
||||
@@ -957,6 +957,26 @@ TEST(vocab_treats_an_out_of_range_special_id_as_absent) {
|
||||
CHECK_EQ(v->pad(), -1);
|
||||
}
|
||||
|
||||
/* The checkpoint's own end-of-generation list -- generation_config.json's eos_token_id, which the
|
||||
* container carries as `generation.eos_token_id` -- ends a generation on every id it names: Gemma 4
|
||||
* names <|tool_response> there, where the model stops after its calls. An id naming no token is
|
||||
* no id. */
|
||||
TEST(vocab_ends_a_generation_on_every_id_the_checkpoint_names) {
|
||||
VocabBuild vb;
|
||||
vb.kind = RAD_TOK_BPE;
|
||||
vb.tokens = { "a", "<eos>", "<|tool_response>", "<|tool_call>" };
|
||||
vb.types = { RAD_TT_NORMAL, RAD_TT_CONTROL, RAD_TT_CONTROL, RAD_TT_CONTROL };
|
||||
vb.eos = 1;
|
||||
vb.eos_ids = { 1, 2, 99, -3 };
|
||||
auto v = std::make_shared<Vocab>();
|
||||
CHECK_OK(v->load(std::move(vb)));
|
||||
CHECK(v->is_eog(1));
|
||||
CHECK(v->is_eog(2));
|
||||
CHECK(!v->is_eog(3));
|
||||
CHECK(!v->is_eog(0));
|
||||
CHECK_EQ(v->eog().size(), (size_t)2);
|
||||
}
|
||||
|
||||
/* ================================================================== chain steps */
|
||||
|
||||
TEST(step_chain_units) {
|
||||
|
||||
Reference in new issue
Block a user