From e3eab050bd6b78230edefc5ce76e439d60a47760 Mon Sep 17 00:00:00 2001 From: Constantin Date: Sun, 25 Oct 2026 06:57:16 -0400 Subject: [PATCH] Add HYV3 BF16 FP8 and GGUF architecture adapters Declare the HYV3 graph with a private attention helper and existing kernels/layouts. Support per-head Q/K normalization, sigmoid-correction routing, the dense-first schedule and TP1/TP2 independent arm reductions with FP32 combine. Add graph, format and plugin tests without calibration or decode optimizations. --- arch/common/rad_block_moe_fp8.h | 180 +++++++--- arch/hyv3_bf16/CMakeLists.txt | 9 + arch/hyv3_bf16/hyv3_bf16.cpp | 5 + arch/hyv3_common/hyv3_attention.h | 216 ++++++++++++ arch/hyv3_common/hyv3_impl.cpp | 540 ++++++++++++++++++++++++++++++ arch/hyv3_fp8/CMakeLists.txt | 9 + arch/hyv3_fp8/hyv3_fp8.cpp | 5 + arch/hyv3_gguf/CMakeLists.txt | 9 + arch/hyv3_gguf/hyv3_gguf.cpp | 7 + tests/arch_test.cpp | 483 ++++++++++++++++++++++++++ tests/hyv3_bf16_fixture.h | 27 ++ tests/shipped_plugins_test.cpp | 36 +- 12 files changed, 1484 insertions(+), 42 deletions(-) create mode 100644 arch/hyv3_bf16/CMakeLists.txt create mode 100644 arch/hyv3_bf16/hyv3_bf16.cpp create mode 100644 arch/hyv3_common/hyv3_attention.h create mode 100644 arch/hyv3_common/hyv3_impl.cpp create mode 100644 arch/hyv3_fp8/CMakeLists.txt create mode 100644 arch/hyv3_fp8/hyv3_fp8.cpp create mode 100644 arch/hyv3_gguf/CMakeLists.txt create mode 100644 arch/hyv3_gguf/hyv3_gguf.cpp create mode 100644 tests/hyv3_bf16_fixture.h diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h index 9690f686..1c82f109 100644 --- a/arch/common/rad_block_moe_fp8.h +++ b/arch/common/rad_block_moe_fp8.h @@ -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. */ diff --git a/arch/hyv3_bf16/CMakeLists.txt b/arch/hyv3_bf16/CMakeLists.txt new file mode 100644 index 00000000..f9f3cc1b --- /dev/null +++ b/arch/hyv3_bf16/CMakeLists.txt @@ -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) diff --git a/arch/hyv3_bf16/hyv3_bf16.cpp b/arch/hyv3_bf16/hyv3_bf16.cpp new file mode 100644 index 00000000..37ee1c4c --- /dev/null +++ b/arch/hyv3_bf16/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" diff --git a/arch/hyv3_common/hyv3_attention.h b/arch/hyv3_common/hyv3_attention.h new file mode 100644 index 00000000..25389ec4 --- /dev/null +++ b/arch/hyv3_common/hyv3_attention.h @@ -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 + +#include +#include +#include + +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 */ diff --git a/arch/hyv3_common/hyv3_impl.cpp b/arch/hyv3_common/hyv3_impl.cpp new file mode 100644 index 00000000..363f023c --- /dev/null +++ b/arch/hyv3_common/hyv3_impl.cpp @@ -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 +#include "hyv3_attention.h" +#include +#include + +#include +#include +#include +#include +#include +#include + +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 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 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(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[] = { "" }; +static const RadChatFormat kHyv3ChatFormat = { + .struct_size = sizeof(RadChatFormat), + .name = "hyv3", + .reasoning_open = "", + .reasoning_close = "", + .reasoning_breaks = kHyv3ToolTriggers, + .n_reasoning_breaks = 1, + .reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT, + .section_open = "", + .section_close = "", + .name_prefix = "", + .name_suffix = "", + .call_end = "", + .arg_prefix = "", + .arg_name_suffix = "\n", + .arg_value_prefix = "", + .arg_value_suffix = "", + .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 diff --git a/arch/hyv3_fp8/CMakeLists.txt b/arch/hyv3_fp8/CMakeLists.txt new file mode 100644 index 00000000..d4b547fd --- /dev/null +++ b/arch/hyv3_fp8/CMakeLists.txt @@ -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) diff --git a/arch/hyv3_fp8/hyv3_fp8.cpp b/arch/hyv3_fp8/hyv3_fp8.cpp new file mode 100644 index 00000000..033b4463 --- /dev/null +++ b/arch/hyv3_fp8/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" diff --git a/arch/hyv3_gguf/CMakeLists.txt b/arch/hyv3_gguf/CMakeLists.txt new file mode 100644 index 00000000..482270f4 --- /dev/null +++ b/arch/hyv3_gguf/CMakeLists.txt @@ -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) diff --git a/arch/hyv3_gguf/hyv3_gguf.cpp b/arch/hyv3_gguf/hyv3_gguf.cpp new file mode 100644 index 00000000..77d0e99f --- /dev/null +++ b/arch/hyv3_gguf/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) diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index d8eee1b1..55007e9e 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -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(); diff --git a/tests/hyv3_bf16_fixture.h b/tests/hyv3_bf16_fixture.h new file mode 100644 index 00000000..b6800fb8 --- /dev/null +++ b/tests/hyv3_bf16_fixture.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +/* 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 diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index 884a9df2..82a695db 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -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("")); + CHECK_EQ(std::string(f->reasoning_close), std::string("")); + 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("")); + CHECK_EQ(std::string(f->section_open), std::string("")); + CHECK_EQ(std::string(f->section_close), std::string("")); + CHECK_EQ(std::string(f->name_prefix), std::string("")); + CHECK_EQ(std::string(f->name_suffix), std::string("")); + CHECK_EQ(std::string(f->arg_prefix), std::string("")); + CHECK_EQ(std::string(f->arg_name_suffix), std::string("\n")); + CHECK_EQ(std::string(f->arg_value_prefix), std::string("")); + CHECK_EQ(std::string(f->arg_value_suffix), std::string("")); + REQUIRE(f->n_triggers == 1 && f->triggers != nullptr); + CHECK_EQ(std::string(f->triggers[0]), std::string("")); + 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: