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.
This commit is contained in:
Constantin authored and StillDeadcode committed 2026-10-25 12:09:29 +01:00
1 parent 7e04bcac2b
commit e3eab050bd
12 files changed
+1484 -42

No files matched your search

+139 -41
View File
@@ -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. */
+9
View File
@@ -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)
+5
View File
@@ -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"
+216
View File
@@ -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 */
+540
View File
@@ -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
+9
View File
@@ -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)
+5
View File
@@ -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"
+9
View File
@@ -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)
+7
View File
@@ -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)