diff --git a/arch/nemotronh/CMakeLists.txt b/arch/nemotronh/CMakeLists.txt new file mode 100644 index 00000000..d362b6f5 --- /dev/null +++ b/arch/nemotronh/CMakeLists.txt @@ -0,0 +1,7 @@ +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(nemotronh LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() +rad_add_plugin(nemotronh architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/nemotronh.cpp) diff --git a/arch/nemotronh/nemotronh.cpp b/arch/nemotronh/nemotronh.cpp new file mode 100644 index 00000000..d1b2c946 --- /dev/null +++ b/arch/nemotronh/nemotronh.cpp @@ -0,0 +1,1142 @@ +/* nemotronh -- NVIDIA's Nemotron-H hybrids from the bf16 checkpoint: Nemotron-3.5-Bolt-74B-A9B + * (`model_type: nemotron_h_omni` around a `nemotron_h_puzzle` language model, + * NemotronH_Omni_Reasoning_V3), its language model; the routed experts as the recipe stores them. + * + * 88 blocks, each one mixer behind its own RMS norm and a residual add: 40 Mamba-2, 40 routed + * feed-forward and 8 attention, in the order `layers_block_type` gives + * Mamba-2: 128 heads of 64 in 8 groups, a 128-wide state, a 4-tap causal convolution with bias + * and SiLU over x|B|C, dt = softplus(dt + dt_bias), a D skip, and RMSNormGated over groups of + * 1024 of y * silu(z) + * attention: 32 query heads and 2 KV heads of 128, no position encoding (NoPE) + * feed-forward: a latent MoE. The router scores the normed hidden state (sigmoid, a correction + * bias for the selection only, top-9, normalised, x5); the routed experts run in a 1024-wide + * latent (fc1_latent_proj in front, fc2_latent_proj behind) and are ungated, + * down(relu(up(x))^2). Count and width differ by layer (Puzzle's `block_configs`: 240 to 496 + * experts of 1536 to 2560). A shared expert of 5376, relu^2 as well, reads the hidden state. + * + * ============================== THE LATENT FEED-FORWARD ============================== + * + * MoeFP8 serves the routed arm with its Geom at the latent width: its input is fc1's output + * (quantised here), the router reads the hidden state over Config::router_k, and its gather writes + * the routed sum back into the latent plane. fc2 has no bias and is linear, so under tensor + * parallelism each rank applies it (replicated) to its partial latent sum and adds its slice of the + * shared expert; one all-reduce over the hidden width then sums both arms (Config::no_reduce). fc1 + * is replicated too: the latent is every rank's input. + * + * ============================== THE MAMBA-2 MIXER ============================== + * + * in_proj's rows are z | x | B | C | dt (8192, 8192, 1024, 1024, 128). It is served as three linears + * over row maps of the one tensor: z, x|B|C (the convolution's input) and dt. Under tensor + * parallelism each rank takes whole heads and their groups' B and C, and dt's 128 rows split 32 a + * rank at four, which is no whole 128-row scale block; dt is its own linear so a recipe can keep + * it bf16 while the others are block fp8. + * + * The scan is `ssd_update`, Mamba-2's recurrence a token at a time (libref/ref_ssd.cpp), for + * prefill and decode. dt is not clamped: the checkpoint's `time_step_limit` is (0, inf), as vLLM + * serves it; HF's torch path clamps to time_step_min, which moves 13 % of the steps of the first + * layers. + * + * RMSNormGated is three ops: act_mul (silu of z times y), a gainless rmsnorm over rows of 1024 (the + * group), and mul_weight with the 8192 gains. A rank's heads are whole groups. + * + * ============================== RANKS, SPECULATION, VISION ============================== + * + * One, two or four ranks. At four each of the 2 KV heads is replicated over a rank pair (AttnFP8's + * spans), the LiLiCorr drafter's 2 the same way (Dflash2's spans). Speculating, the scan keeps its + * state in ssd_update's anchor form (one committed state and a scratch of per-token records), at + * most 31 drafts a step; the convolution's window is ple_conv's rolling one. Pictures and video go + * through the C-RADIO tower (radio.h) when the container holds it. A finite `time_step_limit` is + * refused by name, and so is every other geometry the release does not have. + * docs/ARCHITECTURES.md describes the model. */ +#include +#include +#include +#include +#include +#include "radio.h" +#include +#include +#include +#include +#include + +namespace nemotronh { +using namespace rad::arch; + +enum Kind { kMamba, kMoe, kAttn }; + +/* The released geometry this graph is written for; a checkpoint that differs is refused by name. */ +struct Shape { + int64_t n_embd = 0, n_layer = 0, heads = 0, head_dim = 0, state = 0, groups = 0, conv = 0, + latent = 0, ff_shared = 0; + double route_scale = 1; + std::vector kind; + std::vector experts, ff, top_k; /* per layer; 0 off the routed layers */ +}; + +static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) { + return rad_meta_geti(m, key, fallback); +} + +/* One all-reduce of [rows, n_embd] in place, or 0 at one rank. */ +static rad_op reduce(RadBuilder* b, const Geom& g, rad_buf x, bool exact = false) { + if (g.world <= 1) return 0; + 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", g.dtype), + RAD_INT("exact", exact ? 1 : g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); +} + +struct Mamba { + struct Wire { + ActFP8 input{}; /* [T, n_embd] the normed hidden state */ + rad_buf z = 0; /* [T, W] */ + rad_buf xbc = 0; /* [T, W + 2 GN] the convolution's input */ + rad_buf conv = 0; /* [T, W + 2 GN] its output */ + rad_buf dt = 0; /* [T, H] */ + rad_buf y = 0; /* [T, W] the scan's output */ + ActFP8 core_out{}; /* [T, W] the gated norm's, the out-projection's input */ + rad_buf out = 0; /* [T, n_embd] */ + }; + Geom g{}; + Wire w{}; + int layer = 0; + /* This rank's heads, groups and widths. */ + int64_t H = 0, P = 0, N = 0, G = 0, W = 0, GN = 0; + rad_kvgroup state = 0, history = 0; + LinearFP8 in_z{}, in_xbc{}, in_dt{}, output{}; + QuantFP8 out_quant{}; + rad_weight taps = 0, bias = 0, alog = 0, dtb = 0, dskip = 0, gain = 0; + rad_op op_conv = 0, op_prefill = 0, op_verify = 0, op_gate = 0, op_norm = 0, op_gain = 0, + op_ar = 0; + + static constexpr int64_t kNormGroup = 1024; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& s, int l, + const Wire& wire, const char* pre, rad_kvgroup st, rad_kvgroup cv) { + g = geom; + w = wire; + layer = l; + state = st; + history = cv; + H = s.heads / g.world; + P = s.head_dim; + N = s.state; + G = s.groups / g.world; + W = H * P; + GN = G * N; + const int64_t Wa = s.heads * s.head_dim, GNa = s.groups * s.state; + const auto grp = grp_layer(l); + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, st)); + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, cv)); + /* in_proj as three row maps: z, x|B|C, dt. */ + const char* src = nm.ckpt("%s.in_proj.weight", pre); + RAD_ARCH_TRY(map_rows(b, nm.f("blk.%d.ssm_in_z.weight", l), { { src, 0, Wa } })); + RAD_ARCH_TRY(map_rows(b, nm.f("blk.%d.ssm_in_xbc.weight", l), + { { src, (int)Wa, Wa + 2 * GNa } })); + RAD_ARCH_TRY(map_rows(b, nm.f("blk.%d.ssm_dt.weight", l), + { { src, (int)(2 * Wa + 2 * GNa), s.heads } })); + in_z.mapped = in_xbc.mapped = in_dt.mapped = true; + RAD_ARCH_TRY(in_z.declare(b, nm, g, nm.f("blk.%d.ssm_in_z", l), W, g.n_embd, RAD_SHARD_ROW, + grp, { src }, w.input, w.z)); + RAD_ARCH_TRY(in_xbc.declare(b, nm, g, nm.f("blk.%d.ssm_in_xbc", l), W + 2 * GN, g.n_embd, + RAD_SHARD_ROW, grp, { src }, w.input, w.xbc, 0, + { W, GN, GN })); + RAD_ARCH_TRY(in_dt.declare(b, nm, g, nm.f("blk.%d.ssm_dt", l), H, g.n_embd, RAD_SHARD_ROW, + grp, { src }, w.input, w.dt)); + + const char *tn = nm.f("blk.%d.ssm_conv1d.weight", l), *bn = nm.f("blk.%d.ssm_conv1d.bias", l), + *an = nm.f("blk.%d.ssm_a_log", l), *dn = nm.f("blk.%d.ssm_dt.bias", l), + *sn = nm.f("blk.%d.ssm_d", l), *gn = nm.f("blk.%d.ssm_norm.weight", l); + RAD_ARCH_TRY(map_copy(b, tn, nm.ckpt("%s.conv1d.weight", pre))); + RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.conv1d.bias", pre))); + RAD_ARCH_TRY(map_copy(b, an, nm.ckpt("%s.A_log", pre))); + RAD_ARCH_TRY(map_copy(b, dn, nm.ckpt("%s.dt_bias", pre))); + RAD_ARCH_TRY(map_copy(b, sn, nm.ckpt("%s.D", pre))); + RAD_ARCH_TRY(map_copy(b, gn, nm.ckpt("%s.norm.weight", pre))); + taps = decl_w(b, tn, RAD_BF16, { W + 2 * GN, s.conv }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, + grp, 0, { W, GN, GN }); + bias = decl_w(b, bn, RAD_BF16, { W + 2 * GN }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp, 0, + { W, GN, GN }); + alog = decl_w(b, an, RAD_F32, { H }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp); + dtb = decl_w(b, dn, RAD_F32, { H }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp); + dskip = decl_w(b, sn, RAD_F32, { H }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp); + gain = decl_w(b, gn, RAD_F32, { W }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp); + if (!taps || !bias || !alog || !dtb || !dskip || !gain) return RAD_E_INVAL; + + op_conv = rw(b, + RAD_OP(b, "ple_conv_bias", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", W + 2 * GN), + RAD_INT("width", s.conv), RAD_INT("dilation", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(taps, bias)), + { w.xbc }, { w.conv }); + for (int verify = 0; verify < 2; ++verify) { + const rad_op op = + rw(b, + RAD_OP(b, "ssd_update", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", H), + RAD_INT("head_dim", P), RAD_INT("d_state", N), + RAD_INT("groups", G), + RAD_STR("mode", verify ? "verify" : "prefill"), + RAD_STR("dtype", "bf16"), + RAD_STR("state_form", + g.max_spec > 0 ? "anchor" : "per_candidate")), + RAD_WEIGHTS(alog, dtb, dskip)), + { w.conv, w.dt }, { w.y }); + if (verify) + op_verify = op; + else + op_prefill = op; + } + /* RMSNormGated: norm(y * silu(z)) * gain, normed over groups of 1024 (whole groups on a + * rank; read as rows of 1024 of the contiguous plane). */ + op_gate = rw(b, + RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", W), + RAD_STR("act", "silu"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.z, w.y }, { w.core_out.x }); + op_norm = rw(b, + RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * (W / kNormGroup)), + RAD_INT("n", kNormGroup), RAD_F64("eps", g.eps), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.core_out.x }, { w.core_out.x }); + op_gain = rw(b, + RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", W), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(gain)), + { w.core_out.x }, { w.core_out.x }); + if (!op_conv || !op_prefill || !op_verify || !op_gate || !op_norm || !op_gain) + return RAD_E_INVAL; + const char* on = nm.f("blk.%d.ssm_out", l); + RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.out_proj.weight", pre) })); + if (!output.reads_x) RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, W)); + RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, W, RAD_SHARD_COL, grp, + { nm.ckpt("%s.out_proj.weight", pre) }, w.core_out, w.out)); + op_ar = reduce(b, g, w.out); + return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK; + } + + /* The recurrent core over the decode rows (verify) and then the prefill rows, as KdaState. */ + void step(RadCtx* c, const RadBatch* batch) const { + const auto *st = kv_batch(batch, state), *cv = kv_batch(batch, history); + if (!st || !cv || !st->state_index || !cv->state_index) { + rad_step_fail(c, "nemotronh Mamba-2 requires recurrent and convolution state indices"); + return; + } + const int64_t T = batch->n_tok, S = batch->n_seq; + const int64_t pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1; + in_z.step(c, w.input, w.z, T); + in_xbc.step(c, w.input, w.xbc, T); + in_dt.step(c, w.input, w.dt, T); + int64_t D = 0, DT = 0; + batch_split(batch, &D, &DT); + for (int verify = 1; verify >= 0; --verify) { + const int64_t seq0 = verify ? 0 : D, seqs = verify ? D : S - D, rows = verify ? DT : T; + if (!seqs) continue; + const RadOperand cu = praw(batch->cu_seqlens + seq0, RAD_I32, seqs + 1); + const RadOperand init = praw(batch->ctx_lens + seq0, RAD_I32, seqs); + const RadOperand accepted = + verify ? praw(batch->num_accepted, RAD_I32, seqs) : RAD_NONE; + RAD_ISSUE_N(c, op_conv, rows, brows(w.xbc, rows), RAD_W(taps), + kv_cache(history, layer), cu, RAD_NONE, + praw(cv->state_index + seq0, RAD_I32, seqs), init, accepted, + RAD_W(bias), brows(w.conv, rows)); + RAD_ISSUE_N(c, verify ? op_verify : op_prefill, rows, bcol(w.conv, 0, W, rows), + bcol(w.conv, W, GN, rows), bcol(w.conv, W + GN, GN, rows), + brows(w.dt, rows), RAD_W(alog), RAD_W(dtb), RAD_W(dskip), + kv_cache(state, layer), + praw2(st->state_index + seq0 * pitch, RAD_I32, seqs, pitch), cu, accepted, + init, brows(w.y, rows)); + } + RAD_ISSUE_N(c, op_gate, T, brows(w.z, T), brows(w.y, T), brows(w.core_out.x, T)); + RAD_ISSUE_N(c, op_norm, T * (W / kNormGroup), brows(w.core_out.x, T), RAD_NONE, + brows(w.core_out.x, T)); + RAD_ISSUE_N(c, op_gain, T, brows(w.core_out.x, T), RAD_W(gain), brows(w.core_out.x, T)); + out_quant.step(c, T); + output.step(c, w.core_out, w.out, T); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.out, T), RAD_NONE); + } +}; + +/* The latent feed-forward around MoeFP8 (see the header). */ +struct LatentMoe { + struct Wire { + ActFP8 h{}; /* [T, n_embd] the normed hidden state */ + ActFP8 lat{}; /* [T, latent] fc1's output, then the routed sum */ + rad_buf routed = 0; /* [T, n_embd] fc2's output, then the block's delta */ + rad_buf sup = 0; /* [T, ff_shared / world] */ + ActFP8 sff{}; /* [T, ff_shared / world] */ + rad_buf sout = 0; /* [T, n_embd] */ + MoeFP8::Wire moe{}; /* the routed arm's own planes; its h and route are set here */ + }; + Geom g{}; + Wire w{}; + LinearFP8 fc1{}, fc2{}, sh_up{}, sh_down{}; + QuantFP8 lat_in{}, lat_out{}; + GateQuantFP8 sh_act{}; + MoeFP8 moe{}; + rad_op op_join = 0, op_ar = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& s, int l, + const Wire& wire, const char* pre, MoeFP8::Src& ms, int64_t sh_lo, int64_t sh_hi, + int64_t sh_w) { + g = geom; + w = wire; + const auto grp = grp_layer(l); + RAD_ARCH_TRY(fc1.declare(b, nm, g, nm.f("blk.%d.ffn_latent_in", l), s.latent, g.n_embd, + RAD_SHARD_NONE, grp, + { nm.ckpt("%s.fc1_latent_proj.weight", pre) }, w.h, w.lat.x)); + /* The routed arm reads the latent's codes unless its experts are bf16. */ + if (!ms.cfg.expert_bf16) RAD_ARCH_TRY(lat_in.declare(b, g, w.lat, s.latent)); + Geom ge = g; + ge.n_embd = s.latent; + ge.n_ff_all = s.ff[(size_t)l]; + MoeFP8::Wire mw = w.moe; + mw.h = w.lat; + mw.route = w.h.x; + RAD_ARCH_TRY(moe.declare(b, nm, ge, l, mw, ms, false, false)); + const char* f2 = nm.f("blk.%d.ffn_latent_out", l); + RAD_ARCH_TRY(fc2.probe(b, nm, g, f2, { nm.ckpt("%s.fc2_latent_proj.weight", pre) })); + if (!fc2.reads_x) RAD_ARCH_TRY(lat_out.declare(b, g, w.lat, s.latent)); + RAD_ARCH_TRY(fc2.declare(b, nm, g, f2, g.n_embd, s.latent, RAD_SHARD_NONE, grp, + { nm.ckpt("%s.fc2_latent_proj.weight", pre) }, w.lat, w.routed)); + /* The shared expert over the hidden state, this rank's slice of its 5376 columns. */ + if (sh_w > 0) { + const char* dn = nm.f("blk.%d.ffn_down_shexp", l); + RAD_ARCH_TRY(sh_down.probe(b, nm, g, dn, + { nm.ckpt("%s.shared_experts.down_proj.weight", pre) })); + RAD_ARCH_TRY(sh_up.declare(b, nm, g, nm.f("blk.%d.ffn_up_shexp", l), sh_w, g.n_embd, + RAD_SHARD_ROW, grp, + { nm.ckpt("%s.shared_experts.up_proj.weight", pre) }, w.h, + w.sup, 0, {}, sh_lo, sh_hi)); + RAD_ARCH_TRY(sh_act.declare(b, g, w.sup, w.sff, sh_w, "relu2", 0, true, false)); + RAD_ARCH_TRY(sh_down.declare(b, nm, g, dn, g.n_embd, sh_w, RAD_SHARD_COL, grp, + { nm.ckpt("%s.shared_experts.down_proj.weight", pre) }, + w.sff, w.sout, 0, {}, sh_lo, sh_hi)); + op_join = 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.routed, w.sout }, { w.routed }); + if (!op_join) return RAD_E_INVAL; + } + op_ar = reduce(b, g, w.routed); + return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK; + } + void step(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + fc1.step(c, w.h, w.lat.x, T); + lat_in.step(c, T); + moe.step(c, batch); + lat_out.step(c, T); + fc2.step(c, w.lat, w.routed, T); + if (op_join) { + sh_up.step(c, w.h, w.sup, T); + sh_act.step(c, w.sup, T); + sh_down.step(c, w.sff, w.sout, T); + RAD_ISSUE_N(c, op_join, T, brows(w.routed, T), brows(w.sout, T), brows(w.routed, T)); + } + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.routed, T), RAD_NONE); + } +}; + +struct Layer { + Kind kind = kMamba; + rad_weight gain = 0; + NormQuantFP8 norm{}; + Mamba mamba{}; + LatentMoe moe{}; + AttnFP8 attn{}; + rad_op op_add = 0; +}; +struct Model { + Names nm{}; + Geom g{}; + Shape s{}; + std::vector layers; + rad_kvgroup kv_attn = 0, kv_state = 0, kv_conv = 0; + rad_buf x = 0, y = 0, final_hidden = 0, logit_input = 0, logits = 0; + ActFP8 act{}; + Mamba::Wire mw{}; + AttnFP8::Wire aw{}; + LatentMoe::Wire ew{}; + /* The routed arm's planes by (experts, width): layers of one class share them. */ + std::map, MoeFP8::Wire> classes; + rad_weight token = 0, head = 0, final_gain = 0; + rad_op embed = 0, embed_ar = 0, norm = 0, gather = 0, head_op = 0; + /* The vision encoder (C-RADIO and its projector) and the scatter of its rows over the token + * embeddings they replace. */ + Radio radio{}; + MediaRows media{}; + /* LiLiCorr, the drafter (`--draft-model`): the trunk's residual stream after each tapped block + * into one column slice of `dfsrc` a tap; the DFlash2 backbone in LiLiCorr's mode at absolute + * layers n_layer.. of its own KV group, and the correlator after it. */ + enum { MAX_TAPS = 8 }; + int n_taps = 0; + int tap_layer[MAX_TAPS] = {}; + rad_buf dfsrc = 0; + rad_op op_tap = 0; + bool have_df = false; + rad_kvgroup kv_draft = 0; + Dflash2 df{}; + Dflash2::Wire dfw{}; + LiliCorr lili{}; + LiliCorr::Wire lw{}; +}; +static std::unique_ptr models[MAX_RANKS]; +static thread_local std::unique_ptr probe_model; + +static int read_shape(const RadModelMeta* meta, Shape& s) { + s.n_embd = meta->n_embd; + s.n_layer = meta->n_layers; + s.heads = cfg(meta, "mamba_num_heads", 0); + s.head_dim = cfg(meta, "mamba_head_dim", 0); + s.state = cfg(meta, "ssm_state_size", 0); + s.groups = cfg(meta, "n_groups", 0); + s.conv = cfg(meta, "conv_kernel", 0); + s.latent = cfg(meta, "moe_latent_size", 0); + s.ff_shared = cfg(meta, "moe_shared_expert_intermediate_size", 0) * + cfg(meta, "n_shared_experts", 0); + s.route_scale = rad_meta_getf(meta, "routed_scaling_factor", 0.0); + /* `layers_block_type` names each block; `block_configs..*` (Puzzle) gives a routed layer's + * expert count, width and top-k, the top-level keys where it is absent. */ + bool kinds_ok = true; + for_each_token(rad_meta_gets(meta, "layers_block_type", ""), [&](const char* t, size_t n) { + const std::string k(t, n); + if (k == "mamba") s.kind.push_back(kMamba); + else if (k == "moe") s.kind.push_back(kMoe); + else if (k == "attention") s.kind.push_back(kAttn); + else kinds_ok = false; + return true; + }); + s.experts.assign((size_t)s.n_layer, 0); + s.ff.assign((size_t)s.n_layer, 0); + s.top_k.assign((size_t)s.n_layer, 0); + bool moe_ok = true; + for (int64_t l = 0; l < (int64_t)s.kind.size() && l < s.n_layer; ++l) { + if (s.kind[(size_t)l] != kMoe) continue; + char key[96]; + auto per = [&](const char* field, const char* global) { + std::snprintf(key, sizeof key, "block_configs.%lld.%s", (long long)l, field); + return cfg(meta, key, cfg(meta, global, 0)); + }; + s.experts[(size_t)l] = per("n_routed_experts", "n_routed_experts"); + s.ff[(size_t)l] = per("moe_intermediate_size", "moe_intermediate_size"); + s.top_k[(size_t)l] = per("num_experts_per_tok", "num_experts_per_tok"); + moe_ok = moe_ok && s.experts[(size_t)l] > 0 && s.ff[(size_t)l] > 0 && + s.top_k[(size_t)l] > 0 && s.top_k[(size_t)l] <= s.experts[(size_t)l] && + s.experts[(size_t)l] <= 512 && s.ff[(size_t)l] % RAD_FP8_BLOCK == 0; + } + /* A clamp the scan does not apply: present only when the limit is a list of numbers. */ + bool unclamped = true; + { + std::vector lim; + for_each_token(rad_meta_gets(meta, "time_step_limit", ""), [&](const char* t, size_t) { + lim.push_back(std::strtod(t, nullptr)); + return true; + }); + unclamped = lim.empty() || (lim.size() == 2 && lim[0] <= 0 && std::isinf(lim[1])); + } + const char* act = rad_meta_gets(meta, "mlp_hidden_act", rad_meta_gets(meta, "hidden_act", "")); + const struct { + const char* what; + bool ok; + } need[] = { + { "a block type per layer (mamba, moe, attention)", + kinds_ok && (int64_t)s.kind.size() == s.n_layer }, + { "Mamba-2 heads of 64 in groups that divide them", + s.head_dim == 64 && s.heads > 0 && s.groups > 0 && s.heads % s.groups == 0 }, + { "a Mamba-2 inner width of whole 1024-wide norm groups", + (s.heads * s.head_dim) % (s.groups * Mamba::kNormGroup) == 0 || + (s.heads * s.head_dim) == s.groups * Mamba::kNormGroup }, + { "a state of 128", s.state == 128 }, + { "a 4-tap convolution with bias", s.conv == 4 && cfg(meta, "use_conv_bias", 0) != 0 }, + { "no in_proj or out_proj bias", cfg(meta, "mamba_proj_bias", 0) == 0 && + cfg(meta, "use_bias", 0) == 0 }, + { "an unclamped dt (time_step_limit (0, inf))", unclamped }, + { "a SiLU Mamba activation", + !std::strcmp(rad_meta_gets(meta, "mamba_hidden_act", "silu"), "silu") }, + { "relu2 experts", !std::strcmp(act, "relu2") }, + { "routed layers with experts, width and top-k", moe_ok }, + { "a latent of whole 128-column blocks", + s.latent > 0 && s.latent % RAD_FP8_BLOCK == 0 }, + { "one shared expert of whole 128-column blocks", + cfg(meta, "n_shared_experts", 0) == 1 && s.ff_shared % RAD_FP8_BLOCK == 0 }, + { "sigmoid scoring", + !std::strcmp(rad_meta_gets(meta, "scoring_func", ""), "sigmoid") }, + { "ungrouped routing", cfg(meta, "n_group", 1) == 1 && cfg(meta, "topk_group", 1) == 1 }, + { "a positive routed_scaling_factor", s.route_scale > 0 }, + { "no attention or MLP bias", cfg(meta, "attention_bias", 0) == 0 && + cfg(meta, "mlp_bias", 0) == 0 }, + { "no MTP layers", cfg(meta, "num_nextn_predict_layers", 0) == 0 }, + { "a residual stream in the activation dtype", cfg(meta, "residual_in_fp32", 0) == 0 }, + { "untied embeddings", cfg(meta, "tie_word_embeddings", 0) == 0 }, + }; + for (const auto& n : need) + if (!n.ok) { + fprintf(stderr, "radiance: nemotronh: this plugin serves %s, and the checkpoint " + "differs\n", n.what); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* A rank's slice of a width of `blocks` 128-column blocks: blocks [lo, hi) in the order of the + * ranks starting at `first`, the first `blocks % world` ranks of that order one block wider. */ +static void slice_of(int64_t blocks, int world, int rank, int first, int64_t* lo, int64_t* hi) { + const int p = ((rank - first) % world + world) % world; + const int64_t base = blocks / world, extra = blocks % world; + *lo = p * base + std::min(p, extra); + *hi = *lo + base + (p < extra ? 1 : 0); +} + +/* ------------------------------------------------------------------ declare */ +static int buffers(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& s = m.s; + auto& nm = m.nm; + const int64_t T = g.max_tok, E = g.n_embd; + const int64_t H = s.heads / g.world, W = H * s.head_dim, GN = s.groups / g.world * s.state; + auto bf = [&](const char* n, std::initializer_list shape) { + return decl_b(b, nm.f("%s", n), RAD_BF16, shape); + }; + m.x = bf("residual", { T, E }); + m.y = bf("mixer_delta", { T, E }); + m.act.x = bf("normed", { T, E }); + RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E)); + m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, E }, RAD_BUF_PERSIST); + m.logit_input = bf("logit_input", { g.max_logit_rows, E }); + 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)); + + auto& mw = m.mw; + mw.input = m.act; + mw.out = m.y; + mw.z = bf("ssm_z", { T, W }); + mw.xbc = bf("ssm_xbc", { T, W + 2 * GN }); + mw.conv = bf("ssm_conv", { T, W + 2 * GN }); + mw.dt = bf("ssm_dt", { T, H }); + mw.y = bf("ssm_y", { T, W }); + mw.core_out.x = bf("ssm_out", { T, W }); + RAD_ARCH_TRY(mw.core_out.declare_qs(b, nm, g, "ssm_out", W)); + + auto& aw = m.aw; + aw.x = m.x; + aw.h = m.act; + aw.qkv = bf("attn_qkv", { T, g.qkv_dim() }); + aw.q = bf("attn_q", { T, g.q_dim() }); + aw.attn.x = bf("attn_out", { T, g.q_dim() }); + RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "attn_out", g.q_dim())); + return RAD_OK; +} + +/* The latent feed-forward's planes, and the routed arm's per (experts, width) class. */ +static int moe_buffers(RadBuilder* b, Model& m, const std::vector& msrc, + int64_t sh_w) { + auto& g = m.g; + auto& s = m.s; + auto& nm = m.nm; + const int64_t T = g.max_tok, E = g.n_embd, L = s.latent; + auto bf = [&](const char* n, std::initializer_list shape) { + return decl_b(b, nm.f("%s", n), RAD_BF16, shape); + }; + auto& ew = m.ew; + ew.h = m.act; + ew.lat.x = bf("latent", { T, L }); + RAD_ARCH_TRY(ew.lat.declare_qs(b, nm, g, "latent", L)); + ew.routed = m.y; + if (sh_w > 0) { + ew.sup = bf("shared_up", { T, sh_w }); + ew.sff.x = bf("shared_ff", { T, sh_w }); + RAD_ARCH_TRY(ew.sff.declare_qs(b, nm, g, "shared_ff", sh_w)); + ew.sout = bf("shared_out", { T, E }); + } + Geom gl = g; + gl.n_embd = L; + for (int64_t l = 0; l < s.n_layer; ++l) { + if (s.kind[(size_t)l] != kMoe) continue; + const MoeFP8::Config& c = msrc[(size_t)l].cfg; + const auto key = std::make_pair(c.n_expert_all, c.n_ff_exp); + if (m.classes.count(key)) continue; + const int64_t F = c.n_ff_exp, k = c.top_k, rows = c.rows > 0 ? c.rows : T; + char tag[64]; + std::snprintf(tag, sizeof tag, "e%lldf%lld", (long long)c.n_expert_all, (long long)F); + MoeFP8::Wire w{}; + w.logits = decl_b(b, nm.f("%s.router_logits", tag), RAD_F32, { T, c.n_expert_all }); + w.ids = decl_b(b, nm.f("%s.expert_ids", tag), RAD_I32, { T, k }); + w.ew = decl_b(b, nm.f("%s.expert_weights", tag), RAD_F32, { T, k }); + w.eoff = decl_b(b, nm.f("%s.expert_offsets", tag), RAD_I32, { c.n_expert + 1 }); + w.ecnt = decl_b(b, nm.f("%s.expert_counts", tag), RAD_I32, { c.n_expert }); + w.sorted = decl_b(b, nm.f("%s.expert_sorted", tag), RAD_I32, { rows * k }); + w.egu = bf(nm.f("%s.expert_up", tag), { rows * k, F }); + w.eff.x = bf(nm.f("%s.expert_ff", tag), { rows * k, F }); + RAD_ARCH_TRY(w.eff.declare_qs(b, nm, gl, nm.f("%s.expert_ff", tag), F, rows * k)); + w.edn = bf(nm.f("%s.expert_down", tag), { rows * k, L }); + if (c.expert_rot) { + w.hr.q = decl_b(b, nm.f("%s.latent_rot.q", tag), RAD_F8E4M3, { T, L }); + w.hr.s = decl_b(b, nm.f("%s.latent_rot.s", tag), RAD_F32, { T, L / RAD_FP8_BLOCK }); + if (!w.hr.q || !w.hr.s) return RAD_E_INVAL; + } + if (!w.logits || !w.ids || !w.ew || !w.eoff || !w.ecnt || !w.sorted || !w.egu || + !w.eff.x || !w.edn) + return RAD_E_INVAL; + m.classes[key] = w; + } + return RAD_OK; +} + +/* LiLiCorr: the DFlash2 backbone with sinks (rad_block_dflash2.h, Config::lili), its KV group and + * buffers, then the correlator (rad_block_lilicorr.h) over the backbone's draft rows, proposing a + * block of `max_spec` tokens through the walk. The drafter's own config is the container's + * `draft.` keys (rad-convert --draft-model); what this implementation does not apply is refused. */ +static int declare_lilicorr(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Model& m, int base_layer) { + Names& nm = m.nm; + Geom dg{}; + /* Two KV heads: at four ranks each is replicated over two (Dflash2 reads k and v at kv_off). */ + RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "LiLiCorr", true)); + auto dc_i = [&](const char* k, long long d) { + char key[160]; + std::snprintf(key, sizeof key, "draft.dflash_config.%s", k); + return rad_meta_geti(meta, key, d); + }; + auto dc_f = [&](const char* k, double d) { + char key[160]; + std::snprintf(key, sizeof key, "draft.dflash_config.%s", k); + return rad_meta_getf(meta, key, d); + }; + const long long trained = rad_meta_geti(meta, "draft.block_size", dc_i("block_size", 0)); + Dflash2::Config dc{}; + dc.lili = 1; + dc.n_taps = m.n_taps; + dc.block = ctx->max_spec + 1; + dc.taps = dc_i("conv_kernel_size", 2); + dc.group = dc_i("conv_group_size", 16); + dc.causal = dc_i("causal", 0) ? 1 : 0; + if (dc_i("use_swa", 0)) + dc.window = dc_i("swa_window_size", rad_meta_geti(meta, "draft.sliding_window", 0)); + /* The correlator has a slot embedding a draft position, trained at one block: run at it. */ + if (trained <= 1 || dc.block != trained) { + fprintf(stderr, "radiance: nemotronh: LiLiCorr was trained at block_size %lld (%lld draft " + "tokens) and its correlator has a learned embedding for each of them; this " + "serve asks for %d draft tokens\n", + trained, trained - 1, ctx->max_spec); + return RAD_E_UNSUPPORTED; + } + if (!dc_i("lilicorr_enabled", 0) || !rad_meta_geti(meta, "draft.attention_sink_bias", + dc_i("attention_sink_bias", 0))) { + fprintf(stderr, "radiance: nemotronh: the drafter's dflash_config is not LiLiCorr's " + "(lilicorr_enabled and attention_sink_bias)\n"); + return RAD_E_UNSUPPORTED; + } + const double escale = dc_f("input_embedding_scale", 1.0); + if (escale != 1.0) { + fprintf(stderr, "radiance: nemotronh: LiLiCorr scaling its input embedding by %g is not " + "implemented\n", escale); + return RAD_E_UNSUPPORTED; + } + LiliCorr::Config lc{}; + lc.steps = dc.steps(); + lc.k = dc_i("lilicorr_candidate_topk", 8); + lc.hs = dc_i("lilicorr_hidden_size", 1024); + lc.n_head = dc_i("lilicorr_num_heads", 8); + lc.n_layer = dc_i("lilicorr_num_layers", 2); + lc.mlp = (int64_t)std::llround((double)lc.hs * dc_f("lilicorr_mlp_ratio", 2.0)); + lc.fdim = dc_i("lilicorr_factor_dim", 1024); + lc.eps = dg.eps; + lc.vec_eps = dc_f("lilicorr_vector_eps", 1e-4); + lc.scale = dc_f("lilicorr_logit_scale", 8.0); + if (lc.k < 2 || lc.k > 64 || (lc.k & (lc.k - 1)) || lc.steps * lc.k > 64 || + lc.hs % lc.n_head || lc.hs / lc.n_head > 128) { + fprintf(stderr, "radiance: nemotronh: LiLiCorr's lattice (%lld positions of %lld, %lld " + "heads over %lld) is outside what lili_attn serves\n", + (long long)lc.steps, (long long)lc.k, (long long)lc.n_head, (long long)lc.hs); + return RAD_E_UNSUPPORTED; + } + + RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, &m.kv_draft)); + + const int64_t qd = dg.n_head * dg.head_dim; + const int64_t kvd = dg.n_head_kv * dg.head_dim; + int64_t qr = dg.max_seqs * dc.block; + if (qr > dg.max_tok) qr = dg.max_tok; + const int64_t sr = dg.max_seqs * dc.steps(); + const int64_t lr = sr * lc.k; + const int64_t E = dg.n_embd; + const uint32_t A = dg.act_dtype; + + Dflash2::Wire& dw = m.dfw; + dw.src = m.dfsrc; + /* PERSIST: the context pass writes it, the next query pass reads the anchor's row from it, + * so no transient may share it in between. */ + dw.c = decl_b(b, nm.f("df_c"), A, {dg.max_tok, E}, RAD_BUF_PERSIST); + dw.ck = decl_b(b, nm.f("df_ck"), A, {dg.max_tok, kvd}); + dw.cv = decl_b(b, nm.f("df_cv"), A, {dg.max_tok, kvd}); + dw.x = decl_b(b, nm.f("df_x"), A, {qr, E}); + dw.h = decl_b(b, nm.f("df_h"), A, {qr, E}); + dw.h2 = decl_b(b, nm.f("df_h2"), A, {qr, E}); + dw.coef = decl_b(b, nm.f("df_coef"), A, {qr, dc.coef_dim(E)}); + dw.q = decl_b(b, nm.f("df_q"), A, {qr, qd}); + dw.k = decl_b(b, nm.f("df_k"), A, {qr, kvd}); + dw.v = decl_b(b, nm.f("df_v"), A, {qr, kvd}); + dw.attn = decl_b(b, nm.f("df_attn"), A, {qr, qd}); + dw.gate_up = decl_b(b, nm.f("df_gate_up"), A, {qr, 2 * dg.n_ff}); + dw.ffn = decl_b(b, nm.f("df_ffn"), A, {qr, dg.n_ff}); + dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * E}); + dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(dc.n_taps * E)}); + dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, E}); + dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(E)}); + dw.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, E}); + dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(E)}); + dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd}); + dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)}); + dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff}); + dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)}); + dw.sel_h = decl_b(b, nm.f("df_selh"), A, {sr, E}); + /* The proposal buffer (RadDrafterDecl::proposal), written by the walk. */ + dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()}); + RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.token, "draft", + nm.ckpt("language_model.lm_head.weight"), dw)); + + LiliCorr::Wire& lw = m.lw; + const int64_t sw = 2 + 2 * LiliCorr::row_k(lc.k); + lw.sel_h = dw.sel_h; + lw.c = dw.c; + lw.tokens = dw.tokens; + lw.logits = decl_b(b, nm.f("lili_logits"), RAD_F32, {sr, dg.n_vocab}); + lw.stats = decl_b(b, nm.f("lili_stats"), RAD_F32, {sr, sw}); + if (dg.world > 1) + lw.sgath = decl_b(b, nm.f("lili_sgath"), RAD_F32, {sr, (int64_t)dg.world * sw}); + lw.pas = decl_b(b, nm.f("lili_pas"), A, {sr, lc.hs}); + lw.cand = decl_b(b, nm.f("lili_cand"), RAD_I32, {lr}); + lw.feat = decl_b(b, nm.f("lili_feat"), A, {lr, lc.hs}); + lw.hh = decl_b(b, nm.f("lili_hh"), A, {lr, lc.hs}); + lw.emb = decl_b(b, nm.f("lili_emb"), A, {lr, E}); + lw.y = decl_b(b, nm.f("lili_y"), A, {lr, lc.hs}); + lw.qkv = decl_b(b, nm.f("lili_qkv"), A, {lr, 3 * lc.hs}); + lw.att = decl_b(b, nm.f("lili_att"), A, {lr, lc.hs}); + lw.up = decl_b(b, nm.f("lili_up"), A, {lr, lc.mlp}); + lw.ups = decl_b(b, nm.f("lili_ups"), A, {lr, lc.mlp}); + lw.cat = decl_b(b, nm.f("lili_cat"), A, {lr, 3 * lc.hs}); + lw.fh = decl_b(b, nm.f("lili_fh"), A, {lr, lc.hs}); + lw.fhs = decl_b(b, nm.f("lili_fhs"), A, {lr, lc.hs}); + lw.edges = decl_b(b, nm.f("lili_edges"), A, {lr, 2 * lc.fdim}); + lw.anc = decl_b(b, nm.f("lili_anc"), A, {dg.max_seqs, E}); + lw.ast = decl_b(b, nm.f("lili_ast"), A, {dg.max_seqs, lc.hs}); + lw.an = decl_b(b, nm.f("lili_an"), A, {dg.max_seqs, lc.hs}); + lw.aout = decl_b(b, nm.f("lili_aout"), A, {dg.max_seqs, lc.fdim}); + RAD_ARCH_TRY(m.lili.declare(b, nm, dg, lc, m.head, m.token, "draft", lw)); + m.have_df = true; + + RadDrafterDecl drf{}; + drf.name = "lilicorr"; + drf.kind = RAD_DRAFT_BLOCK; + drf.depth = ctx->max_spec; + drf.block = dc.block; + drf.proposal = dw.tokens; + drf.proposal_pitch = dc.steps(); + drf.window = dc.window; + drf.mask_token = (int32_t)dc_i("mask_token_id", -1); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: nemotronh: the LiLiCorr checkpoint declares no " + "dflash_config.mask_token_id\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + rad_note(b, "LiLiCorr drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv%s x %lld " + "with sinks, ffn %lld, %s attention with a %lld-token window, %d trunk taps; a " + "%lld x %lld candidate lattice proposes %lld tokens", + (long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, + (long long)dg.n_head, (long long)dg.n_head_kv, + dg.world > dg.n_head_kv_all ? " (replicated)" : "", (long long)dg.head_dim, + (long long)dg.n_ff, dc.causal ? "causal" : "non-causal", (long long)dc.window, + m.n_taps, (long long)lc.steps, (long long)lc.k, (long long)dc.steps()); + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS) + return RAD_E_INVAL; + const int world = ctx->world_size ? ctx->world_size : 1; + auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank]; + slot = std::make_unique(); + auto& m = *slot; + auto& g = m.g; + auto& s = m.s; + m.nm = Names(ctx->scope); + auto& nm = m.nm; + RAD_ARCH_TRY(read_shape(meta, s)); + if (world != 1 && world != 2 && world != 4) { + fprintf(stderr, "radiance: nemotronh: --tp %d; the head and expert splits are built for 1, " + "2 or 4 ranks\n", world); + return RAD_E_UNSUPPORTED; + } + if (s.heads % world || s.groups % world || (s.heads / world * s.head_dim) % Mamba::kNormGroup) { + fprintf(stderr, "radiance: nemotronh: %lld Mamba heads in %lld groups do not split over %d " + "ranks in whole groups of the gated norm\n", + (long long)s.heads, (long long)s.groups, world); + return RAD_E_UNSUPPORTED; + } + if (ctx->max_spec > 31) { + fprintf(stderr, "radiance: nemotronh: the Mamba-2 verify pass keeps at most 32 records a " + "sequence, so --num-speculative-tokens is at most 31\n"); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(geom_from(g, meta, ctx, "bf16", RAD_BF16)); + + /* Each routed layer's experts: its own count and width; the slice of each expert this rank + * holds, even, or by slice_of at four ranks (2, 2, 1, 1 of six blocks, by number mod 4). */ + std::vector msrc((size_t)s.n_layer); + bool calib = calib_dir() != nullptr, any_bf16 = false; + for (int l = 0; l < (int)s.n_layer; ++l) { + if (s.kind[(size_t)l] != kMoe) continue; + const char* pre = nm.ckpt("language_model.backbone.layers.%d.mixer", l); + MoeFP8::Src& ms = msrc[(size_t)l]; + MoeFP8::Config& c = ms.cfg; + const int64_t ne = s.experts[(size_t)l], ff = s.ff[(size_t)l]; + c.n_expert = c.n_expert_all = ne; + c.top_k = s.top_k[(size_t)l]; + c.sigmoid_router = 1; + c.route_scale = s.route_scale; + c.norm_topk = cfg(meta, "norm_topk_prob", 1) != 0; + c.ungated = 1; + c.router_k = g.n_embd; + c.no_reduce = 1; + c.rows = g.max_tok; + /* RADIANCE_CALIB_LAYERS splits the calibration over runs (calib_layer_on). */ + c.calib = calib && calib_layer_on(l) ? 1 : 0; + c.probed_expert = (int64_t)g.rank * (ne / world); + const int64_t eb = ff / RAD_FP8_BLOCK; + if (eb % world == 0) { + c.n_ff_exp = ff / world; + } else if (world == 4) { + int64_t widest = 0; + for (int q = 0; q < 4; ++q) { + int64_t lo, hi; + slice_of(eb, world, g.rank, q, &lo, &hi); + c.ff_lo4[q] = lo * RAD_FP8_BLOCK; + c.ff_hi4[q] = hi * RAD_FP8_BLOCK; + widest = std::max(widest, c.ff_hi4[q] - c.ff_lo4[q]); + } + c.n_ff_exp = widest; + } else { + fprintf(stderr, "radiance: nemotronh: layer %d's experts of %lld do not split over %d " + "ranks in 128-column blocks\n", l, (long long)ff, world); + return RAD_E_UNSUPPORTED; + } + ms.router = nm.ckpt("%s.gate.weight", pre); + ms.router_bias = nm.ckpt("%s.gate.e_score_correction_bias", pre); + ms.experts = nm.ckpt("%s.experts", pre); + RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, ms, &c)); + any_bf16 = any_bf16 || c.expert_bf16; + } + /* Whole experts per rank for a calibration run and for bf16 experts: rank r owns experts + * [r E/W, (r+1) E/W) of each layer. */ + if (world > 1 && (calib || any_bf16)) + for (int l = 0; l < (int)s.n_layer; ++l) { + if (s.kind[(size_t)l] != kMoe) continue; + auto& c = msrc[(size_t)l].cfg; + int64_t per = 0; + RAD_ARCH_TRY(divide_or_fail(c.n_expert_all, world, "n_routed_experts", &per)); + c.n_expert = per; + c.expert_base = (int64_t)g.rank * per; + c.n_ff_exp = s.ff[(size_t)l]; + for (int q = 0; q < 4; ++q) c.ff_lo4[q] = c.ff_hi4[q] = 0; + } + /* The shared expert's slice: even, or slice_of's whole blocks. */ + int64_t sh_lo = 0, sh_hi = 0, sh_w = s.ff_shared / world; + { + const int64_t sb = s.ff_shared / RAD_FP8_BLOCK; + if (sb % world) { + slice_of(sb, world, g.rank, 0, &sh_lo, &sh_hi); + sh_lo *= RAD_FP8_BLOCK; + sh_hi *= RAD_FP8_BLOCK; + sh_w = sh_hi - sh_lo; + } + } + RAD_ARCH_TRY(buffers(b, m)); + RAD_ARCH_TRY(moe_buffers(b, m, msrc, sh_w)); + { + RadKVGroupDecl d{}; + d.kind = RAD_KV_FULL; + d.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + d.n_head_kv = g.n_head_kv; + d.head_dim = g.head_dim; + m.kv_attn = rad_decl_kv_group(b, nm.f("kv_attn"), &d); + g.kv_dtype = rad_dtype_name(d.dtype); + d = {}; + d.kind = RAD_KV_LINEAR; + d.dtype = RAD_F32; + d.n_head_kv = s.heads / world; + d.state_dim[0] = s.head_dim; + d.state_dim[1] = s.state; + m.kv_state = rad_decl_kv_group(b, nm.f("kv_ssm"), &d); + d = {}; + d.kind = RAD_KV_CONV; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.head_dim = (s.heads * s.head_dim + 2 * s.groups * s.state) / world; + d.conv_width = s.conv; + m.kv_conv = rad_decl_kv_group(b, nm.f("kv_ssm_conv"), &d); + if (!m.kv_attn || !m.kv_state || !m.kv_conv) return RAD_E_INVAL; + } + + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), + nm.ckpt("language_model.backbone.embeddings.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("language_model.lm_head.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), + nm.ckpt("language_model.backbone.norm_f.weight"))); + 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.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, g.n_embd }, RAD_ACCESS_VOCAB, + RAD_SHARD_ROW, grp_model()); + m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, 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", "bf16"), + RAD_INT("vocab_offset", g.vocab_off)), + RAD_WEIGHTS(m.token)), + {}, { m.x }); + /* Exact: each token's embedding comes from one rank and the others add zero. */ + m.embed_ar = reduce(b, g, m.x, true); + /* Images and video: the tower's rows replace their placeholders' embeddings before that + * reduction (rank 0 carries them, the others zeros). Its weight groups follow the layers'. */ + RAD_ARCH_TRY(m.radio.declare(b, meta, ctx, nm, g.n_embd, (int)s.n_layer)); + if (m.radio.on) RAD_ARCH_TRY(m.media.declare(b, g.max_tok, g.n_embd, m.x)); + + /* LiLiCorr's taps, only when the container carries the drafter and the deployment speculates: + * the residual stream after each block `target_layer_ids` names (vLLM's aux layer id + 1, the + * output of that block), copied into its column slice of `dfsrc` by `cast`. */ + if (ctx->max_spec > 0) { + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "LiLiCorr")) { + m.n_taps = parse_layer_ids( + rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr), s.n_layer, + m.tap_layer, Model::MAX_TAPS); + if (m.n_taps <= 0) { + fprintf(stderr, "radiance: nemotronh: the LiLiCorr drafter names no trunk layer " + "this model has (dflash_config.target_layer_ids)\n"); + return RAD_E_UNSUPPORTED; + } + m.dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, + { g.max_tok, (int64_t)m.n_taps * g.n_embd }); + m.op_tap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.x }, { m.dfsrc }); + if (!m.dfsrc || !m.op_tap) return RAD_E_INVAL; + } + } + + m.layers.resize((size_t)s.n_layer); + for (int l = 0; l < (int)s.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.kind = s.kind[(size_t)l]; + const char* pre = nm.ckpt("language_model.backbone.layers.%d", l); + const char* mx = nm.ckpt("%s.mixer", pre); + if (lay.kind == kAttn) { + AttnFP8::Src as{}; + as.norm = nm.ckpt("%s.norm.weight", pre); + as.q = nm.ckpt("%s.q_proj.weight", mx); + as.k = nm.ckpt("%s.k_proj.weight", mx); + as.v = nm.ckpt("%s.v_proj.weight", mx); + as.o = nm.ckpt("%s.o_proj.weight", mx); + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn)); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, l, m.kv_attn, 0, m.aw, as)); + continue; + } + const char* nn = nm.f(lay.kind == kMoe ? "blk.%d.ffn_norm.weight" : "blk.%d.attn_norm.weight", + l); + RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.norm.weight", pre))); + lay.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(l)); + RAD_ARCH_TRY(lay.norm.declare(b, g, lay.gain, m.x, m.act, g.n_embd)); + if (lay.kind == kMamba) { + RAD_ARCH_TRY(lay.mamba.declare(b, nm, g, s, l, m.mw, mx, m.kv_state, m.kv_conv)); + } else { + LatentMoe::Wire ew = m.ew; + const MoeFP8::Config& c = msrc[(size_t)l].cfg; + ew.moe = m.classes[std::make_pair(c.n_expert_all, c.n_ff_exp)]; + RAD_ARCH_TRY(lay.moe.declare(b, nm, g, s, l, ew, mx, msrc[(size_t)l], sh_lo, sh_hi, + sh_w)); + } + lay.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", "bf16")), + RAD_NOWEIGHTS), + { m.x, m.y }, { m.x }); + if (!lay.op_add) return RAD_E_INVAL; + } + m.norm = 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_STR("dtype", "bf16")), + RAD_WEIGHTS(m.final_gain)), + { m.x }, { m.final_hidden }); + 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", "bf16")), + RAD_NOWEIGHTS), + { m.final_hidden }, { m.logit_input }); + m.head_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", "bf16")), + RAD_WEIGHTS(m.head)), + { m.logit_input }, { m.logits }); + if (!m.embed || !m.norm || !m.gather || !m.head_op) return RAD_E_INVAL; + if (m.n_taps > 0) RAD_ARCH_TRY(declare_lilicorr(b, meta, ctx, m, (int)s.n_layer)); + int64_t n_m = 0, n_e = 0, n_a = 0; + for (Kind k : s.kind) (k == kMamba ? n_m : k == kMoe ? n_e : n_a) += 1; + rad_note(b, + "Nemotron-H (nemotronh): TP%d, %lld blocks: %lld Mamba-2, %lld latent MoE, %lld NoPE " + "attention; experts %s", + world, (long long)s.n_layer, (long long)n_m, (long long)n_e, (long long)n_a, + world > 1 && (calib || any_bf16) ? "whole per rank" : "sliced per rank"); + return RAD_OK; +} + +/* ------------------------------------------------------------------ step */ +/* RADIANCE_DEBUG_NEMOTRONH_DUMP=DIR: the residual stream after each block, every row of every + * step, as `/s.t.l.r.bf16` ([rows, n_embd] bf16). A diagnostic for + * comparing against a reference model block by block; it synchronises the stream. */ +static void dump(RadCtx* c, const RadBatch* batch, rad_buf x, int64_t E, int layer) { + static const char* dir = std::getenv("RADIANCE_DEBUG_NEMOTRONH_DUMP"); + if (!dir || !*dir) return; + const int64_t T = batch->n_tok; + void* p = rad_buf_ptr(c, x); + if (!p) return; + std::vector h((size_t)(T * E)); + if (rad_memcpy_async(h.data(), p, T * E * 2, rad_stream(c)) < 0) return; + rad_stream_sync(rad_stream(c)); + char path[512]; + std::snprintf(path, sizeof path, "%s/s%d.t%lld.l%d.r%d.bf16", dir, batch->step, (long long)T, + layer, rad_rank(c)); + if (FILE* f = std::fopen(path, "wb")) { + std::fwrite(h.data(), 2, h.size(), f); + std::fclose(f); + } +} + +/* The drafter's side of the same diagnostic, `/d..r.`: on its query + * pass the batch's tokens (the anchor, then the masks) and anchor rows, the context pass's normed + * fc rows `c` (still the last context pass's), the draft rows `selh`, the candidates and the + * proposal. With the trunk step's per-block dumps (the taps) a reference recomputes the pass. */ +static void dump_draft(RadCtx* c, const RadBatch* batch, const char* what, const void* p, + int64_t bytes, const char* dt) { + static const char* dir = std::getenv("RADIANCE_DEBUG_NEMOTRONH_DUMP"); + if (!dir || !*dir || !p || bytes <= 0) return; + std::vector h((size_t)bytes); + if (rad_memcpy_async(h.data(), p, bytes, rad_stream(c)) < 0) return; + rad_stream_sync(rad_stream(c)); + char path[512]; + std::snprintf(path, sizeof path, "%s/d%d.%s.r%d.%s", dir, batch->step, what, rad_rank(c), dt); + if (FILE* f = std::fopen(path, "wb")) { + std::fwrite(h.data(), 1, h.size(), f); + std::fclose(f); + } +} + +static void step(RadCtx* c, const RadBatch* batch) { + auto& m = *models[rad_rank(c)]; + const int64_t T = batch->n_tok, E = m.g.n_embd; + if (batch->enc) { + m.radio.step(c, batch); + return; + } + /* A drafter pass runs only the drafter: positive is LiLiCorr's query pass (the backbone, then + * the correlator over its draft rows), negative its context pass over the rows the trunk step + * just ran, whose taps are in `dfsrc`. */ + if (batch->draft_pass) { + if (!m.have_df) { + rad_step_fail(c, "nemotronh: a drafter pass, and no drafter is declared (the container " + "carries none, or the deployment does not speculate)"); + return; + } + if (batch->draft_pass > 0) { + const int64_t n = batch->n_seq, S = n * m.lili.cfg.steps, E = m.g.n_embd; + m.df.step(c, batch); + /* Before the correlator: `selh` is dead after its last read there, and the arena may + * hand its bytes to a later op (at four ranks it does). */ + dump_draft(c, batch, "selh", rad_buf_ptr(c, m.dfw.sel_h), S * E * 2, "bf16"); + m.lili.step(c, batch); + dump_draft(c, batch, "tok", batch->token_ids, batch->n_tok * 4, "i32"); + dump_draft(c, batch, "arow", batch->anchor_rows, n * 4, "i32"); + dump_draft(c, batch, "c", rad_buf_ptr(c, m.dfw.c), m.g.max_tok * E * 2, "bf16"); + dump_draft(c, batch, "cand", rad_buf_ptr(c, m.lw.cand), S * m.lili.cfg.k * 4, "i32"); + dump_draft(c, batch, "tokens", rad_buf_ptr(c, m.dfw.tokens), S * 4, "i32"); + } else { + m.df.context(c, batch); + } + return; + } + RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T)); + m.media.step(c, batch, m.x, T); + if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * E, brows(m.x, T), RAD_NONE); + for (const auto& l : m.layers) { + if (l.kind == kAttn) { + l.attn.step(c, batch); + } else { + l.norm.step(c, T); + if (l.kind == kMamba) + l.mamba.step(c, batch); + else + l.moe.step(c, batch); + RAD_ISSUE_N(c, l.op_add, T, brows(m.x, T), brows(m.y, T), brows(m.x, T)); + } + const int li = (int)(&l - m.layers.data()); + dump(c, batch, m.x, E, li); + /* The drafter's taps: this block's output, which the next block overwrites. */ + for (int t = 0; t < m.n_taps; ++t) + if (m.tap_layer[t] == li) + RAD_ISSUE(c, m.op_tap, brows(m.x, T), bcol(m.dfsrc, (int64_t)t * E, E, T)); + } + RAD_ISSUE_N(c, m.norm, T, brows(m.x, T), RAD_W(m.final_gain), brows(m.final_hidden, T)); + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.final_hidden, T), + praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.logit_input, batch->n_out)); + RAD_ISSUE_N(c, m.head_op, batch->n_out, brows(m.logit_input, batch->n_out), RAD_W(m.head), + brows(m.logits, batch->n_out)); + } +} +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->shape_probe_ok = 1; + /* LiLiCorr proposes exactly its trained block less the anchor. */ + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "LiLiCorr")) { + const long long bs = rad_meta_geti(meta, "draft.block_size", + rad_meta_geti(meta, "draft.dflash_config.block_size", 8)); + out->draft_depth = bs > 1 ? (int)(bs - 1) : 7; + out->draft_depth_fixed = 1; + } + /* The vision encoder's rows per output row, so a pass bound is whole merged rows. */ + if (Radio::present(meta)) { + const double r = rad_meta_getf(meta, "downsample_ratio", 0.0); + const int64_t mg = r > 0.0 ? (int64_t)std::llround(1.0 / r) : 0; + out->enc_merge = mg * mg; + } + return RAD_OK; +} +} // namespace nemotronh +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(nemotronh) +RAD_ARCH_PLUGIN(nemotronh, "nemotronh", "", "0.1.0", + "Nemotron-H (nemotron_h_omni/puzzle): Mamba-2, latent relu^2 MoE and NoPE attention") +#endif diff --git a/arch/nemotronh/radio.h b/arch/nemotronh/radio.h new file mode 100644 index 00000000..edea3261 --- /dev/null +++ b/arch/nemotronh/radio.h @@ -0,0 +1,348 @@ +/* radio.h -- Nemotron-H Omni's vision encoder: C-RADIO (v4-H) and the projector after it (mlp1). + * + * Per encoder pass (RadBatch::enc). The processor (core/mm, Family::Radio) gives every segment + * `n_prefix` zero rows ahead of its patches, with coordinate (-1, k): + * + * x = rows @ W^T one GEMM for both projections: a row is a + * tubelet's frames then a picture's patch, the part + * not in use zero, and W = [video_embedder | + * embedder] concatenated at convert; no bias + * x += CPE(table, row, col), or prefix[k] grid_embed_cpe: the 128 x 128 table resampled + * half-pixel bilinear onto a square of the grid's + * longer side and cropped to it; a prefix row takes + * the k-th class or register token + * depth times (pre-norm, LayerScale 1): + * x += proj(attn(qkv(LN1(x)))) full attention within a segment, no rotary + * x += fc2(gelu(fc1(LN2(x)))) exact GELU + * y = each segment's patch rows gather_rows: the prefix rows dropped + * out = l2(relu(l1(rms(y viewed [P/4, 4 * width])))^2) + * + * which is transformers' RadioModel (make_preprocessor_external) then NemotronH_Omni's vision + * projector with vision_final_layernorm off. The pixel shuffle (ps v2) is the view: the processor + * keeps a 2 x 2 block's patches consecutive, (dy, dx), the order the shuffle concatenates them; + * the tower is order-independent within a segment (attention is permutation-equivariant, every + * other layer is per row, the position term is sampled at each row's own coordinate). + * + * A pass is one grid (RadEncoderDecl::one_grid), so its segments are equally long and each + * segment's patch rows sit at a fixed offset, which `step` gathers with slices of one identity + * index. Replicated, per-request weights and pass-sized activations, as in + * arch/common/rad_block_vit.h's tower. + */ +#ifndef NEMOTRONH_RADIO_H +#define NEMOTRONH_RADIO_H + +#include + +#include +#include +#include +#include + +namespace nemotronh { + +using namespace rad::arch; + +struct Radio { + int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, merge = 0, side = 0, npre = 0; + int64_t tubelet = 0, head_dim = 0, patch_dim = 0, proj_hidden = 0, n_embd = 0, P = 0, R = 0; + float eps = 1e-6f; + bool on = false; + + struct Layer { + rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0; + rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0; + rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0; + rad_op ln1 = 0, qkv = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0; + }; + std::vector L; + rad_weight w_patch = 0, w_pos = 0, w_pre = 0, mn_w = 0, m1_w = 0, m2_w = 0; + rad_op op_patch = 0, op_pos = 0, op_seq = 0, op_gather = 0, op_mln = 0, op_m1 = 0; + rad_op op_act = 0, op_m2 = 0; + rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_seq = 0, b_g = 0, b_mn = 0; + rad_buf b_mf = 0, b_ma = 0, b_out = 0; + + /* A tower to declare: the container is a Nemotron-H Omni one, whose vision_config is RADIO's. */ + static bool present(const RadModelMeta* m) { + return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "radio") && + rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0; + } + + int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, + int64_t model_embd, int first_group); + void step(RadCtx* c, const RadBatch* batch) const; +}; + +inline int Radio::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, + int64_t model_embd, int first_group) { + on = false; + if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK; + + depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0); + width = rad_meta_geti(m, "vision_config.hidden_size", 0); + heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0); + ff = (int64_t)std::llround(rad_meta_getf(m, "vision_config.mlp_ratio", 0.0) * (double)width); + patch = rad_meta_geti(m, "vision_config.patch_size", 0); + eps = (float)rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-6); + side = rad_meta_geti(m, "vision_config.max_img_size", 0) / (patch > 0 ? patch : 1); + npre = rad_meta_geti(m, "vision_config.num_cls_tokens", 0) + + rad_meta_geti(m, "vision_config.num_registers", 0); + tubelet = rad_meta_geti(m, "vision_config.video_temporal_patch_size", + rad_meta_geti(m, "video_temporal_patch_size", 0)); + const double ratio = rad_meta_getf(m, "downsample_ratio", 0.0); + merge = ratio > 0.0 ? (int64_t)std::llround(1.0 / ratio) : 0; + proj_hidden = rad_meta_geti(m, "projector_hidden_size", 0); + n_embd = model_embd; + const int64_t chans = rad_meta_geti(m, "vision_config.num_channels", 3); + if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || side <= 0 || + npre <= 0 || tubelet <= 0 || merge <= 0 || proj_hidden <= 0 || width % heads || + chans != 3) { + fprintf(stderr, "radiance: nemotronh: the container's RADIO vision_config is incomplete or " + "inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, " + "table %lld, prefix %lld, tubelet %lld, merge %lld, projector %lld)\n", + (long long)depth, (long long)width, (long long)heads, (long long)ff, + (long long)patch, (long long)side, (long long)npre, (long long)tubelet, + (long long)merge, (long long)proj_hidden); + return RAD_E_INVAL; + } + /* What this tower serves of RADIO's options: the plain GELU MLP, LayerScale 1 (no stored + * scales), q/k/v with biases, and no final layer norm before the projector. */ + const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu"); + const bool swiglu = rad_meta_geti(m, "vision_config.use_swiglu_ffn", 0) != 0 || + !std::strcmp(rad_meta_gets(m, "vision_config.use_swiglu_ffn", ""), "true"); + const bool final_ln = rad_meta_geti(m, "vision_final_layernorm", 0) != 0 || + !std::strcmp(rad_meta_gets(m, "vision_final_layernorm", ""), "true"); + if (std::strcmp(act, "gelu") || swiglu || final_ln || + rad_meta_getf(m, "vision_config.layerscale_value", 1.0) != 1.0) { + fprintf(stderr, "radiance: nemotronh: this RADIO tower (activation '%s'%s%s, layer scale " + "%g) is not the one served: GELU MLP, layer scale 1, no final layer norm\n", + act, swiglu ? ", SwiGLU" : "", final_ln ? ", final layer norm" : "", + rad_meta_getf(m, "vision_config.layerscale_value", 1.0)); + return RAD_E_UNSUPPORTED; + } + head_dim = width / heads; + const int64_t pp = chans * patch * patch; + patch_dim = pp * (1 + tubelet); + const int64_t mm = merge * merge, mw = mm * width; + + /* A pass's rows, prefix rows included; the output rows are at most a quarter of them. */ + P = ctx->max_enc_patches; + const int64_t max_seg = P; + if (ctx->shape_probe) { + const int64_t r = std::min(P, ctx->max_tok); + P = std::max(mm, r / mm * mm); + } + R = P / mm; + if (R <= 0) return RAD_E_SHAPE; + const int ACC = RAD_ACCESS_PER_REQUEST; + + auto bw = [&](const char* dn, const char* src, std::initializer_list shp, + RadWeightGroup g) -> rad_weight { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g); + }; + const char* pg = "vision_model.radio_model.model.patch_generator."; + /* [video_embedder | embedder] along K: one GEMM for a row of either kind. */ + if (map_concat(b, nm.f("v.patch.weight"), + { nm.ckpt("%svideo_embedder.weight", pg), nm.ckpt("%sembedder.weight", pg) }, + 1) < 0) + return RAD_E_INVAL; + /* Whether the tower is here at all: its stem's encoding, which convert answers from the + * checkpoint and load from the container alike. A text-only cut (a few blocks for a host + * reference) or a container converted without it serves text; the map left behind is inert. */ + { + RadEncoding enc; + if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) { + rad_note(b, "nemotronh: vision_config names a RADIO tower its weights are not here " + "for; serving text"); + return RAD_OK; + } + } + w_patch = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim }, ACC, + RAD_SHARD_NONE, grp_model()); + /* The checkpoint's [1, side * side, width] read as the [side * side, width] table. */ + w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%spos_embed", pg), { side * side, width }, grp_model()); + w_pre = bw(nm.f("v.prefix.weight"), nm.ckpt("%scls_token.token", pg), { npre, width }, + grp_model()); + L.assign((size_t)depth, Layer{}); + for (int64_t i = 0; i < depth; ++i) { + Layer& l = L[(size_t)i]; + const RadWeightGroup g = grp_layer(first_group + (int)i); + const int li = (int)i; + const char* e = "vision_model.radio_model.model.blocks.%d.%s"; + l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt(e, li, "norm1.weight"), { width }, g); + l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt(e, li, "norm1.bias"), { width }, g); + l.qkv_w = bw(nm.f("v.blk.%d.qkv.weight", li), nm.ckpt(e, li, "attn.qkv.weight"), { 3 * width, width }, g); + l.qkv_b = bw(nm.f("v.blk.%d.qkv.bias", li), nm.ckpt(e, li, "attn.qkv.bias"), { 3 * width }, g); + l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt(e, li, "attn.proj.weight"), { width, width }, g); + l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt(e, li, "attn.proj.bias"), { width }, g); + l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, li, "norm2.weight"), { width }, g); + l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt(e, li, "norm2.bias"), { width }, g); + l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt(e, li, "mlp.fc1.weight"), { ff, width }, g); + l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt(e, li, "mlp.fc1.bias"), { ff }, g); + l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt(e, li, "mlp.fc2.weight"), { width, ff }, g); + l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt(e, li, "mlp.fc2.bias"), { width }, g); + if (!l.n1w || !l.n1b || !l.n2w || !l.n2b || !l.qkv_w || !l.qkv_b || !l.out_w || + !l.out_b || !l.up_w || !l.up_b || !l.down_w || !l.down_b) + return RAD_E_INVAL; + } + mn_w = bw(nm.f("v.proj.norm.weight"), nm.ckpt("mlp1.0.weight"), { mw }, grp_model()); + m1_w = bw(nm.f("v.proj.fc1.weight"), nm.ckpt("mlp1.1.weight"), { proj_hidden, mw }, grp_model()); + m2_w = bw(nm.f("v.proj.fc2.weight"), nm.ckpt("mlp1.3.weight"), { n_embd, proj_hidden }, grp_model()); + if (!w_patch || !w_pos || !w_pre || !mn_w || !m1_w || !m2_w) return RAD_E_INVAL; + + /* ---- activations. `g` holds the gathered patch rows at `width` and is read by the norm as + * R rows of mm * width (the pixel shuffle's view, no copy). */ + b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width }); + b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width }); + b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width }); + b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width }); + b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff }); + b_seq = decl_b(b, nm.f("v.seq"), RAD_I32, { P }); + b_g = decl_b(b, nm.f("v.g"), RAD_BF16, { R, mw }); + b_mn = decl_b(b, nm.f("v.mn"), RAD_BF16, { R, mw }); + b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, proj_hidden }); + b_ma = decl_b(b, nm.f("v.ma"), RAD_BF16, { R, proj_hidden }); + b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd }); + if (!b_x || !b_h || !b_qkv || !b_att || !b_ff || !b_seq || !b_g || !b_mn || !b_mf || !b_ma || + !b_out) + return RAD_E_INVAL; + + auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w, + rad_weight bias) -> rad_op { + return RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16"), RAD_STR("act", a)), + RAD_WEIGHTS(w, bias)); + }; + auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op { + return RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto lnorm = [&](int64_t rows, rad_weight w, rad_weight bias) -> rad_op { + return RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + }; + + op_patch = rw(b, gemm(P, width, patch_dim, w_patch), {}, { b_x }); + op_pos = rw(b, RAD_OP(b, "grid_embed_cpe", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), + RAD_INT("side", side), RAD_INT("n_prefix", npre), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_pos, w_pre)), + { b_x }, { b_x }); + op_seq = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("start", 0), RAD_INT("step", 1)), + RAD_NOWEIGHTS), + {}, { b_seq }); + for (Layer& l : L) { + l.ln1 = rw(b, lnorm(P, l.n1w, l.n1b), { b_x }, { b_h }); + l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv }); + l.attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)), + RAD_INT("max_seqlen", max_seg)), + RAD_NOWEIGHTS), + { b_qkv }, { b_att }); + l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x }); + l.ln2 = rw(b, lnorm(P, l.n2w, l.n2b), { b_x }, { b_h }); + l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff }); + l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x }); + } + op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_x, b_seq }, { b_g }); + op_mln = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", mw), RAD_F64("eps", 1e-5), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(mn_w)), + { b_g }, { b_mn }); + op_m1 = rw(b, gemm(R, proj_hidden, mw, m1_w), { b_mn }, { b_mf }); + /* relu(x)^2: act_mul's "relu" with the one tensor in both operands. */ + op_act = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_hidden), + RAD_STR("act", "relu"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_mf }, { b_ma }); + op_m2 = rw(b, gemm(R, n_embd, proj_hidden, m2_w), { b_ma }, { b_out }); + + if (!ctx->shape_probe) { + RadEncoderDecl e{}; + e.name = "vision"; + e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO; + e.patch_dim = patch_dim; + e.merge = mm; + e.max_patches = P; + e.n_embd = n_embd; + e.out = b_out; + e.one_grid = 1; + RAD_ARCH_TRY(rad_declare_encoder(b, &e)); + rad_note(b, "RADIO tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld " + "(tubelet %lld), %lld x %lld position table, %lld prefix rows; projector %lld " + "-> %lld -> %lld; %lld rows a pass", + (long long)depth, (long long)width, (long long)heads, (long long)head_dim, + (long long)ff, (long long)patch, (long long)tubelet, (long long)side, + (long long)side, (long long)npre, (long long)mw, (long long)proj_hidden, + (long long)n_embd, (long long)P); + } + on = true; + return RAD_OK; +} + +inline void Radio::step(RadCtx* c, const RadBatch* batch) const { + const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg; + const int64_t mm = merge * merge; + const int64_t gh = S > 0 && batch->enc_seg_h ? batch->enc_seg_h[0] : 0; + const int64_t gw = S > 0 && batch->enc_seg_w ? batch->enc_seg_w[0] : 0; + const int64_t seg = npre + gh * gw, Rn = S * gh * gw / (mm > 0 ? mm : 1); + if (!on || Pn <= 0 || Pn > P || S <= 0 || gh <= 0 || gw <= 0 || (gh * gw) % mm || + S * seg != Pn || Rn > R) { + rad_step_fail(c, "nemotronh: an encoder pass this program's RADIO tower cannot serve: no " + "tower, more rows than it was declared for, or segments that are not one " + "grid of whole merged rows behind their prefix rows"); + return; + } + const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim); + const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn); + const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1); + + RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn)); + RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd, RAD_W(w_pre)); + RAD_ISSUE_N(c, op_seq, Pn, brows(b_seq, Pn)); + for (const Layer& l : L) { + RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE, + brows(b_qkv, Pn)); + RAD_ISSUE_N(c, l.attn, Pn, + bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn), + bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn)); + RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b), + brows(b_x, Pn), brows(b_x, Pn)); + RAD_ISSUE_N(c, l.ln2, Pn, brows(b_x, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE, + brows(b_ff, Pn)); + RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b), + brows(b_x, Pn), brows(b_x, Pn)); + } + /* Each segment's patch rows, behind its prefix rows, into `g` at width: segment s's are rows + * [s * seg + npre, (s + 1) * seg) of x, which the identity index names by a slice. */ + const int64_t hw = gh * gw; + for (int64_t s = 0; s < S; ++s) + RAD_ISSUE_N(c, op_gather, hw, brows(b_x, Pn), brow_slice(b_seq, s * seg + npre, hw, 1), + brow_slice(b_g, s * hw / mm, hw / mm, mm * width)); + RAD_ISSUE_N(c, op_mln, Rn, brows(b_g, Rn), RAD_W(mn_w), brows(b_mn, Rn)); + RAD_ISSUE_N(c, op_m1, Rn, brows(b_mn, Rn), RAD_W(m1_w), brows(b_mf, Rn)); + RAD_ISSUE_N(c, op_act, Rn, brows(b_mf, Rn), brows(b_mf, Rn), brows(b_ma, Rn)); + RAD_ISSUE_N(c, op_m2, Rn, brows(b_ma, Rn), RAD_W(m2_w), brows(b_out, Rn)); +} + +} /* namespace nemotronh */ + +#endif /* NEMOTRONH_RADIO_H */ diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 3d95f5cf..dd33d470 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -19,6 +19,7 @@ plugin claims. | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert, or Qwen's FP8 release as it ships | | `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Pictures through its vision tower (`arch/common/rad_block_glm_vision.h`); bf16 KV | | `arch/bailing_hybrid` | `bailinghybrid` | *(empty)* | Ling-3.0-flash and its fine-tunes (Ling-3.0-flash-Sante) from the bf16 checkpoint: 35 KDA and 7 dense latent-attention (MLA) layers with a rotary part and a head-wise gate, 512 experts at top-8 under group-limited sigmoid routing with an ungated shared expert, the routed experts as the recipe stores them (`data/recipes/ling3-w4a8-rtn.recipe`); its MTP layer is a serial drafter; bf16 KV | +| `arch/nemotronh` | `nemotronh` | *(empty)* | Nemotron-3.5-Bolt-74B-A9B (`nemotron_h_omni` around `nemotron_h_puzzle`), its language model from the bf16 checkpoint: 40 Mamba-2, 40 latent-MoE and 8 NoPE attention blocks in the order `layers_block_type` gives, 240 to 496 ungated relu^2 experts a layer in a 1024-wide latent with a relu^2 shared expert; linears and experts as the recipe stores them (`data/recipes/nemotron74-fp8.recipe`, `nemotron74-w4nl64-gptq.recipe`); pictures and video through its C-RADIO tower (`arch/nemotronh/radio.h`); bf16 KV | | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank | | `arch/spark25_bf16` | `spark25` | *(empty)* | Spark X2.6, bf16 checkpoint, mixed sliding/full attention, TP1 or TP with exact collectives ([geometry](#spark25-spark-x26)). Optional DSpark drafter when the container already holds `draft.*` tensors, TP1 only. | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | @@ -2067,6 +2068,74 @@ same model and this engine 0.8%. The transcripts match word for word. --- +# `nemotronh`: Nemotron-3.5-Bolt-74B-A9B + +`arch/nemotronh` serves the language model of Nemotron-3.5-Bolt-74B-A9B (`model_type: +nemotron_h_omni`, NemotronH_Omni_Reasoning_V3; the text model is `llm_config`, `nemotron_h_puzzle`) +from the bf16 checkpoint. The reference is vLLM's `nemotron_h.py` and `mamba_mixer2.py`; NVIDIA's HF +`modeling_nemotron_h.py` agrees except for the CPU scan (below). The plugin reuses `MoeFP8` for the +routed arm and `AttnFP8` for attention; its Mamba-2 block and the latent feed-forward around +`MoeFP8` are in the plugin file. + +``` +88 blocks, hidden 4096, vocab 131072 (embedding and lm_head separate), RMS eps 1e-5; each block one + mixer behind its own norm and a residual add, the type from `layers_block_type` +40 Mamba-2: 128 heads of 64 in 8 groups, state 128 + in_proj 4096 -> z 8192 | x 8192 | B 1024 | C 1024 | dt 128, no bias + x|B|C through a causal depthwise conv of width 4 with bias, then SiLU + dt' = softplus(dt + dt_bias), unclamped; A = -exp(A_log); a D skip per head + y = scan(x, B, C, dt'); RMSNormGated: norm over groups of 1024 of y * silu(z), times 8192 gains + out_proj 8192 -> 4096 +40 latent MoE: router on the normed hidden state (sigmoid, a correction bias for the selection + only, one group, top-9, normalized, x5) + fc1_latent_proj 4096 -> 1024; routed experts in the latent, ungated: down(relu(up(x))^2); + per layer (`block_configs`) 240 to 496 experts of 1536 to 2560; fc2_latent_proj 1024 -> 4096 + one shared expert on the hidden state, 4096 -> 5376 -> 4096, relu^2 +8 attention: 32 query heads, 2 KV heads of 128, no position encoding +``` + +Traps: + +- **The layer count is not stated.** `llm_config` has no `num_hidden_layers`; HF derives it from + `block_configs`. The checkpoint reader counts `layers_block_type` when the key is absent, and + flattens the array of objects `block_configs` into `block_configs..`, from which the + plugin reads each routed layer's experts, width and top-k. +- **dt is not clamped.** `time_step_limit` is (0, inf), and vLLM passes exactly that to its scan. + HF's CPU path `torch_forward` clamps dt' below at `time_step_min` (0.001), which in the first + layers moves 13 % of the (token, head) steps, and it is also wrong past its first 128-token chunk + (the state handoff between chunks): HF on the CPU is no reference beyond 128 tokens. +- **The gated norm normalises the product, per group.** `norm(y * silu(z)) * w` with the RMS over + 1024 channels (8 groups of the 8192), not `norm(y) * w * silu(z)` (the delta net's + `gdn_gated_rmsnorm`). Served as `act_mul` (silu), a gainless `rmsnorm` over rows of 1024 and + `mul_weight`; a rank's heads are whole groups. +- **The router reads the hidden state, the experts the latent.** `MoeFP8` runs at the latent width + (`Config::router_k` sizes the router, `Wire::route` feeds it); fc2 is linear and has no bias, so + each rank applies it to its partial latent sum and one all-reduce over the hidden width sums the + routed and shared arms (`Config::no_reduce`). +- **relu^2 is `act_mul`'s relu over one operand twice:** relu(x) * x, rounded once, which is + torch's `relu(x) ** 2` in bf16 bit for bit. +- **The bf16 checkpoint has no BOS in its template.** Its chat template sets none, as llama.cpp + does for the MoE form. + +**KV groups.** + +| group | kind | per layer | layers | +|---|---|---|---| +| `kv_attn` | `RAD_KV_FULL`, bf16, 2 / tp heads of 128 (1 at four ranks, replicated over a pair), block 16 | keys and values | 8 attention | +| `kv_ssm` | `RAD_KV_LINEAR`, f32, 64 x 128 a head | the recurrent state, 128 / tp heads a rank | 40 Mamba-2 | +| `kv_ssm_conv` | `RAD_KV_CONV`, bf16, width 4 | the convolution history, (8192 + 2048) / tp channels a rank | 40 Mamba-2 | +| `kv_draft` | `RAD_KV_WINDOW` (1024), bf16, 2 / tp heads of 128 (1 at four ranks, replicated over a pair), block 16 | the LiLiCorr drafter's keys and values | its 5 layers, past the trunk | + +**Speculation.** With drafts the scan keeps `ssd_update`'s anchor form (the committed state and a +scratch of per-token records: decay, `dt' x`, B), at most 31 drafts a step. NVIDIA's LiLiCorr block +drafter proposes 7: 32 query heads over 2 KV heads of 128, which four ranks replicate as the trunk's +attention does (`drafter_geom`'s `kv_repl_ok`: each rank reads its head's k and v rows at `kv_off`, +and `attn_paged_sink` runs at gqa 8 instead of 16). + +**Vision.** `arch/nemotronh/radio.h` serves the C-RADIO (v4-H) tower and its `mlp1` projector when +the container holds them (`vision_config.model_type` `radio`): pictures, and video in tubelets of +two frames, through `core/mm`'s `Radio` family. + # `minimaxmusic3`: MiniMax-Music3, songs `arch/minimaxmusic3` declares an audio generator (`rad_declare_audio_generator`), which makes the diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index e167c1b7..7cb7876b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,12 +10,12 @@ # fast every test with none of slow, gpu, oot and perf, set at the end of this file: the # inner loop (`ctest --preset fast`, or `ctest -L fast`) # -# arch_test and glm5next_test do not link rad_core: they supply their own recording fake of the -# declare-phase C ABI (arch_fakes.h), so plugins are tested without depending on core/build/'s -# builder. With the archive linked, a new ABI call missing from the fake would pull in -# rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a single -# undefined reference. -set(RAD_TESTS_NO_CORE arch_test glm5next_test nemotron35_test spark25_arch_test) +# arch_test, glm5next_test, nemotron35_test, spark25_arch_test and nemotronh_test do not link rad_core: they supply +# their own recording fake of the declare-phase C ABI (arch_fakes.h), so plugins are tested without +# depending on core/build/'s builder. With the archive linked, a new ABI call missing from the fake +# would pull in rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a +# single undefined reference. +set(RAD_TESTS_NO_CORE arch_test glm5next_test nemotron35_test spark25_arch_test nemotronh_test) # fixture_test tests tools/kfixture.cpp and tools/opshapes.cpp (the seeded draw, the reduction and # the on-disk recording) directly, kbench_test tools/kbench_core.cpp (rad-kbench's rules), and @@ -386,10 +386,10 @@ if(TARGET abi_layout_test) COMPILE_OPTIONS "-std=c11;-pedantic-errors;-Wall;-Wextra") endif() -# arch_test reads libref's vocabulary from $RADIANCE_HOME/kernels to check that each architecture -# declares on it, and glm5next_test the loaded libraries' op schemas, so libref is built before -# them. -foreach(t arch_test glm5next_test) +# arch_test and nemotronh_test read libref's vocabulary from $RADIANCE_HOME/kernels to check that +# each architecture declares on it, and glm5next_test the loaded libraries' op schemas, so libref is +# built before them. +foreach(t arch_test glm5next_test nemotronh_test) if(TARGET libref AND TARGET ${t}) add_dependencies(${t} libref) endif() diff --git a/tests/nemotronh_test.cpp b/tests/nemotronh_test.cpp new file mode 100644 index 00000000..a1fa183b --- /dev/null +++ b/tests/nemotronh_test.cpp @@ -0,0 +1,329 @@ +/* nemotronh_test.cpp -- Nemotron-3.5-Bolt's plugin (nemotronh) with its LiLiCorr drafter, declared + * and stepped against the recording builder of arch_fakes.h. + * + * The metadata is a nine-block cut of the released config, as rad-info --meta prints a container + * converted from it (the vision tower's keys left out): every block kind, one attention block, and + * the drafter with 32 query heads over 2 KV heads of 128. */ +#define RAD_ARCH_NO_EXPORTS 1 + +#include "arch_fakes.h" + +#include + +/* ==================================================================== the plugin under test */ +#include "../arch/nemotronh/nemotronh.cpp" + +namespace { + +const char* const k_nemo[][2] = { + { "tie_word_embeddings", "0" }, + { "attention_bias", "0" }, + { "block_configs.1.moe_intermediate_size", "2048" }, + { "block_configs.1.n_routed_experts", "240" }, + { "block_configs.1.num_experts_per_tok", "9" }, + { "block_configs.3.moe_intermediate_size", "1536" }, + { "block_configs.3.n_routed_experts", "240" }, + { "block_configs.3.num_experts_per_tok", "9" }, + { "block_configs.5.moe_intermediate_size", "2048" }, + { "block_configs.5.n_routed_experts", "240" }, + { "block_configs.5.num_experts_per_tok", "9" }, + { "block_configs.8.moe_intermediate_size", "2304" }, + { "block_configs.8.n_routed_experts", "304" }, + { "block_configs.8.num_experts_per_tok", "9" }, + { "conv_kernel", "4" }, + { "hidden_act", "relu2" }, + { "layers_block_type", "mamba moe mamba moe mamba moe mamba attention moe" }, + { "mamba_head_dim", "64" }, + { "mamba_hidden_act", "silu" }, + { "mamba_num_heads", "128" }, + { "mamba_proj_bias", "0" }, + { "mlp_bias", "0" }, + { "mlp_hidden_act", "relu2" }, + { "moe_latent_size", "1024" }, + { "moe_shared_expert_intermediate_size", "5376" }, + { "n_group", "1" }, + { "n_groups", "8" }, + { "n_shared_experts", "1" }, + { "norm_topk_prob", "1" }, + { "num_nextn_predict_layers", "0" }, + { "residual_in_fp32", "0" }, + { "routed_scaling_factor", "5" }, + { "scoring_func", "sigmoid" }, + { "ssm_state_size", "128" }, + { "topk_group", "1" }, + { "use_bias", "0" }, + { "use_conv_bias", "1" }, + { "draft.architectures", "LiLiCorrDraftModel" }, + { "draft.attention_sink_bias", "1" }, + { "draft.block_size", "8" }, + { "draft.dflash_config.attention_sink_bias", "1" }, + { "draft.dflash_config.causal", "0" }, + { "draft.dflash_config.conv_group_size", "16" }, + { "draft.dflash_config.conv_kernel_size", "2" }, + { "draft.dflash_config.lilicorr_candidate_topk", "8" }, + { "draft.dflash_config.lilicorr_enabled", "1" }, + { "draft.dflash_config.lilicorr_factor_dim", "1024" }, + { "draft.dflash_config.lilicorr_hidden_size", "1024" }, + { "draft.dflash_config.lilicorr_logit_scale", "8" }, + { "draft.dflash_config.lilicorr_mlp_ratio", "2" }, + { "draft.dflash_config.lilicorr_num_heads", "8" }, + { "draft.dflash_config.lilicorr_num_layers", "2" }, + { "draft.dflash_config.lilicorr_vector_eps", "0.0001" }, + { "draft.dflash_config.mask_token_id", "990" }, + { "draft.dflash_config.projector_type", "lilicorr" }, + { "draft.dflash_config.swa_window_size", "1024" }, + { "draft.dflash_config.target_layer_ids", "[1,2,3,5,6,8]" }, + { "draft.dflash_config.use_swa", "1" }, + { "draft.head_dim", "128" }, + { "draft.hidden_size", "4096" }, + { "draft.intermediate_size", "12288" }, + { "draft.layer_types", "sliding_attention sliding_attention sliding_attention " + "sliding_attention sliding_attention" }, + { "draft.num_attention_heads", "32" }, + { "draft.num_hidden_layers", "5" }, + { "draft.num_key_value_heads", "2" }, + { "draft.rms_norm_eps", "9.9999999999999995e-07" }, + { "draft.rope_theta", "10000" }, + { "draft.sliding_window", "1024" }, + { "draft.use_sliding_window", "1" }, + { "draft.vocab_size", "131072" }, +}; + +struct Nemo { + std::vector keys, vals; + Nemo() { + for (const auto& kv : k_nemo) { + keys.push_back(kv[0]); + vals.push_back(kv[1]); + } + } + RadModelMeta meta() const { + RadModelMeta m{}; + m.arch_id = "nemotronh"; + m.name = "test-nemotron-3.5-bolt-c9"; + m.quant = ""; + m.n_layers = 9; + m.n_embd = 4096; + m.n_head = 32; + m.n_head_kv = 2; + m.head_dim = 128; + m.n_ff = 2688; + m.n_vocab = 131072; + m.n_ctx_train = 262144; + m.rms_eps = 1e-5f; + m.rope_theta = 10000.0f; + m.rope_scale = 1.0f; + m.n_kv = (int)keys.size(); + m.kv_key = keys.data(); + m.kv_val = vals.data(); + return m; + } +}; + +/* The weights as the release recipes store them: the drafter's linears and every trunk linear block + * fp8, dt's rows of in_proj bf16 (32 a rank at four ranks, no whole scale block). The drafter's + * keys come first: the fake answers the first key a name contains. */ +void nemo_encs(RadBuilder& b) { + const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); + b.encs = { { "dflash.fc.", fp8 }, { "dflash.blk.", fp8 }, { "ssm_dt", rad_enc_plain(RAD_BF16) }, + { "blk.", fp8 } }; +} + +int buf_named(const RadBuilder& b, const char* name) { + for (size_t i = 0; i < b.bufs.size(); ++i) + if (b.bufs[i].name == name) return (int)(i + 1); + return 0; +} +bool noted(const RadBuilder& b, const char* text) { + for (const auto& n : b.notes) + if (n.find(text) != std::string::npos) return true; + return false; +} +rad_kvgroup kv_named(const RadBuilder& b, const char* name) { + for (size_t i = 0; i < b.kv_groups.size(); ++i) + if (b.kv_groups[i].name == name) return (rad_kvgroup)(i + 1); + return 0; +} + +RadBuildCtx nemo_ctx(int rank, int world) { + RadBuildCtx c = build_ctx(rank, world); + c.max_spec = 7; /* LiLiCorr's trained block of 8 */ + return c; +} + +} // namespace + +/* drafter_geom keeps refusing fewer KV heads than ranks unless the drafter block reads k and v at + * kv_off; with `kv_repl_ok` it replicates them as geom_from does the target's: one head a rank, + * ranks {0, 1} on head 0 and {2, 3} on head 1. The target's own kv_off is not inherited. */ +TEST(drafter_geom_replicates_kv_heads_only_when_the_block_asks) { + using namespace rad::arch; + Nemo f; + const RadModelMeta meta = f.meta(); + for (int world : { 2, 4 }) + for (int rank = 0; rank < world; ++rank) { + const RadBuildCtx ctx = nemo_ctx(rank, world); + Geom t{}; + REQUIRE_EQ(geom_from(t, &meta, &ctx, "bf16", RAD_BF16), RAD_OK); + Geom dg{}; + if (world == 4) { + CHECK_EQ(t.kv_off, (int64_t)(rank / 2) * 128); /* the target replicates too */ + CHECK_EQ(drafter_geom(dg, t, &meta, "LiLiCorr"), (int)RAD_E_INVAL); + } + REQUIRE_EQ(drafter_geom(dg, t, &meta, "LiLiCorr", true), RAD_OK); + CHECK_EQ(dg.n_head, 32 / world); + CHECK_EQ(dg.n_head_kv, 1); + CHECK_EQ(dg.n_head_kv_all, 2); + CHECK_EQ(dg.gqa(), 32 / world); + CHECK_EQ(dg.kv_off, world == 4 ? (int64_t)(rank / 2) * 128 : (int64_t)0); + } +} + +/* The drafter at two and four ranks. Each rank keeps one KV head in `kv_draft`; at four its k and v + * are the rows of its replicated head, [kv_off, kv_off + 128) of the 256-row projection (codes, and + * the scale plane in 128-row blocks), and q stays an even share. The sinked attention then runs 8 + * query heads over that head (gqa 8, a libr4d row of its own) where two ranks run 16 (gqa 16). At + * two ranks nothing is spanned: the even shard is the head. */ +TEST(lilicorr_replicates_its_two_kv_heads_at_four_ranks) { + Nemo f; + const RadModelMeta meta = f.meta(); + for (int world : { 2, 4 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + nemo_encs(b); + const RadBuildCtx ctx = nemo_ctx(rank, world); + REQUIRE_EQ(nemotronh::declare(&b, &meta, &ctx), RAD_OK); + CHECK(nemotronh::models[rank]->have_df); + const rad_kvgroup kvd = kv_named(b, "kv_draft"); + REQUIRE(kvd != 0); + CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, 1); + CHECK_EQ(b.kv_groups[kvd - 1].d.head_dim, 128); + CHECK_EQ(b.bufs[buf_named(b, "df_q") - 1].d.shape[1], (int64_t)(32 / world) * 128); + CHECK_EQ(b.bufs[buf_named(b, "df_k") - 1].d.shape[1], (int64_t)128); + CHECK_EQ(b.bufs[buf_named(b, "df_cv") - 1].d.shape[1], (int64_t)128); + int sinks = 0; + for (const auto& o : b.ops) + if (o.op == "attn_paged_sink") { + CHECK_EQ(pint(&o, "gqa"), 32 / world); + CHECK_EQ(pint(&o, "n_head"), 32 / world); + CHECK_EQ(pint(&o, "head_dim"), 128); + ++sinks; + } + CHECK_EQ(sinks, 5); + const int64_t kv0 = (rank / 2) * 128; + for (int l = 0; l < 5; ++l) { + for (const char* kv : { "attn_k", "attn_v" }) { + const std::string base = "dflash.blk." + std::to_string(l) + "." + kv; + const RecWeight* w = find_w(b, base + ".weight"); + const RecWeight* s = find_w(b, base + ".scale"); + REQUIRE(w != nullptr && s != nullptr); + CHECK_EQ(w->d.shape[0], 128); + CHECK_EQ(w->span_set, world == 4); + CHECK_EQ(s->span_set, world == 4); + if (world == 4) { + CHECK_EQ(w->span_lo, kv0); + CHECK_EQ(w->span_hi, kv0 + 128); + CHECK_EQ(s->span_lo, kv0 / 128); + CHECK_EQ(s->span_hi, kv0 / 128 + 1); + } + } + const RecWeight* q = + find_w(b, "dflash.blk." + std::to_string(l) + ".attn_q.weight"); + REQUIRE(q != nullptr); + CHECK(!q->span_set); + CHECK_EQ(q->d.shape[0], (int64_t)(32 / world) * 128); + } + /* the target's attention replicates its two heads the same way */ + const rad_kvgroup kva = kv_named(b, "kv_attn"); + REQUIRE(kva != 0); + CHECK_EQ(b.kv_groups[kva - 1].d.n_head_kv, 1); + CHECK(noted(b, world == 4 ? "kv (replicated) x 128" : "/ 1 kv x 128")); + } +} + +/* A speculative step at four ranks: the trunk's verify of two sequences, the drafter's context pass + * over its rows and its query pass, each without a step failure and lint-clean. */ +TEST(nemotronh_tp4_steps_lint_clean_with_the_lilicorr_drafter) { + Nemo f; + const RadModelMeta meta = f.meta(); + for (int rank : { 0, 3 }) { + RadBuilder b; + nemo_encs(b); + const RadBuildCtx ctx = nemo_ctx(rank, 4); + REQUIRE_EQ(nemotronh::declare(&b, &meta, &ctx), RAD_OK); + auto trunk = kit(b, { 8, 8 }, {}); + auto cpass = context_pass(b, *trunk); + auto qpass = query_pass(b, 2, 8, 7); + std::vector anchors = { 7, 15 }; /* each sequence's last committed row */ + qpass->b.anchor_rows = anchors.data(); + auto v = run_passes(b, nemotronh::step, { trunk.get(), cpass.get(), qpass.get() }, rank, 4); + CHECK_PASSES(b, v); + /* the drafter ran: its five layers' sinked attention and its keys into the cache */ + const std::vector q = issued_ops(b, *v[2]); + CHECK_EQ(count_issued(q, "attn_paged_sink"), 5); + CHECK_EQ(count_issued(q, "kv_store"), 5); + CHECK_EQ(count_issued(issued_ops(b, *v[1]), "kv_store"), 5); + } +} + +/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and + * must get the real declare's graph: the same ops with the same fixed parameters, only ranged row + * counts and buffer rows smaller. The drafter's split fc gathers its message as a range; a fixed + * numel there left every level unplanned, and sixteen sequences short of the lent arena. */ +TEST(nemotronh_sizing_declares_match_the_real_graph_at_every_arena_level) { + Nemo f; + const RadModelMeta meta = f.meta(); + for (int world : { 2, 4 }) + for (int64_t R : { 256, 1024 }) { + RadBuildCtx c = nemo_ctx(1, world); + c.max_tok = 4096; + c.max_seqs = 16; + RadBuilder full; + nemo_encs(full); + REQUIRE_EQ(nemotronh::declare(&full, &meta, &c), RAD_OK); + RadBuildCtx p = c; + p.max_tok = R; + p.shape_probe = 1; + RadBuilder small; + nemo_encs(small); + REQUIRE_EQ(nemotronh::declare(&small, &meta, &p), RAD_OK); + REQUIRE_EQ(small.ops.size(), full.ops.size()); + int differ = 0; + for (size_t i = 0; i < full.ops.size(); ++i) { + if (small.ops[i].op != full.ops[i].op) { + ++differ; + continue; + } + REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); + for (size_t k = 0; k < full.ops[i].p.size(); ++k) { + const RecParam& a = full.ops[i].p[k]; + const RecParam& q = small.ops[i].p[k]; + if (a.kind == RAD_P_RANGE) continue; + if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { + fprintf(stderr, " world %d R %lld: op %zu '%s' param '%s': %lld real, " + "%lld small\n", world, (long long)R, i, + full.ops[i].op.c_str(), a.key.c_str(), a.ival, q.ival); + ++differ; + } + } + } + CHECK_EQ(differ, 0); + REQUIRE_EQ(small.bufs.size(), full.bufs.size()); + for (size_t i = 0; i < full.bufs.size(); ++i) + for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) + CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); + } +} + +/* The probe states LiLiCorr's fixed depth, the trained block less its anchor: what --tp 4 serves + * with `--num-speculative-tokens 7`. */ +TEST(nemotronh_probe_names_lilicorrs_depth) { + Nemo f; + const RadModelMeta meta = f.meta(); + RadArchProbe pr{}; + REQUIRE_EQ(nemotronh::probe(&meta, &pr), RAD_OK); + CHECK_EQ(pr.draft_depth, 7); + CHECK_EQ(pr.draft_depth_fixed, 1); +} + +RAD_TEST_MAIN() diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index ba7e1dcf..7210a0cf 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -97,7 +97,7 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { { "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "hunyuan3d2", "" }, { "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" }, { "laya", "" }, { "lfm2", "" }, { "llama", "" }, { "mistral3", "" }, - { "llama", "fp8_e4m3" }, { "nomicbert", "" }, { "qwen35", "" }, + { "llama", "fp8_e4m3" }, { "nemotronh", "" }, { "nomicbert", "" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, { "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" },