Archived
Merge branch 'main' into fix-stage-drain
This commit is contained in:
commit
bcdc89eded
43 files changed
+3197
-157
No files matched your search
@@ -94,6 +94,11 @@ license text is in the file named beside each.
|
||||
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
|
||||
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
|
||||
|
||||
tests/data/chat/hyv3/chat_template.jinja is Tencent's Hy-Memory-30B-A3B chat template,
|
||||
copied unchanged from tencent/Hy-Memory-30B-A3B on Hugging Face.
|
||||
Copyright (C) 2026 Tencent. All rights reserved. Licensed under Apache-2.0 (LICENSE).
|
||||
Its source and content checksum are recorded in tests/data/chat/hyv3/README.md.
|
||||
|
||||
core/server/systemone.cpp carries text from Liquid AI's d1 (prompt.py and api.py in the
|
||||
LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the option codes and their
|
||||
fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid
|
||||
|
||||
+3
-4
@@ -1554,14 +1554,13 @@ typedef struct RadChatFormat {
|
||||
const char* reasoning_open; /* "" when the model does not reason */
|
||||
const char* reasoning_close;
|
||||
/* Literals that end a reasoning block the model forgot to close, when a call starts there.
|
||||
* Each must be the call opener: `call_open`, or `name_prefix` when there is no call_open. */
|
||||
* Each must be a call opener (`call_open`, or `name_prefix` without one) or section_open. */
|
||||
const char* const* reasoning_breaks;
|
||||
uint32_t n_reasoning_breaks;
|
||||
uint32_t reasoning_in_prompt; /* RAD_CHAT_THINK_* */
|
||||
|
||||
/* Around all of a turn's calls, and between two calls beyond whitespace. The parser does not
|
||||
* read these yet, so a format that sets one is refused at startup by name; they are fields so
|
||||
* supporting them later does not change the struct. */
|
||||
/* Around the complete list of calls. section_open and section_close must be set together.
|
||||
* call_separator is additional text between calls beyond whitespace; it is not supported. */
|
||||
const char* section_open;
|
||||
const char* section_close;
|
||||
const char* call_separator;
|
||||
|
||||
+6
-1
@@ -453,8 +453,13 @@ typedef struct RadGenBatch {
|
||||
|
||||
/* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */
|
||||
enum {
|
||||
RAD_GEN_COND_REBALANCE = 1 /* the conditioning at the plugin's fixed rebalance gains (the
|
||||
RAD_GEN_COND_REBALANCE = 1, /* the conditioning at the plugin's fixed rebalance gains (the
|
||||
* request field `rebalance`; Krea 2: its text taps) */
|
||||
/* which of the plugin's rebalance presets, beside RAD_GEN_COND_REBALANCE: 0 its default
|
||||
* gains, Krea 2: 1 balanced, 2 detail, 3 subtle (arch/krea2). A plugin declares these bits in
|
||||
* RadGeneratorDecl::cond_opts when it has presets. */
|
||||
RAD_GEN_COND_REBALANCE_PRESET = 0xff00,
|
||||
RAD_GEN_COND_REBALANCE_PRESET_SHIFT = 8
|
||||
};
|
||||
|
||||
/* An entry's flags on a DENOISE pass. */
|
||||
|
||||
+139
-41
@@ -189,6 +189,9 @@ struct MoeFP8 {
|
||||
int swiglu_quant = 0;
|
||||
/* A shared arm without its sigmoid gate: the gate plane is filled with 1. */
|
||||
int shared_ungated = 0;
|
||||
/* Add the routed and shared BF16 outputs in FP32, then round once to BF16, as HYV3's
|
||||
* enable_moe_fp32_combine path does. This bypasses moe_gather's fused shared-arm add. */
|
||||
int shared_fp32_combine = 0;
|
||||
/* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for
|
||||
* Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8`
|
||||
* registry row). It is the stored encoding: probe() reads it from the first expert's
|
||||
@@ -278,7 +281,10 @@ struct MoeFP8 {
|
||||
ActFP8 eff{}; /* [rows * top_k, n_ff_exp] */
|
||||
rad_buf edn = 0; /* [rows * top_k, n_embd] bf16, in sorted order */
|
||||
/* back in token order, and the shared expert, one row per token */
|
||||
rad_buf moe = 0; /* [max_tok, n_embd] bf16 */
|
||||
rad_buf moe = 0; /* [max_tok, n_embd] bf16; separate routed output if needed */
|
||||
rad_buf moe_f32 = 0; /* [max_tok, n_embd] f32; shared_fp32_combine only */
|
||||
rad_buf shared_f32 = 0;/* [max_tok, n_embd] f32; shared_fp32_combine only */
|
||||
rad_buf combined_f32 = 0; /* [max_tok, n_embd] f32; shared_fp32_combine only */
|
||||
rad_buf sgu = 0; /* [max_tok, 2 * n_ff_shared] bf16 */
|
||||
ActFP8 sff{}; /* [max_tok, n_ff_shared] */
|
||||
rad_buf sout = 0; /* [max_tok, n_embd] bf16 */
|
||||
@@ -306,6 +312,13 @@ struct MoeFP8 {
|
||||
* already fused gate rows first, as this block wants. */
|
||||
const char* experts_gate_up = nullptr;
|
||||
const char* experts_down = nullptr;
|
||||
/* Some GGUF writers retain gate and up as separate stacked tensors. These three fields
|
||||
* describe that layout; each expert's gate/up slices are fused at conversion. */
|
||||
const char* experts_gate = nullptr;
|
||||
const char* experts_up = nullptr;
|
||||
const char* shared_mlp_gate = nullptr;
|
||||
const char* shared_mlp_up = nullptr;
|
||||
const char* shared_mlp_down = nullptr;
|
||||
const char* shared_gate = nullptr; /* mlp.shared_expert_gate.weight, [1, n_embd] */
|
||||
};
|
||||
|
||||
@@ -413,6 +426,8 @@ struct MoeFP8 {
|
||||
mutable bool calib_dne_failed = false;
|
||||
void calib_experts_pass(RadCtx* c_, int64_t slots) const;
|
||||
rad_op op_sgate = 0;
|
||||
rad_op op_moe_to_f32 = 0, op_shared_to_f32 = 0, op_combine_f32 = 0, op_combined_to_bf16 = 0;
|
||||
rad_op op_moe_ar = 0, op_shared_ar = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
bool ar_out = false;
|
||||
/* Which wires the consumer of this block's all-reduce takes. Set before declare; see
|
||||
@@ -530,21 +545,30 @@ inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const c
|
||||
|
||||
/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the
|
||||
* checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */
|
||||
inline int moe_map_gate_up(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
|
||||
long long ge) {
|
||||
if (src.experts_gate_up) return map_slice(b, guw, src.experts_gate_up, (int)ge);
|
||||
if (src.experts_gate && src.experts_up)
|
||||
return map_slice_concat(b, guw, {src.experts_gate, src.experts_up}, (int)ge);
|
||||
return map_concat(b, guw, {nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge),
|
||||
nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge)});
|
||||
}
|
||||
|
||||
inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
|
||||
const char* dnw, long long ge, bool gate_up) {
|
||||
if (src.experts_gate_up) {
|
||||
/* The slice index is global: the checkpoint holds every expert. */
|
||||
if (gate_up) RAD_ARCH_TRY(map_slice(b, guw, src.experts_gate_up, (int)ge));
|
||||
if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
|
||||
if (src.experts_gate_up || src.experts_gate)
|
||||
return map_slice(b, dnw, src.experts_down, (int)ge);
|
||||
}
|
||||
const char* gate = nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge);
|
||||
const char* up = nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge);
|
||||
if (gate_up) RAD_ARCH_TRY(map_concat(b, guw, { gate, up }));
|
||||
return map_copy(b, dnw, nm.ckpt("%s.%lld.down_proj.weight", src.experts, ge));
|
||||
}
|
||||
|
||||
inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg) {
|
||||
if (!cfg || (!src.experts && !src.experts_gate_up)) return RAD_E_INVAL;
|
||||
if (!cfg || (!src.experts && !src.experts_gate_up && !src.experts_gate)) return RAD_E_INVAL;
|
||||
const bool split_stack = src.experts_gate || src.experts_up;
|
||||
if ((src.experts_gate_up && split_stack) ||
|
||||
(split_stack && (!src.experts_gate || !src.experts_up || !src.experts_down ||
|
||||
src.experts)) ||
|
||||
(src.experts_gate_up && (!src.experts_down || src.experts))) return RAD_E_INVAL;
|
||||
/* The caller names the expert in model numbering (the first this rank owns under expert
|
||||
* parallelism); declare() skips the ones mapped here.
|
||||
*
|
||||
@@ -559,9 +583,7 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
|
||||
int f = 0;
|
||||
for (long long ge = g0; ge < gn && ge <= g0 + kMaxProtected; ++ge) {
|
||||
const char* guw = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge);
|
||||
if (src.experts_gate_up) RAD_ARCH_TRY(map_slice(b, guw, src.experts_gate_up, (int)ge));
|
||||
else RAD_ARCH_TRY(map_concat(b, guw, { nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge),
|
||||
nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge) }));
|
||||
RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
|
||||
cfg->probed_count = ge - g0 + 1;
|
||||
RadEncoding e{};
|
||||
f = 0;
|
||||
@@ -604,8 +626,17 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (c.rows <= 0) c.rows = g.max_tok;
|
||||
/* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the
|
||||
* all-reduce carries the others' share. */
|
||||
const bool shared = c.n_ff_shared > 0 && src.shared;
|
||||
const bool split_shared = src.shared_mlp_gate || src.shared_mlp_up || src.shared_mlp_down;
|
||||
if (split_shared && (!src.shared_mlp_gate || !src.shared_mlp_up || !src.shared_mlp_down ||
|
||||
src.shared)) return RAD_E_INVAL;
|
||||
const bool shared = c.n_ff_shared > 0 && (src.shared || src.shared_mlp_gate);
|
||||
if (shared && c.shared_ungated && src.shared_gate) return RAD_E_INVAL;
|
||||
if (c.shared_fp32_combine && (!shared || !w.moe || !w.moe_f32 || !w.shared_f32 ||
|
||||
!w.combined_f32)) {
|
||||
fprintf(stderr, "radiance: layer %d requests an FP32 shared/routed combine without its "
|
||||
"shared arm and scratch buffers\n", l);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by
|
||||
* the fused router's gate write (see there). */
|
||||
bool sgate_concurrent = false;
|
||||
@@ -793,12 +824,16 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
{w.logits}, {w.ids, w.ew, w.sorted, w.eoff, w.ecnt});
|
||||
}
|
||||
|
||||
/* Exactly one of a prefix or the two stacked tensors. */
|
||||
const bool stacked = src.experts_gate_up != nullptr;
|
||||
if (stacked != (src.experts_down != nullptr) || (stacked == (src.experts != nullptr))) {
|
||||
fprintf(stderr, "radiance: a routed feed-forward takes EITHER an `experts` prefix or "
|
||||
"both stacked tensors; got prefix %s, gate_up %s, down %s\n",
|
||||
/* Exactly one of a per-expert prefix, fused stacked gate_up, or separate stacked gate/up. */
|
||||
const bool split_stack = src.experts_gate || src.experts_up;
|
||||
const bool stacked = src.experts_gate_up || split_stack;
|
||||
if ((src.experts_gate_up && split_stack) ||
|
||||
(split_stack && (!src.experts_gate || !src.experts_up)) ||
|
||||
stacked != (src.experts_down != nullptr) || (stacked == (src.experts != nullptr))) {
|
||||
fprintf(stderr, "radiance: a routed feed-forward needs a per-expert prefix or complete "
|
||||
"stacked expert tensors; prefix %s, gate_up %s, gate %s, up %s, down %s\n",
|
||||
src.experts ? "yes" : "no", src.experts_gate_up ? "yes" : "no",
|
||||
src.experts_gate ? "yes" : "no", src.experts_up ? "yes" : "no",
|
||||
src.experts_down ? "yes" : "no");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -1287,12 +1322,14 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (!b_gram_dne || !op_gram_dne) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The gather folds the shared arm in, so `w.moe` is never written; `scale_rows` plus a
|
||||
* separate gather would be two dispatches per layer and a 160 KiB round trip. */
|
||||
gfold = shared;
|
||||
/* Normally the gather folds the shared arm in, saving a dispatch and round trip. HYV3 asks
|
||||
* for an FP32 addition of the two already-rounded BF16 outputs, so it gathers routed output
|
||||
* separately and combines the two arms below. */
|
||||
const bool separate_fp32_combine = shared && c.shared_fp32_combine;
|
||||
gfold = shared && !separate_fp32_combine;
|
||||
for (int form = scatter_inv ? 0 : 1; form < 2 && !op_gather; ++form) {
|
||||
rad_buf grd[5] = { w.edn, w.ew, form ? w.sorted : w.inv, w.sout, w.sgate };
|
||||
rad_buf gwr[1] = { w.h.x };
|
||||
rad_buf gwr[1] = { separate_fp32_combine ? w.moe : w.h.x };
|
||||
op_gather = RAD_OP(b, form ? "moe_gather" : "moe_gather_inv",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("top_k", c.top_k), RAD_STR("dtype", g.dtype),
|
||||
@@ -1314,8 +1351,16 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
/* Probe the down projection first: what it reads (codes, or the bf16 plane for a plain
|
||||
* weight) decides what the gate writes. */
|
||||
const char* down_base = nm.f("blk.%d.ffn_down_shexp", l);
|
||||
RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base,
|
||||
{ nm.ckpt("%s.down_proj.weight", src.shared) }));
|
||||
const char* shared_down = src.shared_mlp_down
|
||||
? src.shared_mlp_down
|
||||
: nm.ckpt("%s.down_proj.weight", src.shared);
|
||||
const char* shared_gate = src.shared_mlp_gate
|
||||
? src.shared_mlp_gate
|
||||
: nm.ckpt("%s.gate_proj.weight", src.shared);
|
||||
const char* shared_up = src.shared_mlp_up
|
||||
? src.shared_mlp_up
|
||||
: nm.ckpt("%s.up_proj.weight", src.shared);
|
||||
RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, { shared_down }));
|
||||
/* The code pair the gate writes, E4M3 or int8 (ActFP8::q8_fed); an int8 down projection
|
||||
* that quantises for itself also writes the int8 pair on this lane. */
|
||||
if (w.sff.cq()) {
|
||||
@@ -1335,8 +1380,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* gate/up row parts stay, as a property of the stacked checkpoint tensor. */
|
||||
RAD_ARCH_TRY(sh_gate_up.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up_shexp", l),
|
||||
2 * c.n_ff_shared, g.n_embd, RAD_SHARD_ROW, grp_layer(l),
|
||||
{ nm.ckpt("%s.gate_proj.weight", src.shared),
|
||||
nm.ckpt("%s.up_proj.weight", src.shared) },
|
||||
{ shared_gate, shared_up },
|
||||
w.h, w.sgu, c.rows,
|
||||
{ c.n_ff_shared, c.n_ff_shared },
|
||||
c.shared_lo, c.shared_hi));
|
||||
@@ -1347,7 +1391,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
c.swiglu_limit));
|
||||
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
|
||||
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
|
||||
{ nm.ckpt("%s.down_proj.weight", src.shared) },
|
||||
{ shared_down },
|
||||
w.sff, w.sout, c.rows, {},
|
||||
c.shared_lo, c.shared_hi));
|
||||
/* The shared gate, replicated like the router so every rank computes the same gate. One
|
||||
@@ -1371,6 +1415,25 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
}
|
||||
|
||||
if (separate_fp32_combine) {
|
||||
const auto cast = [&](const char* from, const char* to) {
|
||||
return RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("from", from), RAD_STR("to", to)),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
op_moe_to_f32 = rw(b, cast("bf16", "f32"), {w.moe}, {w.moe_f32});
|
||||
op_shared_to_f32 = rw(b, cast("bf16", "f32"), {w.sout}, {w.shared_f32});
|
||||
op_combine_f32 = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.moe_f32, w.shared_f32}, {w.combined_f32});
|
||||
op_combined_to_bf16 = rw(b, cast("f32", "bf16"), {w.combined_f32}, {w.h.x});
|
||||
if (!op_moe_to_f32 || !op_shared_to_f32 || !op_combine_f32 || !op_combined_to_bf16)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- The router GEMM and `router_topk_scatter` as one op, plus the shared gate when the
|
||||
* layer has one; up to the pair's row bound and the skinny GEMM's decode band. Unresolved, the
|
||||
* separate ops run. Declared here, after the gate weight, because it names both weights;
|
||||
@@ -1426,7 +1489,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
} else {
|
||||
sigmoid_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows
|
||||
? c.rows : kMoeSortRows / c.top_k;
|
||||
const bool gate = op_sgate != 0 && c.shared_ungated;
|
||||
const bool gate = op_sgate != 0 && c.shared_ungated && !c.shared_fp32_combine;
|
||||
if (gate && !sgate_concurrent) {
|
||||
fprintf(stderr, "radiance: layer %d: the fused selection writes the shared gate "
|
||||
"ahead of its declared writer, which needs `sgate` out of the "
|
||||
@@ -1456,14 +1519,25 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
}
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
if (g.world > 1) {
|
||||
const auto all_reduce = [&](const char* dtype, rad_buf buffer) {
|
||||
return rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{buffer}, {buffer});
|
||||
};
|
||||
if (separate_fp32_combine) {
|
||||
/* Each arm is a tensor-parallel partial. Reduce the BF16 arm outputs independently,
|
||||
* then perform HYV3's shared+routed addition in F32 before the final BF16 cast. */
|
||||
op_moe_ar = all_reduce(g.dtype, w.moe);
|
||||
op_shared_ar = all_reduce(g.dtype, w.sout);
|
||||
} else {
|
||||
op_ar = all_reduce(g.dtype, w.h.x);
|
||||
}
|
||||
}
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
|
||||
* prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
@@ -1512,12 +1586,15 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* buffers are step-tall, so the pass offset applies as in an MlpFP8 slice. */
|
||||
inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
|
||||
bool gate_done) const {
|
||||
/* `gate_done`: the fused router already wrote this pass's gate. */
|
||||
if (!gate_done && c.shared_ungated)
|
||||
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.sgate, r0, rows, 1));
|
||||
else if (!gate_done)
|
||||
/* `gate_done`: the fused router already wrote this pass's gate. An FP32 combine does not
|
||||
* consume the ungated arm's ones plane, so skip its otherwise redundant fill. */
|
||||
if (!gate_done && c.shared_ungated) {
|
||||
if (!c.shared_fp32_combine)
|
||||
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.sgate, r0, rows, 1));
|
||||
} else if (!gate_done) {
|
||||
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
|
||||
brow_slice(w.sgate, r0, rows, 1));
|
||||
}
|
||||
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
|
||||
}
|
||||
|
||||
@@ -1717,12 +1794,33 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
|
||||
/* The gather last, since with the fold it reads the shared arm (`sout`, `sgate`); it writes
|
||||
* the block's delta into `h.x`. */
|
||||
if (!gather_taken(g, T, gather_out_rows, gather_out_rows6))
|
||||
if (c.shared_fp32_combine || !gather_taken(g, T, gather_out_rows, gather_out_rows6))
|
||||
RAD_ISSUE_N(c_, op_gather, rows, brows(w.edn, rows * k), brow_slice(w.ew, r0, rows, k),
|
||||
brows(gather_inv ? w.inv : w.sorted, rows * k),
|
||||
gfold ? brow_slice(w.sout, r0, rows, g.n_embd) : RAD_NONE,
|
||||
gfold ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
|
||||
brow_slice(c.shared_fp32_combine ? w.moe : w.h.x, r0, rows, g.n_embd));
|
||||
if (op_moe_ar)
|
||||
RAD_ISSUE_N(c_, op_moe_ar, rows * g.n_embd,
|
||||
brow_slice(w.moe, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (op_shared_ar)
|
||||
RAD_ISSUE_N(c_, op_shared_ar, rows * g.n_embd,
|
||||
brow_slice(w.sout, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (c.shared_fp32_combine) {
|
||||
RAD_ISSUE_N(c_, op_moe_to_f32, rows,
|
||||
brow_slice(w.moe, r0, rows, g.n_embd),
|
||||
brow_slice(w.moe_f32, r0, rows, g.n_embd));
|
||||
RAD_ISSUE_N(c_, op_shared_to_f32, rows,
|
||||
brow_slice(w.sout, r0, rows, g.n_embd),
|
||||
brow_slice(w.shared_f32, r0, rows, g.n_embd));
|
||||
RAD_ISSUE_N(c_, op_combine_f32, rows,
|
||||
brow_slice(w.moe_f32, r0, rows, g.n_embd),
|
||||
brow_slice(w.shared_f32, r0, rows, g.n_embd),
|
||||
brow_slice(w.combined_f32, r0, rows, g.n_embd));
|
||||
RAD_ISSUE_N(c_, op_combined_to_bf16, rows,
|
||||
brow_slice(w.combined_f32, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd));
|
||||
}
|
||||
|
||||
/* A write that takes the all-reduce does it once for the whole step, deciding on T, so this
|
||||
* pass must ask with T, not its own rows. */
|
||||
|
||||
@@ -1563,8 +1563,6 @@ struct DenseFP8 {
|
||||
* works against the same E4M3 activation pair. */
|
||||
rad_weight ref = 0;
|
||||
bool mx = false;
|
||||
/* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */
|
||||
bool mapped = false;
|
||||
|
||||
/* `mapped`: the caller made the name map already, to ask the encoding before choosing this
|
||||
* struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */
|
||||
|
||||
@@ -1712,12 +1712,14 @@ struct Model {
|
||||
/* Per-layer embeddings (hidden_size_per_layer_input > 0): the token-identity table
|
||||
* (embed_tokens_per_layer, n_layer x n_ple wide), the context projection of the scaled
|
||||
* embedding and its per-(token, layer) norm, combined into `b_ple` [max_tok, n_layer * n_ple]
|
||||
* that every layer reads its slice of. */
|
||||
* that every layer reads its slice of. At two ranks the table is vocab-sharded like the token
|
||||
* table, and its lookup is reduced the same way (op_ple_ar). The rest of the branch is
|
||||
* replicated, so no layer reduces it. */
|
||||
int64_t n_ple = 0;
|
||||
rad_weight w_ple_tok = 0, w_ple_norm = 0;
|
||||
G4Linear ln_ple_proj{};
|
||||
rad_buf b_ple = 0, b_ple_tok = 0, b_pg = 0;
|
||||
rad_op op_ple_tok = 0, op_ple_norm = 0, op_ple_add = 0;
|
||||
rad_op op_ple_tok = 0, op_ple_ar = 0, op_ple_norm = 0, op_ple_add = 0;
|
||||
/* An image's placeholder positions take the token-identity row of pad_token_id, as the
|
||||
* reference looks them up (Gemma4Model.forward: llm_input_ids = pad where multimodal): that row
|
||||
* times sqrt(n_ple), made as fill(sqrt(n_ple)) * the row, scattered over the image rows. */
|
||||
@@ -2030,10 +2032,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (m.n_ple < 0) { fprintf(stderr, "radiance: gemma4: hidden_size_per_layer_input %lld is negative\n", (long long)m.n_ple); return RAD_E_INVAL; }
|
||||
if (m.n_ple > 0) {
|
||||
const int64_t v_ple = meta_text_geti(meta, "vocab_size_per_layer_input", g.n_vocab_all);
|
||||
if (g.world > 1) {
|
||||
if (g.world > 2) {
|
||||
fprintf(stderr, "radiance: gemma4: per-layer embeddings (hidden_size_per_layer_input %lld) "
|
||||
"are served at one rank only; this model is small enough for one card\n",
|
||||
(long long)m.n_ple);
|
||||
"are served at one or two ranks, not %d: the four-rank junctions keep "
|
||||
"a rank's rows only, and the per-layer branch reads every row\n",
|
||||
(long long)m.n_ple, g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (v_ple != g.n_vocab_all) {
|
||||
@@ -2177,9 +2180,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
/* An image's rows overwrite its placeholders' embeddings after the (all-reduced) lookup and
|
||||
* before the first block: the reference scales token embeddings by sqrt(n_embd) and scatters
|
||||
* the image features in unscaled. */
|
||||
/* An image's rows overwrite its placeholders' embeddings after the lookup and before its
|
||||
* all-reduce (RadBatch::mm_embd: rank 0 holds the rows, every other rank zeros). The
|
||||
* reference scales token embeddings by sqrt(n_embd) and scatters the image features in
|
||||
* unscaled. */
|
||||
if (Gemma4Vision::present(meta) && ctx->max_enc_patches > 0)
|
||||
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
@@ -2216,6 +2220,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("mult", std::sqrt((double)m.n_ple))),
|
||||
RAD_WEIGHTS(m.w_ple_tok)),
|
||||
{}, {m.b_ple_tok});
|
||||
/* A rank's lookup writes zeros for ids outside its vocabulary slice; the all-reduce makes
|
||||
* every row whole. */
|
||||
if (g.world > 1) {
|
||||
m.op_ple_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", P, g.max_tok * P),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_ple_tok}, {m.b_ple_tok});
|
||||
if (!m.op_ple_ar) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(m.ln_ple_proj.declare(b, nm, g, nm.f("ple_model_proj"),
|
||||
{ nm.ckpt("model.language_model.per_layer_model_projection.weight") },
|
||||
P, g.n_embd, RAD_SHARD_NONE, grp_model(), m.b_x, m.b_ple));
|
||||
@@ -2417,7 +2432,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the bits it gives the whole. The buffer the second lane reduces in place is taken out of the
|
||||
* arena's sharing, which the runtime asks of every buffer a second lane touches; it lives
|
||||
* across the whole trunk already. */
|
||||
m.overlap = g.world > 1 && g.wire_exact && m.fuse && g.max_tok >= 2 * kOverlapRows;
|
||||
/* Not with per-layer embeddings: the slices close each layer through j_ma alone, without the
|
||||
* per-layer branch. */
|
||||
m.overlap = g.world > 1 && g.wire_exact && m.fuse && m.n_ple == 0 &&
|
||||
g.max_tok >= 2 * kOverlapRows;
|
||||
for (const Layer& lay : m.layers)
|
||||
m.overlap = m.overlap && lay.attn.op_ar && lay.mlp.op_ar;
|
||||
if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h));
|
||||
@@ -2602,6 +2620,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_note(b, "prefill overlap: off (%s)",
|
||||
!g.wire_exact ? "the lossy all-reduce wire"
|
||||
: !m.fuse ? "the residual junctions are not fused"
|
||||
: m.n_ple > 0 ? "the per-layer branch is not split into slices"
|
||||
: "a step holds fewer than two slices");
|
||||
}
|
||||
if (m.fuse && (g.world == 2 || g.world == 4)) {
|
||||
@@ -2815,18 +2834,22 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
if (m.op_embed_ar)
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.b_x, batch->n_tok), RAD_NONE);
|
||||
/* Before the all-reduce: after it, every rank past 0 would write zeros over its image rows. */
|
||||
if (m.op_mm && batch->n_mm_rows > 0)
|
||||
RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows,
|
||||
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, m.g.n_embd),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok));
|
||||
if (m.op_embed_ar)
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.b_x, batch->n_tok), RAD_NONE);
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
if (m.n_ple > 0) {
|
||||
RAD_ISSUE(c, m.op_ple_tok, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_ple_tok),
|
||||
brows(m.b_ple_tok, T));
|
||||
/* before the pad rows of image positions go in: every rank writes those whole */
|
||||
if (m.op_ple_ar)
|
||||
RAD_ISSUE_N(c, m.op_ple_ar, T * m.g.n_layer * m.n_ple, brows(m.b_ple_tok, T), RAD_NONE);
|
||||
if (m.op_ple_pscat && batch->n_mm_rows > 0) {
|
||||
const int64_t nm_rows = batch->n_mm_rows;
|
||||
RAD_ISSUE_N(c, m.op_ple_pfill, nm_rows, brows(m.b_ple_pad, nm_rows));
|
||||
@@ -2864,8 +2887,10 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
}
|
||||
if (m.fuse && !last) {
|
||||
/* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */
|
||||
l.j_ma.step(c, T, far);
|
||||
/* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op.
|
||||
* With per-layer embeddings it closes the branch, whose output every rank holds whole
|
||||
* (the feed-forward's reduction ran above): no all-reduce in front. */
|
||||
l.j_ma.step(c, T, far && !ple);
|
||||
} else {
|
||||
/* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after
|
||||
* the mlp add, as vLLM's `hidden_states = hidden_states * self.layer_scalar`. The
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hyv3_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hyv3_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_bf16.cpp)
|
||||
@@ -0,0 +1,5 @@
|
||||
#define HYV3_NS hyv3_bf16
|
||||
#define HYV3_QUANT ""
|
||||
#define HYV3_FP8_SOURCE 0
|
||||
#define HYV3_PLUGIN_NAME "hyv3_bf16"
|
||||
#include "../hyv3_common/hyv3_impl.cpp"
|
||||
@@ -0,0 +1,216 @@
|
||||
/* HYV3 full GQA attention with block-scaled FP8 projections and per-head
|
||||
* Q/K RMSNorm before NeoX RoPE (the HYV3 attention path).
|
||||
*
|
||||
* rmsnorm -> q/k/v gemm_nt_q -> per-head q/k RMSNorm -> rope -> kv_store -> attn_paged
|
||||
* -> quant_act_fp8 -> o gemm_nt_q -> [all_reduce] -> residual add
|
||||
*
|
||||
* Unlike AttnFP8, the projections stay separate so Q and K can be normalized independently before
|
||||
* rotation. The weights and all non-attention activations use the same contracts as the other FP8
|
||||
* blocks in rad_fp8.h.
|
||||
*/
|
||||
#ifndef HYV3_ATTENTION_H
|
||||
#define HYV3_ATTENTION_H
|
||||
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnQKFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */
|
||||
rad_buf q = 0; /* [max_tok, q_dim], projected, normed and rotated */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim], projected, normed and rotated */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim], projected */
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* q = nullptr;
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
const char* o = nullptr;
|
||||
double k_scale = 1.0, v_scale = 1.0; /* static FP8-cache descales; 1 for BF16 cache */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
LinearFP8 q{}, k{}, v{}, o{};
|
||||
rad_buf k_descale = 0, v_descale = 0;
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
rad_op op_q_norm = 0, op_k_norm = 0;
|
||||
rad_op op_k_descale = 0, op_v_descale = 0;
|
||||
rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
const Wire& wire, const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, const Wire& wire, const Src& src) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
layer = l;
|
||||
kv = group;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld\n", __func__, g.world,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const bool fp8_cache = std::strcmp(g.kv_dtype, "fp8_e4m3") == 0;
|
||||
if (fp8_cache && (!std::isfinite(src.k_scale) || src.k_scale <= 0.0 ||
|
||||
!std::isfinite(src.v_scale) || src.v_scale <= 0.0)) {
|
||||
fprintf(stderr, "radiance: HYV3 layer %d needs positive finite static K/V descales for "
|
||||
"its FP8 KV cache\n", l);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
if (!w_norm || !w_q_norm || !w_k_norm) return RAD_E_INVAL;
|
||||
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, w.x, w.h, g.n_embd));
|
||||
RAD_ARCH_TRY(q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), q_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.q}, w.h, w.q));
|
||||
RAD_ARCH_TRY(k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.k}, w.h, w.k));
|
||||
RAD_ARCH_TRY(v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.v}, w.h, w.v));
|
||||
|
||||
auto head_norm = [&](int64_t heads, rad_weight wt) {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q});
|
||||
op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, "neox"),
|
||||
{w.k}, {w.k});
|
||||
|
||||
if (fp8_cache) {
|
||||
k_descale = decl_b(b, nm.f("blk.%d.attn_k_descale", l), RAD_F32,
|
||||
{g.max_seqs, g.n_head_kv});
|
||||
v_descale = decl_b(b, nm.f("blk.%d.attn_v_descale", l), RAD_F32,
|
||||
{g.max_seqs, g.n_head_kv});
|
||||
op_k_descale = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", g.n_head_kv),
|
||||
RAD_STR("dtype", "f32"), RAD_F64("value", src.k_scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {k_descale});
|
||||
op_v_descale = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", g.n_head_kv),
|
||||
RAD_STR("dtype", "f32"), RAD_F64("value", src.v_scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {v_descale});
|
||||
}
|
||||
const rad_op attn = decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS);
|
||||
op_attn = fp8_cache ? rw(b, attn, {w.q, k_descale, v_descale}, {w.attn.x})
|
||||
: rw(b, attn, {w.q}, {w.attn.x});
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype),
|
||||
RAD_F64("k_scale", src.k_scale), RAD_F64("v_scale", src.v_scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
|
||||
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), {src.o}, w.attn, w.h.x));
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
return op_attn && op_kv_store && op_add &&
|
||||
(!fp8_cache || (k_descale && v_descale && op_k_descale && op_v_descale))
|
||||
? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
nq_h.step(c, T);
|
||||
q.step(c, w.h, w.q, T);
|
||||
k.step(c, w.h, w.k, T);
|
||||
v.step(c, w.h, w.v, T);
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_kv_store, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, layer));
|
||||
if (op_k_descale) {
|
||||
RAD_ISSUE_N(c, op_k_descale, batch->n_seq, brows(k_descale, batch->n_seq));
|
||||
RAD_ISSUE_N(c, op_v_descale, batch->n_seq, brows(v_descale, batch->n_seq));
|
||||
}
|
||||
if (k_descale && v_descale)
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), brows(k_descale, batch->n_seq),
|
||||
brows(v_descale, batch->n_seq),
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
|
||||
else
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
|
||||
q_attn.step(c, T);
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
|
||||
#endif /* HYV3_ATTENTION_H */
|
||||
@@ -0,0 +1,540 @@
|
||||
/* Shared HYV3 graph. Thin architecture wrappers select the source descriptor and source format. */
|
||||
#ifndef HYV3_NS
|
||||
#define HYV3_NS hyv3_fp8
|
||||
#endif
|
||||
#ifndef HYV3_QUANT
|
||||
#define HYV3_QUANT "fp8"
|
||||
#endif
|
||||
#ifndef HYV3_FP8_SOURCE
|
||||
#define HYV3_FP8_SOURCE 1
|
||||
#endif
|
||||
#ifndef HYV3_PLUGIN_NAME
|
||||
#define HYV3_PLUGIN_NAME "hyv3_fp8"
|
||||
#endif
|
||||
#ifndef HYV3_GGUF_SOURCE
|
||||
#define HYV3_GGUF_SOURCE 0
|
||||
#endif
|
||||
#include <arch/rad_arch.h>
|
||||
#include "hyv3_attention.h"
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace HYV3_NS {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool dense = false;
|
||||
AttnQKFP8 attn{};
|
||||
MlpFP8 dense_mlp{};
|
||||
MoeFP8 moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
int64_t n_ff_expert = 0, n_ff_shared = 0;
|
||||
rad_kvgroup kv_full = 0;
|
||||
|
||||
rad_buf x = 0, h_out = 0, logits = 0;
|
||||
ActFP8 h{};
|
||||
rad_buf q = 0, k = 0, v = 0;
|
||||
ActFP8 attn{};
|
||||
rad_buf dense_gate_up = 0;
|
||||
ActFP8 dense_ffn{};
|
||||
MoeFP8::Wire mw{};
|
||||
|
||||
rad_weight token = 0, final_norm = 0, lm_head = 0;
|
||||
rad_op embed = 0, embed_ar = 0, final_rms = 0, gather = 0, logits_op = 0;
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model models[MAX_RANKS];
|
||||
|
||||
static int check_format(const RadModelMeta* meta) {
|
||||
const char* q = meta && meta->quant ? meta->quant : "";
|
||||
#if HYV3_GGUF_SOURCE
|
||||
if (std::strcmp(q, "gguf_ftype_15") != 0) {
|
||||
fprintf(stderr, "radiance: HYV3 GGUF adapter expects quant descriptor 'gguf_ftype_15'; "
|
||||
"got '%s'\n", *q ? q : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#elif HYV3_FP8_SOURCE
|
||||
if (std::strcmp(q, "fp8") != 0) {
|
||||
fprintf(stderr, "radiance: HYV3 FP8 expects quant descriptor 'fp8'; got '%s'\n",
|
||||
*q ? q : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* fmt = rad_meta_gets(meta, "quantization_config.fmt", nullptr);
|
||||
if (fmt && std::strcmp(fmt, "e4m3") != 0) return RAD_E_UNSUPPORTED;
|
||||
const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr);
|
||||
if (method && std::strcmp(method, "fp8") != 0) return RAD_E_UNSUPPORTED;
|
||||
#else
|
||||
if (*q) {
|
||||
fprintf(stderr, "radiance: HYV3 BF16 expects an unquantized checkpoint; got '%s'\n", q);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#endif
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int check_model_config(const RadModelMeta* meta, const Geom& g, Model& model) {
|
||||
if (meta_text_geti(meta, "qk_norm", 0) != 1 ||
|
||||
meta_text_geti(meta, "moe_router_use_sigmoid", 0) != 1 ||
|
||||
meta_text_geti(meta, "moe_router_enable_expert_bias", 0) != 1 ||
|
||||
meta_text_geti(meta, "route_norm", 0) != 1 ||
|
||||
meta_text_geti(meta, "enable_moe_fp32_combine", 0) != 1 ||
|
||||
meta_text_geti(meta, "attention_bias", 0) != 0 ||
|
||||
meta_text_geti(meta, "mlp_bias", 0) != 0) {
|
||||
fprintf(stderr, "radiance: hyv3 requires QK norm, sigmoid routing with correction bias, "
|
||||
"route normalization, FP32 MoE combine, and bias-free projections\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
const int64_t first_dense = meta_text_geti(meta, "first_k_dense_replace", -1);
|
||||
const int64_t n_expert = meta_text_geti(meta, "num_experts", 0);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", 0);
|
||||
const int64_t n_shared = meta_text_geti(meta, "num_shared_experts", 0);
|
||||
const int64_t moe_intermediate = meta_text_geti(meta, "moe_intermediate_size", 0);
|
||||
const int64_t n_ff_shared = meta_text_geti(meta, "expert_hidden_dim", 0);
|
||||
model.n_ff_expert = meta_text_geti(meta, "expert_hidden_dim", 0);
|
||||
const int64_t route_norm = meta_text_geti(meta, "route_norm", 0);
|
||||
const double route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0);
|
||||
const char* schedule = meta_text_gets(meta, "mlp_layer_types", nullptr);
|
||||
std::vector<int> kinds;
|
||||
|
||||
if (first_dense != 1 || n_expert != meta->n_expert || top_k != meta->n_expert_used ||
|
||||
n_expert != 128 || top_k != 8 || n_shared != 1 || model.n_ff_expert != 768 ||
|
||||
n_ff_shared != 768 || moe_intermediate != 1536 || route_norm != 1 ||
|
||||
!std::isfinite(route_scale) || route_scale <= 0 ||
|
||||
std::fabs(route_scale - 2.826) > 1e-6 || model.n_ff_expert % RAD_FP8_BLOCK != 0) {
|
||||
fprintf(stderr, "radiance: hyv3: unsupported MoE geometry/config; expected 128 experts, "
|
||||
"top-8, 768-wide routed and shared experts, normalized "
|
||||
"sigmoid routing scaled by 2.826, and one dense first layer\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (schedule && *schedule) {
|
||||
RAD_ARCH_TRY(parse_layer_kinds("hyv3", schedule, {"sparse"}, "dense", &kinds));
|
||||
if ((int64_t)kinds.size() != g.n_layer) {
|
||||
fprintf(stderr, "radiance: hyv3: mlp_layer_types names %zu layers; the model has %lld\n",
|
||||
kinds.size(), (long long)g.n_layer);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int want = l == 0 ? 0 : 1;
|
||||
if (kinds[(size_t)l] != want) {
|
||||
fprintf(stderr, "radiance: hyv3: layer %lld has an unsupported MLP kind; expected "
|
||||
"dense at layer 0 and sparse afterwards\n", (long long)l);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int64_t shared_width = n_ff_shared * n_shared;
|
||||
if (shared_width <= 0 || shared_width % RAD_FP8_BLOCK != 0) return RAD_E_SHAPE;
|
||||
model.n_ff_shared = shared_width;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
|
||||
const int64_t blocks = width / RAD_FP8_BLOCK;
|
||||
const int64_t base = blocks / world, rem = blocks % world;
|
||||
const int64_t first = rank * base + std::min<int64_t>(rank, rem);
|
||||
const int64_t count = base + (rank < rem ? 1 : 0);
|
||||
*lo = first * RAD_FP8_BLOCK;
|
||||
*hi = (first + count) * RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = models[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
int status = check_format(meta);
|
||||
if (status < 0) return status;
|
||||
status = geom_from(m.g, meta, ctx, "bf16", RAD_BF16);
|
||||
if (status < 0) return status;
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
if (g.n_layer < 2 || g.n_embd != 2048 || g.n_head_all != 32 || g.n_head_kv_all != 4 ||
|
||||
g.head_dim != 128 || g.n_vocab_all != 120832 ||
|
||||
(g.world != 1 && g.world != 2)) {
|
||||
fprintf(stderr, "radiance: hyv3 supports Hy-Memory's 2048-wide, 32/4-head, "
|
||||
"head_dim=128 geometry at tensor-parallel world sizes 1 or 2\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
status = check_model_config(meta, g, m);
|
||||
if (status < 0) return status;
|
||||
#if HYV3_FP8_SOURCE
|
||||
if ((ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 &&
|
||||
ctx->kv_dtype != RAD_F8E4M3) || ctx->kv_quant != RAD_KVQ_NONE) {
|
||||
fprintf(stderr, "radiance: HYV3 FP8 supports BF16 or plain E4M3 KV cache, not this layout\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#else
|
||||
if ((ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16) ||
|
||||
ctx->kv_quant != RAD_KVQ_NONE) {
|
||||
fprintf(stderr, "radiance: HYV3 BF16 supports a BF16 KV cache only\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#endif
|
||||
status = yarn_from(g, meta, "", g.head_dim);
|
||||
if (status < 0) return status;
|
||||
|
||||
const int64_t n_expert_all = meta_text_geti(meta, "num_experts", meta->n_expert);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
|
||||
if (n_expert_all % g.world != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_expert_local = n_expert_all / g.world;
|
||||
|
||||
/* ---- Full-attention KV cache. All layers share one group. */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
kd.n_head_kv = g.n_head_kv;
|
||||
kd.head_dim = g.head_dim;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &kd);
|
||||
if (!m.kv_full) return RAD_E_INVAL;
|
||||
g.kv_dtype = rad_dtype_name(kd.dtype);
|
||||
|
||||
const int64_t T = g.max_tok, qd = g.q_dim(), kvd = g.kv_dim();
|
||||
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, g.n_embd});
|
||||
m.h.x = decl_b(b, nm.f("h"), RAD_BF16, {T, g.n_embd});
|
||||
RAD_ARCH_TRY(m.h.declare_qs(b, nm, g, "h", g.n_embd, 0, !HYV3_FP8_SOURCE));
|
||||
m.q = decl_b(b, nm.f("attn_q"), RAD_BF16, {T, qd});
|
||||
m.k = decl_b(b, nm.f("attn_k"), RAD_BF16, {T, kvd});
|
||||
m.v = decl_b(b, nm.f("attn_v"), RAD_BF16, {T, kvd});
|
||||
m.attn.x = decl_b(b, nm.f("attn_out"), RAD_BF16, {T, qd});
|
||||
RAD_ARCH_TRY(m.attn.declare_qs(b, nm, g, "attn_out", qd, 0, !HYV3_FP8_SOURCE));
|
||||
m.dense_gate_up = decl_b(b, nm.f("dense_gate_up"), RAD_BF16, {T, 2 * g.n_ff});
|
||||
m.dense_ffn.x = decl_b(b, nm.f("dense_ffn"), RAD_BF16, {T, g.n_ff});
|
||||
RAD_ARCH_TRY(m.dense_ffn.declare_qs(b, nm, g, "dense_ffn", g.n_ff, 0, !HYV3_FP8_SOURCE));
|
||||
m.h_out = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
|
||||
|
||||
/* The router is replicated, while the routed experts are expert-parallel. The shared expert
|
||||
* is split only on whole FP8 scale blocks; the final block remainder is assigned to early
|
||||
* ranks. At TP2, routed and shared BF16 outputs are all-reduced separately before FP32 combine. */
|
||||
MoeFP8::Config mc{};
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.n_expert = n_expert_local;
|
||||
mc.expert_base = n_expert_local * g.rank;
|
||||
mc.probed_expert = mc.expert_base;
|
||||
mc.top_k = top_k;
|
||||
mc.n_ff_exp = m.n_ff_expert;
|
||||
mc.norm_topk = 1;
|
||||
mc.sigmoid_router = 1;
|
||||
mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 2.826);
|
||||
mc.shared_ungated = 1;
|
||||
mc.shared_fp32_combine = 1;
|
||||
mc.router_fuse = 0;
|
||||
mc.rows = T < 2048 ? T : 2048;
|
||||
block_slice_128(m.n_ff_shared, g.world, g.rank, &mc.shared_lo, &mc.shared_hi);
|
||||
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
|
||||
|
||||
#if HYV3_FP8_SOURCE
|
||||
/* The source's per-tensor scales are imported by the recipe to format 9 (block FP8 with F32
|
||||
* 128x128 scales). The model probes the source before recipe planning, so state that encoding
|
||||
* explicitly here. */
|
||||
mc.expert_f32_scale = 1;
|
||||
#endif
|
||||
|
||||
const int64_t R = T, S = mc.rows * top_k;
|
||||
m.mw.x = m.x;
|
||||
m.mw.h = m.h;
|
||||
m.mw.logits = decl_b(b, nm.f("moe_logits"), RAD_F32, {R, n_expert_all});
|
||||
m.mw.ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, top_k});
|
||||
m.mw.ew = decl_b(b, nm.f("moe_weights"), RAD_F32, {R, top_k});
|
||||
m.mw.eoff = decl_b(b, nm.f("moe_offsets"), RAD_I32, {n_expert_local + 1});
|
||||
m.mw.ecnt = decl_b(b, nm.f("moe_counts"), RAD_I32, {n_expert_local}, RAD_BUF_PERSIST);
|
||||
m.mw.sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {S});
|
||||
m.mw.egu = decl_b(b, nm.f("moe_gate_up"), RAD_BF16, {S, 2 * mc.n_ff_exp});
|
||||
m.mw.eff.x = decl_b(b, nm.f("moe_ffn"), RAD_BF16, {S, mc.n_ff_exp});
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, !HYV3_FP8_SOURCE));
|
||||
m.mw.edn = decl_b(b, nm.f("moe_down"), RAD_BF16, {S, g.n_embd});
|
||||
m.mw.moe = decl_b(b, nm.f("moe_routed"), RAD_BF16, {T, g.n_embd});
|
||||
m.mw.moe_f32 = decl_b(b, nm.f("moe_routed_f32"), RAD_F32, {T, g.n_embd});
|
||||
m.mw.shared_f32 = decl_b(b, nm.f("moe_shared_f32"), RAD_F32, {T, g.n_embd});
|
||||
m.mw.combined_f32 = decl_b(b, nm.f("moe_combined_f32"), RAD_F32, {T, g.n_embd});
|
||||
m.mw.sgu = decl_b(b, nm.f("shared_gate_up"), RAD_BF16, {T, 2 * mc.n_ff_shared});
|
||||
m.mw.sff.x = decl_b(b, nm.f("shared_ffn"), RAD_BF16, {T, mc.n_ff_shared});
|
||||
RAD_ARCH_TRY(m.mw.sff.declare_qs(b, nm, g, "shared_ffn", mc.n_ff_shared, 0,
|
||||
!HYV3_FP8_SOURCE));
|
||||
m.mw.sout = decl_b(b, nm.f("shared_out"), RAD_BF16, {T, g.n_embd});
|
||||
m.mw.sgate = decl_b(b, nm.f("shared_one"), RAD_BF16, {T, 1});
|
||||
|
||||
/* ---- Token embedding and head. */
|
||||
#if HYV3_GGUF_SOURCE
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("token_embd.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("output_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("output.weight"),
|
||||
nm.ckpt("token_embd.weight")));
|
||||
#else
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.embed_tokens.weight")));
|
||||
#endif
|
||||
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.final_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.token)),
|
||||
{}, {m.x});
|
||||
if (g.world > 1)
|
||||
m.embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.x}, {m.x});
|
||||
|
||||
AttnQKFP8::Wire aw{};
|
||||
aw.x = m.x; aw.h = m.h; aw.q = m.q; aw.k = m.k; aw.v = m.v; aw.attn = m.attn;
|
||||
MlpFP8::Wire dw{};
|
||||
dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn;
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.dense = (l == 0);
|
||||
#if HYV3_GGUF_SOURCE
|
||||
const char* pre = nm.ckpt("blk.%lld", (long long)l);
|
||||
#else
|
||||
const char* pre = nm.ckpt("model.layers.%lld", (long long)l);
|
||||
#endif
|
||||
AttnQKFP8::Src as{};
|
||||
#if HYV3_GGUF_SOURCE
|
||||
as.norm = nm.ckpt("%s.attn_norm.weight", pre);
|
||||
as.q = nm.ckpt("%s.attn_q.weight", pre);
|
||||
as.k = nm.ckpt("%s.attn_k.weight", pre);
|
||||
as.v = nm.ckpt("%s.attn_v.weight", pre);
|
||||
as.q_norm = nm.ckpt("%s.attn_q_norm.weight", pre);
|
||||
as.k_norm = nm.ckpt("%s.attn_k_norm.weight", pre);
|
||||
as.o = nm.ckpt("%s.attn_output.weight", pre);
|
||||
#else
|
||||
as.norm = nm.ckpt("%s.input_layernorm.weight", pre);
|
||||
as.q = nm.ckpt("%s.self_attn.q_proj.weight", pre);
|
||||
as.k = nm.ckpt("%s.self_attn.k_proj.weight", pre);
|
||||
as.v = nm.ckpt("%s.self_attn.v_proj.weight", pre);
|
||||
as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre);
|
||||
as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre);
|
||||
as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre);
|
||||
#endif
|
||||
#if HYV3_FP8_SOURCE
|
||||
if (kd.dtype == RAD_F8E4M3) {
|
||||
const std::string sk = "hyv3.kv_cache." + std::to_string(l) + ".k_scale";
|
||||
const std::string sv = "hyv3.kv_cache." + std::to_string(l) + ".v_scale";
|
||||
as.k_scale = meta_text_getf(meta, sk.c_str(), NAN);
|
||||
as.v_scale = meta_text_getf(meta, sv.c_str(), NAN);
|
||||
if (!std::isfinite(as.k_scale) || as.k_scale <= 0.0 ||
|
||||
!std::isfinite(as.v_scale) || as.v_scale <= 0.0) {
|
||||
fprintf(stderr, "radiance: hyv3_fp8: FP8 KV cache needs positive finite scales "
|
||||
"for layer %lld (metadata keys %s and %s)\n",
|
||||
(long long)l, sk.c_str(), sv.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
|
||||
status = lay.attn.declare(b, nm, g, (int)l, m.kv_full, aw, as);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: hyv3: attention layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{};
|
||||
#if HYV3_GGUF_SOURCE
|
||||
ds.norm = nm.ckpt("%s.ffn_norm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.ffn_gate.weight", pre);
|
||||
ds.up = nm.ckpt("%s.ffn_up.weight", pre);
|
||||
ds.down = nm.ckpt("%s.ffn_down.weight", pre);
|
||||
#else
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ds.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.gate_proj.weight", mlp);
|
||||
ds.up = nm.ckpt("%s.up_proj.weight", mlp);
|
||||
ds.down = nm.ckpt("%s.down_proj.weight", mlp);
|
||||
#endif
|
||||
status = lay.dense_mlp.declare(b, nm, g, (int)l, dw, ds);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: hyv3: dense MLP declaration failed (%d)\n", status);
|
||||
return status;
|
||||
}
|
||||
} else {
|
||||
MoeFP8::Src ms{};
|
||||
ms.cfg = mc;
|
||||
#if HYV3_GGUF_SOURCE
|
||||
ms.norm = nm.ckpt("%s.ffn_norm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.ffn_gate_inp.weight", pre);
|
||||
ms.router_bias = nm.ckpt("%s.exp_probs_b", pre);
|
||||
ms.experts_gate = nm.ckpt("%s.ffn_gate_exps.weight", pre);
|
||||
ms.experts_up = nm.ckpt("%s.ffn_up_exps.weight", pre);
|
||||
ms.experts_down = nm.ckpt("%s.ffn_down_exps.weight", pre);
|
||||
ms.shared_mlp_gate = nm.ckpt("%s.ffn_gate_shexp.weight", pre);
|
||||
ms.shared_mlp_up = nm.ckpt("%s.ffn_up_shexp.weight", pre);
|
||||
ms.shared_mlp_down = nm.ckpt("%s.ffn_down_shexp.weight", pre);
|
||||
#else
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.router.gate.weight", mlp);
|
||||
ms.router_bias = nm.ckpt("%s.expert_bias", mlp);
|
||||
ms.experts = nm.ckpt("%s.experts", mlp);
|
||||
ms.shared = nm.ckpt("%s.shared_mlp", mlp);
|
||||
#endif
|
||||
#if !HYV3_FP8_SOURCE
|
||||
status = MoeFP8::probe(b, nm, (int)l, ms, &ms.cfg);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: HYV3: expert format probe failed at layer %lld (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
#endif
|
||||
status = lay.moe.declare(b, nm, g, (int)l, m.mw, ms);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: hyv3: MoE layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m.final_rms = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.final_norm)),
|
||||
{m.x}, {m.h.x});
|
||||
m.gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.h.x}, {m.h_out});
|
||||
m.logits_op = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.lm_head)),
|
||||
{m.h_out}, {m.logits});
|
||||
|
||||
rad_note(b, "HYV3: %lld layers (dense first, then top-%lld/%lld sigmoid MoE), %lld/%lld "
|
||||
"attention/KV heads x %lld; expert width %lld, shared width %lld, router scale %.3f",
|
||||
(long long)g.n_layer, (long long)top_k, (long long)n_expert_all,
|
||||
(long long)g.n_head_all, (long long)g.n_head_kv_all, (long long)g.head_dim,
|
||||
(long long)m.n_ff_expert, (long long)m.n_ff_shared, mc.route_scale);
|
||||
#if HYV3_FP8_SOURCE
|
||||
rad_note(b, "E4M3 per-tensor scales are imported to 128x128 F32 planes; Q/K RMSNorm precedes "
|
||||
"NeoX RoPE and shared/routed outputs combine in FP32");
|
||||
#elif HYV3_GGUF_SOURCE
|
||||
rad_note(b, "GGUF-source HYV3; Q4_K/Q6_K tensors are decoded and recipe-converted to native "
|
||||
"Radiance weights, adding quantization loss to an already-lossy source");
|
||||
#else
|
||||
rad_note(b, "BF16-source HYV3; per-weight recipes may quantize linears or routed experts; "
|
||||
"Q/K RMSNorm precedes NeoX RoPE and shared/routed outputs combine in FP32");
|
||||
#endif
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(c)];
|
||||
RAD_ISSUE(c, m.embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token),
|
||||
brows(m.x, batch->n_tok));
|
||||
if (m.embed_ar)
|
||||
RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.x, batch->n_tok), RAD_NONE);
|
||||
|
||||
for (Layer& layer : m.layers) {
|
||||
layer.attn.step(c, batch);
|
||||
if (layer.dense) layer.dense_mlp.step(c, batch);
|
||||
else layer.moe.step(c, batch);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.final_rms, brows(m.x, batch->n_tok), RAD_W(m.final_norm),
|
||||
brows(m.h.x, batch->n_tok));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.gather, batch->n_out,
|
||||
brows(m.h.x, batch->n_tok), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.h_out, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.logits_op, batch->n_out,
|
||||
brows(m.h_out, batch->n_out), RAD_W(m.lm_head),
|
||||
brows(m.logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace HYV3_NS
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(HYV3_NS)
|
||||
static const char* const kHyv3ToolTriggers[] = { "<tool_calls>" };
|
||||
static const RadChatFormat kHyv3ChatFormat = {
|
||||
.struct_size = sizeof(RadChatFormat),
|
||||
.name = "hyv3",
|
||||
.reasoning_open = "<think>",
|
||||
.reasoning_close = "</think>",
|
||||
.reasoning_breaks = kHyv3ToolTriggers,
|
||||
.n_reasoning_breaks = 1,
|
||||
.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT,
|
||||
.section_open = "<tool_calls>",
|
||||
.section_close = "</tool_calls>",
|
||||
.name_prefix = "<tool_call>",
|
||||
.name_suffix = "<tool_sep>",
|
||||
.call_end = "</tool_call>",
|
||||
.arg_prefix = "<arg_key>",
|
||||
.arg_name_suffix = "</arg_key>\n",
|
||||
.arg_value_prefix = "<arg_value>",
|
||||
.arg_value_suffix = "</arg_value>",
|
||||
.string_value = RAD_CHAT_VALUE_RAW,
|
||||
.other_value = RAD_CHAT_VALUE_JSON,
|
||||
.triggers = kHyv3ToolTriggers,
|
||||
.n_triggers = 1,
|
||||
.args_form = RAD_CHAT_ARGS_TAGGED,
|
||||
};
|
||||
extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
|
||||
return &kHyv3ChatFormat;
|
||||
}
|
||||
extern "C" const char* rad_arch_id(void) { return "hyv3"; }
|
||||
extern "C" const char* rad_arch_quant(void) { return HYV3_QUANT; }
|
||||
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
|
||||
return HYV3_NS::declare(b, m, c);
|
||||
}
|
||||
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
|
||||
HYV3_NS::step(c, batch);
|
||||
}
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) {
|
||||
static const RadPluginInfo info = {
|
||||
RAD_PLUGIN_ARCH, HYV3_PLUGIN_NAME, "0.2.0",
|
||||
"Tencent Hy-Memory HYV3: Q/K-normalized full attention and sigmoid MoE", ""
|
||||
};
|
||||
return &info;
|
||||
}
|
||||
#endif
|
||||
|
||||
#undef HYV3_NS
|
||||
#undef HYV3_QUANT
|
||||
#undef HYV3_FP8_SOURCE
|
||||
#undef HYV3_PLUGIN_NAME
|
||||
#undef HYV3_GGUF_SOURCE
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hyv3_fp8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hyv3_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_fp8.cpp)
|
||||
@@ -0,0 +1,5 @@
|
||||
#define HYV3_NS hyv3_fp8
|
||||
#define HYV3_QUANT "fp8"
|
||||
#define HYV3_FP8_SOURCE 1
|
||||
#define HYV3_PLUGIN_NAME "hyv3_fp8"
|
||||
#include "../hyv3_common/hyv3_impl.cpp"
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hyv3_gguf LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hyv3_gguf architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_gguf.cpp)
|
||||
@@ -0,0 +1,7 @@
|
||||
#define HYV3_NS hyv3_gguf
|
||||
#define HYV3_QUANT "gguf_ftype_15"
|
||||
#define HYV3_FP8_SOURCE 0
|
||||
#define HYV3_GGUF_SOURCE 1
|
||||
#define HYV3_PLUGIN_NAME "hyv3_gguf"
|
||||
#include "../hyv3_common/hyv3_impl.cpp"
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
+54
-26
@@ -73,10 +73,30 @@ enum { kMaxLanes = 8 };
|
||||
static const int kTaps[] = { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 };
|
||||
enum { kNTaps = 12 };
|
||||
|
||||
/* The rebalance a request may ask for (`rebalance`, RAD_GEN_COND_REBALANCE): every tap times a fixed
|
||||
* gain before the text fusion, ComfyUI's ConditioningKrea2Rebalance (nova452) at its defaults --
|
||||
* multiplier 4 times the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1. */
|
||||
static const double kRebalance[] = { 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 };
|
||||
/* The rebalance presets a request may ask for (`rebalance`, RAD_GEN_COND_REBALANCE with the row in
|
||||
* RAD_GEN_COND_REBALANCE_PRESET): every tap times a fixed gain before the text fusion.
|
||||
* legacy ComfyUI's ConditioningKrea2Rebalance (nova452) at its defaults -- multiplier 4 times
|
||||
* the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1, about 9x the taps' RMS.
|
||||
* balanced, detail, subtle
|
||||
* comfyui-krea2-conditioning's presets (huwhitememes) with renormalize on, multiplier 1:
|
||||
* the weights times s = sqrt(sum m_t / sum w_t^2 m_t), m_t the mean square of tap t over
|
||||
* the prompt's rows. The node measures s per prompt; here it is a constant, m_t averaged
|
||||
* over twenty prompts through krea/Krea-2-Turbo's text encoder
|
||||
* (scripts/krea2_rebalance_calib.py), and per prompt s stayed within 1.7 % of it.
|
||||
* A preset row the plugin does not know scales nothing: the plain model. */
|
||||
enum { kNPresets = 4 };
|
||||
static const double kRebalance[kNPresets][kNTaps] = {
|
||||
{ 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 },
|
||||
/* balanced: 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1 at s 0.44109 */
|
||||
{ 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 1.1027, 2.2055, 0.4852,
|
||||
1.7644, 0.44109 },
|
||||
/* detail: 0.8, 0.8, 0.9, 0.9, 1, 1, 1.2, 3, 6, 1.5, 5, 1.2 at s 0.35702 */
|
||||
{ 0.28562, 0.28562, 0.32132, 0.32132, 0.35702, 0.35702, 0.42842, 1.0711, 2.1421, 0.53553,
|
||||
1.7851, 0.42842 },
|
||||
/* subtle: 1, 1, 1, 1, 1, 1, 1, 1.5, 2, 1, 1.5, 1 at s 0.84759 */
|
||||
{ 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 1.2714, 1.6952, 0.84759,
|
||||
1.2714, 0.84759 },
|
||||
};
|
||||
|
||||
static const char* kSysPrompt =
|
||||
"Describe the image by detailing the color, shape, size, texture, quantity, text, spatial "
|
||||
@@ -90,7 +110,7 @@ struct TeLayer {
|
||||
GateQuantFP8 gq{};
|
||||
rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0;
|
||||
rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0;
|
||||
rad_op op_gain = 0; /* the tap's rebalance gain into te.h2 */
|
||||
rad_op op_gain[kNPresets] = {}; /* the tap's rebalance gain into te.h2, a preset each */
|
||||
rad_op op_tap_g = 0; /* the scatter from te.h2, when rebalanced */
|
||||
int tap = -1; /* this layer's output is tap `tap`, or none */
|
||||
};
|
||||
@@ -138,7 +158,7 @@ struct Model {
|
||||
ActFP8 a_th{}, a_tattn{}, a_tffn{};
|
||||
std::vector<TeLayer> te;
|
||||
rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */
|
||||
std::string tap_mul[kNTaps]; /* chan_affine's `mul` for each tap's rebalance gain */
|
||||
std::string tap_mul[kNPresets][kNTaps]; /* chan_affine's `mul` for each preset's tap gain */
|
||||
std::string tap_add; /* chan_affine's `add`: zeros */
|
||||
|
||||
/* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks
|
||||
@@ -390,15 +410,17 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
(int)kGainCh);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int t = 0; t < kNTaps; ++t) {
|
||||
char v[32];
|
||||
std::snprintf(v, sizeof v, "%.9g", kRebalance[t]);
|
||||
m.tap_mul[t].clear();
|
||||
for (int k = 0; k < kGainCh; ++k) {
|
||||
if (k) m.tap_mul[t] += ' ';
|
||||
m.tap_mul[t] += v;
|
||||
for (int p = 0; p < kNPresets; ++p)
|
||||
for (int t = 0; t < kNTaps; ++t) {
|
||||
char v[32];
|
||||
std::snprintf(v, sizeof v, "%.9g", kRebalance[p][t]);
|
||||
std::string& s = m.tap_mul[p][t];
|
||||
s.clear();
|
||||
for (int k = 0; k < kGainCh; ++k) {
|
||||
if (k) s += ' ';
|
||||
s += v;
|
||||
}
|
||||
}
|
||||
}
|
||||
m.tap_add.clear();
|
||||
for (int k = 0; k < kGainCh; ++k) m.tap_add += k ? " 0" : "0";
|
||||
|
||||
@@ -482,14 +504,18 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
L.op_add2 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx);
|
||||
if (L.tap >= 0) {
|
||||
/* f32 arithmetic, rounded once into bf16 (`round` 0) */
|
||||
L.op_gain = rw(b, RAD_OP(b, "chan_affine",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", kGainCh),
|
||||
RAD_STR("mul", m.tap_mul[L.tap].c_str()),
|
||||
RAD_STR("add", m.tap_add.c_str()),
|
||||
RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("round", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_tx }, { m.b_th2 });
|
||||
for (int p = 0; p < kNPresets; ++p) {
|
||||
L.op_gain[p] = rw(b, RAD_OP(b, "chan_affine",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows),
|
||||
RAD_INT("n", kGainCh),
|
||||
RAD_STR("mul", m.tap_mul[p][L.tap].c_str()),
|
||||
RAD_STR("add", m.tap_add.c_str()),
|
||||
RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("round", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_tx }, { m.b_th2 });
|
||||
if (!L.op_gain[p]) return RAD_E_INVAL;
|
||||
}
|
||||
L.op_tap_g = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows),
|
||||
RAD_INT("n", g.n_embd), RAD_STR("dtype", "bf16")),
|
||||
@@ -503,7 +529,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_tx, m.b_tidx, m.b_taps }, { m.b_taps });
|
||||
if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2 ||
|
||||
(L.tap >= 0 && (!L.op_tap || !L.op_gain || !L.op_tap_g)))
|
||||
(L.tap >= 0 && (!L.op_tap || !L.op_tap_g)))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return m.op_embed && m.op_iota ? RAD_OK : RAD_E_INVAL;
|
||||
@@ -1186,7 +1212,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.cond_rows = kCondRows;
|
||||
d.rope_hw_scale = 1.0;
|
||||
d.rope_text_l = 0;
|
||||
d.cond_opts = RAD_GEN_COND_REBALANCE;
|
||||
d.cond_opts = RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET;
|
||||
RAD_ARCH_TRY(rad_declare_generator(b, &d));
|
||||
}
|
||||
rad_note(b, "rank %d/%d: Krea 2%s -- text encoder %d of %lld layers, text fusion %zu + %zu "
|
||||
@@ -1205,7 +1231,9 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const Geom& g = m.gt;
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
const bool rebalance = batch->gen_b && (batch->gen_b->cond_opts & RAD_GEN_COND_REBALANCE);
|
||||
const int32_t opts = batch->gen_b ? batch->gen_b->cond_opts : 0;
|
||||
const int preset = (opts & RAD_GEN_COND_REBALANCE_PRESET) >> RAD_GEN_COND_REBALANCE_PRESET_SHIFT;
|
||||
const bool rebalance = (opts & RAD_GEN_COND_REBALANCE) && preset < kNPresets;
|
||||
RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok),
|
||||
brows(m.b_tx, T));
|
||||
RAD_ISSUE_N(c, m.op_iota, T, brows(m.b_tidx, T));
|
||||
@@ -1230,7 +1258,7 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T));
|
||||
if (L.tap >= 0 && rebalance)
|
||||
RAD_ISSUE_N(c, L.op_gain, T, brows(m.b_tx, T), brows(m.b_th2, T));
|
||||
RAD_ISSUE_N(c, L.op_gain[preset], T, brows(m.b_tx, T), brows(m.b_th2, T));
|
||||
if (L.tap >= 0)
|
||||
RAD_ISSUE_N(c, rebalance ? L.op_tap_g : L.op_tap, T,
|
||||
brows(rebalance ? m.b_th2 : m.b_tx, T), brows(m.b_tidx, T),
|
||||
|
||||
@@ -910,9 +910,9 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const char* bn = nm.f("%s.bias", base);
|
||||
RAD_ARCH_TRY(map_rows(b, wn, { { src_w, (int)(md * ada_rows), ada_rows } }));
|
||||
RAD_ARCH_TRY(map_rows(b, bn, { { src_b, (int)(md * ada_rows), ada_rows } }));
|
||||
B.ada[md].mapped = true;
|
||||
/* The row slice is mapped above (DenseFP8 takes that as its argument). */
|
||||
RAD_ARCH_TRY(B.ada[md].declare(b, nm, base, m.Ws, td, acc, RAD_SHARD_ROW,
|
||||
grp_layer(grp), { src_w }));
|
||||
grp_layer(grp), { src_w }, {}, true));
|
||||
B.ada_b[md] = decl_w(b, bn, RAD_BF16, { m.Ws }, acc, RAD_SHARD_ROW, grp_layer(grp));
|
||||
if (!B.ada_b[md]) return RAD_E_INVAL;
|
||||
B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias",
|
||||
|
||||
@@ -287,6 +287,7 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
/* Dimensions come from GGUF's `<arch>.<field>` keys, so one plugin covers a family; other keys
|
||||
* pass through in the free-form list. */
|
||||
const std::string a = out->arch;
|
||||
if (a == "hy_v3") out->arch = "hyv3";
|
||||
auto gi = [&](const char* suffix, int64_t dflt) -> int64_t {
|
||||
int64_t v = 0;
|
||||
return g.get_i64(a + "." + suffix, &v) ? v : dflt;
|
||||
@@ -353,6 +354,36 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
std::vector<std::string> toks;
|
||||
if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size();
|
||||
if (m.n_vocab == 0) m.n_vocab = gi("vocab_size", 0);
|
||||
if (a == "hy_v3") {
|
||||
/* GGUF keeps reserved vocabulary rows beyond the tokenizer string array. The model matrices
|
||||
* are authoritative for the row count (Hy-Memory has 120832 rows and 120818 strings). */
|
||||
const GgufTensor* emb = g.tensor("token_embd.weight");
|
||||
if (emb && emb->n_dims >= 2) m.n_vocab = emb->ne[1];
|
||||
|
||||
int64_t gating = 0, norm = 0;
|
||||
double route_scale = 1.0;
|
||||
g.get_i64("hy_v3.expert_gating_func", &gating);
|
||||
g.get_i64("hy_v3.expert_weights_norm", &norm);
|
||||
g.get_f64("hy_v3.expert_weights_scale", &route_scale);
|
||||
const int64_t expert_width = gi("expert_feed_forward_length", 0);
|
||||
const int64_t shared_width = gi("expert_shared_feed_forward_length", 0);
|
||||
out->kv("qk_norm", g.tensor("blk.0.attn_q_norm.weight") &&
|
||||
g.tensor("blk.0.attn_k_norm.weight") ? "1" : "0");
|
||||
out->kv("moe_router_use_sigmoid", gating == 2 ? "1" : "0");
|
||||
out->kv("moe_router_enable_expert_bias", g.tensor("blk.1.exp_probs_b") ? "1" : "0");
|
||||
out->kv("enable_moe_fp32_combine", shared_width > 0 ? "1" : "0");
|
||||
out->kv("route_norm", norm ? "1" : "0");
|
||||
out->kv("router_scaling_factor", fmt("%.17g", route_scale));
|
||||
out->kv("first_k_dense_replace", g.tensor("blk.0.ffn_gate.weight") &&
|
||||
g.tensor("blk.1.ffn_gate_inp.weight") ? "1" : "0");
|
||||
out->kv("num_shared_experts", shared_width > 0 ? "1" : "0");
|
||||
out->kv("expert_hidden_dim", fmt("%lld", (long long)expert_width));
|
||||
out->kv("moe_intermediate_size", fmt("%lld", (long long)(2 * expert_width)));
|
||||
out->kv("num_experts", fmt("%lld", (long long)m.n_expert));
|
||||
out->kv("num_experts_per_tok", fmt("%lld", (long long)m.n_expert_used));
|
||||
out->kv("attention_bias", "0");
|
||||
out->kv("mlp_bias", "0");
|
||||
}
|
||||
|
||||
/* Everything else, stringified, for the plugin. Arrays are summarised (small integer arrays
|
||||
* spelled out); tokenizer keys are skipped, since the vocab has its own section. */
|
||||
@@ -859,6 +890,33 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
RAD_TRY(add_companions());
|
||||
RAD_TRY(add_torch_files());
|
||||
}
|
||||
/* HYV3's FP8 release indexes its static per-layer K/V cache descales as scalar F32 tensors in
|
||||
* kv_cache_scales.safetensors. They are runtime attention parameters, not model weights; carry
|
||||
* them through metadata so the architecture can bake them into kv_store and descale operands. */
|
||||
if (meta_.arch == "hyv3") {
|
||||
for (int64_t l = 0; l < meta_.m.n_layers; ++l) {
|
||||
for (const char* which : {"k", "v"}) {
|
||||
const std::string source = "model.layers." + std::to_string(l) +
|
||||
".self_attn." + which + "_cache.scale";
|
||||
const SrcTensor* t = find(source);
|
||||
if (!t) continue;
|
||||
if (t->rad_dtype != RAD_F32 || !t->data || t->bytes < 4 ||
|
||||
(!t->shape.empty() && t->numel() != 1)) {
|
||||
RAD_ERR("%s: HYV3 KV cache scale must be a scalar F32", source.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
float scale = 0.0f;
|
||||
std::memcpy(&scale, t->data, sizeof scale);
|
||||
if (!std::isfinite(scale) || scale <= 0.0f) {
|
||||
RAD_ERR("%s: HYV3 KV cache scale must be positive and finite", source.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
char value[32];
|
||||
std::snprintf(value, sizeof value, "%.9g", (double)scale);
|
||||
meta_.set("hyv3.kv_cache." + std::to_string(l) + "." + which + "_scale", value);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* FP8's block, where the checkpoint states one. */
|
||||
if (const char* bs = meta_.get("quantization_config.weight_block_size")) {
|
||||
long long r = 0, c = 0;
|
||||
@@ -2302,9 +2360,9 @@ namespace {
|
||||
/* ---------------------------------------------------------------- GGUF block types
|
||||
*
|
||||
* ggml block types decodable to f32. Their geometry lives in core/text; decoding lives here, where
|
||||
* weights are read. K-quants are refused rather than half-implemented. */
|
||||
* weights are read. Q4_K and Q6_K are the K-quants this HYV3 GGUF adapter needs. */
|
||||
enum { GGML_F32 = 0, GGML_F16 = 1, GGML_Q4_0 = 2, GGML_Q4_1 = 3, GGML_Q5_0 = 6, GGML_Q5_1 = 7,
|
||||
GGML_Q8_0 = 8, GGML_BF16 = 30 };
|
||||
GGML_Q8_0 = 8, GGML_Q4_K = 12, GGML_Q6_K = 14, GGML_BF16 = 30 };
|
||||
|
||||
int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
|
||||
auto half = [&](const uint8_t* q) { uint16_t h; std::memcpy(&h, q, 2); return rad_f16_to_f32(h); };
|
||||
@@ -2357,6 +2415,45 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
case GGML_Q4_K:
|
||||
for (int64_t b = 0; b < n / 256; ++b, p += 144) {
|
||||
const float d = half(p), dmin = half(p + 2);
|
||||
const uint8_t* scales = p + 4;
|
||||
const uint8_t* qs = p + 16;
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
uint32_t sc, mn;
|
||||
if (j < 4) {
|
||||
sc = scales[j] & 63u;
|
||||
mn = scales[j + 4] & 63u;
|
||||
} else {
|
||||
sc = (scales[j + 4] & 15u) | ((uint32_t)(scales[j - 4] >> 6) << 4);
|
||||
mn = (scales[j + 4] >> 4) | ((uint32_t)(scales[j] >> 6) << 4);
|
||||
}
|
||||
const float ds = d * (float)sc, ms = dmin * (float)mn;
|
||||
for (int l = 0; l < 32; ++l) {
|
||||
const int v = j * 32 + l;
|
||||
const uint8_t q = qs[32 * (v / 64) + v % 32];
|
||||
const int code = (v % 64) < 32 ? q & 15 : q >> 4;
|
||||
dst[b * 256 + v] = ds * (float)code - ms;
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
case GGML_Q6_K:
|
||||
for (int64_t b = 0; b < n / 256; ++b, p += 210) {
|
||||
const uint8_t* ql = p;
|
||||
const uint8_t* qh = p + 128;
|
||||
const int8_t* scales = (const int8_t*)(p + 192);
|
||||
const float d = half(p + 208);
|
||||
for (int k = 0; k < 256; ++k) {
|
||||
const int n128 = k / 128, t = (k % 128) / 32, l = k % 32;
|
||||
const uint8_t lo = ql[64 * n128 + l + 32 * (t & 1)];
|
||||
const int code = (int)((t < 2 ? lo & 15 : lo >> 4) |
|
||||
(((qh[32 * n128 + l] >> (2 * t)) & 3) << 4));
|
||||
dst[b * 256 + k] = d * (float)scales[k / 16] * (float)(code - 32);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
default:
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
+4
-3
@@ -119,10 +119,11 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>&
|
||||
kv_ = kv;
|
||||
ranks_ = ranks;
|
||||
table_ = DiscreteTable{};
|
||||
if (decl_.cond_opts & ~(uint32_t)RAD_GEN_COND_REBALANCE) {
|
||||
if (decl_.cond_opts & ~(uint32_t)(RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET)) {
|
||||
RAD_ERR("image generator: '%s' declares conditioning options 0x%x, and this engine knows "
|
||||
"only RAD_GEN_COND_REBALANCE (0x%x)", decl_.name ? decl_.name : "",
|
||||
(unsigned)decl_.cond_opts, (unsigned)RAD_GEN_COND_REBALANCE);
|
||||
"only RAD_GEN_COND_REBALANCE (0x%x) and its preset (0x%x)",
|
||||
decl_.name ? decl_.name : "", (unsigned)decl_.cond_opts, (unsigned)RAD_GEN_COND_REBALANCE,
|
||||
(unsigned)RAD_GEN_COND_REBALANCE_PRESET);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (discrete()) {
|
||||
|
||||
+25
-7
@@ -65,7 +65,7 @@ struct ImgReq {
|
||||
std::string background = "auto", format = "png", quality = "auto";
|
||||
int32_t compression = -1;
|
||||
bool stream = false;
|
||||
bool rebalance = false;
|
||||
int32_t rebalance = 0; /* RadGenBatch::cond_opts: RAD_GEN_COND_REBALANCE and its preset */
|
||||
std::vector<mm::FrameRGBA> images;
|
||||
bool has_mask = false;
|
||||
mm::FrameRGBA mask;
|
||||
@@ -397,15 +397,33 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
r.seed = (uint64_t)body["seed"].get<int64_t>();
|
||||
r.seed_given = body["seed"].is_number_unsigned() || body["seed"].get<int64_t>() != -1;
|
||||
}
|
||||
/* The conditioning at the plugin's fixed rebalance gains (Krea 2: its text taps at
|
||||
* ConditioningKrea2Rebalance's defaults). `false` is accepted everywhere. */
|
||||
/* The conditioning at the plugin's fixed rebalance gains (Krea 2: its text taps). true or
|
||||
* "legacy" ConditioningKrea2Rebalance's defaults; "balanced", "detail", "subtle" the
|
||||
* comfyui-krea2-conditioning presets at the taps' RMS, on a model that declares presets
|
||||
* (RAD_GEN_COND_REBALANCE_PRESET). `false` is accepted everywhere. */
|
||||
if (body.contains("rebalance") && !body["rebalance"].is_null()) {
|
||||
if (!body["rebalance"].is_boolean())
|
||||
return error_response(err_bad("rebalance", "expected true or false"), req.peer);
|
||||
r.rebalance = body["rebalance"].get<bool>();
|
||||
const json& rb = body["rebalance"];
|
||||
static const char* const kPresets[] = { "legacy", "balanced", "detail", "subtle" };
|
||||
bool ok = rb.is_boolean();
|
||||
if (ok) r.rebalance = rb.get<bool>() ? RAD_GEN_COND_REBALANCE : 0;
|
||||
else if (rb.is_string())
|
||||
for (int i = 0; i < 4; ++i)
|
||||
if (rb.get<std::string>() == kPresets[i]) {
|
||||
r.rebalance = RAD_GEN_COND_REBALANCE | (i << RAD_GEN_COND_REBALANCE_PRESET_SHIFT);
|
||||
ok = true;
|
||||
}
|
||||
if (!ok)
|
||||
return error_response(err_bad("rebalance", "expected true, false, \"legacy\", "
|
||||
"\"balanced\", \"detail\" or \"subtle\""),
|
||||
req.peer);
|
||||
if (r.rebalance && !(info.cond_opts & RAD_GEN_COND_REBALANCE))
|
||||
return error_response(err_unsupported("rebalance", "this model has no rebalance"),
|
||||
req.peer);
|
||||
if ((r.rebalance & RAD_GEN_COND_REBALANCE_PRESET) &&
|
||||
!(info.cond_opts & RAD_GEN_COND_REBALANCE_PRESET))
|
||||
return error_response(err_unsupported("rebalance", "this model's rebalance has no "
|
||||
"presets; use true"),
|
||||
req.peer);
|
||||
}
|
||||
if (str("negative_prompt", &r.negative) < 0)
|
||||
return error_response(err_bad("negative_prompt", "expected a string"), req.peer);
|
||||
@@ -539,7 +557,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
g->scheduler = r.scheduler;
|
||||
g->seed = r.seed;
|
||||
g->previews = r.previews;
|
||||
g->cond_opts = r.rebalance ? RAD_GEN_COND_REBALANCE : 0;
|
||||
g->cond_opts = r.rebalance;
|
||||
/* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is
|
||||
* that at s + 1. */
|
||||
g->cfg = (float)(info.cfg_original ? r.cfg + 1.0 : r.cfg);
|
||||
|
||||
+36
-8
@@ -173,15 +173,34 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
return reasoning_anywhere_check(f, why);
|
||||
}
|
||||
|
||||
if (!f.section_open.empty() || !f.section_close.empty())
|
||||
return no("a section around all calls (section_open/section_close) is not read by the "
|
||||
"streaming parser");
|
||||
if (f.section_open.empty() != f.section_close.empty())
|
||||
return no("section_open and section_close must be set together");
|
||||
if (!f.section_open.empty()) {
|
||||
const std::string so = trim_ws(f.section_open), sc = trim_ws(f.section_close);
|
||||
if (so.empty() || sc.empty()) return no("section_open/section_close may not be whitespace");
|
||||
if (so != f.section_open || sc != f.section_close)
|
||||
return no("section_open/section_close must not have surrounding whitespace");
|
||||
if (confusable(so, sc))
|
||||
return no("section_open " + show(so) + " and section_close " + show(sc) +
|
||||
" cannot be told apart");
|
||||
for (const std::string* d : { &f.reasoning_open, &f.reasoning_close, &f.call_open,
|
||||
&f.call_close, &f.name_prefix, &f.name_suffix,
|
||||
&f.call_end, &f.arg_prefix, &f.arg_name_suffix,
|
||||
&f.arg_value_prefix, &f.arg_value_suffix }) {
|
||||
if (!d->empty() && confusable(so, trim_ws(*d)))
|
||||
return no("section_open " + show(so) + " overlaps delimiter " + show(*d));
|
||||
if (!d->empty() && confusable(sc, trim_ws(*d)))
|
||||
return no("section_close " + show(sc) + " overlaps delimiter " + show(*d));
|
||||
}
|
||||
}
|
||||
if (!f.call_separator.empty())
|
||||
return no("a separator between calls (call_separator " + show(f.call_separator) +
|
||||
") is not read by the streaming parser; tagged calls separate on whitespace");
|
||||
if (f.call_open.empty() && !f.call_close.empty())
|
||||
return no("call_close without call_open");
|
||||
const bool object = f.object_args();
|
||||
if (object && !f.section_open.empty())
|
||||
return no("section-wrapped object arguments are not supported");
|
||||
/* Without a suffix the name ends at what follows it: the object's `{`, or a tagged call's
|
||||
* first argument or close. */
|
||||
if (!f.name_suffix.empty()) {
|
||||
@@ -238,9 +257,10 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
show(f.name_prefix) + " cannot be told apart");
|
||||
}
|
||||
const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open;
|
||||
const std::string section_opener = trim_ws(f.section_open);
|
||||
for (const std::string& b : f.reasoning_breaks)
|
||||
if (b != opener)
|
||||
return no("reasoning break " + show(b) + " is not the call opener " + show(opener));
|
||||
if (b != opener && (section_opener.empty() || b != section_opener))
|
||||
return no("reasoning break " + show(b) + " is not a call or section opener");
|
||||
if (!f.reasoning_breaks.empty() && !f.has_reasoning())
|
||||
return no("reasoning_breaks without a reasoning block");
|
||||
for (const std::string& t : f.triggers)
|
||||
@@ -432,6 +452,8 @@ std::string chat_format_describe(const ChatFormat& f) {
|
||||
(f.reasoning_anywhere ? " anywhere" : "");
|
||||
else
|
||||
s += " no reasoning";
|
||||
if (f.has_tools() && !f.section_open.empty())
|
||||
s += "; section " + show(f.section_open) + ".." + show(f.section_close);
|
||||
if (f.has_tools() && f.object_args()) {
|
||||
s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) +
|
||||
" {OBJECT";
|
||||
@@ -912,11 +934,17 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
? seq({ wrapped, rep(seq({ space(), wrapped }), 0, -1), space() })
|
||||
: seq({ wrapped, space() });
|
||||
} else {
|
||||
G next = seq({ space(), opt(wrap(leaf(until_pattern({ opener })))), choice });
|
||||
/* Section-wrapped dialects contain only calls and whitespace. In particular,
|
||||
* inter-call prose must not consume a section close and admit later calls. */
|
||||
G next = f.section_open.empty()
|
||||
? seq({ space(), opt(wrap(leaf(until_pattern({ opener })))), choice })
|
||||
: seq({ space(), choice });
|
||||
calls = req.parallel_tool_calls
|
||||
? seq({ lit(""), space(), choice, rep(next, 0, -1), space(), lit("") })
|
||||
: seq({ lit(""), space(), choice, space(), lit("") });
|
||||
? seq({ choice, rep(next, 0, -1), space() })
|
||||
: seq({ choice, space() });
|
||||
}
|
||||
if (!f.section_open.empty())
|
||||
calls = seq({ lit(f.section_open), space(), calls, space(), lit(f.section_close) });
|
||||
b.add_rule("tool-call", render(calls));
|
||||
if (req.require_call) {
|
||||
/* Nothing after the calls: a complete grammar admits only the end of the turn,
|
||||
|
||||
+1
-1
@@ -104,7 +104,7 @@ struct ChatFormat {
|
||||
/* ------------------------------------------------------------------ tool calls
|
||||
* `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the
|
||||
* format has no tool calls. */
|
||||
std::string section_open, section_close; /* around all calls; not read yet, must be empty */
|
||||
std::string section_open, section_close; /* around the complete list of calls */
|
||||
/* Between two calls, beyond whitespace (a JSON-array format would use ", "). Tagged calls are
|
||||
* self-delimiting. Not read yet, must be empty. */
|
||||
std::string call_separator;
|
||||
|
||||
+124
-20
@@ -720,12 +720,15 @@ struct ReplyFormat::Impl {
|
||||
ChatFormat f;
|
||||
/* Each tag split into its core and the whitespace around it that is optional to match. */
|
||||
std::string open_core, open_trail, close_core, close_trail, ns_core, ns_trail, end_core,
|
||||
end_trail, co_core, co_trail;
|
||||
end_trail, co_core, co_trail, section_open_core, section_close_core;
|
||||
/* What begins a call in content. First the format's own opener: call_open's core, or
|
||||
* name_prefix when calls are not wrapped. A wrapped format also takes name_prefix alone,
|
||||
* second, since models often write a call without its wrapper; a wrapper written without
|
||||
* its trailing whitespace is read too. */
|
||||
std::vector<std::string> openers;
|
||||
std::vector<std::string> openers, text_markers;
|
||||
size_t section_open_hit = (size_t)-1, section_close_hit = (size_t)-1;
|
||||
size_t think_open_hit = (size_t)-1, think_close_hit = (size_t)-1;
|
||||
size_t body_section_close_hit = (size_t)-1;
|
||||
/* What ends an argument name: arg_name_suffix and arg_value_prefix, back to back. */
|
||||
std::string name_end;
|
||||
/* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so it was
|
||||
@@ -792,6 +795,16 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
split_ws(f.call_open, &m.co_core, &m.co_trail);
|
||||
if (f.call_open.empty()) m.openers = { f.name_prefix };
|
||||
else m.openers = { m.co_core, f.name_prefix };
|
||||
m.text_markers = m.openers;
|
||||
if (!f.section_open.empty()) {
|
||||
std::string section_trail;
|
||||
split_ws(f.section_open, &m.section_open_core, §ion_trail);
|
||||
split_ws(f.section_close, &m.section_close_core, §ion_trail);
|
||||
m.section_open_hit = m.text_markers.size();
|
||||
m.text_markers.push_back(m.section_open_core);
|
||||
m.section_close_hit = m.text_markers.size();
|
||||
m.text_markers.push_back(m.section_close_core);
|
||||
}
|
||||
m.name_end = f.arg_name_suffix + f.arg_value_prefix;
|
||||
m.object = f.has_tools() && f.object_args();
|
||||
m.name_open = f.has_tools() && !m.object && f.name_suffix.empty();
|
||||
@@ -808,15 +821,16 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
m.think_breaks.build(b);
|
||||
}
|
||||
if (f.reasoning_anywhere && f.has_reasoning()) {
|
||||
std::vector<std::string> t;
|
||||
if (f.has_tools()) t = m.openers;
|
||||
std::vector<std::string> t = m.text_markers;
|
||||
m.think_open_hit = t.size();
|
||||
t.push_back(m.open_core);
|
||||
m.think_close_hit = t.size();
|
||||
t.push_back(m.close_core);
|
||||
m.text_think.build(t);
|
||||
m.think_only.build({ m.open_core, m.close_core });
|
||||
}
|
||||
if (m.object) {
|
||||
m.text.build(m.openers);
|
||||
m.text.build(m.text_markers);
|
||||
std::string trail;
|
||||
split_ws(f.call_close, &m.cc_core, &trail);
|
||||
std::vector<std::string> bare{ ",", "}", "]" }, key{ ":", ",", "}" };
|
||||
@@ -851,7 +865,7 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
m.obj_bare.build(bare);
|
||||
m.obj_key.build(key);
|
||||
} else if (f.has_tools()) {
|
||||
m.text.build(m.openers);
|
||||
m.text.build(m.text_markers);
|
||||
m.arg_name.build({ m.name_end });
|
||||
m.value.build({ f.arg_value_suffix });
|
||||
std::string trail;
|
||||
@@ -864,11 +878,17 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
return a.find(b) == std::string::npos && b.find(a) == std::string::npos;
|
||||
};
|
||||
if (!apart(m.cc_core, f.arg_prefix) || !apart(m.cc_core, m.end_core)) m.cc_core.clear();
|
||||
if (m.cc_core.empty()) m.junk.build({ f.arg_prefix, m.end_core });
|
||||
else m.junk.build({ f.arg_prefix, m.end_core, m.cc_core });
|
||||
std::vector<std::string> junk{ f.arg_prefix, m.end_core };
|
||||
if (!m.cc_core.empty()) junk.push_back(m.cc_core);
|
||||
if (!m.section_close_core.empty()) {
|
||||
m.body_section_close_hit = junk.size();
|
||||
junk.push_back(m.section_close_core);
|
||||
}
|
||||
m.junk.build(junk);
|
||||
}
|
||||
const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open,
|
||||
&f.call_close, &f.name_prefix, &f.name_suffix,
|
||||
const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.section_open,
|
||||
&f.section_close, &f.call_open, &f.call_close,
|
||||
&f.name_prefix, &f.name_suffix,
|
||||
&f.call_end, &f.arg_prefix, &m.name_end,
|
||||
&f.arg_value_suffix, &f.object_string_open,
|
||||
&f.object_string_close };
|
||||
@@ -1139,6 +1159,11 @@ struct ReplyStream::Impl {
|
||||
St st;
|
||||
bool strict = true, finished = false, fed_tail = false;
|
||||
bool post_call = false; /* content after a call */
|
||||
bool section_active = false;
|
||||
size_t section_calls_at_open = 0;
|
||||
/* The last completed inner call is not executable until another call starts or the outer
|
||||
* section closes. Deferring CallEnd keeps truncation consistent with the one-shot parse. */
|
||||
size_t pending_section_call = (size_t)-1;
|
||||
|
||||
/* delimiter scan */
|
||||
uint16_t ds = 0;
|
||||
@@ -1413,6 +1438,40 @@ struct ReplyStream::Impl {
|
||||
return p + 1;
|
||||
}
|
||||
|
||||
void complete_section_call() {
|
||||
if (pending_section_call == (size_t)-1) return;
|
||||
msg.calls[pending_section_call].closed = true;
|
||||
event(ReplyEvent::CallEnd, (uint32_t)pending_section_call, {});
|
||||
pending_section_call = (size_t)-1;
|
||||
}
|
||||
|
||||
void open_section() {
|
||||
if (section_active) { lenient(); return; }
|
||||
section_active = true;
|
||||
section_calls_at_open = calls;
|
||||
}
|
||||
|
||||
void close_section() {
|
||||
if (!section_active) { lenient(); return; }
|
||||
if (calls == section_calls_at_open) lenient();
|
||||
complete_section_call();
|
||||
section_active = false;
|
||||
}
|
||||
|
||||
/* A section close before call_end leaves the last call incomplete: it must never be exposed
|
||||
* as an executable tool call. Keep its bytes available to content_with_open_call(). */
|
||||
void abandon_call_at_section_close() {
|
||||
lenient();
|
||||
if (cur == 2) publish(2, true);
|
||||
cur = -1;
|
||||
section_active = false;
|
||||
post_call = false;
|
||||
ds = 0;
|
||||
hold.clear();
|
||||
lhold.clear();
|
||||
st = St::Text;
|
||||
}
|
||||
|
||||
/* The call opener has matched at `att`; whether a call follows is decided below. */
|
||||
void begin_attempt(St from) {
|
||||
origin = from;
|
||||
@@ -1472,6 +1531,7 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
|
||||
void begin_call(bool exact) {
|
||||
complete_section_call();
|
||||
if (!exact || tool < 0) lenient();
|
||||
if (!P.opt.parallel_tool_calls && calls > 0) lenient();
|
||||
if (cur >= 0) publish(cur, false);
|
||||
@@ -1810,8 +1870,12 @@ struct ReplyStream::Impl {
|
||||
args_out(close);
|
||||
}
|
||||
publish(2, true);
|
||||
msg.calls.back().closed = true;
|
||||
event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {});
|
||||
if (section_active) {
|
||||
pending_section_call = msg.calls.size() - 1;
|
||||
} else {
|
||||
msg.calls.back().closed = true;
|
||||
event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {});
|
||||
}
|
||||
cur = -1;
|
||||
lpos = 0;
|
||||
lhold.clear();
|
||||
@@ -1984,9 +2048,19 @@ struct ReplyStream::Impl {
|
||||
p = scan(d, p, e, &hit, [this](const char* q, size_t n) { think_out(q, n); });
|
||||
if (hit == 0) { trail = 0; st = St::ThinkCloseWs; }
|
||||
else if (hit > 0) {
|
||||
att = d.pattern(hit);
|
||||
att_at = here(p) - att.size();
|
||||
begin_attempt(St::Think);
|
||||
const std::string& marker = d.pattern(hit);
|
||||
if (!F.section_open_core.empty() && marker == F.section_open_core) {
|
||||
open_section();
|
||||
st = St::Text;
|
||||
} else if (!F.section_open_core.empty() && !section_active) {
|
||||
/* A call-looking tag cannot bypass the required outer section, including
|
||||
* when it appears in an unclosed reasoning block. */
|
||||
think_out(marker.data(), marker.size());
|
||||
} else {
|
||||
att = marker;
|
||||
att_at = here(p) - att.size();
|
||||
begin_attempt(St::Think);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
@@ -2004,14 +2078,35 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
p = scan(*text_dfa, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit < 0) return p;
|
||||
if (P.anywhere && !P.calls) {
|
||||
if (hit == 0) { trail = 0; st = St::ThinkOpenWs; }
|
||||
else lenient(); /* A reasoning close with no block open. */
|
||||
return p;
|
||||
}
|
||||
if ((size_t)hit < n_open) {
|
||||
att_at = here(p) - F.openers[(size_t)hit].size();
|
||||
begin_text_attempt(hit);
|
||||
} else if ((size_t)hit == n_open) {
|
||||
if (!F.section_open_core.empty() && !section_active) {
|
||||
/* The call-looking tag is ordinary content outside the required wrapper. */
|
||||
const std::string& marker = F.text_markers[(size_t)hit];
|
||||
text_out(marker.data(), marker.size());
|
||||
} else {
|
||||
att_at = here(p) - F.openers[(size_t)hit].size();
|
||||
begin_text_attempt(hit);
|
||||
}
|
||||
} else if ((size_t)hit == F.section_open_hit) {
|
||||
open_section();
|
||||
} else if ((size_t)hit == F.section_close_hit) {
|
||||
if (!section_active) {
|
||||
lenient();
|
||||
const std::string& marker = F.text_markers[(size_t)hit];
|
||||
text_out(marker.data(), marker.size());
|
||||
} else {
|
||||
close_section();
|
||||
}
|
||||
} else if ((size_t)hit == F.think_open_hit) {
|
||||
/* A reasoning block opens again, later in the reply. */
|
||||
trail = 0;
|
||||
st = St::ThinkOpenWs;
|
||||
} else {
|
||||
} else if ((size_t)hit == F.think_close_hit) {
|
||||
/* Its close with no block open: not part of the answer. */
|
||||
lenient();
|
||||
}
|
||||
@@ -2153,10 +2248,12 @@ struct ReplyStream::Impl {
|
||||
const std::string& ap = F.f.arg_prefix;
|
||||
const std::string& fc = F.end_core;
|
||||
const std::string& cc = F.cc_core;
|
||||
const std::string& sc = F.section_close_core;
|
||||
const bool a_ok = extends(ap, c);
|
||||
const bool f_ok = extends(fc, c);
|
||||
const bool c_ok = wrapped && extends(cc, c);
|
||||
if (!a_ok && !f_ok && !c_ok) {
|
||||
const bool s_ok = !sc.empty() && extends(sc, c);
|
||||
if (!a_ok && !f_ok && !c_ok && !s_ok) {
|
||||
lenient();
|
||||
st = St::Junk;
|
||||
ds = 0;
|
||||
@@ -2171,6 +2268,7 @@ struct ReplyStream::Impl {
|
||||
if (a_ok && lpos == ap.size()) { start_arg(); return p + 1; }
|
||||
if (f_ok && lpos == fc.size()) { finish_call_strictness(); end_core_done(); return p + 1; }
|
||||
if (c_ok && lpos == cc.size()) { end_call_at_close(); return p + 1; }
|
||||
if (s_ok && lpos == sc.size()) { abandon_call_at_section_close(); return p + 1; }
|
||||
return p + 1;
|
||||
}
|
||||
|
||||
@@ -2251,6 +2349,8 @@ struct ReplyStream::Impl {
|
||||
p = scan(F.junk, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit == 0) start_arg();
|
||||
else if (hit == 1) end_core_done();
|
||||
else if (hit >= 0 && (size_t)hit == F.body_section_close_hit)
|
||||
abandon_call_at_section_close();
|
||||
else if (hit == 2 && wrapped) end_call_at_close();
|
||||
else if (hit == 2) text_out(F.cc_core.data(), F.cc_core.size());
|
||||
return p;
|
||||
@@ -2804,6 +2904,10 @@ struct ReplyStream::Impl {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (section_active) {
|
||||
lenient();
|
||||
section_active = false;
|
||||
}
|
||||
hold.clear();
|
||||
ds = 0;
|
||||
if (!think_text) think_pend.clear();
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# HYV3 from the BF16 checkpoint, with attention, dense/shared projections and routed experts rounded
|
||||
# to block FP8. F32 scale planes are intentional: MoeFP8 format 9 consumes a 128x128 grid with
|
||||
# F32 scales. Activations are dynamically quantized to E4M3 at runtime; the BF16 output head, router,
|
||||
# norms and embeddings stay as stored.
|
||||
#
|
||||
# rad-convert <Hy-Memory-30B-A3B-BF16> \
|
||||
# --recipe data/recipes/hy-memory-30b-a3b-bf16-fp8.recipe -o hy-memory-30b-a3b-fp8.rad
|
||||
|
||||
blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=f32
|
||||
blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=f32
|
||||
blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=f32
|
||||
blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=f32
|
||||
|
||||
blk.0.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=f32
|
||||
blk.0.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=f32
|
||||
blk.*.ffn_gate_up_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=f32
|
||||
blk.*.ffn_down_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=f32
|
||||
|
||||
blk.*.ffn_*_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=f32
|
||||
@@ -0,0 +1,18 @@
|
||||
# HYV3 from BF16 with OCP MXFP4 weights: e2m1 codes and one e8m0 scale per 32 values of K. Quantize
|
||||
# attention, dense/shared projections and routed experts; router, norms, embeddings and output head
|
||||
# stay BF16. Both the regular linears and MoeFP8's expert format-8 path consume this encoding.
|
||||
#
|
||||
# rad-convert <Hy-Memory-30B-A3B-BF16> \
|
||||
# --recipe data/recipes/hy-memory-30b-a3b-bf16-mxfp4.recipe -o hy-memory-30b-a3b-mxfp4.rad
|
||||
|
||||
blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
|
||||
blk.0.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
blk.0.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
blk.*.ffn_gate_up_shexp.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
blk.*.ffn_down_shexp.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
|
||||
blk.*.ffn_*_exps.*.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
@@ -0,0 +1,22 @@
|
||||
# Hy-Memory-30B-A3B from Tencent's BF16 safetensors checkpoint. Quantize attention projections,
|
||||
# the dense first MLP and routed experts to native INT4. Keep shared MLPs, routers, norms, embeddings
|
||||
# and the output head at BF16. Routed experts use signed INT4 with BF16 group scales; other linears
|
||||
# use asymmetric U4 with F16 scales and U8 zero points. The byte-sized zero points keep TP2 column
|
||||
# shards aligned even when a projection has an odd number of 128-value groups per rank.
|
||||
#
|
||||
# rad-convert <Hy-Memory-30B-A3B-BF16> \
|
||||
# --recipe data/recipes/hy-memory-30b-a3b-bf16-w4.recipe -o hy-memory-30b-a3b-w4.rad
|
||||
#
|
||||
# The W4 GEMMs consume dynamic INT8 activations. Routed/shared outputs are reduced independently at
|
||||
# TP2 then combined in FP32. Use --tp 2 at serve time if one device cannot hold the .rad weights and
|
||||
# KV cache.
|
||||
|
||||
blk.*.attn_q.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
blk.*.attn_k.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
blk.*.attn_v.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
blk.*.attn_output.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
|
||||
blk.0.ffn_gate_up.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
blk.0.ffn_down.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
|
||||
blk.*.ffn_*_exps.*.weight rtn codes=i4 group=128 scale=bf16
|
||||
@@ -0,0 +1,17 @@
|
||||
# HYV3 from BF16 with signed INT8 W8A8 linears. Attention, the dense first MLP, shared MLPs and
|
||||
# output head are quantized on the 128-value K grid. Routed experts stay BF16: the current MoE block
|
||||
# has no INT8 expert kernel, so this recipe does not pretend the expert weights are W8.
|
||||
#
|
||||
# rad-convert <Hy-Memory-30B-A3B-BF16> \
|
||||
# --recipe data/recipes/hy-memory-30b-a3b-bf16-w8.recipe -o hy-memory-30b-a3b-w8.rad
|
||||
|
||||
blk.*.attn_q.weight rtn codes=i8 group=128 scale=bf16 clamp=sym
|
||||
blk.*.attn_k.weight rtn codes=i8 group=128 scale=bf16 clamp=sym
|
||||
blk.*.attn_v.weight rtn codes=i8 group=128 scale=bf16 clamp=sym
|
||||
blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym
|
||||
|
||||
blk.0.ffn_gate_up.weight rtn codes=i8 group=128 scale=bf16 clamp=sym
|
||||
blk.0.ffn_down.weight rtn codes=i8 group=128 scale=bf16 clamp=sym
|
||||
blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym
|
||||
blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym
|
||||
output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym
|
||||
@@ -0,0 +1,34 @@
|
||||
# hy-memory-30b-a3b-fp8.recipe -- Tencent's Hy-Memory-30B-A3B-FP8 release.
|
||||
#
|
||||
# rad-convert <Hy-Memory-30B-A3B-FP8 checkpoint directory> \
|
||||
# --recipe data/recipes/hy-memory-30b-a3b-fp8.recipe --kv-cache-dtype fp8 \
|
||||
# -o hy-memory-30b-a3b-fp8.rad
|
||||
#
|
||||
# The checkpoint stores E4M3 projection codes with one F32 weight scale per tensor. Import keeps
|
||||
# those codes and expands each scalar to the 128x128 F32 scale grid read by Radiance's FP8 GEMMs.
|
||||
# Runtime activation quantization is dynamic; source `.input_scale` calibration scalars are ignored.
|
||||
# The attention/MLP norms and router projection are widened to F32 (exact for BF16 source values),
|
||||
# as required by their RMSNorm and FP32 sigmoid-router kernels. Embeddings, lm_head, and the model's
|
||||
# BF16 activations remain BF16; expert correction biases are already F32.
|
||||
#
|
||||
# The indexed kv_cache_scales.safetensors tensors are carried into model metadata during import.
|
||||
# The plugin can use those per-layer K/V descales for an E4M3 KV cache (`--kv-cache-dtype fp8`),
|
||||
# or use a BF16 cache for higher precision.
|
||||
|
||||
blk.*.attn_q.weight import block=128x128 scale=f32
|
||||
blk.*.attn_k.weight import block=128x128 scale=f32
|
||||
blk.*.attn_v.weight import block=128x128 scale=f32
|
||||
blk.*.attn_output.weight import block=128x128 scale=f32
|
||||
blk.0.ffn_gate_up.weight import block=128x128 scale=f32
|
||||
blk.0.ffn_down.weight import block=128x128 scale=f32
|
||||
blk.*.ffn_gate_up_exps.*.weight import block=128x128 scale=f32
|
||||
blk.*.ffn_down_exps.*.weight import block=128x128 scale=f32
|
||||
blk.*.ffn_gate_up_shexp.weight import block=128x128 scale=f32
|
||||
blk.*.ffn_down_shexp.weight import block=128x128 scale=f32
|
||||
|
||||
blk.*.attn_norm.weight cast dtype=f32
|
||||
blk.*.attn_q_norm.weight cast dtype=f32
|
||||
blk.*.attn_k_norm.weight cast dtype=f32
|
||||
blk.*.ffn_norm.weight cast dtype=f32
|
||||
blk.*.glm_router.weight cast dtype=f32
|
||||
output_norm.weight cast dtype=f32
|
||||
@@ -0,0 +1,30 @@
|
||||
# Convert the local llama.cpp Hy-Memory Q4_K_M GGUF into native Radiance encodings. Q4_K/Q6_K
|
||||
# source blocks are decoded to f32, then the attention, dense-first MLP and routed experts are
|
||||
# requantized to Radiance W4; embeddings, output head, routers, norms and shared MLPs are cast to
|
||||
# BF16. This adds loss to an already-quantized source; for best quality, quantize the BF16
|
||||
# safetensors checkpoint with hy-memory-30b-a3b-bf16-w4.recipe instead.
|
||||
#
|
||||
# rad-convert Hy-Memory-30B-A3B-Q4_K_M.gguf \
|
||||
# --tokenizer <Hy-Memory-30B-A3B-BF16>/tokenizer.json \
|
||||
# --recipe data/recipes/hy-memory-30b-a3b-gguf-q4k-to-w4.recipe -o hy-memory-30b-a3b-gguf-w4.rad
|
||||
|
||||
# The model matrices have 120832 rows while the GGUF tokenizer lists 120818 strings.
|
||||
token_embd.weight cast dtype=bf16
|
||||
output.weight cast dtype=bf16
|
||||
|
||||
blk.*.attn_norm.weight cast dtype=bf16
|
||||
blk.*.attn_q_norm.weight cast dtype=bf16
|
||||
blk.*.attn_k_norm.weight cast dtype=bf16
|
||||
blk.*.ffn_norm.weight cast dtype=bf16
|
||||
blk.*.ffn_gate_up_shexp.weight cast dtype=bf16
|
||||
blk.*.ffn_down_shexp.weight cast dtype=bf16
|
||||
|
||||
blk.*.attn_q.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
blk.*.attn_k.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
blk.*.attn_v.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
blk.*.attn_output.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
|
||||
blk.0.ffn_gate_up.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
blk.0.ffn_down.weight rtn codes=u4 zero=u8 group=128 scale=f16
|
||||
|
||||
blk.*.ffn_*_exps.*.weight rtn codes=i4 group=128 scale=bf16
|
||||
@@ -11,6 +11,9 @@ plugin claims.
|
||||
| `arch/llama_dense_fp8` | `llama` | *(empty)* | the same graph from a bf16 checkpoint, linears made block fp8 by a recipe or kept bf16. MiniCPM5-2B |
|
||||
| `arch/qwen35_bf16` | `qwen35` | *(empty)* | the Qwen3.5/3.6/3.8 dense hybrid, served bf16 |
|
||||
| `arch/qwen35_fp8` | `qwen35` | `fp8_e4m3` | the same, block-scaled FP8 weights and activations |
|
||||
| `arch/hyv3_bf16` | `hyv3` | *(empty)* | Tencent Hy-Memory-30B-A3B BF16 safetensors; BF16, W4, W8A8, block-FP8 or MXFP4 weights by recipe; TP1/2, BF16 KV |
|
||||
| `arch/hyv3_fp8` | `hyv3` | `fp8` | Tencent Hy-Memory-30B-A3B-FP8; imported per-tensor E4M3 weights, one dense layer then sigmoid-routed MoE; TP1/2, BF16 or static-scaled E4M3 KV |
|
||||
| `arch/hyv3_gguf` | `hyv3` | `gguf_ftype_15` | llama.cpp Hy-Memory Q4_K_M GGUF, dequantized and recipe-converted to native Radiance weights; TP1/2 |
|
||||
| `arch/qwen35_w8a8` | `qwen35` | `w8a8_fwht128` | `qwen35_fp8` with an int8 trunk: i8 weights with a bf16 scale per 128 of K, rotated by a 128-wide Hadamard, against int8 activations under the same rotation (`data/recipes/q38-27b-w8a8-df2.recipe`) |
|
||||
| `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed |
|
||||
| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert |
|
||||
@@ -286,6 +289,57 @@ head (393 against 282 tok/s on two R9700s). `sage-a1.5-mxfp4-df2.rad` is the sam
|
||||
the experts and the drafter's linears at MXFP4. `--num-speculative-tokens auto` takes the depth the
|
||||
drafter states.
|
||||
|
||||
## `hyv3`
|
||||
|
||||
`arch/hyv3_bf16` supports the Tencent BF16 safetensors checkpoint, and `arch/hyv3_fp8` supports
|
||||
Tencent's FP8 checkpoint. Both use the same graph: 48 layers, with a dense first
|
||||
MLP followed by 47 layers routing top-8 of 128 experts. The routed and shared MLP widths are both
|
||||
768 in the checkpoint tensors. Attention applies per-head Q/K RMSNorm before NeoX RoPE. Routing selects
|
||||
with sigmoid scores plus the correction bias, but normalizes the selected unbiased scores and
|
||||
multiplies them by 2.826. Routed and shared BF16 outputs are reduced independently at TP2, then added
|
||||
in FP32 and rounded once to BF16 before the residual add.
|
||||
|
||||
Convert the public FP8 checkpoint with
|
||||
`data/recipes/hy-memory-30b-a3b-fp8.recipe`; it preserves the E4M3 codes and expands the checkpoint's
|
||||
scalar F32 scales to the 128x128 F32 scale planes the GEMMs read. Norms and the router projection
|
||||
are widened to F32. Linear activations use Radiance's dynamic FP8 quantization; the checkpoint's
|
||||
static `.input_scale` calibration scalars are ignored, so numerical parity with vendor quantization
|
||||
is not established. The checkpoint index includes scalar per-layer K/V descales from
|
||||
`kv_cache_scales.safetensors`; conversion carries them into metadata for `kv_store` and paged
|
||||
attention. Use `--kv-cache-dtype fp8` for the checkpoint's static-scaled E4M3 cache, or `bf16` for a
|
||||
higher-precision cache. The plugin refuses the unrelated `fp8_v4` and `k6_v4` cache layouts.
|
||||
The vendor FP8-source import and static-scaled FP8 KV path have structural/unit coverage only;
|
||||
an end-to-end conversion and serving run of Tencent's FP8 checkpoint is not yet validated.
|
||||
This is distinct from the BF16-derived block-FP8 artifact tested below.
|
||||
|
||||
The BF16 checkpoint can be converted without quantizing any weights, or with
|
||||
`data/recipes/hy-memory-30b-a3b-bf16-w4.recipe`, which quantizes attention projections, the first
|
||||
dense MLP and routed experts to INT4. Shared MLPs, router, norms, embeddings and the output head stay
|
||||
BF16. The asymmetric linear W4A8 and signed expert W4A8 kernels use dynamic INT8 activations.
|
||||
BF16-source block-FP8 and MXFP4 recipes quantize experts and regular linears; the W8 recipe quantizes
|
||||
regular linears and the output head while routed experts remain BF16. Use TP2 at serve time if one
|
||||
device cannot hold the model and cache.
|
||||
|
||||
The local llama.cpp Q4_K_M source is supported by `arch/hyv3_gguf` and
|
||||
`data/recipes/hy-memory-30b-a3b-gguf-q4k-to-w4.recipe`. It decodes Q4_K/Q6_K source tensors and
|
||||
re-quantizes them to native Radiance encodings; this adds loss to an already-quantized checkpoint.
|
||||
The GGUF's `hunyuan-dense` pre-tokenizer name is not in Radiance's tokenizer table, so pass the
|
||||
matching BF16 repository's `tokenizer.json` with `--tokenizer`. Prefer the BF16 source recipe when
|
||||
available. Both the BF16 W4 and GGUF-to-W4 artifacts passed a short TP2 generation smoke test; the
|
||||
BF16-source W8, block-FP8 and MXFP4 variants did too. These checks establish basic loading and
|
||||
inference only, not numerical parity or broad quality.
|
||||
|
||||
The plugins declare the native OpenAI tool-call format: an outer `<tool_calls>` section,
|
||||
`<tool_call>NAME<tool_sep>` calls, and tagged `<arg_key>`/`<arg_value>` arguments. The parser and
|
||||
grammar preserve that section in non-streaming and streaming responses and accept replayed
|
||||
OpenAI tool results through the checkpoint's chat template. When `reasoning_effort` is `low` or
|
||||
`high`, the template opens `<think>` in the generation prompt and the parser returns that block
|
||||
as reasoning rather than answer text. The default template effort is `no_think`.
|
||||
|
||||
Architecture tests cover geometry, GGUF tensor maps, dense-to-MoE scheduling, TP1/TP2 graph lint,
|
||||
and FP32 combine order; checkpoint tests cover Q4_K/Q6_K block decoding. Numerical parity against Tencent/llama.cpp
|
||||
remains untested.
|
||||
|
||||
## `qwen35_w8a8`
|
||||
|
||||
The dense build again, behind `#if QWEN35_W8A8`, for a container `data/recipes/q38-27b-w8a8-df2.recipe`
|
||||
|
||||
+4
-1
@@ -273,6 +273,9 @@ and runs.
|
||||
| `qwen35_fp8` | the same, block-scaled fp8 |
|
||||
| `qwen35_w8a8` | the same, an int8 trunk rotated by a 128-wide Hadamard |
|
||||
| `qwen35moe_fp8` | Qwen3.5 / 3.6 MoE (35B-A3B), 256 experts, 8 a token |
|
||||
| `hyv3_bf16` | Tencent Hy-Memory-30B-A3B BF16 checkpoint; BF16, W4, W8A8, block-FP8 and MXFP4 recipes, TP1/2 |
|
||||
| `hyv3_fp8` | Tencent Hy-Memory-30B-A3B FP8 checkpoint: imported FP8 weights, dense-first MoE, TP1/2, BF16 or static-scaled E4M3 KV |
|
||||
| `hyv3_gguf` | llama.cpp Hy-Memory Q4_K_M input converted via `hy-memory-30b-a3b-gguf-q4k-to-w4.recipe`; requires `--tokenizer <BF16-checkpoint>/tokenizer.json` |
|
||||
| `qwen4exp_fp8` | Qwen4-Exp / Qwen3.8-Flash-Next: hybrid Gated DeltaNet + gated attention, 512 experts |
|
||||
| `gemma4` | Gemma 4 text decoders (26B-A4B MoE and the dense members): bf16 trunk, routed experts bf16 or block fp8, and the DFlash drafter |
|
||||
| `gemma4_bf16` | Gemma 4 dense in bf16, with its vision tower |
|
||||
@@ -2385,7 +2388,7 @@ more field:
|
||||
|
||||
| field | |
|
||||
|---|---|
|
||||
| `rebalance` | `true` multiplies the twelve text taps by fixed gains before the text fusion, as ComfyUI's ConditioningKrea2Rebalance at its defaults (multiplier 4 times 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1); it applies to the negative prompt's conditioning too. `false` (the default) is the plain model. A boolean, or `true`/`false`/`1`/`0` in a form; a model without it refuses `true` with a 400 |
|
||||
| `rebalance` | `true` (or `"legacy"`) multiplies the twelve text taps by fixed gains before the text fusion, as ComfyUI's ConditioningKrea2Rebalance at its defaults (multiplier 4 times 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1), about nine times the taps' RMS; it applies to the negative prompt's conditioning too. `"balanced"`, `"detail"` and `"subtle"` are comfyui-krea2-conditioning's presets (renormalize on, multiplier 1): their per-layer weights times a constant that keeps the taps' RMS, measured over twenty prompts through Krea 2 Turbo's text encoder (`scripts/krea2_rebalance_calib.py`; the node's per-prompt factor stayed within 1.7 % of it), so they shift the balance between layers without the default's overall gain. `false` (the default) is the plain model. A boolean or a preset's name, also in a form (`true`/`false`/`1`/`0` or the name); a model without it refuses anything but `false` with a 400 |
|
||||
|
||||
**Anima** makes RGB pictures, 1024x1024 by default, sides rounded down to multiples of 16, up to
|
||||
1536x1536 (9216 latent tokens; the card's range is 512x512 to 1536x1536). Base and Aesthetic run 30
|
||||
|
||||
@@ -24,6 +24,7 @@ and `agentreplay.py` need `python3`. Scripts find each other through `$(dirname
|
||||
| `convfn.sh` | Rebuilds the container `fnserve.sh` serves, as `w4nl64-i8lm.new.rad` beside it, from `data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`. Needs `CALIB=<dir>`: the recipe's expert rule runs GPTQ against the calibration Grams there (`docs/MOE-W4.md`). |
|
||||
| `hfget.sh` | Fetches a Hugging Face repo with `curl` and `jq`. Resumable, and skips the duplicate weight formats a repo often carries beside its safetensors. `radiance --model <repo id>` runs it. |
|
||||
| `krea2_native.py` | Rewrites a Krea 2 DiT single file in Krea's own key names (`turbo.safetensors`, civitai and ComfyUI finetunes) as diffusers' transformer file, bytes unchanged, so it converts as the `transformer/` of a Krea 2 pipeline directory (`docs/GUIDE.md`). |
|
||||
| `krea2_rebalance_calib.py` | Measures the constant of each Krea 2 rebalance preset (`rebalance`: balanced, detail, subtle): the taps' mean squares over twenty prompts through a pipeline's text encoder, and the renormalising factor arch/krea2 holds for them (`docs/GUIDE.md`). Needs torch and transformers. |
|
||||
|
||||
## Measuring
|
||||
|
||||
|
||||
Executable
+98
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
# krea2_rebalance_calib.py -- the constants of arch/krea2's rebalance presets (`rebalance`:
|
||||
# "balanced", "detail", "subtle"): each preset's per-layer weights times s, the factor
|
||||
# comfyui-krea2-conditioning's renormalize applies at multiplier 1.
|
||||
#
|
||||
# krea2_rebalance_calib.py <Krea 2 pipeline directory> [out.json]
|
||||
#
|
||||
# The node scales tap t by w_t and renormalises so the taps keep their total energy:
|
||||
# s = sqrt(sum_t m_t / sum_t w_t^2 m_t), m_t the mean square of tap t over the prompt's rows. The
|
||||
# plugin cannot measure m_t per request without a reduction across the encoder's rows, so it takes
|
||||
# s as a constant: m_t averaged over the twenty prompts below, each run through the release's text
|
||||
# encoder in arch/krea2's template with its system prefix dropped, as the plugin keeps the rows.
|
||||
# The script prints, per preset, that s, the per-prompt range of s, and the twelve gains, and for
|
||||
# the default gains (`rebalance: true`) their factor on the taps' RMS.
|
||||
#
|
||||
# Measured on krea/Krea-2-Turbo's text_encoder (bf16, CPU, about a minute): balanced 0.44109
|
||||
# (per prompt 0.43449 to 0.44879), detail 0.35702, subtle 0.84759; the default gains are 9.07x the
|
||||
# taps' RMS. Needs torch and transformers.
|
||||
import json
|
||||
import sys
|
||||
|
||||
import torch
|
||||
from transformers import AutoModel, AutoTokenizer
|
||||
|
||||
# Tap t is the hidden state after layer TAPS[t] - 1 (hidden_states[TAPS[t]]), arch/krea2's kTaps.
|
||||
TAPS = [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35]
|
||||
SYS = ("Describe the image by detailing the color, shape, size, texture, quantity, text, spatial "
|
||||
"relationships of the objects and background:")
|
||||
DROP = f"<|im_start|>system\n{SYS}<|im_end|>\n<|im_start|>user\n"
|
||||
PRESETS = {
|
||||
"balanced": [1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1],
|
||||
"detail": [0.8, 0.8, 0.9, 0.9, 1, 1, 1.2, 3, 6, 1.5, 5, 1.2],
|
||||
"subtle": [1, 1, 1, 1, 1, 1, 1, 1.5, 2, 1, 1.5, 1],
|
||||
}
|
||||
# ConditioningKrea2Rebalance's defaults: multiplier 4 times these, no renormalisation.
|
||||
DEFAULT = [4 * w for w in PRESETS["balanced"]]
|
||||
PROMPTS = [
|
||||
"a cat",
|
||||
"portrait of an old fisherman with a weathered face, grey beard, wool cap, soft window light",
|
||||
"a young woman with freckles and red hair laughing in a sunflower field, golden hour, 35mm photo",
|
||||
"close-up of a man's face, sharp focus on the eyes, studio lighting, black background",
|
||||
"a mountain lake at dawn with mist over the water and pine trees on the shore",
|
||||
"a busy street market in Marrakech, colorful spices, people in motion, afternoon sun",
|
||||
"a neon sign that reads \"OPEN 24 HOURS\" above the door of a small diner at night, rain on the street",
|
||||
"a hand-written note on yellow paper saying 'Buy milk, call mom, feed the dog'",
|
||||
"an astronaut riding a horse on the moon, earth in the sky, cinematic",
|
||||
"three red apples and two green pears on a wooden table, top-down view",
|
||||
"a cozy living room with a fireplace, a grey sofa, a knitted blanket and a sleeping dog",
|
||||
"architectural photo of a brutalist concrete building against a blue sky, wide angle",
|
||||
"a watercolor painting of a lighthouse on a cliff during a storm",
|
||||
"anime style illustration of a girl with a sword standing on a rooftop at sunset",
|
||||
"macro photo of a dewdrop on a spider web, bokeh background",
|
||||
"a group of five friends sitting around a campfire at night, smiling, warm light on their faces",
|
||||
"a vintage red car parked in front of a gas station in the desert, 1960s, film grain",
|
||||
"a bowl of ramen with a soft-boiled egg, chopsticks resting on the side, steam rising",
|
||||
"an elderly woman knitting in a rocking chair next to a window, her cat on her lap, overcast daylight, "
|
||||
"muted colors, documentary photography, shallow depth of field, the room is full of old books and plants",
|
||||
"a futuristic city skyline with flying cars, holographic billboards in Japanese and English, dusk",
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) not in (2, 3):
|
||||
sys.exit(__doc__ or "usage: krea2_rebalance_calib.py <pipeline directory> [out.json]")
|
||||
pipe = sys.argv[1]
|
||||
tok = AutoTokenizer.from_pretrained(f"{pipe}/tokenizer")
|
||||
model = AutoModel.from_pretrained(f"{pipe}/text_encoder", dtype=torch.bfloat16).eval()
|
||||
lm = getattr(model, "language_model", model)
|
||||
n_drop = len(tok(DROP, add_special_tokens=False).input_ids)
|
||||
rows = []
|
||||
with torch.no_grad():
|
||||
for p in PROMPTS:
|
||||
text = DROP + p + "<|im_end|>\n<|im_start|>assistant\n"
|
||||
ids = tok(text, add_special_tokens=False, return_tensors="pt").input_ids
|
||||
hs = lm(input_ids=ids, output_hidden_states=True).hidden_states
|
||||
rows.append([hs[i][0, n_drop:].float().pow(2).mean().item() for i in TAPS])
|
||||
M = torch.tensor(rows, dtype=torch.float64) # (prompts, taps)
|
||||
m = M.mean(0)
|
||||
out = {"taps": TAPS, "m_mean": m.tolist(), "presets": {}}
|
||||
for name, w in PRESETS.items():
|
||||
w2 = torch.tensor(w, dtype=torch.float64) ** 2
|
||||
per = (M.sum(1) / (M * w2).sum(1)).sqrt()
|
||||
s = float((m.sum() / (m * w2).sum()).sqrt())
|
||||
out["presets"][name] = {"s": s, "s_min": float(per.min()), "s_max": float(per.max()),
|
||||
"gains": [x * s for x in w]}
|
||||
d2 = torch.tensor(DEFAULT, dtype=torch.float64) ** 2
|
||||
out["default_rms_gain"] = float(((m * d2).sum() / m.sum()).sqrt())
|
||||
for name, p in out["presets"].items():
|
||||
print(f"{name:9s} s {p['s']:.5f} ({p['s_min']:.5f} to {p['s_max']:.5f}) gains "
|
||||
+ ", ".join(f"{g:.5g}" for g in p["gains"]))
|
||||
print(f"default gains: {out['default_rms_gain']:.2f}x the taps' RMS")
|
||||
if len(sys.argv) == 3:
|
||||
with open(sys.argv[2], "w") as f:
|
||||
json.dump(out, f, indent=1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+647
-13
@@ -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;
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -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 %}
|
||||
@@ -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
|
||||
@@ -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):
|
||||
|
||||
@@ -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
@@ -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 };
|
||||
{
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user