Merge branch 'main' into fix-stage-drain

This commit is contained in:
C_Tamas committed 2026-10-25 14:19:31 +01:00
commit bcdc89eded
43 files changed
+3197 -157

No files matched your search

+647 -13
View File
@@ -50,6 +50,11 @@
#undef QWEN35_NS
#undef QWEN35_ARCH_ID
#include "../arch/qwen35_w8a8/qwen35_w8a8.cpp"
/* Tencent Hy-Memory: FP8 full attention with Q/K norm and sigmoid-correction MoE. */
#include "../arch/hyv3_fp8/hyv3_fp8.cpp"
#include "../arch/hyv3_bf16/hyv3_bf16.cpp"
#include "../arch/hyv3_gguf/hyv3_gguf.cpp"
#include "hyv3_bf16_fixture.h"
/* The LLaMA family from a dense checkpoint: llama_fp8 under its other descriptor. */
#undef LLAMA_DENSE_SRC
#undef LLAMA_NS
@@ -348,6 +353,484 @@ TEST(llama_reads_its_rotary_scaling_by_type) {
}
}
TEST(fp8_qk_attention_normalizes_before_neox_rope) {
using namespace rad::arch;
RadModelMeta meta{};
meta.arch_id = "hyv3"; meta.name = "test-hyv3"; meta.quant = "fp8";
meta.n_layers = 1; meta.n_embd = 2048; meta.n_head = 32; meta.n_head_kv = 4;
meta.head_dim = 128; meta.n_ff = 6912; meta.n_vocab = 120832;
meta.n_ctx_train = 262144; meta.rms_eps = 1e-5f; meta.rope_theta = 11158840.0f;
RadBuildCtx ctx = build_ctx();
Geom g{};
CHECK_OK(geom_from(g, &meta, &ctx, "bf16", RAD_BF16));
RadBuilder b;
Names nm("");
RadKVGroupDecl kd{};
kd.kind = RAD_KV_FULL; kd.dtype = RAD_BF16; kd.n_head_kv = g.n_head_kv;
kd.head_dim = g.head_dim;
const rad_kvgroup kv = rad_decl_kv_group(&b, "kv_attn", &kd);
CHECK_OK(rad_bind_layer_kv(&b, 0, kv));
AttnQKFP8::Wire w{};
w.x = decl_b(&b, nm.f("x"), RAD_BF16, {g.max_tok, g.n_embd});
w.h.x = decl_b(&b, nm.f("h"), RAD_BF16, {g.max_tok, g.n_embd});
CHECK_OK(w.h.declare_qs(&b, nm, g, "h", g.n_embd));
w.q = decl_b(&b, nm.f("q"), RAD_BF16, {g.max_tok, g.q_dim()});
w.k = decl_b(&b, nm.f("k"), RAD_BF16, {g.max_tok, g.kv_dim()});
w.v = decl_b(&b, nm.f("v"), RAD_BF16, {g.max_tok, g.kv_dim()});
w.attn.x = decl_b(&b, nm.f("attn"), RAD_BF16, {g.max_tok, g.q_dim()});
CHECK_OK(w.attn.declare_qs(&b, nm, g, "attn", g.q_dim()));
const rad_op init = rw(&b, RAD_OP(&b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype), RAD_F64("value", 0.0)),
RAD_NOWEIGHTS),
{}, {w.x});
AttnQKFP8::Src src{};
src.norm = nm.ckpt("model.layers.0.input_layernorm.weight");
src.q = nm.ckpt("model.layers.0.self_attn.q_proj.weight");
src.k = nm.ckpt("model.layers.0.self_attn.k_proj.weight");
src.v = nm.ckpt("model.layers.0.self_attn.v_proj.weight");
src.q_norm = nm.ckpt("model.layers.0.self_attn.q_norm.weight");
src.k_norm = nm.ckpt("model.layers.0.self_attn.k_norm.weight");
src.o = nm.ckpt("model.layers.0.self_attn.o_proj.weight");
AttnQKFP8 attn;
CHECK_OK(attn.declare(&b, nm, g, 0, kv, w, src));
const RecWeight* qw = find_w(b, "blk.0.attn_q.weight");
const RecWeight* kw = find_w(b, "blk.0.attn_k.weight");
const RecWeight* qn = find_w(b, "blk.0.attn_q_norm.weight");
CHECK(qw && kw && qn);
CHECK_EQ(qw->d.shape[0], 4096); CHECK_EQ(qw->d.shape[1], 2048);
CHECK_EQ(kw->d.shape[0], 512); CHECK_EQ(kw->d.shape[1], 2048);
CHECK_EQ(qn->d.shape[0], 128); CHECK_EQ(qn->d.dtype, (uint32_t)RAD_F32);
CHECK_EQ(qn->d.shard, RAD_SHARD_NONE);
int q_norms = 0, k_norms = 0;
for (const auto& op : b.ops) if (op.op == "rmsnorm" && pint(&op, "n") == 128) {
if (op.w.size() == 1 && op.w[0] == attn.w_q_norm) ++q_norms;
if (op.w.size() == 1 && op.w[0] == attn.w_k_norm) ++k_norms;
}
CHECK_EQ(q_norms, 1); CHECK_EQ(k_norms, 1);
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch;
RAD_ISSUE(&run, init, brows(w.x, batch.n_tok));
attn.step(&run, &batch);
auto issue_of = [&](rad_op h) {
for (size_t i = 0; i < run.issues.size(); ++i)
if (run.issues[i].op == h) return (int)i;
return -1;
};
const int q_norm_issue = issue_of(attn.op_q_norm), k_norm_issue = issue_of(attn.op_k_norm);
const int q_rope_issue = issue_of(attn.op_rope_q), k_rope_issue = issue_of(attn.op_rope_k);
const int attn_issue = issue_of(attn.op_attn);
CHECK(q_norm_issue >= 0); CHECK(k_norm_issue >= 0); CHECK(attn_issue >= 0);
CHECK(q_rope_issue >= 0); CHECK(k_rope_issue >= 0);
CHECK(q_norm_issue < q_rope_issue); CHECK(k_norm_issue < k_rope_issue);
CHECK(q_rope_issue < attn_issue); CHECK(k_rope_issue < attn_issue);
const auto lint = lint_step(b, {&run});
CHECK(lint.empty());
}
static RadModelMeta hyv3_fp8_test_meta() {
static const char* keys[] = {
"qk_norm", "moe_router_use_sigmoid", "moe_router_enable_expert_bias", "route_norm",
"enable_moe_fp32_combine", "attention_bias", "mlp_bias", "first_k_dense_replace",
"num_experts", "num_experts_per_tok", "num_shared_experts", "expert_hidden_dim",
"moe_intermediate_size", "router_scaling_factor", "mlp_layer_types",
"hyv3.kv_cache.0.k_scale", "hyv3.kv_cache.0.v_scale",
"hyv3.kv_cache.1.k_scale", "hyv3.kv_cache.1.v_scale",
};
static const char* vals[] = {
"1", "1", "1", "1", "1", "0", "0", "1", "128", "8", "1", "768", "1536",
"2.826", "dense sparse", "0.0376674123", "0.0004359654",
"0.0224609375", "0.0005318778",
};
RadModelMeta meta{};
meta.arch_id = "hyv3"; meta.name = "test-hyv3"; meta.quant = "fp8";
meta.n_layers = 2; meta.n_embd = 2048; meta.n_head = 32; meta.n_head_kv = 4;
meta.head_dim = 128; meta.n_ff = 6912; meta.n_vocab = 120832;
meta.n_ctx_train = 262144; meta.rms_eps = 1e-5f; meta.rope_theta = 11158840.0f;
meta.n_expert = 128; meta.n_expert_used = 8;
meta.n_kv = (int)(sizeof(keys) / sizeof(keys[0])); meta.kv_key = keys; meta.kv_val = vals;
return meta;
}
TEST(hyv3_bf16_declares_checkpoint_geometry_and_plain_moe) {
RadModelMeta meta = hyv3_fp8_test_meta();
meta.quant = "";
RadArchProbe probe{};
CHECK_OK(hyv3_bf16::probe(&meta, &probe));
RadBuilder b;
const RadEncoding plain = rad_enc_plain(RAD_BF16);
b.encs = {
{ "attn_q.weight", plain }, { "attn_k.weight", plain },
{ "attn_v.weight", plain }, { "attn_output.weight", plain },
{ "ffn_gate_up.weight", plain }, { "ffn_down.weight", plain },
{ "ffn_gate_up_exps", plain }, { "ffn_down_exps", plain },
{ "ffn_gate_up_shexp.weight", plain }, { "ffn_down_shexp.weight", plain },
{ "output.weight", plain },
};
RadBuildCtx ctx = build_ctx();
const int rc = hyv3_bf16::declare(&b, &meta, &ctx);
CHECK_EQ(rc, RAD_OK);
if (rc < 0) return;
const RecWeight* q_norm = find_w(b, "blk.0.attn_q_norm.weight");
const RecWeight* k_norm = find_w(b, "blk.0.attn_k_norm.weight");
const RecWeight* q = find_w(b, "blk.0.attn_q.weight");
const RecWeight* k = find_w(b, "blk.0.attn_k.weight");
const RecWeight* v = find_w(b, "blk.0.attn_v.weight");
const RecWeight* o = find_w(b, "blk.0.attn_output.weight");
const RecWeight* dense = find_w(b, "blk.0.ffn_gate_up.weight");
const RecWeight* dense_down = find_w(b, "blk.0.ffn_down.weight");
const RecWeight* expert = find_w(b, "blk.1.ffn_gate_up_exps.0.weight");
const RecWeight* expert_down = find_w(b, "blk.1.ffn_down_exps.0.weight");
const RecWeight* shared = find_w(b, "blk.1.ffn_gate_up_shexp.weight");
const RecWeight* shared_down = find_w(b, "blk.1.ffn_down_shexp.weight");
const RecWeight* router = find_w(b, "blk.1.glm_router.weight");
const RecWeight* correction = find_w(b, "blk.1.glm_router.correction");
REQUIRE(q_norm && k_norm && q && k && v && o && dense && dense_down && expert &&
expert_down && shared && shared_down && router && correction);
CHECK_EQ(q_norm->d.shape[0], hyv3_bf16_fixture::q_norm[0]);
CHECK_EQ(k_norm->d.shape[0], hyv3_bf16_fixture::k_norm[0]);
CHECK_EQ(router->d.shape[0], hyv3_bf16_fixture::router[0]);
CHECK_EQ(router->d.shape[1], hyv3_bf16_fixture::router[1]);
CHECK_EQ(correction->d.shape[0], hyv3_bf16_fixture::correction[0]);
CHECK_EQ(q->d.shape[0], hyv3_bf16_fixture::q_proj[0]);
CHECK_EQ(q->d.shape[1], hyv3_bf16_fixture::q_proj[1]);
CHECK_EQ(k->d.shape[0], hyv3_bf16_fixture::k_proj[0]);
CHECK_EQ(k->d.shape[1], hyv3_bf16_fixture::k_proj[1]);
CHECK_EQ(v->d.shape[0], hyv3_bf16_fixture::v_proj[0]);
CHECK_EQ(v->d.shape[1], hyv3_bf16_fixture::v_proj[1]);
CHECK_EQ(o->d.shape[0], hyv3_bf16_fixture::o_proj[0]);
CHECK_EQ(o->d.shape[1], hyv3_bf16_fixture::o_proj[1]);
CHECK_EQ(dense->d.shape[0], hyv3_bf16_fixture::dense_gate[0] +
hyv3_bf16_fixture::dense_up[0]);
CHECK_EQ(dense->d.shape[1], hyv3_bf16_fixture::dense_gate[1]);
CHECK_EQ(dense_down->d.shape[0], hyv3_bf16_fixture::dense_down[0]);
CHECK_EQ(dense_down->d.shape[1], hyv3_bf16_fixture::dense_down[1]);
CHECK_EQ(expert->d.shape[0], hyv3_bf16_fixture::expert_gate[0] +
hyv3_bf16_fixture::expert_up[0]);
CHECK_EQ(expert->d.shape[1], hyv3_bf16_fixture::expert_gate[1]);
CHECK_EQ(expert_down->d.shape[0], hyv3_bf16_fixture::expert_down[0]);
CHECK_EQ(expert_down->d.shape[1], hyv3_bf16_fixture::expert_down[1]);
CHECK_EQ(shared->d.shape[0], hyv3_bf16_fixture::shared_gate[0] +
hyv3_bf16_fixture::shared_up[0]);
CHECK_EQ(shared->d.shape[1], hyv3_bf16_fixture::shared_gate[1]);
CHECK_EQ(shared_down->d.shape[0], hyv3_bf16_fixture::shared_down[0]);
CHECK_EQ(shared_down->d.shape[1], hyv3_bf16_fixture::shared_down[1]);
const auto& moe = hyv3_bf16::models[0].layers[1].moe;
CHECK_EQ(moe.c.n_ff_exp, 768);
CHECK_EQ(moe.c.n_ff_shared, 768);
CHECK_EQ(moe.c.expert_bf16, 1);
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch;
hyv3_bf16::step(&run, &batch);
CHECK(lint_step(b, {&run}).empty());
}
TEST(hyv3_gguf_maps_llamacpp_moe_tensors_and_lints_tp2) {
RadModelMeta meta = hyv3_fp8_test_meta();
meta.quant = "gguf_ftype_15";
RadArchProbe probe{};
CHECK_OK(hyv3_gguf::probe(&meta, &probe));
const RadEncoding plain = rad_enc_plain(RAD_BF16);
for (int rank = 0; rank < 2; ++rank) {
RadBuilder b;
b.encs = {
{ "attn_q.weight", plain }, { "attn_k.weight", plain },
{ "attn_v.weight", plain }, { "attn_output.weight", plain },
{ "ffn_gate_up.weight", plain }, { "ffn_down.weight", plain },
{ "ffn_gate_up_exps", plain }, { "ffn_down_exps", plain },
{ "ffn_gate_up_shexp.weight", plain }, { "ffn_down_shexp.weight", plain },
{ "output.weight", plain },
};
RadBuildCtx ctx = build_ctx(rank, 2);
const int rc = hyv3_gguf::declare(&b, &meta, &ctx);
CHECK_EQ(rc, RAD_OK);
if (rc < 0) continue;
auto mapped = [&](const char* target, const char* source) {
for (const RecMap& m : b.maps)
if (m.declared == target && m.src.size() == 1 && m.src[0] == source) return true;
return false;
};
CHECK(mapped("blk.0.attn_q.weight", "blk.0.attn_q.weight"));
CHECK(mapped("blk.1.glm_router.weight", "blk.1.ffn_gate_inp.weight"));
CHECK(mapped("blk.1.glm_router.correction", "blk.1.exp_probs_b"));
CHECK(mapped("token_embd.weight", "token_embd.weight"));
const std::string expert_name =
"blk.1.ffn_gate_up_exps." + std::to_string(rank * 64) + ".weight";
const std::string down_name =
"blk.1.ffn_down_exps." + std::to_string(rank * 64) + ".weight";
bool expert_gate_up = false, expert_down = false, shared_gate_up = false;
for (const RecMap& m : b.maps) {
if (m.declared == expert_name && m.src.size() == 2 &&
m.src[0] == "blk.1.ffn_gate_exps.weight" &&
m.src[1] == "blk.1.ffn_up_exps.weight") expert_gate_up = true;
if (m.declared == down_name && m.src.size() == 1 &&
m.src[0] == "blk.1.ffn_down_exps.weight") expert_down = true;
if (m.declared == "blk.1.ffn_gate_up_shexp.weight" && m.src.size() == 2 &&
m.src[0] == "blk.1.ffn_gate_shexp.weight" &&
m.src[1] == "blk.1.ffn_up_shexp.weight") shared_gate_up = true;
}
CHECK(expert_gate_up); CHECK(expert_down); CHECK(shared_gate_up);
const auto& moe = hyv3_gguf::models[rank].layers[1].moe;
CHECK_EQ(moe.c.expert_bf16, 1);
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch;
hyv3_gguf::step(&run, &batch);
CHECK(lint_step(b, {&run}).empty());
}
}
TEST(hyv3_bf16_selects_native_int4_expert_kernels_from_recipe_encodings) {
RadModelMeta meta = hyv3_fp8_test_meta();
meta.quant = "";
const RadEncoding plain = rad_enc_plain(RAD_BF16);
const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
RadEncoding w4a = rad_enc_affine(RAD_U4, RAD_F16, 1, 128);
rad_enc_add_plane(&w4a, "zero", RAD_U8, 1, 128);
for (int rank = 0; rank < 2; ++rank) {
RadBuilder b;
b.encs = {
{ "attn_q.weight", w4a }, { "attn_k.weight", w4a },
{ "attn_v.weight", w4a }, { "attn_output.weight", w4a },
{ "ffn_gate_up.weight", w4a }, { "ffn_down.weight", w4a },
{ "ffn_gate_up_exps", w4 }, { "ffn_down_exps", w4 },
{ "ffn_gate_up_shexp.weight", plain }, { "ffn_down_shexp.weight", plain },
{ "output.weight", plain },
};
RadBuildCtx ctx = build_ctx(rank, 2);
const int rc = hyv3_bf16::declare(&b, &meta, &ctx);
CHECK_EQ(rc, RAD_OK);
if (rc < 0) continue;
const auto& moe = hyv3_bf16::models[rank].layers[1].moe;
CHECK_EQ(moe.c.expert_w4, 1);
CHECK_EQ(moe.c.expert_bf16, 0);
CHECK_EQ(moe.c.n_ff_exp, 768);
CHECK_EQ(moe.c.expert_base, rank * 64);
int asym_w4_gemms = 0;
for (const RecOp& op : b.ops) {
const RecParam* dtype = op.op == "gemm_nt_q" ? param(&op, "dtype") : nullptr;
if (dtype && dtype->sval == "w4a8i8_asym") ++asym_w4_gemms;
}
CHECK(asym_w4_gemms > 0);
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch;
hyv3_bf16::step(&run, &batch);
CHECK(lint_step(b, {&run}).empty());
}
}
TEST(hyv3_bf16_supports_int8_linear_recipes_at_tp2) {
RadModelMeta meta = hyv3_fp8_test_meta();
meta.quant = "";
const RadEncoding plain = rad_enc_plain(RAD_BF16);
const RadEncoding w8 = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
for (int rank = 0; rank < 2; ++rank) {
RadBuilder b;
b.encs = {
{ "attn_q.weight", w8 }, { "attn_k.weight", w8 },
{ "attn_v.weight", w8 }, { "attn_output.weight", w8 },
{ "ffn_gate_up.weight", w8 }, { "ffn_down.weight", w8 },
{ "ffn_gate_up_exps", plain }, { "ffn_down_exps", plain },
{ "ffn_gate_up_shexp.weight", w8 }, { "ffn_down_shexp.weight", w8 },
{ "output.weight", w8 },
};
RadBuildCtx ctx = build_ctx(rank, 2);
const int rc = hyv3_bf16::declare(&b, &meta, &ctx);
CHECK_EQ(rc, RAD_OK);
if (rc < 0) continue;
int i8_gemms = 0;
for (const RecOp& op : b.ops) {
const RecParam* dtype = op.op == "gemm_nt_q" ? param(&op, "dtype") : nullptr;
if (dtype && dtype->sval == "i8a8") ++i8_gemms;
}
CHECK(i8_gemms > 0);
CHECK_EQ(find_w(b, "output.weight")->d.dtype, (uint32_t)RAD_I8);
const auto& moe = hyv3_bf16::models[rank].layers[1].moe;
CHECK_EQ(moe.c.expert_bf16, 1);
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch;
hyv3_bf16::step(&run, &batch);
CHECK(lint_step(b, {&run}).empty());
}
}
TEST(hyv3_bf16_selects_block_fp8_and_mxfp4_expert_formats) {
RadModelMeta meta = hyv3_fp8_test_meta();
meta.quant = "";
const RadEncoding plain = rad_enc_plain(RAD_BF16);
const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
for (int format = 0; format < 2; ++format) {
const RadEncoding encoded = format == 0 ? fp8 : mx;
for (int rank = 0; rank < 2; ++rank) {
RadBuilder b;
b.encs = {
{ "attn_q.weight", encoded }, { "attn_k.weight", encoded },
{ "attn_v.weight", encoded }, { "attn_output.weight", encoded },
{ "ffn_gate_up.weight", encoded }, { "ffn_down.weight", encoded },
{ "ffn_gate_up_exps", encoded }, { "ffn_down_exps", encoded },
{ "ffn_gate_up_shexp.weight", encoded }, { "ffn_down_shexp.weight", encoded },
{ "output.weight", plain },
};
RadBuildCtx ctx = build_ctx(rank, 2);
const int rc = hyv3_bf16::declare(&b, &meta, &ctx);
CHECK_EQ(rc, RAD_OK);
if (rc < 0) continue;
const auto& moe = hyv3_bf16::models[rank].layers[1].moe;
CHECK_EQ(moe.c.expert_f32_scale, format == 0 ? 1 : 0);
CHECK_EQ(moe.c.expert_mx, format == 0 ? 0 : 1);
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch;
hyv3_bf16::step(&run, &batch);
CHECK(lint_step(b, {&run}).empty());
}
}
}
TEST(hyv3_fp8_declares_dense_then_sigmoid_moe_with_fp32_combine) {
RadModelMeta meta = hyv3_fp8_test_meta();
RadBuildCtx ctx = build_ctx();
RadBuilder b;
RadArchProbe probe{};
CHECK_OK(hyv3_fp8::probe(&meta, &probe));
const int rc = hyv3_fp8::declare(&b, &meta, &ctx);
CHECK_EQ(rc, RAD_OK);
if (rc < 0) return;
const RecWeight* q_norm = find_w(b, "blk.0.attn_q_norm.weight");
const RecWeight* dense = find_w(b, "blk.0.ffn_gate_up.weight");
const RecWeight* expert = find_w(b, "blk.1.ffn_gate_up_exps.0.weight");
const RecMap* expert_map = find_map(b, "blk.1.ffn_gate_up_exps.0.weight");
const RecWeight* shared = find_w(b, "blk.1.ffn_gate_up_shexp.weight");
const RecWeight* router = find_w(b, "blk.1.glm_router.weight");
const RecWeight* bias = find_w(b, "blk.1.glm_router.correction");
CHECK(q_norm && dense && expert && expert_map && shared && router && bias);
CHECK_EQ(expert_map->src.size(), 2u);
CHECK_EQ(expert_map->src[0], std::string("model.layers.1.mlp.experts.0.gate_proj.weight"));
CHECK_EQ(expert_map->src[1], std::string("model.layers.1.mlp.experts.0.up_proj.weight"));
CHECK_EQ(q_norm->d.shape[0], 128);
CHECK_EQ(dense->d.shape[0], 13824); CHECK_EQ(dense->d.shape[1], 2048);
CHECK_EQ(expert->d.shape[0], 1536); CHECK_EQ(expert->d.shape[1], 2048);
CHECK_EQ(shared->d.shape[0], 1536); CHECK_EQ(shared->d.shape[1], 2048);
CHECK_EQ(router->d.shape[0], 128); CHECK_EQ(router->d.shape[1], 2048);
CHECK_EQ(bias->d.shape[0], 128); CHECK_EQ(bias->d.dtype, (uint32_t)RAD_F32);
auto& model = hyv3_fp8::models[0];
auto& moe = model.layers[1].moe;
CHECK_EQ(moe.c.n_ff_exp, 768); CHECK_EQ(moe.c.n_ff_shared, 768);
CHECK_EQ(moe.c.expert_f32_scale, 1);
CHECK_EQ(moe.c.route_scale, 2.826); CHECK_EQ(moe.c.sigmoid_router, 1);
CHECK_EQ(moe.c.shared_fp32_combine, 1); CHECK_EQ(moe.gfold, false);
const RecOp* gather = b.op_of(moe.op_gather);
CHECK(gather != nullptr);
CHECK_EQ(gather->writes.size(), 1u);
CHECK_EQ(gather->writes[0], moe.w.moe);
CHECK(moe.op_moe_to_f32 && moe.op_shared_to_f32 && moe.op_combine_f32 &&
moe.op_combined_to_bf16);
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch;
hyv3_fp8::step(&run, &batch);
auto issue_of = [&](rad_op h) {
for (size_t i = 0; i < run.issues.size(); ++i)
if (run.issues[i].op == h) return (int)i;
return -1;
};
const int gather_i = issue_of(moe.op_gather), routed_i = issue_of(moe.op_moe_to_f32);
const int shared_i = issue_of(moe.op_shared_to_f32), add_i = issue_of(moe.op_combine_f32);
const int cast_i = issue_of(moe.op_combined_to_bf16);
CHECK(gather_i >= 0 && routed_i >= 0 && shared_i >= 0 && add_i >= 0 && cast_i >= 0);
CHECK(gather_i < routed_i && routed_i < add_i && shared_i < add_i && add_i < cast_i);
const auto lint = lint_step(b, {&run});
CHECK(lint.empty());
}
TEST(hyv3_fp8_tensor_parallel_partitions_experts_and_shared_width) {
RadModelMeta meta = hyv3_fp8_test_meta();
for (int rank = 0; rank < 2; ++rank) {
RadBuildCtx ctx = build_ctx(rank, 2);
ctx.kv_dtype = RAD_F8E4M3;
RadBuilder b;
const int rc = hyv3_fp8::declare(&b, &meta, &ctx);
CHECK_EQ(rc, RAD_OK);
if (rc < 0) continue;
auto& model = hyv3_fp8::models[rank];
const auto& moe = model.layers[1].moe;
CHECK_EQ(moe.c.n_expert, 64);
CHECK_EQ(moe.c.expert_base, rank * 64);
CHECK_EQ(moe.c.n_ff_shared, 384);
CHECK_EQ(moe.c.shared_lo, rank * 384);
CHECK_EQ(moe.c.shared_hi, (rank + 1) * 384);
CHECK(moe.op_moe_ar && moe.op_shared_ar && !moe.op_ar);
CHECK(find_w(b, rank == 0 ? "blk.1.ffn_gate_up_exps.0.weight"
: "blk.1.ffn_gate_up_exps.64.weight") != nullptr);
CHECK_EQ(model.g.n_ff, 3456);
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch; run.rank = rank;
hyv3_fp8::step(&run, &batch);
auto issue_of = [&](rad_op h) {
for (size_t i = 0; i < run.issues.size(); ++i)
if (run.issues[i].op == h) return (int)i;
return -1;
};
CHECK(issue_of(moe.op_gather) < issue_of(moe.op_moe_ar));
CHECK(issue_of(moe.op_moe_ar) < issue_of(moe.op_moe_to_f32));
CHECK(issue_of(moe.op_shared_ar) < issue_of(moe.op_shared_to_f32));
CHECK(issue_of(moe.op_combine_f32) < issue_of(moe.op_combined_to_bf16));
CHECK(lint_step(b, {&run}).empty());
}
}
TEST(hyv3_fp8_uses_static_layerwise_fp8_kv_descales) {
RadModelMeta meta = hyv3_fp8_test_meta();
RadBuildCtx ctx = build_ctx();
ctx.kv_dtype = RAD_F8E4M3;
RadBuilder b;
const int rc = hyv3_fp8::declare(&b, &meta, &ctx);
CHECK_EQ(rc, RAD_OK);
if (rc < 0) return;
CHECK_EQ(b.kv_groups[0].d.dtype, (uint32_t)RAD_F8E4M3);
auto& attn = hyv3_fp8::models[0].layers[0].attn;
CHECK(attn.op_k_descale && attn.op_v_descale);
CHECK(attn.k_descale && attn.v_descale);
const RecWeight* q = find_w(b, "blk.0.attn_q.weight");
CHECK(q != nullptr);
if (q) CHECK_EQ(q->d.shape[0], 4096);
const RecOp* k_fill = b.op_of(attn.op_k_descale);
const RecOp* v_fill = b.op_of(attn.op_v_descale);
CHECK(k_fill != nullptr && v_fill != nullptr);
if (k_fill) CHECK(std::fabs(pflt(k_fill, "value") - 0.0376674123) < 1e-9);
if (v_fill) CHECK(std::fabs(pflt(v_fill, "value") - 0.0004359654) < 1e-10);
const RecOp* store = b.op_of(attn.op_kv_store);
CHECK(store != nullptr);
if (store) {
CHECK(std::fabs(pflt(store, "k_scale") - 0.0376674123) < 1e-9);
CHECK(std::fabs(pflt(store, "v_scale") - 0.0004359654) < 1e-10);
}
const auto& attn1 = hyv3_fp8::models[0].layers[1].attn;
const RecOp* store1 = b.op_of(attn1.op_kv_store);
CHECK(store1 != nullptr);
if (store1) {
CHECK(std::fabs(pflt(store1, "k_scale") - 0.0224609375) < 1e-10);
CHECK(std::fabs(pflt(store1, "v_scale") - 0.0005318778) < 1e-10);
}
RadBatch batch = decode_batch();
RadCtx run{}; run.b = &b; run.batch = &batch;
hyv3_fp8::step(&run, &batch);
auto issue_of = [&](rad_op h) {
for (size_t i = 0; i < run.issues.size(); ++i)
if (run.issues[i].op == h) return (int)i;
return -1;
};
CHECK(issue_of(attn.op_k_descale) < issue_of(attn.op_attn));
CHECK(issue_of(attn.op_v_descale) < issue_of(attn.op_attn));
CHECK(lint_step(b, {&run}).empty());
}
TEST(the_alternation_puts_full_attention_at_3_and_7) {
RadBuilder b;
RadModelMeta meta = qwen35_meta();
@@ -3823,6 +4306,47 @@ TEST(gemma4_declares_two_kv_groups_and_binds_the_schedule) {
}
}
/* A step with an image: the rows go into the token lookup before its all-reduce, since
* RadBatch::mm_embd holds them at rank 0 and zeros at every other rank. */
TEST(gemma4_scatters_image_rows_into_the_lookup_before_its_all_reduce) {
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));
const char* vk[] = { "vision_config.model_type", "vision_config.hidden_size",
"vision_config.num_attention_heads", "vision_config.head_dim",
"vision_config.intermediate_size", "vision_config.pooling_kernel_size",
"vision_config.position_embedding_size", "vision_config.num_hidden_layers",
"vision_config.patch_size", "vision_config.rope_parameters.rope_theta",
"vision_config.rope_parameters.rope_type", "vision_config.hidden_activation" };
const char* vv[] = { "gemma4_vision", "768", "12", "64", "3072", "3", "10240", "2", "16", "100",
"default", "gelu_pytorch_tanh" };
keys.insert(keys.end(), std::begin(vk), std::end(vk));
vals.insert(vals.end(), std::begin(vv), std::end(vv));
static const int32_t rows[] = { 4, 5, 6, 7, 8, 9, 10, 11 };
static uint16_t embd[8 * 5376];
for (int world : { 1, 2 }) {
for (int rank = 0; rank < world; ++rank) {
RadBuilder b;
RadModelMeta meta = gemma4_meta();
meta.n_kv = (int)keys.size(); meta.kv_key = keys.data(); meta.kv_val = vals.data();
RadBuildCtx ctx = build_ctx(rank, world);
ctx.max_enc_patches = 9 * 64;
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
RadBatch batch = prefill_batch();
batch.n_mm_rows = 8; batch.mm_rows = rows; batch.mm_embd = embd;
RadCtx c; c.b = &b; c.rank = rank; c.world = world; c.batch = &batch;
gemma4_bf16::step(&c, &batch);
CHECK_LINT(b, &c);
CHECK(c.step_fail.empty());
const std::vector<std::string> ops = issued_ops(b, c);
REQUIRE(ops.size() > 3);
CHECK_EQ(ops[0], std::string("embed_lookup"));
CHECK_EQ(ops[1], std::string("scatter_rows"));
CHECK(c.issues[1].opd[0].raw == embd);
if (world == 2) CHECK_EQ(ops[2], std::string("all_reduce"));
}
}
}
/* The E2B/E4B form on the same twelve layers: the last four share KV (no cache of their own),
* per-layer embeddings 64 wide, a global class with its own v (attention_k_eq_v 0) and no
* num_global_key_value_heads, so the global layers take num_key_value_heads. */
@@ -3885,13 +4409,103 @@ TEST(a_gemma4_e4b_form_shares_kv_and_runs_the_per_layer_branch) {
}
}
/* The per-layer branch is not split across ranks, and a model whose every layer shares KV has no
* cache to read. */
/* At two ranks the per-layer table is vocab-sharded like the token table and its lookup is reduced
* like the token lookup, before anything reads it; the rest of the branch is replicated. A step
* reduces the two lookups and, a layer, attention's and the feed-forward's partial sums -- folded
* into the attention junction where it resolves -- and never the branch's output, which every rank
* holds whole. The prefill overlap, whose slices skip the branch, stays off. */
TEST(the_gemma4_e4b_form_runs_at_two_ranks) {
const int64_t L = 12, P = 12 * 64;
for (bool w4 : { false, true }) {
for (int rank : { 0, 1 }) {
RadBuilder b;
if (w4) {
const RadEncoding e = rad_enc_affine(RAD_I4, RAD_F16, 1, 128);
b.encs = { { "attn_q.", e }, { "attn_k.", e }, { "attn_v.", e }, { "attn_o.", e },
{ "ffn_gate_up.", e }, { "ffn_down.", e } };
}
RadModelMeta meta = gemma4_e4b_meta();
RadBuildCtx ctx = build_ctx(rank, 2);
ctx.max_tok = 4096; /* past two slices of the overlap */
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
CHECK(!gemma4_bf16::g_model[rank].overlap);
CHECK_EQ(gemma4_bf16::g_model[rank].fuse, w4);
/* the per-layer table takes the token table's slice of the vocabulary */
const RecOp* tok = find_op(b, "embed_lookup", 0);
const RecOp* ple = find_op(b, "embed_lookup", 1);
REQUIRE(tok != nullptr && ple != nullptr);
CHECK_EQ(pint(ple, "n_embd"), P);
CHECK_EQ(pint(ple, "n_vocab"), pint(tok, "n_vocab"));
CHECK_EQ(pint(ple, "vocab_offset"), pint(tok, "vocab_offset"));
RadBatch batch = decode_batch();
RadCtx c; c.b = &b; c.rank = rank; c.world = 2; c.batch = &batch;
gemma4_bf16::step(&c, &batch);
CHECK_LINT(b, &c);
CHECK(c.step_fail.empty());
const std::vector<std::string> ops = issued_ops(b, c);
REQUIRE(ops.size() > 4);
CHECK_EQ(ops[0], std::string("embed_lookup"));
CHECK_EQ(ops[1], std::string("all_reduce"));
CHECK_EQ(ops[2], std::string("embed_lookup"));
CHECK_EQ(ops[3], std::string("all_reduce"));
CHECK_EQ(c.issues[3].n, batch.n_tok * P);
const int folded = count_issued(ops, "ar_rmsnorm_quant_i8");
CHECK_EQ(count_issued(ops, "all_reduce") + folded, (int)(2 + 2 * L));
CHECK_EQ(folded, w4 ? (int)L : 0);
}
}
}
/* With an image at two ranks, the pad rows of the image positions go into the per-layer inputs
* after their lookup's all-reduce: every rank writes them whole, so before it they would count
* twice. */
TEST(the_gemma4_e4b_form_writes_image_pad_rows_after_the_per_layer_all_reduce) {
std::vector<const char*> keys(std::begin(k_gem4e_keys), std::end(k_gem4e_keys));
std::vector<const char*> vals(std::begin(k_gem4e_vals), std::end(k_gem4e_vals));
const char* vk[] = { "vision_config.model_type", "vision_config.hidden_size",
"vision_config.num_attention_heads", "vision_config.head_dim",
"vision_config.intermediate_size", "vision_config.pooling_kernel_size",
"vision_config.position_embedding_size", "vision_config.num_hidden_layers",
"vision_config.patch_size", "vision_config.rope_parameters.rope_theta",
"vision_config.rope_parameters.rope_type", "vision_config.hidden_activation" };
const char* vv[] = { "gemma4_vision", "768", "12", "64", "3072", "3", "10240", "2", "16", "100",
"default", "gelu_pytorch_tanh" };
keys.insert(keys.end(), std::begin(vk), std::end(vk));
vals.insert(vals.end(), std::begin(vv), std::end(vv));
static const int32_t rows[] = { 4, 5, 6, 7, 8, 9, 10, 11 };
static uint16_t embd[8 * 5376];
for (int rank : { 0, 1 }) {
RadBuilder b;
RadModelMeta meta = gemma4_e4b_meta();
meta.n_kv = (int)keys.size(); meta.kv_key = keys.data(); meta.kv_val = vals.data();
RadBuildCtx ctx = build_ctx(rank, 2);
ctx.max_enc_patches = 9 * 64;
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
RadBatch batch = prefill_batch();
batch.n_mm_rows = 8; batch.mm_rows = rows; batch.mm_embd = embd;
RadCtx c; c.b = &b; c.rank = rank; c.world = 2; c.batch = &batch;
gemma4_bf16::step(&c, &batch);
CHECK_LINT(b, &c);
CHECK(c.step_fail.empty());
const std::vector<std::string> ops = issued_ops(b, c);
size_t i = 0; /* the per-layer lookup: the second embed_lookup */
for (int seen = 0; i < ops.size(); ++i)
if (ops[i] == "embed_lookup" && ++seen == 2) break;
REQUIRE(i + 4 < ops.size());
const std::vector<std::string> want = { "all_reduce", "fill", "mul_weight", "scatter_rows" };
CHECK(std::vector<std::string>(ops.begin() + (long)i + 1, ops.begin() + (long)i + 5) == want);
}
}
/* The per-layer branch is served at one or two ranks, and a model whose every layer shares KV has
* no cache to read. */
TEST(the_gemma4_e4b_form_is_refused_where_it_cannot_run) {
{
RadBuilder b;
RadModelMeta meta = gemma4_e4b_meta();
RadBuildCtx ctx = build_ctx(0, 2);
RadBuildCtx ctx = build_ctx(0, 4);
CHECK_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_E_UNSUPPORTED);
}
{
@@ -10129,7 +10743,7 @@ TEST(flashnext_a_spanned_prefill_runs_a_pass_at_a_time_with_its_all_reduces_besi
ctx.max_mixed_tok = 2048;
REQUIRE_EQ(stderr_of_rc([&] { return qwen4exp_fp8::declare(&b, &meta, &ctx); }),
RAD_OK);
const qwen4exp_fp8::Model& m = qwen4exp_fp8::g_model[rank];
qwen4exp_fp8::Model& m = qwen4exp_fp8::g_model[rank];
CHECK(m.span_on);
CHECK_EQ(m.pipe_on, world > 2);
CHECK_EQ(m.qsacfg.plane_rows, 2048);
@@ -10165,6 +10779,10 @@ TEST(flashnext_a_spanned_prefill_runs_a_pass_at_a_time_with_its_all_reduces_besi
CHECK(score > 0);
CHECK_EQ(wide_score, 0);
CHECK(conv > 0);
/* This fake runtime has no engine teardown between model redeclarations. */
rad_dev_free(m.pipe_cu_h, RAD_MEM_HOST_PINNED);
m.pipe_cu_h = nullptr;
m.pipe_cu_tried = false;
if (world < 4) {
CHECK_EQ(ar, world > 1 ? 1 : 0);
CHECK_EQ(ar_lane0, ar);
@@ -10360,13 +10978,24 @@ MetaKV krea2_meta() {
} /* namespace */
/* `rebalance` (RAD_GEN_COND_REBALANCE, declared in the generator's cond_opts): each of the twelve
* taps is scaled into te.h2 by its gain (ComfyUI's ConditioningKrea2Rebalance at its defaults,
* multiplier 4 times 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1), f32 and rounded once, and the
* tap's scatter reads te.h2. Without it the pass issues no scale and scatters te.x. */
/* `rebalance` (RAD_GEN_COND_REBALANCE, declared in the generator's cond_opts with its presets):
* each of the twelve taps is scaled into te.h2 by its preset's gain (row 0 ComfyUI's
* ConditioningKrea2Rebalance at its defaults, multiplier 4 times 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1,
* 4, 1; rows 1 to 3 balanced, detail, subtle), f32 and rounded once, and the tap's scatter reads
* te.h2. Without it, or with a preset row the plugin does not know, the pass issues no scale and
* scatters te.x. */
TEST(krea2_rebalance_scales_each_tap_and_is_off_without_the_option) {
MetaKV mk = krea2_meta();
const double gains[12] = { 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 };
/* RAD_GEN_COND_REBALANCE_PRESET rows 0 (the default), 1 balanced, 2 detail, 3 subtle */
const double gains[4][12] = {
{ 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 },
{ 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 1.1027, 2.2055, 0.4852,
1.7644, 0.44109 },
{ 0.28562, 0.28562, 0.32132, 0.32132, 0.35702, 0.35702, 0.42842, 1.0711, 2.1421, 0.53553,
1.7851, 0.42842 },
{ 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 1.2714, 1.6952, 0.84759,
1.2714, 0.84759 },
};
RadArchProbe probe{};
REQUIRE_EQ(krea2::probe(mk.meta(), &probe), RAD_OK);
CHECK_EQ(probe.gen_rows, (int64_t)2 * (16384 + 512));
@@ -10375,7 +11004,8 @@ TEST(krea2_rebalance_scales_each_tap_and_is_off_without_the_option) {
RadBuilder b;
RadBuildCtx ctx = qimg_ctx(rank, world);
REQUIRE_EQ(stderr_of_rc([&] { return krea2::declare(&b, mk.meta(), &ctx); }), RAD_OK);
CHECK_EQ(b.generator.cond_opts, (uint32_t)RAD_GEN_COND_REBALANCE);
CHECK_EQ(b.generator.cond_opts,
(uint32_t)(RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET));
const RecBuf* bx = find_b(b, "te.x");
const RecBuf* bh = find_b(b, "te.h2");
const RecBuf* bt = find_b(b, "te.taps");
@@ -10383,9 +11013,13 @@ TEST(krea2_rebalance_scales_each_tap_and_is_off_without_the_option) {
const rad_buf x = (rad_buf)(bx - b.bufs.data() + 1);
const rad_buf h2 = (rad_buf)(bh - b.bufs.data() + 1);
const rad_buf taps = (rad_buf)(bt - b.bufs.data() + 1);
for (bool rebalance : { false, true }) {
/* -1: no option; 0 to 3 the presets; 4 a row the plugin does not know */
for (int preset : { -1, 0, 1, 2, 3, 4 }) {
const bool rebalance = preset >= 0 && preset < 4;
auto k = gen_pass(b, RAD_GEN_PASS_COND, 12);
k->g.cond_opts = rebalance ? RAD_GEN_COND_REBALANCE : 0;
k->g.cond_opts = preset >= 0 ? RAD_GEN_COND_REBALANCE |
(preset << RAD_GEN_COND_REBALANCE_PRESET_SHIFT)
: 0;
RadCtx c{ .b = &b, .batch = &k->b, .rank = rank, .world = world };
krea2::step(&c, &k->b);
CHECK(c.step_fail.empty());
@@ -10418,7 +11052,7 @@ TEST(krea2_rebalance_scales_each_tap_and_is_off_without_the_option) {
const std::vector<double> mul = list(pstr(g, "mul")), add = list(pstr(g, "add"));
CHECK_EQ(mul.size(), (size_t)64);
CHECK_EQ(add.size(), (size_t)64);
for (double v : mul) CHECK_EQ(v, gains[tap]);
for (double v : mul) CHECK_EQ(v, gains[preset][tap]);
for (double v : add) CHECK_EQ(v, 0.0);
}
++tap;
+58
View File
@@ -87,6 +87,12 @@ static const TemplateFixture& qwen() {
return f;
}
static const TemplateFixture& hyv3() {
static const TemplateFixture f("RAD_TEST_HYV3_JINJA", "hyv3/chat_template.jinja",
"<|hy_begin▁of▁sentence|>", "<eos:6124c78e>");
return f;
}
static json tools_json() {
return json::parse(R"([{
"type": "function",
@@ -106,6 +112,58 @@ static json tools_json() {
"required":["path","old_string","new_string"]}}}])");
}
static json hyv3_tools_json() {
return json::parse(R"([{
"type":"function","function":{"name":"lookup_weather","description":"Look up weather.",
"parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}},
{"type":"function","function":{"name":"add","description":"Add two integers.",
"parameters":{"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"integer"}},
"required":["a","b"]}}}])");
}
TEST(hyv3_template_renders_openai_tool_schemas_and_replayed_history) {
if (!hyv3().need()) return;
REQUIRE(hyv3().t->caps().tools && hyv3().t->caps().tool_calls);
const json tools = hyv3_tools_json();
json messages = json::array({
{{"role", "system"}, {"content", "Use tools when useful."}},
{{"role", "user"}, {"content", "Check Toronto weather and add 20 and 22."}}
});
ChatOptions opt;
opt.add_generation_prompt = true;
ChatPrompt prompt;
CHECK_OK(hyv3().t->apply(messages, tools, opt, &prompt));
if (!prompt.error.empty()) return;
CHECK(prompt.prompt.find("<tools>") != std::string::npos);
CHECK(prompt.prompt.find("<tool_calls>") != std::string::npos);
CHECK(prompt.prompt.find("<tool_call>{function-name}<tool_sep>") != std::string::npos);
CHECK(prompt.generation_prompt.find("<|hy_Assistant|>") != std::string::npos);
messages.push_back({{"role", "assistant"}, {"content", ""},
{"tool_calls", json::array({
{{"id", "call-weather"}, {"type", "function"},
{"function", {{"name", "lookup_weather"},
{"arguments", "{\"city\":\"Toronto\"}"}}}},
{{"id", "call-add"}, {"type", "function"},
{"function", {{"name", "add"}, {"arguments", "{\"a\":20,\"b\":22}"}}}}
})}});
messages.push_back({{"role", "tool"}, {"tool_call_id", "call-weather"},
{"content", "Cloudy, 12 C."}});
messages.push_back({{"role", "tool"}, {"tool_call_id", "call-add"}, {"content", "42"}});
messages.push_back({{"role", "user"}, {"content", "Summarize the results."}});
prompt = ChatPrompt{};
CHECK_OK(hyv3().t->apply(messages, tools, opt, &prompt));
if (!prompt.error.empty()) return;
CHECK(prompt.prompt.find("<tool_calls>") != std::string::npos);
CHECK(prompt.prompt.find("<tool_call>lookup_weather<tool_sep>") != std::string::npos);
CHECK(prompt.prompt.find("<arg_key>city</arg_key>") != std::string::npos);
CHECK(prompt.prompt.find("Toronto") != std::string::npos);
CHECK(prompt.prompt.find("<tool_responses>") != std::string::npos);
CHECK(prompt.prompt.find("Cloudy, 12 C.") != std::string::npos);
CHECK(prompt.prompt.find("<tool_response>\n42\n</tool_response>") != std::string::npos);
CHECK(prompt.prompt.find("Summarize the results.") != std::string::npos);
}
/* Render one turn, passing `effort` as the template's reasoning_effort when set. */
static int render_turn(ChatPrompt* p, bool with_tools, const char* effort) {
json msgs = json::array();
+251 -1
View File
@@ -1052,6 +1052,33 @@ TEST(no_template_is_a_format_with_no_reasoning_and_no_calls) {
static const char* const kBreaks[] = { "<tool_call>\n" };
static const char* const kTriggers[] = { "<tool_call>\n" };
static RadChatFormat hyv3_abi() {
static const char* const triggers[] = { "<tool_calls>" };
RadChatFormat c;
std::memset(&c, 0, sizeof c);
c.struct_size = sizeof c;
c.name = "hyv3-native";
c.reasoning_open = "<think>";
c.reasoning_close = "</think>";
c.reasoning_breaks = triggers;
c.n_reasoning_breaks = 1;
c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
c.section_open = "<tool_calls>";
c.section_close = "</tool_calls>";
c.name_prefix = "<tool_call>";
c.name_suffix = "<tool_sep>";
c.call_end = "</tool_call>";
c.arg_prefix = "<arg_key>";
c.arg_name_suffix = "</arg_key>\n";
c.arg_value_prefix = "<arg_value>";
c.arg_value_suffix = "</arg_value>";
c.string_value = RAD_CHAT_VALUE_RAW;
c.other_value = RAD_CHAT_VALUE_JSON;
c.triggers = triggers;
c.n_triggers = 1;
return c;
}
static RadChatFormat qwen_abi() {
RadChatFormat c;
std::memset(&c, 0, sizeof c);
@@ -1268,7 +1295,7 @@ TEST(a_format_the_parser_cannot_read_is_refused_by_name) {
CHECK(refused([](RadChatFormat& c) { c.arg_prefix = "</function>\n"; }, "told apart"));
CHECK(refused([](RadChatFormat& c) { c.reasoning_close = ""; }, "reasoning_close"));
static const char* const other[] = { "<call>" };
CHECK(refused([](RadChatFormat& c) { c.reasoning_breaks = other; }, "call opener"));
CHECK(refused([](RadChatFormat& c) { c.reasoning_breaks = other; }, "opener"));
CHECK(refused([](RadChatFormat& c) { c.string_value = RAD_CHAT_VALUE_JSON; }, "string_value"));
}
@@ -1446,6 +1473,68 @@ TEST(the_chat_bridge_derives_the_whole_request_from_one_format) {
CHECK(why.find("a>b") != std::string::npos);
}
/* The declared format preserves HYV3's outer section and all of its argument markers. */
TEST(hyv3_plugin_format_runs_through_the_chat_template_bridge) {
std::shared_ptr<Vocab> v = vocab_with(fixture("hyv3"));
REQUIRE(v != nullptr);
RadChatFormat c = hyv3_abi();
server::ChatTemplateBridge br;
CHECK_OK(br.init(*v, &c, "hyv3_bf16"));
CHECK(br.supports_tools());
CHECK_EQ(br.tool_refusal(), std::string());
const json tools = json::parse(R"([{"type":"function","function":{"name":"lookup_weather",
"parameters":{"type":"object","properties":{"city":{"type":"string"}},
"required":["city"]}}}])");
const server::ChatRender r = bridge_render(br, tools);
REQUIRE(!r.prompt.empty());
CHECK(!r.grammar.empty());
CHECK(r.grammar_lazy);
REQUIRE(r.grammar_triggers.size() == 1);
CHECK_EQ(r.grammar_triggers[0].value, std::string("<tool_calls>"));
for (const char* marker : { "<think>", "</think>", "<tool_calls>", "</tool_calls>",
"<tool_call>", "<tool_sep>",
"<arg_key>", "</arg_key>", "<arg_value>", "</arg_value>" })
CHECK(std::find(r.preserved_tokens.begin(), r.preserved_tokens.end(), marker) !=
r.preserved_tokens.end());
REQUIRE(r.parser != nullptr);
std::unique_ptr<server::IReplyReader> rd = r.parser->open();
rd->feed("Cloudy.\n<tool_calls><tool_call>lookup_weather<tool_sep>\n"
"<arg_key>city</arg_key>\n<arg_value>Toronto</arg_value>\n"
"</tool_call></tool_calls>", nullptr);
rd->finish(nullptr);
const server::ParsedMessage pm = rd->message();
CHECK_EQ(pm.content, std::string("Cloudy."));
REQUIRE(pm.tool_calls.size() == 1);
CHECK_EQ(pm.tool_calls[0].name, std::string("lookup_weather"));
CHECK_EQ(pm.tool_calls[0].arguments, std::string("{\"city\":\"Toronto\"}"));
}
TEST(hyv3_plugin_format_splits_requested_reasoning_before_native_tools) {
std::shared_ptr<Vocab> v = vocab_with(fixture("hyv3"));
REQUIRE(v != nullptr);
RadChatFormat c = hyv3_abi();
server::ChatTemplateBridge br;
CHECK_OK(br.init(*v, &c, "hyv3_bf16"));
const json msgs = json::array({ { {"role", "user"}, {"content", "List the files."} } });
server::ChatRenderOptions opt;
opt.template_kwargs["reasoning_effort"] = json("high").dump();
server::ChatRender out;
std::string why;
CHECK_OK(br.apply(msgs, agent_tools(), opt, &out, &why));
REQUIRE(out.parser != nullptr);
CHECK(out.generation_prompt.ends_with("<think>"));
auto rd = out.parser->open();
rd->feed("Plan.</think>Checking.<tool_calls><tool_call>bash<tool_sep>"
"<arg_key>command</arg_key>\n<arg_value>ls</arg_value>"
"</tool_call></tool_calls>", nullptr);
rd->finish(nullptr);
const server::ParsedMessage m = rd->message();
CHECK_EQ(m.reasoning, std::string("Plan."));
CHECK_EQ(m.content, std::string("Checking."));
REQUIRE(m.tool_calls.size() == 1);
CHECK_EQ(m.tool_calls[0].name, std::string("bash"));
}
/* GLM-5.3-Flash's template reads list items as `m.content.0.type`, jinja2's dotted index, and
* writes calls as `<tool_call>NAME<arg_key>K</arg_key><arg_value>V</arg_value></tool_call>`. The
* capability probe renders with tools and tool calls, so a runtime that throws on the dotted index
@@ -1579,6 +1668,167 @@ static int object_admits(const std::string& gbnf, const std::string& text) {
return gr->complete() ? 1 : 0;
}
TEST(hyv3_sectioned_tagged_calls_parse_stream_and_constrain) {
RadChatFormat abi = hyv3_abi();
ChatFormat f;
std::string why;
CHECK_OK(chat_format_from_abi(&abi, &f, &why));
CHECK_OK(chat_format_check(f, &why));
const json tools = json::parse(R"([{"type":"function","function":{"name":"lookup_weather",
"parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}},
{"type":"function","function":{"name":"add","parameters":{"type":"object",
"properties":{"a":{"type":"integer"},"b":{"type":"integer"}},"required":["a","b"]}}}])");
ReplyOptions ro;
ro.tools = &tools;
const std::shared_ptr<const ReplyParser> p = parser_of(f, ro);
REQUIRE(p != nullptr);
const std::string reply =
"Checking both results.<tool_calls>\n"
"<tool_call>lookup_weather<tool_sep>\n"
"<arg_key>city</arg_key>\n<arg_value>Québec & Montréal</arg_value>\n"
"</tool_call>\n"
"<tool_call>add<tool_sep>\n"
"<arg_key>a</arg_key>\n<arg_value>20</arg_value>\n"
"<arg_key>b</arg_key>\n<arg_value>22</arg_value>\n"
"</tool_call>\n</tool_calls>";
bool strict = false;
const ReplyMessage m = reply_parse(*p, reply, &strict);
CHECK(strict);
CHECK_EQ(m.content, std::string("Checking both results."));
REQUIRE(m.calls.size() == 2);
CHECK_EQ(m.calls[0].name, std::string("lookup_weather"));
CHECK_EQ(m.calls[0].arguments, std::string("{\"city\":\"Québec & Montréal\"}"));
CHECK(m.calls[0].closed);
CHECK_EQ(m.calls[1].name, std::string("add"));
CHECK_EQ(m.calls[1].arguments, std::string("{\"a\":20,\"b\":22}"));
CHECK(m.calls[1].closed);
CHECK(m.content.find("<tool_calls>") == std::string::npos);
CHECK(m.content.find("</tool_calls>") == std::string::npos);
const std::string stream_error = stream_all(*p, reply);
if (!stream_error.empty()) ::radtest::fail(__FILE__, __LINE__, stream_error);
ChatGrammarRequest gq;
gq.tools = &tools;
ChatGrammar g;
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
CHECK(g.lazy);
CHECK(g.trigger_words == std::vector<std::string>{ "<tool_calls>" });
const size_t section = reply.find("<tool_calls>");
REQUIRE(section != std::string::npos);
CHECK_EQ(object_admits(g.text, reply.substr(section)), 1);
gq.parallel_tool_calls = false;
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
CHECK_EQ(object_admits(g.text, reply.substr(section)), 0);
/* A quoted call tag outside the section remains user-visible content, not an invocation. */
const std::string outside = "Example: <tool_call>add<tool_sep>";
const ReplyMessage quoted = reply_parse(*p, outside, &strict);
CHECK_EQ(quoted.calls.size(), (size_t)0);
CHECK_EQ(quoted.content, outside);
/* A section close cannot turn a call missing its own close tag into an executable call. */
const std::string truncated =
"<tool_calls>\n<tool_call>add<tool_sep>\n"
"<arg_key>a</arg_key>\n<arg_value>20</arg_value>\n</tool_calls>";
const ReplyMessage incomplete = reply_parse(*p, truncated, &strict);
CHECK(!strict);
REQUIRE(incomplete.calls.size() == 1);
CHECK(!incomplete.calls[0].closed);
const std::string truncated_stream_error = stream_all(*p, truncated);
if (!truncated_stream_error.empty())
::radtest::fail(__FILE__, __LINE__, truncated_stream_error);
}
TEST(section_wrapped_calls_do_not_cross_section_boundaries) {
ChatFormat f;
std::string why;
RadChatFormat abi = hyv3_abi();
CHECK_OK(chat_format_from_abi(&abi, &f, &why));
ReplyOptions ro;
ro.tools = &agent_tools();
const auto p = parser_of(f, ro);
REQUIRE(p != nullptr);
const std::string call = "<tool_call>bash<tool_sep>"
"<arg_key>command</arg_key>\n<arg_value>ls</arg_value></tool_call>";
ChatGrammarRequest gq;
gq.tools = &agent_tools();
ChatGrammar g;
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
CHECK_EQ(object_admits(g.text, "<tool_calls>" + call + call + "</tool_calls>"), 1);
/* The inter-call grammar must not swallow an earlier section close as prose. */
CHECK_EQ(object_admits(g.text, "<tool_calls>" + call + "</tool_calls>" +
call + "</tool_calls>"), 0);
/* A wrapped dialect whose call close duplicates call_end has no distinct close scanner.
* Its section close must still abandon a malformed call, not close it as executable. */
f.call_open = "<call>";
f.call_close = f.call_end;
const auto wrapped = parser_of(f, ro);
REQUIRE(wrapped != nullptr);
bool strict = true;
const std::string malformed = "<tool_calls><call><tool_call>bash<tool_sep>junk</tool_calls>";
const ReplyMessage m = reply_parse(*wrapped, malformed, &strict);
CHECK(!strict);
REQUIRE(m.calls.size() == 1);
CHECK(!m.calls[0].closed);
const std::string err = stream_all(*wrapped, malformed);
if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err);
}
TEST(section_wrapped_calls_stream_consistently_at_every_truncation) {
ChatFormat f;
std::string why;
RadChatFormat abi = hyv3_abi();
CHECK_OK(chat_format_from_abi(&abi, &f, &why));
ReplyOptions ro;
ro.tools = &agent_tools();
const auto p = parser_of(f, ro);
REQUIRE(p != nullptr);
const std::string call = "<tool_call>bash<tool_sep>"
"<arg_key>command</arg_key>\n<arg_value>ls</arg_value></tool_call>";
const std::string reply = "<tool_calls>" + call + call + "</tool_calls>";
for (size_t n = 0; n <= reply.size(); ++n) {
const std::string err = stream_all(*p, reply.substr(0, n), 0);
if (!err.empty()) {
::radtest::fail(__FILE__, __LINE__, "truncated at " + std::to_string(n) + ": " + err);
break;
}
}
const ReplyMessage incomplete = reply_parse(*p, "<tool_calls>" + call);
REQUIRE(incomplete.calls.size() == 1);
CHECK(!incomplete.calls[0].closed);
}
TEST(section_wrapped_calls_cannot_bypass_the_wrapper_in_reasoning) {
ChatFormat f;
std::string why;
RadChatFormat abi = hyv3_abi();
CHECK_OK(chat_format_from_abi(&abi, &f, &why));
f.reasoning_open = "<think>";
f.reasoning_close = "</think>";
f.reasoning_breaks = { f.section_open, f.name_prefix };
ReplyOptions ro;
ro.tools = &agent_tools();
const auto p = parser_of(f, ro);
REQUIRE(p != nullptr);
const std::string call = "<tool_call>bash<tool_sep>"
"<arg_key>command</arg_key>\n<arg_value>ls</arg_value></tool_call>";
const std::string text = "<think>Example: " + call + "</think>Answer.";
const ReplyMessage quoted = reply_parse(*p, text);
CHECK(quoted.calls.empty());
CHECK_EQ(quoted.reasoning, "Example: " + call);
CHECK_EQ(quoted.content, std::string("Answer."));
const std::string err = stream_all(*p, text);
if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err);
const ReplyMessage actual = reply_parse(*p, "<think>Plan.<tool_calls>" + call +
"</tool_calls>");
REQUIRE(actual.calls.size() == 1);
CHECK(actual.calls[0].closed);
}
TEST(json_arguments_behind_a_name_tag_read_as_one_object) {
std::shared_ptr<const ReplyParser> p = object_format(false);
REQUIRE(p != nullptr);
+143 -8
View File
@@ -60,7 +60,8 @@ void write_shard(const std::string& path, const std::vector<T>& ts) {
const uint64_t n = hdr.size();
std::fwrite(&n, 8, 1, f);
std::fwrite(hdr.data(), 1, hdr.size(), f);
for (const T& t : ts) std::fwrite(t.bytes.data(), 1, t.bytes.size(), f);
for (const T& t : ts)
if (!t.bytes.empty()) std::fwrite(t.bytes.data(), 1, t.bytes.size(), f);
std::fclose(f);
}
@@ -88,6 +89,12 @@ T bf16(const std::string& name, std::vector<int64_t> shape, float tag) {
return t;
}
T cache_scale_f32(const std::string& name, float value) {
T t{ name, "F32", {1}, std::vector<uint8_t>(4) };
std::memcpy(t.bytes.data(), &value, sizeof value);
return t;
}
T fp8(const std::string& name, std::vector<int64_t> shape) {
T t{ name, "F8_E4M3", shape, {} };
int64_t n = 1;
@@ -1684,6 +1691,53 @@ struct ConfigCase {
} /* namespace */
TEST(hyv3_static_kv_cache_scales_are_carried_into_model_metadata) {
const std::string dir = fresh_dir();
write_file(dir + "/config.json", R"({"model_type":"hy_v3","num_hidden_layers":1})");
write_shard(dir + "/kv_cache_scales.safetensors", {
cache_scale_f32("model.layers.0.self_attn.k_cache.scale", 0.0376674123f),
cache_scale_f32("model.layers.0.self_attn.v_cache.scale", 0.0004359654f),
});
write_file(dir + "/model.safetensors.index.json",
R"({"weight_map":{"model.layers.0.self_attn.k_cache.scale":"kv_cache_scales.safetensors","model.layers.0.self_attn.v_cache.scale":"kv_cache_scales.safetensors"}})");
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
const char* k = ck.meta().get("hyv3.kv_cache.0.k_scale");
const char* v = ck.meta().get("hyv3.kv_cache.0.v_scale");
REQUIRE(k && v);
CHECK(std::fabs(std::strtod(k, nullptr) - 0.0376674123) < 1e-9);
CHECK(std::fabs(std::strtod(v, nullptr) - 0.0004359654) < 1e-10);
std::filesystem::remove_all(dir);
}
TEST(hyv3_static_kv_cache_scales_reject_invalid_values_and_shapes) {
const char* name = "model.layers.0.self_attn.k_cache.scale";
std::vector<T> invalid;
for (float value : {0.0f, -1.0f, NAN, INFINITY})
invalid.push_back(cache_scale_f32(name, value));
invalid.push_back(bf16(name, {1}, 1.0f));
T nonscalar = cache_scale_f32(name, 1.0f);
nonscalar.shape = {2};
nonscalar.bytes.resize(8);
invalid.push_back(std::move(nonscalar));
for (const T& t : invalid) {
const std::string dir = write_checkpoint({t},
R"({"model_type":"hy_v3","num_hidden_layers":1})");
Checkpoint ck;
CHECK_EQ(ck.open(dir), RAD_E_FORMAT);
}
/* A true rank-zero scalar and a one-element vector both satisfy the checkpoint contract. */
T scalar = cache_scale_f32(name, 0.5f);
scalar.shape.clear();
const std::string dir = write_checkpoint({scalar},
R"({"model_type":"hy_v3","num_hidden_layers":1})");
Checkpoint ck;
CHECK_OK(ck.open(dir));
const char* scale = ck.meta().get("hyv3.kv_cache.0.k_scale");
REQUIRE(scale != nullptr);
CHECK_EQ(std::strtod(scale, nullptr), 0.5);
}
TEST(config_json_fills_the_model_meta_as_each_family_spells_it) {
const ConfigCase cases[] = {
{ "a multimodal MoE: text_config first, head_dim read rather than derived, the expert "
@@ -1815,8 +1869,7 @@ TEST(a_concat_declared_in_pieces_joins_every_piece_in_order) {
/* ================================================================== GGUF as a source
*
* A GGUF tensor's dimensions are stored fastest first and are reversed once into the row-major
* shape everything else uses; the legacy block types decode by their definitions; a K-quant is
* refused with its name, not decoded as something else. */
* shape everything else uses; the legacy and Q4_K/Q6_K block types decode by their definitions. */
namespace {
struct GKv {
@@ -1951,7 +2004,22 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) {
const std::string dir = fresh_dir();
const std::string path = dir + "/m.gguf";
std::vector<float> w8, w40, w41, w50, w51;
GTensor k4{ "t.q4_k", 12, { 256, 2 }, std::vector<uint8_t>(2 * 144, 0) };
std::vector<uint8_t> q4k(144, 0);
const uint16_t q4d = h16(0.5f), q4min = h16(0.25f);
std::memcpy(q4k.data(), &q4d, 2);
std::memcpy(q4k.data() + 2, &q4min, 2);
const uint8_t q4scales[12] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
0x47, 0x48, 0x21, 0x32, 0x43, 0x54};
std::memcpy(q4k.data() + 4, q4scales, sizeof q4scales);
q4k[16] = 0x21; /* low/high nibbles of values 0 and 32 */
q4k[16 + 64] = 0x32; /* values 128 and 160, including packed high scale bits */
GTensor k4{ "t.q4_k", 12, { 256, 1 }, q4k };
std::vector<uint8_t> q6k(210, 0);
const uint16_t q6d = h16(0.5f);
std::memcpy(q6k.data() + 208, &q6d, 2);
q6k[0] = 0x21; q6k[32] = 0x43; q6k[128] = 0xD3;
q6k[192] = 2; q6k[194] = 3; q6k[196] = 4; q6k[198] = 5;
GTensor k6{ "t.q6_k", 14, { 256, 1 }, q6k };
GTensor f16{ "t.f16", 1, { 64, 4, 2 }, {} };
for (int i = 0; i < 64 * 4 * 2; ++i) {
const uint16_t v = h16((float)i * 0.5f);
@@ -1961,7 +2029,7 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) {
write_gguf(path, llama_kvs(7),
{ legacy_blocks("t.q8_0", 8, &w8), legacy_blocks("t.q4_0", 2, &w40),
legacy_blocks("t.q4_1", 3, &w41), legacy_blocks("t.q5_0", 6, &w50),
legacy_blocks("t.q5_1", 7, &w51), k4, f16 });
legacy_blocks("t.q5_1", 7, &w51), k4, k6, f16 });
Checkpoint ck;
REQUIRE_EQ(ck.open(path), RAD_OK);
CHECK(ck.is_gguf());
@@ -1973,6 +2041,7 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) {
{ "t.q5_1", &w51 } };
for (const auto& l : legacy) prog.name_map.push_back(map(l.name, RAD_MAP_COPY, { l.name }));
prog.name_map.push_back(map("t.q4_k", RAD_MAP_COPY, { "t.q4_k" }));
prog.name_map.push_back(map("t.q6_k", RAD_MAP_COPY, { "t.q6_k" }));
prog.name_map.push_back(map("t.f16", RAD_MAP_COPY, { "t.f16" }));
std::string why;
for (const auto& l : legacy) {
@@ -1996,11 +2065,24 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) {
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "t.q4_k", false, &w, &why), RAD_OK);
CHECK_EQ(w.shape[0], (int64_t)2);
CHECK_EQ(w.shape[0], (int64_t)1);
CHECK_EQ(w.shape[1], (int64_t)256);
std::vector<float> f(256);
CHECK_EQ(ckpt_rows_f32(w, 0, 1, f.data(), &why), (int)RAD_E_UNSUPPORTED);
CHECK(has(why, "q4_K"));
REQUIRE_EQ(ckpt_rows_f32(w, 0, 1, f.data(), &why), RAD_OK);
CHECK_EQ(f[0], -0.75f);
CHECK_EQ(f[32], 0.5f);
CHECK_EQ(f[128], 12.5f);
CHECK_EQ(f[160], 22.25f);
}
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "t.q6_k", false, &w, &why), RAD_OK);
std::vector<float> f(256);
REQUIRE_EQ(ckpt_rows_f32(w, 0, 1, f.data(), &why), RAD_OK);
CHECK_EQ(f[0], 17.0f);
CHECK_EQ(f[32], -43.5f);
CHECK_EQ(f[64], -28.0f);
CHECK_EQ(f[96], 50.0f);
}
{
/* A plain f16 tensor of rank 3 is trivial and reversed in every dimension. */
@@ -2044,6 +2126,59 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) {
}
}
TEST(hyv3_gguf_metadata_normalizes_architecture_and_config_fields) {
const std::string path = fresh_dir() + "/hyv3.gguf";
const std::vector<GKv> kvs = {
{ "general.architecture", 8, 0, { "hy_v3" } },
{ "hy_v3.block_count", 4, 2, {} },
{ "hy_v3.embedding_length", 4, 4, {} },
{ "hy_v3.attention.head_count", 4, 2, {} },
{ "hy_v3.attention.head_count_kv", 4, 1, {} },
{ "hy_v3.attention.key_length", 4, 2, {} },
{ "hy_v3.feed_forward_length", 4, 8, {} },
{ "hy_v3.context_length", 4, 1024, {} },
{ "hy_v3.expert_count", 4, 4, {} },
{ "hy_v3.expert_used_count", 4, 2, {} },
{ "hy_v3.expert_feed_forward_length", 4, 2, {} },
{ "hy_v3.expert_shared_feed_forward_length", 4, 2, {} },
{ "hy_v3.expert_weights_norm", 4, 1, {} },
{ "hy_v3.expert_weights_scale", 6, 2.826, {} },
{ "hy_v3.expert_gating_func", 4, 2, {} },
{ "hy_v3.attention.layer_norm_rms_epsilon", 6, 1e-5, {} },
{ "hy_v3.rope.freq_base", 6, 11158840.0, {} },
{ "tokenizer.ggml.tokens", 9, 0, { "a", "b" } },
{ "general.file_type", 4, 15, {} },
};
auto f32 = [](const char* name, std::vector<uint64_t> ne) {
size_t count = 1;
for (uint64_t d : ne) count *= (size_t)d;
return GTensor{ name, 0, std::move(ne), std::vector<uint8_t>(count * sizeof(float), 0) };
};
write_gguf(path, kvs, { f32("token_embd.weight", {4, 4}),
f32("blk.0.attn_q_norm.weight", {2}),
f32("blk.0.attn_k_norm.weight", {2}),
f32("blk.0.ffn_gate.weight", {4, 4}),
f32("blk.1.ffn_gate_inp.weight", {4, 4}),
f32("blk.1.exp_probs_b", {4}) });
Checkpoint ck;
REQUIRE_EQ(ck.open(path), RAD_OK);
CHECK_EQ(ck.meta().arch, std::string("hyv3"));
CHECK_EQ(ck.meta().quant, std::string("gguf_ftype_15"));
CHECK_EQ(ck.meta().m.n_vocab, (int64_t)4); /* matrix rows exceed tokenizer strings */
CHECK_EQ(std::string(ck.meta().get("qk_norm")), std::string("1"));
CHECK_EQ(std::string(ck.meta().get("moe_router_use_sigmoid")), std::string("1"));
CHECK_EQ(std::string(ck.meta().get("moe_router_enable_expert_bias")), std::string("1"));
CHECK_EQ(std::string(ck.meta().get("enable_moe_fp32_combine")), std::string("1"));
CHECK_EQ(std::string(ck.meta().get("route_norm")), std::string("1"));
CHECK_EQ(std::string(ck.meta().get("first_k_dense_replace")), std::string("1"));
CHECK_EQ(std::string(ck.meta().get("num_shared_experts")), std::string("1"));
CHECK_EQ(std::string(ck.meta().get("expert_hidden_dim")), std::string("2"));
CHECK_EQ(std::string(ck.meta().get("moe_intermediate_size")), std::string("4"));
CHECK_EQ(std::string(ck.meta().get("num_experts")), std::string("4"));
CHECK_EQ(std::string(ck.meta().get("num_experts_per_tok")), std::string("2"));
CHECK_EQ(ck.meta().get("router_scaling_factor") != nullptr, true);
}
/* ================================================================== a diffusers pipeline
*
* model_index.json and one folder per component read as one checkpoint: the text encoder's
+13
View File
@@ -0,0 +1,13 @@
# Hy-Memory chat-template fixture
`chat_template.jinja` is an unchanged copy of the template distributed with
[Tencent Hy-Memory-30B-A3B](https://huggingface.co/tencent/Hy-Memory-30B-A3B).
- Source file: `chat_template.jinja`
- SHA-256: `8759492d33deb19b2f58855f62d3e431276da89d698b2800d1e353fbb12d5320`
- Copyright (C) 2026 Tencent. All rights reserved.
- License: Apache-2.0; see the repository's root `LICENSE` and `NOTICE`.
Tests use the original template to validate tool-schema rendering, tool-result replay,
reasoning prefixes, and native section-wrapped tool-call parsing. No model weights or
calibration corpus are included in this fixture.
+233
View File
@@ -0,0 +1,233 @@
{# ----------‑‑‑ special token variables ‑‑‑---------- #}
{%- set HYTK = '' %}
{%- set bos_token = '<|hy_begin▁of▁sentence|>' %}
{%- set pad_token = '<|hy_▁pad▁|>' %}
{%- set user_token = '<|hy_User|>' %}
{%- set assistant_token = '<|hy_Assistant|>' %}
{%- set eos_token = '<eos:6124c78e>' %}
{# ----------‑‑‑ tokens with md5 encoding (conditional on HYTK) ‑‑‑---------- #}
{%- if HYTK %}
{%- set think_begin_token = '<think:{}>'.format(HYTK) %}
{%- set think_end_token = '</think:{}>'.format(HYTK) %}
{%- set toolcalls_begin_token = '<tool_calls:{}>'.format(HYTK) %}
{%- set toolcalls_end_token = '</tool_calls:{}>'.format(HYTK) %}
{%- set toolcall_begin_token = '<tool_call:{}>'.format(HYTK) %}
{%- set toolcall_end_token = '</tool_call:{}>'.format(HYTK) %}
{%- set toolsep_token = '<tool_sep:{}>'.format(HYTK) %}
{%- set argkey_begin_token = '<arg_key:{}>'.format(HYTK) %}
{%- set argkey_end_token = '</arg_key:{}>'.format(HYTK) %}
{%- set argvalue_begin_token = '<arg_value:{}>'.format(HYTK) %}
{%- set argvalue_end_token = '</arg_value:{}>'.format(HYTK) %}
{%- set toolresponses_begin_token = '<tool_responses:{}>'.format(HYTK) %}
{%- set toolresponses_end_token = '</tool_responses:{}>'.format(HYTK) %}
{%- set toolresponse_begin_token = '<tool_response:{}>'.format(HYTK) %}
{%- set toolresponse_end_token = '</tool_response:{}>'.format(HYTK) %}
{%- set reasoning_mode_token = '<|reasoning_mode|>' %}
{%- set toolcalls_begin_ds_token = '<|tool▁calls▁begin|>' %}
{%- set toolcalls_end_ds_token = '<|tool▁calls▁end|>' %}
{%- set toolcall_begin_ds_token = '<|tool▁call▁begin|>' %}
{%- set toolcall_end_ds_token = '<|tool▁call▁end|>' %}
{%- set toolsep_ds_token = '<|tool▁sep|>' %}
{%- set tooloutput_begin_ds_token = '<|tool▁output▁begin|>' %}
{%- set tooloutput_end_ds_token = '<|tool▁output▁end|>' %}
{%- else %}
{%- set think_begin_token = '<think>' %}
{%- set think_end_token = '</think>' %}
{%- set toolcalls_begin_token = '<tool_calls>' %}
{%- set toolcalls_end_token = '</tool_calls>' %}
{%- set toolcall_begin_token = '<tool_call>' %}
{%- set toolcall_end_token = '</tool_call>' %}
{%- set toolsep_token = '<tool_sep>' %}
{%- set argkey_begin_token = '<arg_key>' %}
{%- set argkey_end_token = '</arg_key>' %}
{%- set argvalue_begin_token = '<arg_value>' %}
{%- set argvalue_end_token = '</arg_value>' %}
{%- set toolresponses_begin_token = '<tool_responses>' %}
{%- set toolresponses_end_token = '</tool_responses>' %}
{%- set toolresponse_begin_token = '<tool_response>' %}
{%- set toolresponse_end_token = '</tool_response>' %}
{%- set reasoning_mode_token = '<|reasoning_mode|>' %}
{%- set toolcalls_begin_ds_token = '<|tool▁calls▁begin|>' %}
{%- set toolcalls_end_ds_token = '<|tool▁calls▁end|>' %}
{%- set toolcall_begin_ds_token = '<|tool▁call▁begin|>' %}
{%- set toolcall_end_ds_token = '<|tool▁call▁end|>' %}
{%- set toolsep_ds_token = '<|tool▁sep|>' %}
{%- set tooloutput_begin_ds_token = '<|tool▁output▁begin|>' %}
{%- set tooloutput_end_ds_token = '<|tool▁output▁end|>' %}
{%- endif %}
{# ----------‑‑‑ hyperparameters variables ‑‑‑---------- #}
{%- if not add_generation_prompt is defined %}
{%- set add_generation_prompt = false %}
{%- endif %}
{%- if not interleaved_thinking is defined %}
{%- set interleaved_thinking = false %}
{%- endif %}
{%- if not tools %}
{%- set interleaved_thinking = false %}
{%- endif %}
{%- if not is_training is defined %}
{%- set is_training = false %}
{%- endif %}
{%- if not is_ai_search is defined %}
{%- set is_ai_search = false %}
{%- endif %}
{%- if not reasoning_effort is defined or reasoning_effort not in ['high', 'low', 'no_think'] %}
{%- set reasoning_effort = 'no_think' %}
{%- endif %}
{%- macro visible_text(content) -%}
{%- if content is string -%}
{{- content }}
{%- elif content is iterable and content is not mapping -%}
{%- for item in content -%}
{%- if item is mapping and item.type == 'text' -%}
{{- item.text }}
{%- elif item is string -%}
{{- item }}
{%- endif -%}
{%- endfor -%}
{%- elif content is none -%}
{{- '' }}
{%- else -%}
{{- content }}
{%- endif -%}
{%- endmacro -%}
{%- set ns = namespace(last_user_index=-1) %}
{%- set sp_ns = namespace(system_prompt='', is_first_sp=true) %}
{%- for message in messages %}
{%- if message['role'] == 'system' %}
{%- set sp_ns.system_prompt = sp_ns.system_prompt + visible_text(message['content']) %}
{%- endif %}
{%- if message['role'] == 'user' %}
{%- set ns.last_user_index = loop.index0 %}
{%- endif %}
{%- endfor %}
{%- if reasoning_effort is defined and reasoning_effort is string and reasoning_effort != '' and not tools %}
{%- set sp_ns.system_prompt = sp_ns.system_prompt + reasoning_mode_token + 'reasoning_effort:' + reasoning_effort %}
{%- endif %}
{{- bos_token }}
{{- sp_ns.system_prompt }}
{%- if tools %}
{%- if sp_ns.system_prompt != '' %}
{{- '\n\n# Tools\n\nYou may call one or more functions to assist with the user query.' }}
{%- else %}
{{- '# Tools\n\nYou may call one or more functions to assist with the user query.' }}
{%- endif %}
{{- '\n\nYou are provided with function signatures within <tools></tools> XML tags:' }}
{{- '\n<tools>\n' }}
{%- for tool in tools %}
{%- if loop.index0 > 0 %}
{{- '\n' }}
{%- endif %}
{{- tool | tojson }}
{%- endfor %}
{{- '\n</tools>\n\n' }}
{{- 'For function call returns, you should first print ' + toolcalls_begin_token + '\n' }}
{{- 'For each function call, you should return object like:\n' }}
{{- toolcall_begin_token + '{function-name}' + toolsep_token + '\n' }}
{{- argkey_begin_token + '{arg-key-1}' + argkey_end_token + '\n' }}
{{- argvalue_begin_token + '{arg-value-1}' + argvalue_end_token + '\n' }}
{{- argkey_begin_token + '{arg-key-2}' + argkey_end_token + '\n' }}
{{- argvalue_begin_token + '{arg-value-2}' + argvalue_end_token + '\n' }}
{{- '...\n' }}
{{- toolcall_end_token + '\n' }}
{%- if reasoning_effort is defined and reasoning_effort is string and reasoning_effort != '' %}
{{- 'At the end of function call returns, you should print ' + toolcalls_end_token + reasoning_mode_token + 'reasoning_effort:' + reasoning_effort }}
{%- else %}
{{- 'At the end of function call returns, you should print ' + toolcalls_end_token }}
{%- endif %}
{%- endif %}
{%- set prev_ns = namespace(is_tool=false, is_tool_first=true) %}
{%- set last_ns = namespace(last_is_assistant=false) %}
{%- for message in messages %}
{%- if message['role'] == 'user' %}
{%- if prev_ns.is_tool and not is_ai_search %}
{{- toolresponses_end_token }}
{%- endif %}
{{- user_token + visible_text(message['content']) }}
{%- set prev_ns.is_tool = false %}
{%- endif %}
{%- if message['role'] == 'assistant' %}
{%- if is_training %}
{%- if 'reasoning_content' in message and message['reasoning_content'] is string %}
{%- set content = think_begin_token + message['reasoning_content'] + think_end_token + visible_text(message['content']) %}
{%- else %}
{%- set content = think_begin_token + think_end_token + visible_text(message['content']) %}
{%- endif %}
{%- else %}
{%- if interleaved_thinking %}
{%- if loop.index0 > ns.last_user_index and 'reasoning_content' in message and message['reasoning_content'] is string %}
{%- set content = think_begin_token + message['reasoning_content'] + think_end_token + visible_text(message['content']) %}
{%- else %}
{%- set content = think_begin_token + think_end_token + visible_text(message['content']) %}
{%- endif %}
{%- else %}
{%- set content = think_begin_token + think_end_token + visible_text(message['content']) %}
{%- endif %}
{%- endif %}
{%- if prev_ns.is_tool and not is_ai_search %}
{{- toolresponses_end_token }}
{%- endif %}
{{- assistant_token }}
{%- if message['tool_calls'] is defined and message['tool_calls'] %}
{%- set prev_ns.is_tool_first = true %}
{{- content }}
{{- toolcalls_begin_token + '\n' }}
{%- for tool in message['tool_calls'] %}
{%- set arguments = tool['function']['arguments'] %}
{{- toolcall_begin_token + tool['function']['name'] + toolsep_token + '\n' }}
{%- for key, value in arguments.items() %}
{{- argkey_begin_token + key + argkey_end_token + '\n' }}
{%- if value is not string %}
{%- set value = value | tojson(ensure_ascii=False) %}
{%- endif %}
{{- argvalue_begin_token + value + argvalue_end_token + '\n' }}
{%- endfor %}
{{- toolcall_end_token + '\n' }}
{%- endfor %}
{{- toolcalls_end_token + eos_token }}
{%- else %}
{%- if not loop.last or is_training %}
{{- content + eos_token }}
{%- else %}
{{- content }}
{%- endif %}
{%- endif %}
{%- set prev_ns.is_tool = false %}
{%- endif %}
{%- if message['role'] == 'tool' %}
{%- set prev_ns.is_tool = true %}
{%- if prev_ns.is_tool_first and not is_ai_search %}
{{- toolresponses_begin_token + '\n' }}
{%- set prev_ns.is_tool_first = false %}
{%- endif %}
{%- if is_ai_search %}
{{- tooloutput_begin_ds_token + visible_text(message['content']) + tooloutput_end_ds_token }}
{%- else %}
{{- toolresponse_begin_token + '\n' + visible_text(message['content']) + '\n' + toolresponse_end_token + '\n' }}
{%- endif %}
{%- endif %}
{%- if loop.last and message['role'] == 'assistant' %}
{%- set last_ns.last_is_assistant = true %}
{%- endif %}
{%- endfor %}
{%- if prev_ns.is_tool and not is_ai_search %}
{{- toolresponses_end_token }}
{%- endif %}
{%- if add_generation_prompt %}
{%- if not last_ns.last_is_assistant %}
{%- if is_ai_search %}
{{- assistant_token }}
{{- think_begin_token + think_end_token }}
{%- elif reasoning_effort is defined and reasoning_effort in ['low', 'high'] %}
{{- assistant_token + think_begin_token }}
{%- elif reasoning_effort is defined and reasoning_effort == 'no_think' %}
{{- assistant_token + think_begin_token + think_end_token }}
{%- else %}
{{- assistant_token }}
{%- endif %}
{%- endif %}
{%- endif %}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include <cstdint>
/* Shapes read from the local Tencent Hy-Memory-30B-A3B-BF16 model.safetensors headers and checked
* against its config.json (48 layers, hidden=2048, 32 Q heads, 4 KV heads, 128 experts). Keep these
* source tensor shapes separate from the architecture's declared, sometimes concatenated shapes. */
namespace hyv3_bf16_fixture {
constexpr char source[] = "Hy-Memory-30B-A3B-BF16 / model.safetensors headers";
constexpr int64_t q_proj[2] = { 4096, 2048 };
constexpr int64_t k_proj[2] = { 512, 2048 };
constexpr int64_t v_proj[2] = { 512, 2048 };
constexpr int64_t o_proj[2] = { 2048, 4096 };
constexpr int64_t q_norm[1] = { 128 };
constexpr int64_t k_norm[1] = { 128 };
constexpr int64_t dense_gate[2] = { 6912, 2048 };
constexpr int64_t dense_up[2] = { 6912, 2048 };
constexpr int64_t dense_down[2] = { 2048, 6912 };
constexpr int64_t expert_gate[2] = { 768, 2048 };
constexpr int64_t expert_up[2] = { 768, 2048 };
constexpr int64_t expert_down[2] = { 2048, 768 };
constexpr int64_t shared_gate[2] = { 768, 2048 };
constexpr int64_t shared_up[2] = { 768, 2048 };
constexpr int64_t shared_down[2] = { 2048, 768 };
constexpr int64_t router[2] = { 128, 2048 };
constexpr int64_t correction[1] = { 128 };
} // namespace hyv3_bf16_fixture
+38
View File
@@ -277,6 +277,44 @@ TEST(rebalance_reaches_a_model_that_declares_it_and_is_refused_by_one_that_does_
CHECK_EQ(s.f->srv->router().dispatch(q).status, 400);
}
/* `rebalance` also names a preset: "legacy" is `true`, "balanced", "detail" and "subtle" set
* RAD_GEN_COND_REBALANCE with the preset's row in RAD_GEN_COND_REBALANCE_PRESET, in JSON and in a
* form. A model whose rebalance declares no presets takes `true` and "legacy" and refuses the
* others with a 400 naming the field; an unknown name is a 400 everywhere. */
TEST(rebalance_presets_reach_a_model_that_declares_them) {
Images s;
const int32_t R = RAD_GEN_COND_REBALANCE, sh = RAD_GEN_COND_REBALANCE_PRESET_SHIFT;
s.img.inf.cond_opts = RAD_GEN_COND_REBALANCE;
s.gen({ { "prompt", "x" }, { "rebalance", "legacy" } });
CHECK_EQ(s.last().cond_opts, R);
for (const char* p : { "balanced", "detail", "subtle" }) {
const json e = s.gen({ { "prompt", "x" }, { "rebalance", p } }, 400);
CHECK_EQ(str_at(e["error"], "param"), std::string("rebalance"));
}
s.img.inf.cond_opts = RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET;
const struct { const char* name; int32_t opts; } kWant[] = {
{ "legacy", R }, { "balanced", R | 1 << sh }, { "detail", R | 2 << sh }, { "subtle", R | 3 << sh },
};
for (const auto& w : kWant) {
s.gen({ { "prompt", "x" }, { "rebalance", w.name } });
CHECK_EQ(s.last().cond_opts, w.opts);
}
s.gen({ { "prompt", "x" }, { "rebalance", true } });
CHECK_EQ(s.last().cond_opts, R);
for (const json& bad : { json("Balanced"), json("strong"), json("") }) {
const json e = s.gen({ { "prompt", "x" }, { "rebalance", bad } }, 400);
CHECK_EQ(str_at(e["error"], "param"), std::string("rebalance"));
}
HttpRequest q;
q.method = "POST";
q.path = "/v1/images/generations";
q.form = { FormPart{ "prompt", "", "", "a cat" }, FormPart{ "rebalance", "", "", "detail" } };
CHECK_EQ(s.f->srv->router().dispatch(q).status, 200);
CHECK_EQ(s.last().cond_opts, R | 2 << sh);
q.form[1].data = "nope";
CHECK_EQ(s.f->srv->router().dispatch(q).status, 400);
}
/* `background: auto` keeps an edited picture's transparency and is opaque otherwise; a mask must
* be the first picture's size. */
/* A model whose card states guidance as cond + s (cond - uncond) and guides by default (Krea 2):
+28
View File
@@ -370,6 +370,34 @@ inline std::shared_ptr<IReplyParser> qwen_reply_parser(const json& tools) {
return std::make_shared<ReplyParserBridge>(rp);
}
/* Hy-Memory's native outer call section, name prefix, and tagged argument wire format. */
inline std::shared_ptr<IReplyParser> hyv3_reply_parser(const json& tools) {
ChatFormat f;
f.reasoning_open = "<think>";
f.reasoning_close = "</think>";
f.reasoning_breaks = { "<tool_calls>" };
f.section_open = "<tool_calls>";
f.section_close = "</tool_calls>";
f.name_prefix = "<tool_call>";
f.name_suffix = "<tool_sep>";
f.call_end = "</tool_call>";
f.arg_prefix = "<arg_key>";
f.arg_name_suffix = "</arg_key>\n";
f.arg_value_prefix = "<arg_value>";
f.arg_value_suffix = "</arg_value>";
f.string_value = ChatValue::Raw;
f.other_value = ChatValue::Json;
f.triggers = { "<tool_calls>" };
std::shared_ptr<const ReplyFormat> rf;
std::string why;
if (ReplyFormat::compile(f, &rf, &why) < 0) return nullptr;
ReplyOptions ro;
ro.tools = &tools;
std::shared_ptr<const ReplyParser> rp;
if (ReplyParser::create(rf, ro, &rp, &why) < 0) return nullptr;
return std::make_shared<ReplyParserBridge>(rp);
}
struct FakeGrammar : IGrammarCompiler {
int from_json_schema(const json&, std::string& out, std::string&) const override {
out = "root ::= object";
+90 -2
View File
@@ -621,6 +621,94 @@ TEST(a_complete_tool_call_is_reported_as_tool_calls) {
CHECK(c["message"]["content"].is_null());
}
TEST(hyv3_native_markup_flows_through_openai_tools_api) {
const json tools = json::parse(R"([{
"type":"function","function":{"name":"lookup_weather","parameters":{"type":"object",
"properties":{"city":{"type":"string"}},"required":["city"]}}},
{"type":"function","function":{"name":"add","parameters":{"type":"object",
"properties":{"a":{"type":"integer"},"b":{"type":"integer"}},"required":["a","b"]}}}])");
const json messages = json::array({
{{"role", "user"}, {"content", "Check Toronto weather and add 20 and 22."}},
{{"role", "assistant"}, {"content", nullptr},
{"tool_calls", json::array({
{{"id", "call-weather"}, {"type", "function"},
{"function", {{"name", "lookup_weather"},
{"arguments", "{\"city\":\"Toronto\"}"}}}},
{{"id", "call-add"}, {"type", "function"},
{"function", {{"name", "add"}, {"arguments", "{\"a\":20,\"b\":22}"}}}}
})}},
{{"role", "tool"}, {"tool_call_id", "call-weather"}, {"content", "Cloudy, 12 C."}},
{{"role", "tool"}, {"tool_call_id", "call-add"}, {"content", "42"}},
{{"role", "user"}, {"content", "Summarize the results."}}
});
const std::string reply =
"The weather is cloudy, and the sum is 42.\n<tool_calls>\n"
"<tool_call>lookup_weather<tool_sep>\n"
"<arg_key>city</arg_key>\n<arg_value>Toronto</arg_value>\n</tool_call>\n"
"<tool_call>add<tool_sep>\n"
"<arg_key>a</arg_key>\n<arg_value>20</arg_value>\n"
"<arg_key>b</arg_key>\n<arg_value>22</arg_value>\n</tool_call>\n</tool_calls>";
Fixture f;
f.tmpl.real_parser = hyv3_reply_parser(tools);
REQUIRE(f.tmpl.real_parser != nullptr);
f.sched.reply = reply;
const std::string body = json({{"messages", messages}, {"tools", tools},
{"parallel_tool_calls", true}, {"max_tokens", 512}}).dump();
HttpResponse buffered = f.post("/v1/chat/completions", body);
CHECK_EQ(buffered.status, 200);
const json c = json::parse(buffered.body)["choices"][0];
CHECK_EQ(c["finish_reason"].get<std::string>(), std::string("tool_calls"));
CHECK_EQ(c["message"]["content"].get<std::string>(),
std::string("The weather is cloudy, and the sum is 42."));
REQUIRE(c["message"]["tool_calls"].size() == 2);
CHECK_EQ(c["message"]["tool_calls"][0]["function"]["name"].get<std::string>(),
std::string("lookup_weather"));
CHECK_EQ(c["message"]["tool_calls"][0]["function"]["arguments"].get<std::string>(),
std::string("{\"city\":\"Toronto\"}"));
CHECK_EQ(c["message"]["tool_calls"][1]["function"]["name"].get<std::string>(),
std::string("add"));
CHECK_EQ(c["message"]["tool_calls"][1]["function"]["arguments"].get<std::string>(),
std::string("{\"a\":20,\"b\":22}"));
CHECK_EQ(f.tmpl.last_tool_msgs, 2);
CHECK(has(f.tmpl.last_prompt, "Summarize the results."));
HttpResponse streamed = f.post("/v1/chat/completions",
json({{"messages", messages}, {"tools", tools},
{"stream", true}, {"max_tokens", 512}}).dump());
CHECK_EQ(streamed.status, 200);
int bad = 0;
std::string finish, content;
std::vector<std::string> names, arguments;
for (const std::string& payload : sse_payloads(drain(streamed), &bad)) {
if (payload == "[DONE]") continue;
const json event = json::parse(payload);
if (event["choices"].empty()) continue;
const json& choice = event["choices"][0];
if (!choice["finish_reason"].is_null())
finish = choice["finish_reason"].get<std::string>();
const json& delta = choice["delta"];
if (delta.contains("content")) content += delta["content"].get<std::string>();
if (!delta.contains("tool_calls")) continue;
for (const json& call : delta["tool_calls"]) {
const size_t i = call["index"].get<size_t>();
if (i >= names.size()) { names.resize(i + 1); arguments.resize(i + 1); }
if (call.contains("function") && call["function"].contains("name"))
names[i] = call["function"]["name"].get<std::string>();
if (call.contains("function") && call["function"].contains("arguments"))
arguments[i] += call["function"]["arguments"].get<std::string>();
}
}
CHECK_EQ(bad, 0);
CHECK_EQ(finish, std::string("tool_calls"));
CHECK_EQ(content, std::string("The weather is cloudy, and the sum is 42."));
REQUIRE(names.size() == 2);
CHECK_EQ(names[0], std::string("lookup_weather"));
CHECK_EQ(arguments[0], std::string("{\"city\":\"Toronto\"}"));
CHECK_EQ(names[1], std::string("add"));
CHECK_EQ(arguments[1], std::string("{\"a\":20,\"b\":22}"));
}
/* The three spellings of "do not think" must all reach the template, and the kwarg must reach
* both places: the lift overwrites the context key `enable_thinking` with its own field
* (chat-auto-parser-helpers.cpp), so a kwarg not also lifted into the field would be discarded
@@ -5152,8 +5240,8 @@ TEST(embeddings_are_truncated_then_normalised_and_failures_named) {
}
{
f.sched.embedding = std::vector<float>(8, 0.0f);
for (const json& x : vectors(R"({"input":"a"})")["data"][0]["embedding"])
CHECK_EQ(x.get<float>(), 0.0f);
const json embedding = vectors(R"({"input":"a"})")["data"][0]["embedding"];
for (const json& x : embedding) CHECK_EQ(x.get<float>(), 0.0f);
}
f.sched.embedding = { 3, 4, 0, 12, 0, 0, 0, 0 };
{
+35 -1
View File
@@ -93,7 +93,9 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
{ "anima", "" }, { "breeze", "" }, { "embeddinggemma2", "" },
{ "fishomni", "bsgemm-moe" }, { "flux3", "" }, { "flux3distilled", "" },
{ "gemma3", "" }, { "gemma4", "" },
{ "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" },
{ "gemma4", "compressed-tensors" }, { "glm5next", "" },
{ "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" },
{ "lfm2", "" }, { "llama", "" },
{ "llama", "fp8_e4m3" }, { "qwen35", "" },
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
@@ -108,6 +110,38 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
CHECK(got == want);
}
TEST(hyv3_plugins_declare_the_checkpoint_native_tool_format) {
Registry r;
const int st = r.load_dir(dir_of("architectures"), {});
if (st == RAD_E_IO && r.plugins().empty())
ARTIFACT_MISSING("the architecture plugins under " + dir_of("architectures"));
CHECK_OK(st);
for (const char* name : { "hyv3_bf16", "hyv3_fp8", "hyv3_gguf" }) {
const Plugin* p = r.plugin(name);
REQUIRE(p != nullptr);
REQUIRE(p->arch_chat_format != nullptr);
const RadChatFormat* f = p->arch_chat_format(nullptr);
REQUIRE(f != nullptr);
CHECK_EQ(std::string(f->reasoning_open), std::string("<think>"));
CHECK_EQ(std::string(f->reasoning_close), std::string("</think>"));
CHECK_EQ(f->reasoning_in_prompt, (uint32_t)RAD_CHAT_THINK_FROM_PROMPT);
REQUIRE(f->reasoning_breaks != nullptr && f->n_reasoning_breaks == 1);
CHECK_EQ(std::string(f->reasoning_breaks[0]), std::string("<tool_calls>"));
CHECK_EQ(std::string(f->section_open), std::string("<tool_calls>"));
CHECK_EQ(std::string(f->section_close), std::string("</tool_calls>"));
CHECK_EQ(std::string(f->name_prefix), std::string("<tool_call>"));
CHECK_EQ(std::string(f->name_suffix), std::string("<tool_sep>"));
CHECK_EQ(std::string(f->arg_prefix), std::string("<arg_key>"));
CHECK_EQ(std::string(f->arg_name_suffix), std::string("</arg_key>\n"));
CHECK_EQ(std::string(f->arg_value_prefix), std::string("<arg_value>"));
CHECK_EQ(std::string(f->arg_value_suffix), std::string("</arg_value>"));
REQUIRE(f->n_triggers == 1 && f->triggers != nullptr);
CHECK_EQ(std::string(f->triggers[0]), std::string("<tool_calls>"));
CHECK_EQ(f->string_value, (uint32_t)RAD_CHAT_VALUE_RAW);
CHECK_EQ(f->other_value, (uint32_t)RAD_CHAT_VALUE_JSON);
}
}
/* A checkpoint whose quantisation was imported weight by weight (Quark, ParoQuant, GPTQ, NVFP4)
* names a tool no plugin claims, so the family's one quantised plugin serves it, and two are
* refused (startup.h). So each family has at most one quantised plugin that takes imports: