diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h index 4ea97b5f..61853ffb 100644 --- a/arch/common/rad_block_dflash2.h +++ b/arch/common/rad_block_dflash2.h @@ -147,6 +147,9 @@ struct Dflash2 { /* The target's embedding scale, applied to the query block as the drafter was trained * (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */ double escale = 1.0; + /* Optional DFlash2 logit transform shipped by Muse Glimmer. */ + double omul = 1.0; + double scap = 0.0; /* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query * pass (prefetch_beside, rad_arch.h); 0 reads none. */ int64_t prefetch = 0; @@ -270,6 +273,9 @@ struct Dflash2 { * 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and * the 2-bit grid otherwise. Set by declare from the copy's encoding. */ bool head_i8 = false; + /* Muse Glimmer's 202048-token vocab is not divisible by the int8/w2a8 head kernels' 128-row + * tile; its copied draft head stays BF16 and uses gemm_nt. */ + bool head_bf16 = false; /* per-layer weights */ rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; @@ -334,7 +340,7 @@ struct Dflash2 { rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {}; /* head and selector */ - rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0; + rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dcap = 0, op_dtopk = 0; rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */ rad_op op_drerank = 0; /* the candidates rescored against the target's head */ /* The target's lm_head, set by the plugin before declare when logit_rerank can read it (fp8 or @@ -482,12 +488,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_ARCH_TRY(map_copy(b, dhn, ck_lm)); /* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which * gemm_nt_q reads at w8a8 against the same quant_act_i8 activation (without its asum). */ + RadEncoding dhe{}; + const bool head_known = weight_enc(b, dhn, &dhe); { - RadEncoding e{}; const RadEncPlane* sc = nullptr; - head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 && - !e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && - (sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 && + head_i8 = head_known && rad_enc_is(&dhe, "affine") && dhe.n_planes == 2 && + !dhe.transform[0] && dhe.plane[0].dtype == RAD_I8 && dhe.plane[0].block[1] == 1 && + (sc = rad_enc_plane(&dhe, "scale")) && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP; } if (head_i8) { @@ -496,6 +503,11 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16, {head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model()); + } else if (head_known && rad_enc_is(&dhe, "plain") && dhe.n_planes == 1 && + dhe.plane[0].dtype == RAD_BF16) { + head_bf16 = true; + w_dh = decl_w(b, dhn, RAD_BF16, {head_rows(g), g.n_embd}, + RAD_ACCESS_PER_TOKEN, dh_split, grp_model()); } else { w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model()); @@ -503,7 +515,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co {head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model()); } - if (!w_dh || !w_dhs) return RAD_E_INVAL; + if (!w_dh || (!head_bf16 && !w_dhs)) return RAD_E_INVAL; } /* ---------------------------------------------------------------- per-layer weights */ @@ -945,12 +957,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), {w.x, w.h2}, {w.x}); - op_final = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_norm)), - {w.x}, {w.h}); + op_final = cfg.omul != 1.0 + ? rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_F64("mult", cfg.omul), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}) + : rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); /* Each residual add and the norm after it as one launch where a library serves add_rmsnorm * (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only * where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run @@ -974,6 +993,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co op_afinal = all ? an(w_norm) : 0; if (!op_afinal) for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0; + /* add_rmsnorm has no `mult`; keep Muse's output_multiplier on the final norm. */ + if (cfg.omul != 1.0) op_afinal = 0; } /* ---------------------------------------------------------------- the head and the selector @@ -991,12 +1012,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co {w.h}, {w.sel_h}); /* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */ if (cfg.lili) return RAD_OK; - op_dquant = rw(b, RAD_OP(b, "quant_act_i8", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), - RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.sel_h}, {w.dq, w.ds, w.dsum}); - op_dlogits = head_i8 + if (!head_bf16) + op_dquant = rw(b, RAD_OP(b, "quant_act_i8", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), + RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.sel_h}, {w.dq, w.ds, w.dsum}); + op_dlogits = head_bf16 + ? rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_dh)), + {w.sel_h}, {w.dlog}) + : head_i8 ? rw(b, RAD_OP(b, "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)), RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP), @@ -1009,6 +1037,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_STR("dtype", "w2a8")), RAD_WEIGHTS(w_dh, w_dhs)), {w.dq, w.ds, w.dsum}, {w.dlog}); + if (cfg.scap > 0.0) { + op_dcap = rw(b, RAD_OP(b, "logit_softcap", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", head_rows(g)), + RAD_F64("cap", cfg.scap), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.dlog}, {w.dlog}); + if (!op_dcap) return RAD_E_INVAL; + } /* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair * plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present * with value 0 is a different declaration from an absent one. */ @@ -1359,12 +1395,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { /* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it * whole. */ - RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum)); - /* The trailing operand is mxfp4's optional reference, absent here. Operands are positional, - * so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric and - * takes no asum. */ - RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs), - brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE); + if (head_bf16) { + RAD_ISSUE_N(c, op_dlogits, S, brows(w.sel_h, S), RAD_W(w_dh), brows(w.dlog, S)); + } else { + RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum)); + /* The trailing operand is mxfp4's optional reference, absent here. Operands are positional, + * so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric + * and takes no asum. */ + RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs), + brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE); + } + if (op_dcap) RAD_ISSUE_N(c, op_dcap, S, brows(w.dlog, S), brows(w.dlog, S)); /* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and * the merge overwrites `cand`/`unary`. */ if (op_dmerge) { diff --git a/arch/museglimmer/dflash2.h b/arch/museglimmer/dflash2.h new file mode 100644 index 00000000..c3f011ba --- /dev/null +++ b/arch/museglimmer/dflash2.h @@ -0,0 +1,198 @@ +/* dflash2.h -- wire rad_block_dflash2.h onto a Muse Glimmer trunk. + * + * Meta's assistant is a plain DFlash (rad_block_muse_dflash.h). incoai's Muse-Glimmer-30B-DFlash2 + * is the DFlash2 block: candidate selector, grouped convolutions, 8 KV heads. The two are + * selected by draft.architectures. Muse's DFlash2 ships output_multiplier and + * final_logit_softcapping; the block applies those (Config::omul / Config::scap). + */ +#pragma once + +#include +#include +#include + +#include + +namespace rad { +namespace arch { + +inline bool muse_draft_is_dflash2(const RadModelMeta* meta) { + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + return da && std::strstr(da, "DFlash2"); +} + +/* Same 12 MiB prefetch qwen35 measured on two R9700s. */ +constexpr int64_t kMuseDf2Prefetch = (int64_t)12 << 20; + +inline int declare_muse_dflash2(Dflash2* ds, Dflash2::Wire* w, rad_kvgroup* kv, + RadBuilder* b, Names& nm, const RadModelMeta* meta, + const RadBuildCtx* ctx, const Geom& target, + const MuseTaps& taps, int base_layer, rad_weight tok_embd, + rad_weight head_w) { + if (!ds || !w || !kv || !b) return RAD_E_INVAL; + Geom dg{}; + RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DFlash2", /*kv_repl_ok=*/true)); + const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size", + rad_meta_geti(meta, "draft.dflash_config.hidden_size", + dg.n_embd)); + if (want_embd != dg.n_embd) { + fprintf(stderr, "radiance: museglimmer: the DFlash2 drafter reads a %lld-wide trunk and " + "this target is %lld wide; they are not the same model\n", + (long long)want_embd, (long long)dg.n_embd); + return RAD_E_UNSUPPORTED; + } + + Dflash2::Config dc{}; + dc.short_block = 1; + dc.prefetch = kMuseDf2Prefetch; + dc.n_taps = taps.n; + dc.block = ctx->max_spec + 1; + dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2); + dc.group = rad_meta_geti(meta, "draft.dflash_config.conv_group_size", 16); + dc.sel_rank = rad_meta_geti(meta, "draft.dflash_config.selector_rank", 0); + dc.sel_topk = rad_meta_geti(meta, "draft.dflash_config.selector_top_k", 0); + dc.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0; + if (rad_meta_geti(meta, "draft.use_sliding_window", 0)) + dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size", + rad_meta_geti(meta, "draft.sliding_window", 0)); + if (dc.sel_rank <= 0 || dc.sel_topk <= 0) { + fprintf(stderr, "radiance: museglimmer: the DFlash2 drafter states no selector geometry " + "(rank %lld, top_k %lld)\n", + (long long)dc.sel_rank, (long long)dc.sel_topk); + return RAD_E_INVAL; + } + + const long long trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); + if (dc.block < 2 || (dc.block & (dc.block - 1))) { + fprintf(stderr, "radiance: museglimmer: DFlash2's convolution masks the block position " + "with block_size - 1, so the query block has to be a power of two. This " + "serve asks for %d draft tokens, which makes it %lld; the checkpoint was " + "trained at %lld.\n", + ctx->max_spec, (long long)dc.block, trained); + return RAD_E_UNSUPPORTED; + } + if (trained > 0 && trained != dc.block) + rad_note(b, "DFlash2 was trained at block_size %lld (%lld draft tokens) and runs at " + "%lld; it accepts less away from its trained block length", + trained, trained - 1, (long long)dc.block); + + dc.escale = rad_meta_getf(meta, "draft.dflash_config.input_embedding_scale", 1.0); + dc.omul = rad_meta_getf(meta, "draft.dflash_config.output_multiplier", 1.0); + dc.scap = rad_meta_getf(meta, "draft.dflash_config.final_logit_softcapping", 0.0); + RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8)); + dc.fc_mapped = true; + + RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, kv)); + + const int64_t qd = dg.n_head * dg.head_dim; + const int64_t kvd = dg.n_head_kv * dg.head_dim; + const uint32_t act_dtype = dc.act_i8 ? RAD_I8 : RAD_F8E4M3; + const int64_t act_group = dc.act_i8 ? dc.act_g8 : RAD_FP8_BLOCK; + const auto act_groups = [act_group](int64_t n) { return (n + act_group - 1) / act_group; }; + 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 spad = ((sr + 15) / 16) * 16; + + Dflash2::Wire& dw = *w; + dw.src = taps.src; + dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd}); + dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd}); + dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd}); + dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd}); + dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd}); + dw.h2 = decl_b(b, nm.f("df_h2"), dg.act_dtype, {qr, dg.n_embd}); + dw.coef = decl_b(b, nm.f("df_coef"), dg.act_dtype, {qr, dc.coef_dim(dg.n_embd)}); + dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd}); + dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd}); + dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd}); + dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd}); + dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff}); + dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff}); + dw.srcq = decl_b(b, nm.f("df_srcq"), act_dtype, + {dg.max_tok, dc.n_taps * dg.n_embd}); + dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, + {dg.max_tok, act_groups(dc.n_taps * dg.n_embd)}); + dw.cq = decl_b(b, nm.f("df_cq"), act_dtype, {dg.max_tok, dg.n_embd}); + dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, act_groups(dg.n_embd)}); + dw.h2q = decl_b(b, nm.f("df_h2q"), act_dtype, {qr, dg.n_embd}); + dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, act_groups(dg.n_embd)}); + dw.atq = decl_b(b, nm.f("df_atq"), act_dtype, {qr, qd}); + dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, act_groups(qd)}); + dw.ffq = decl_b(b, nm.f("df_ffq"), act_dtype, {qr, dg.n_ff}); + dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, act_groups(dg.n_ff)}); + dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd}); + dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank}); + dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd}); + dw.ds = decl_b(b, nm.f("df_ds"), RAD_F32, {sr, 1}); + dw.dsum = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad}); + dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)}); + { + const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16); + if (head_w && (hd == RAD_F8E4M3 || hd == RAD_I8) && + (Dflash2::head_sharded(dg) || dg.world <= 1)) { + ds->w_lm = head_w; + ds->top_w = Dflash2::kRerankR; + } + } + const int64_t tw = ds->w_lm ? ds->top_w : dc.sel_topk; + dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, tw}); + dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, tw}); + if (Dflash2::head_sharded(dg)) { + dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2}); + dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2}); + } + dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()}); + if (ctx->draft_coupling) { + if (dc.steps() > RAD_MTP_COUPLE_MAX_ROUNDS || dc.sel_topk > RAD_DFLASH_COUPLE_MAX_K || + dc.sel_rank % RAD_DFLASH_EDGE_PARTS || dc.sel_rank > RAD_DFLASH_COUPLE_MAX_R) { + fprintf(stderr, "radiance: museglimmer: --draft-coupling on DFlash2 needs at most " + "%d drafts, %d candidates and a selector rank that is a multiple of " + "%d up to %d\n", + RAD_MTP_COUPLE_MAX_ROUNDS, RAD_DFLASH_COUPLE_MAX_K, RAD_DFLASH_EDGE_PARTS, + RAD_DFLASH_COUPLE_MAX_R); + return RAD_E_UNSUPPORTED; + } + dc.q_temp = 0.6; + dw.couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32, + {dg.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, RAD_BUF_PERSIST); + dw.couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32, + {dc.steps(), dg.max_seqs, RAD_MTP_COUPLE_STATE_WORDS}, + RAD_BUF_PERSIST); + if (!dw.couple_draws || !dw.couple_state) return RAD_E_INVAL; + } + + RAD_ARCH_TRY(ds->declare(b, nm, dg, dc, base_layer, *kv, tok_embd, "draft", + nm.ckpt("lm_head.weight"), dw)); + + RadDrafterDecl drf{}; + drf.name = "dflash2"; + 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)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: museglimmer: this DFlash2 checkpoint declares no " + "dflash_config.mask_token_id\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + if (ds->block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, ds->block_lo)); + + rad_note(b, "DFlash2 drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, " + "ffn %lld, %s attention with a %lld-token window, %d trunk tap(s); one forward " + "proposes %lld tokens through the candidate selector", + (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, (long long)dg.head_dim, + (long long)dg.n_ff, dc.causal ? "causal" : "non-causal", (long long)dc.window, + taps.n, (long long)dc.steps()); + if (dc.omul != 1.0 || dc.scap > 0.0) + rad_note(b, "DFlash2 logits: output_multiplier %g, softcap %g", dc.omul, dc.scap); + return RAD_OK; +} + +} /* namespace arch */ +} /* namespace rad */ diff --git a/arch/museglimmer/museglimmer.cpp b/arch/museglimmer/museglimmer.cpp index 513fdb33..a08b06c0 100644 --- a/arch/museglimmer/museglimmer.cpp +++ b/arch/museglimmer/museglimmer.cpp @@ -57,6 +57,7 @@ #include #include #include +#include "dflash2.h" #include #include @@ -120,13 +121,12 @@ struct Model { rad_op op_media_rows = 0; MuseTower vit{}; - /* ---- the DFlash drafter (arch/common/rad_block_muse_dflash.h): declared last, only when the - * container carries one and the serve asks for drafts. It reads the trunk's residual stream at - * `draft.target_layer_ids`, keeps its own KV group, and proposes `block_size - 1` tokens a - * pass for the trunk to verify. */ - bool have_df = false; + /* ---- Meta's DFlash or incoai's DFlash2, selected by draft.architectures. */ + bool have_df = false, have_df2 = false; MuseDflash df{}; MuseDflash::Wire dfw{}; + Dflash2 df2{}; + Dflash2::Wire df2w{}; MuseTaps taps{}; rad_kvgroup kv_draft = 0; @@ -653,12 +653,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer)); - /* ---- the DFlash drafter, declared last: its passes run after the whole trunk's, and the - * planner lays lifetimes out in declaration order. */ + /* ---- the drafter is declared last so its buffers cannot overlap trunk temporaries. */ if (m.taps.n > 0) { - RAD_ARCH_TRY(declare_muse_dflash(&m.df, &m.dfw, &m.kv_draft, b, nm, meta, ctx, g, m.taps, - (int)g.n_layer, m.w_tok, m.w_lm_head)); - m.have_df = true; + if (muse_draft_is_dflash2(meta)) { + RAD_ARCH_TRY(declare_muse_dflash2(&m.df2, &m.df2w, &m.kv_draft, b, nm, meta, ctx, g, + m.taps, (int)g.n_layer, m.w_tok, m.w_lm_head)); + m.have_df2 = true; + } else { + RAD_ARCH_TRY(declare_muse_dflash(&m.df, &m.dfw, &m.kv_draft, b, nm, meta, ctx, g, + m.taps, (int)g.n_layer, m.w_tok, m.w_lm_head)); + m.have_df = true; + } } /* ---- notes for --debug-graph. */ @@ -703,6 +708,11 @@ static void step(RadCtx* c, const RadBatch* batch) { /* A draft pass runs only the drafter: >0 the query pass on the staged block, <0 the context * pass that projects and stores K/V for the tokens the trunk just committed. */ if (batch->draft_pass != 0) { + if (m.have_df2) { + if (batch->draft_pass > 0) m.df2.step(c, batch); + else m.df2.context(c, batch); + return; + } if (!m.have_df) { rad_step_fail(c, "this serve stages a draft pass but the container carries no drafter"); return; @@ -738,8 +748,9 @@ static void step(RadCtx* c, const RadBatch* batch) { const int32_t* table = kvb ? kvb->block_table : nullptr; const int32_t* used = kvb ? kvb->seqused : nullptr; - /* -- attention. */ + /* -- attention. The first Hessian sees the normalized input consumed by q/gate/k/v. */ RAD_ISSUE(c, l.op_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T)); + if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, T); RAD_ISSUE(c, l.op_q, brows(m.b_h, T), RAD_W(l.w_q), brows(m.b_q, T)); RAD_ISSUE(c, l.op_gate, brows(m.b_h, T), RAD_W(l.w_gate), brows(m.b_gate, T)); RAD_ISSUE(c, l.op_k, brows(m.b_h, T), RAD_W(l.w_k), brows(m.b_k, T)); @@ -763,6 +774,7 @@ static void step(RadCtx* c, const RadBatch* batch) { brows(m.b_attn, T)); RAD_ISSUE_N(c, l.op_sig, T * m.g.n_head, brows(m.b_gate, T), brows(m.b_gate, T)); RAD_ISSUE(c, l.op_mul, brows(m.b_attn, T), brows(m.b_gate, T), brows(m.b_attn, T)); + if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, T); RAD_ISSUE(c, l.op_o, brows(m.b_attn, T), RAD_W(l.w_o), brows(m.b_h, T)); if (l.op_ar) RAD_ISSUE_N(c, l.op_ar, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE); RAD_ISSUE(c, l.op_post, brows(m.b_h, T), RAD_W(l.w_post), brows(m.b_h, T)); @@ -770,8 +782,10 @@ static void step(RadCtx* c, const RadBatch* batch) { /* -- feed-forward. */ RAD_ISSUE(c, l.op_fnorm, brows(m.b_x, T), RAD_W(l.w_fnorm), brows(m.b_h, T)); + if (l.cs_mlp >= 0) m.calib.tap(c, (size_t)l.cs_mlp, T); RAD_ISSUE(c, l.op_gu, brows(m.b_h, T), RAD_W(l.w_gate_up), brows(m.b_gu, T)); RAD_ISSUE(c, l.op_act, brows(m.b_gu, T), brows(m.b_ffn, T)); + if (l.cs_down >= 0) m.calib.tap(c, (size_t)l.cs_down, T); RAD_ISSUE(c, l.op_down, brows(m.b_ffn, T), RAD_W(l.w_down), brows(m.b_h, T)); if (l.op_far) RAD_ISSUE_N(c, l.op_far, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE); RAD_ISSUE(c, l.op_fpost, brows(m.b_h, T), RAD_W(l.w_fpost), brows(m.b_h, T)); @@ -783,6 +797,7 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_ISSUE(c, m.op_final_norm, brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok)); + if (m.cs_head >= 0) m.calib.tap(c, (size_t)m.cs_head, T); m.calib.after_step(c, T); /* The lm_head runs only on the rows the sampler asked for; a mid-prompt prefill chunk has @@ -806,8 +821,14 @@ static void step(RadCtx* c, const RadBatch* batch) { static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; if (MuseTower::present(meta)) out->enc_merge = 4; - /* The drafter denoises `block_size` positions and the anchor row proposes nothing, so the - * draft width is block_size - 1. It is trained for that one block, hence fixed. */ + /* DFlash2 reads block_size from dflash_config; its anchor row proposes nothing. */ + if (muse_draft_is_dflash2(meta)) { + const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 16); + out->draft_depth = bs > 1 ? (int)(bs - 1) : 15; + out->draft_depth_fixed = 1; + return RAD_OK; + } + /* Meta DFlash denoises `block_size` positions; the anchor proposes nothing. */ const long long bs = rad_meta_geti(meta, "draft.block_size", 0); if (bs > 1) { out->draft_depth = (int)(bs - 1); diff --git a/arch/museglimmer_ct/museglimmer_ct.cpp b/arch/museglimmer_ct/museglimmer_ct.cpp index c03ef50b..9a1eabf7 100644 --- a/arch/museglimmer_ct/museglimmer_ct.cpp +++ b/arch/museglimmer_ct/museglimmer_ct.cpp @@ -11,14 +11,12 @@ * adapter stay bf16 whatever the trunk does: the recipes never touch them, and a container that * quantised tower weights is refused naming the weight. * - * An IQ8R trunk (data/recipes/museglimmer-30b-iq8r.recipe: int8 codes rotated 128 wide by the - * unnormalised Hadamard, a u8 scale per [1 x 256] under a bf16 scale a row) is a whole-trunk form, - * read from layer 0's q projection before any activation is declared. Its linears are rad_fp8.h's - * LinearFP8 at gemm_nt_q i8a8h, group 256, against int8 activations quantised under the same - * rotation: the two pre-norms write them (rmsnorm_had_quant_i8g), the gated product writes the - * down projection's (gated_had_quant_i8g), and the out projection quantises the gated attention - * output itself (had_quant_act_i8g). q, gate, k and v read one pair. Every trunk linear of such a - * container must be IQ8R; anything else in it is refused naming the weight. + * Rotated i8a8h trunks are whole-trunk forms, detected from layer 0's q projection before any + * activation is declared. IQ8R uses a 256-column scale group; computed-trellis IQR (including + * IQ4R-V4) uses 128. Both reuse LinearFP8's encoding-aware IQR views and GEMMs. The two centered + * pre-norms produce rotated int8 pairs, the gated product produces the down-projection pair, and + * o_proj quantises its gated attention input. q, gate, k and v share one pair. Every trunk linear + * must use the same rotated family; mixed encodings fail at declaration with the offending name. * * The lm_head is declared at whatever the model holds (weight_codes_dtype): bf16, or a recipe-made * int8 head (`codes=i8 group=128 scale=bf16`), which `logits_gemm` then reads with the int8 head @@ -30,6 +28,7 @@ #include #include #include +#include "../museglimmer/dflash2.h" #include #include @@ -305,11 +304,10 @@ inline int MlLinear::declare(RadBuilder* b, Names& nm, const Geom& g, const char char en[256]; rad_enc_format(&enc, en, sizeof en); - /* IQ8R is served only as a whole trunk, decided by layer 0's q projection (declare()). */ - if (known && linear_is_iq8r(enc)) { - fprintf(stderr, "radiance: '%s' is IQ8R (%s) and layer 0's attn_q is not; an IQ8R " - "container stores every trunk linear in it " - "(data/recipes/museglimmer-30b-iq8r.recipe)\n", wn, en); + /* Rotated i8a8h encodings are served only as a whole trunk, decided by layer 0's q. */ + if (known && linear_is_w8h(enc)) { + fprintf(stderr, "radiance: '%s' is a rotated i8a8h weight (%s), but layer 0's attn_q " + "does not select a matching whole-trunk path\n", wn, en); return RAD_E_DTYPE; } fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, symmetric " @@ -379,11 +377,10 @@ struct Layer { rad_weight w_fnorm = 0, w_fpost = 0; MlLinear lq, lgate, lk, lv, lo, lgu, ldown; - /* The same seven linears in an IQ8R trunk (Model::iq8r), at gemm_nt_q i8a8h. The pre-norms - * write their int8 pair as rmsnorm_had_quant_i8g where a loaded library declares it (nq_attn, - * nq_ffn; op_norm / op_fnorm stay 0 then), and the gated product writes the down projection's - * as gated_had_quant_i8g (gq_ffn; op_act stays 0). Where they are not declared, the plain norm - * and silu_mul run and the first linear reading each input quantises it (had_quant_act_i8g). */ + /* The seven rotated linears in an IQ8R or IQR trunk, at gemm_nt_q i8a8h. The pre-norms + * write their int8 pair as rmsnorm_had_quant_i8g when available; the gated product writes the + * down-projection pair as gated_had_quant_i8g. Otherwise the first consumer quantises with + * had_quant_act_i8g. `rot_group` is 256 for IQ8R, 128 for computed-trellis IQR. */ LinearFP8 rq, rgate, rk, rv, ro, rgu, rdown; NormQuantFP8 nq_attn, nq_ffn; GateQuantFP8 gq_ffn; @@ -414,12 +411,10 @@ struct Model { rad_buf b_q = 0, b_gate = 0, b_k = 0, b_v = 0, b_attn = 0; rad_buf b_gu = 0, b_ffn = 0; - /* An IQ8R trunk: every trunk linear is IQ8R (layer 0's q projection decides), and the three - * linear inputs carry an int8 code pair at one f32 scale per (row, 256) under the 128-wide - * rotation beside their bf16 plane: `a_h` over `b_h` (both pre-norms' output; q, gate, k, v and - * gate/up read it), `a_attn` over `b_attn` (the gated attention output; o_proj), `a_ffn` over - * `b_ffn` (the gated product; down_proj). */ - bool iq8r = false; + /* A whole-trunk rotated-int8 mode selected from layer 0's q projection. `iq8r` keeps the + * legacy wide-group case explicit; IQR-V4 is computed trellis/MAD at group 128. */ + bool rotated_i8 = false, iq8r = false, iqr_v4 = false; + int64_t rot_group = RAD_FP8_BLOCK; ActFP8 a_h{}, a_attn{}, a_ffn{}; rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0; @@ -434,11 +429,12 @@ struct Model { rad_op op_media_rows = 0; MuseTower vit{}; - /* ---- the DFlash drafter (arch/common/rad_block_muse_dflash.h): same wiring as the bf16 - * plugin declares, so a compressed-tensors container carries the drafter the same way. */ - bool have_df = false; + /* ---- Meta's DFlash or incoai's DFlash2, selected by draft.architectures. */ + bool have_df = false, have_df2 = false; MuseDflash df{}; MuseDflash::Wire dfw{}; + Dflash2 df2{}; + Dflash2::Wire df2w{}; MuseTaps taps{}; rad_kvgroup kv_draft = 0; @@ -593,21 +589,26 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } /* ---- the trunk's form, read from layer 0's q projection before any activation is declared: - * only an IQ8R trunk's activations carry an int8 code pair. The probe makes the weight's name - * map through that layer's own LinearFP8, so neither linear of layer 0 maps it again. */ + * IQ8R and computed-trellis IQR activations carry an int8 code pair. The probe maps layer 0's + * q weight, so neither linear maps it again. */ const char* const pre = "model.language_model.layers"; m.layers.resize((size_t)g.n_layer); RAD_ARCH_TRY(m.layers[0].rq.probe(b, nm, g, nm.f("blk.0.attn_q"), { nm.ckpt("%s.0.self_attn.q_proj.weight", pre) })); { RadEncoding e0{}; - m.iq8r = weight_enc(b, nm.f("blk.0.attn_q.weight"), &e0) && linear_is_iq8r(e0); + const bool known = weight_enc(b, nm.f("blk.0.attn_q.weight"), &e0); + const W8hForm form = known ? linear_w8h_form(e0) : W8hForm::None; + m.iq8r = known && linear_is_iq8r(e0); + m.iqr_v4 = known && !m.iq8r && form == W8hForm::Trellis && linear_w8h_mad(e0); + m.rotated_i8 = m.iq8r || m.iqr_v4; + if (m.rotated_i8) m.rot_group = linear_w8h_group(e0); } - if (m.iq8r && (g.n_embd % RAD_I8_GROUP_WIDE || q_dim % RAD_I8_GROUP_WIDE || - g.n_ff % RAD_I8_GROUP_WIDE)) { - fprintf(stderr, "radiance: museglimmer: the IQ8R trunk keeps one scale a %d of K, which " + if (m.rotated_i8 && (g.n_embd % m.rot_group || q_dim % m.rot_group || + g.n_ff % m.rot_group)) { + fprintf(stderr, "radiance: museglimmer: the rotated trunk's %lld-column activation group " "does not divide this rank's widths (hidden %lld, attention %lld, " - "feed-forward %lld)\n", RAD_I8_GROUP_WIDE, (long long)g.n_embd, + "feed-forward %lld)\n", (long long)m.rot_group, (long long)g.n_embd, (long long)q_dim, (long long)g.n_ff); return RAD_E_UNSUPPORTED; } @@ -623,24 +624,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim}); m.b_gu = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff}); m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff}); - /* An IQ8R trunk's int8 pairs, one scale per (row, 256). `a_h` is fed by the pre-norms where - * rmsnorm_had_quant_i8g is declared; neither norm absorbs a collective (the all-reduce sits - * before the post norm, and the embedding's before the weightless embedding norm), so the - * all-reduce form is not needed at two ranks. `a_ffn` is fed by gated_had_quant_i8g where it - * is declared. `a_attn` is never fed: the attention output is a sigmoid gate and a multiply - * over separate buffers, and o_proj's own had_quant_act_i8g quantises the product (the gated - * quantiser's per-head rows are head_dim wide, narrower than the 256-column group). No E4M3 - * pair: nothing here reads one. */ - if (m.iq8r) { + /* Rotated int8 pairs, one scale per row and `rot_group` columns. The two centered pre-norms + * can fuse normalization and quantisation; the gated product can fuse its quantiser. The + * attention gate/multiply stays BF16, so o_proj quantises that product separately. */ + if (m.rotated_i8) { m.a_h.x = m.b_h; - RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, true, false, RAD_I8_GROUP_WIDE)); + RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, true, false, m.rot_group)); m.a_h.q8_fed = m.a_h.q8_rot = rad_op_declared(b, "rmsnorm_had_quant_i8g") != 0; m.a_attn.x = m.b_attn; RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, true, false, - RAD_I8_GROUP_WIDE)); + m.rot_group)); m.a_ffn.x = m.b_ffn; - RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, true, false, - RAD_I8_GROUP_WIDE)); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, true, false, m.rot_group)); m.a_ffn.q8_fed = m.a_ffn.q8_rot = rad_op_declared(b, "gated_had_quant_i8g") != 0; } /* The lm_head runs over the sampled rows only (RadBatch::out_ids), not the whole step. */ @@ -721,10 +716,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * qk_scale_factor rides the q norm's `mult`. */ (void)attn_scale_num; - /* One linear of an IQ8R trunk: its name map (layer 0's q has it from the probe), its encoding - * checked to be IQ8R, then LinearFP8's declaration (codes view i8 [N, K], one "scale,scale.1" - * u8 view at the logical [N, K], gemm_nt_q at i8a8h, group 256, over `a`'s int8 pair; and - * had_quant_act_i8g over `a.x` unless `a` is fed). */ + /* One rotated linear: IQ8R must stay IQ8R; IQR-V4 must be a computed MAD trellis. LinearFP8 + * selects the stored code/trellis/scale views and gemm_nt_q i8a8h at the proper scale group. */ auto rot_linear = [&](int64_t l, LinearFP8& L, const char* base, std::initializer_list src, int64_t n_out, int64_t n_in, int shard, const ActFP8& a, rad_buf y, @@ -733,12 +726,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c const char* wn = nm.f("%s.weight", base); RadEncoding e{}; const bool known = weight_enc(b, wn, &e); - if (!known || !linear_is_iq8r(e)) { + const W8hForm form = known ? linear_w8h_form(e) : W8hForm::None; + const bool valid = known && (m.iq8r ? linear_is_iq8r(e) + : m.iqr_v4 && form == W8hForm::Trellis && + linear_w8h_mad(e)); + if (!valid || linear_w8h_group(e) != m.rot_group) { char en[256] = "plain bf16"; if (known) rad_enc_format(&e, en, sizeof en); - fprintf(stderr, "radiance: '%s' is %s, and this container's trunk is IQ8R (layer 0's " - "attn_q): every trunk linear of an IQ8R container is IQ8R " - "(data/recipes/museglimmer-30b-iq8r.recipe)\n", wn, en); + fprintf(stderr, "radiance: '%s' is %s, which does not match this container's whole " + "rotated trunk (layer 0 attn_q selects %s)\n", wn, en, + m.iq8r ? "IQ8R" : "computed-trellis IQR"); return RAD_E_DTYPE; } return L.declare(b, nm, g, base, n_out, n_in, shard, grp_layer((int)l), src, a, y, 0, @@ -781,10 +778,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* -- ops, in run order except attn_paged, declared before kv_store like every family: the * two touch disjoint buffers and the block size comes from the resolved kernel. */ - /* The input norm: with an IQ8R trunk fed by its norms, rmsnorm_had_quant_i8g writes the - * bf16 output and its rotated int8 pair in one pass (no residual operand: the residual add - * is the post-normed branch's, not this norm's). */ - if (m.iq8r && m.a_h.q8_fed) + /* A rotated trunk can fuse the centered norm and its int8 pair into one pass. */ + if (m.rotated_i8 && m.a_h.q8_fed) RAD_ARCH_TRY(lay.nq_attn.declare(b, gn, lay.w_norm, m.b_x, m.a_h, g.n_embd)); else lay.op_norm = rw(b, RAD_OP(b, "rmsnorm", @@ -798,7 +793,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c nm.ckpt("%s.%lld.self_attn.gate_proj.weight", pre, (long long)l); const char* const src_k = nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l); const char* const src_v = nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l); - if (m.iq8r) { + if (m.rotated_i8) { /* q, gate, k and v read one int8 pair of the norm output: the norm's, or q's own * quantiser's where the norm writes none. The three after q read it as fed. */ ActFP8 h_shared = m.a_h; @@ -889,8 +884,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_NOWEIGHTS), {m.b_attn, m.b_gate}, {m.b_attn}); const char* const src_o = nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l); - /* IQ8R: o_proj quantises the gated product itself (had_quant_act_i8g into `a_attn`). */ - if (m.iq8r) + /* The rotated path quantises o_proj's gated product into its int8 pair. */ + if (m.rotated_i8) RAD_ARCH_TRY(rot_linear(l, lay.ro, nm.f("blk.%d.attn_output", (int)l), {src_o}, g.n_embd, q_dim, RAD_SHARD_COL, m.a_attn, m.b_h, {})); else @@ -918,9 +913,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_NOWEIGHTS), {m.b_x, m.b_h}, {m.b_x}); - /* ---- the feed-forward, the same double norm. With an IQ8R trunk fed by its norms the - * pre-feed-forward norm writes the int8 pair too, as the input norm does. */ - if (m.iq8r && m.a_h.q8_fed) + /* ---- the feed-forward, the same double norm. A rotated trunk can fuse the norm and pair. */ + if (m.rotated_i8 && m.a_h.q8_fed) RAD_ARCH_TRY(lay.nq_ffn.declare(b, gn, lay.w_fnorm, m.b_x, m.a_h, g.n_embd)); else lay.op_fnorm = rw(b, RAD_OP(b, "rmsnorm", @@ -932,7 +926,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c const char* const src_gate_ff = nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l); const char* const src_up = nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l); const char* const src_down = nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l); - if (m.iq8r) { + if (m.rotated_i8) { /* gate|up in the checkpoint's row order, two row parts; then silu(gate) * up. Where * `a_ffn` is fed, gated_had_quant_i8g writes down_proj's int8 pair, and the bf16 * product only when the calibration taps read it (down_proj reads codes alone). @@ -1073,12 +1067,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer)); } - /* ---- the DFlash drafter, declared last: its passes run after the whole trunk's, and the - * planner lays lifetimes out in declaration order. */ + /* ---- the drafter is declared last so its buffers cannot overlap trunk temporaries. */ if (m.taps.n > 0) { - RAD_ARCH_TRY(declare_muse_dflash(&m.df, &m.dfw, &m.kv_draft, b, nm, meta, ctx, g, m.taps, - (int)g.n_layer, m.w_tok, m.w_lm_head)); - m.have_df = true; + if (muse_draft_is_dflash2(meta)) { + RAD_ARCH_TRY(declare_muse_dflash2(&m.df2, &m.df2w, &m.kv_draft, b, nm, meta, ctx, g, + m.taps, (int)g.n_layer, m.w_tok, m.w_lm_head)); + m.have_df2 = true; + } else { + RAD_ARCH_TRY(declare_muse_dflash(&m.df, &m.dfw, &m.kv_draft, b, nm, meta, ctx, g, + m.taps, (int)g.n_layer, m.w_tok, m.w_lm_head)); + m.have_df = true; + } } /* ---- notes for --debug-graph. */ @@ -1104,11 +1103,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (m.g_rope.theta != g.theta) rad_note(b, "rotary runs on the sliding layers only (theta %g); the full-attention layers " "are NoPE", (double)m.g_rope.theta); - if (m.iq8r) - rad_note(b, "IQ8R trunk: every linear gemm_nt_q i8a8h over int8 codes rotated 128 wide, " - "one scale a (row, %d) on both sides; the pre-norms %s, the gated product %s, " - "o_proj quantises its own input; q, gate, k and v read one pair", - RAD_I8_GROUP_WIDE, + if (m.rotated_i8) + rad_note(b, "%s trunk: gemm_nt_q i8a8h over 128-wide Hadamard codes, one activation scale " + "per %lld K columns; the pre-norms %s, the gated product %s, o_proj quantises " + "its own input; q, gate, k and v read one pair", + m.iq8r ? "IQ8R" : "computed-trellis IQR", (long long)m.rot_group, m.a_h.q8_fed ? "write the codes (rmsnorm_had_quant_i8g)" : "are plain (q and gate/up quantise)", m.a_ffn.q8_fed ? "writes down_proj's codes (gated_had_quant_i8g)" @@ -1132,6 +1131,11 @@ static void step(RadCtx* c, const RadBatch* batch) { /* A draft pass runs only the drafter: >0 the query pass on the staged block, <0 the context * pass that projects and stores K/V for the tokens the trunk just committed. */ if (batch->draft_pass != 0) { + if (m.have_df2) { + if (batch->draft_pass > 0) m.df2.step(c, batch); + else m.df2.context(c, batch); + return; + } if (!m.have_df) { rad_step_fail(c, "this serve stages a draft pass but the container carries no drafter"); return; @@ -1171,7 +1175,8 @@ static void step(RadCtx* c, const RadBatch* batch) { * declared a quantiser (op_q) issues it first, over the pair's bf16 plane. */ if (l.nq_attn.op) l.nq_attn.step(c, T); else RAD_ISSUE(c, l.op_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T)); - if (m.iq8r) { + if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, T); + if (m.rotated_i8) { l.rq.step(c, m.a_h, m.b_q, T); l.rgate.step(c, m.a_h, m.b_gate, T); l.rk.step(c, m.a_h, m.b_k, T); @@ -1201,7 +1206,8 @@ static void step(RadCtx* c, const RadBatch* batch) { brows(m.b_attn, T)); RAD_ISSUE_N(c, l.op_sig, T * m.g.n_head, brows(m.b_gate, T), brows(m.b_gate, T)); RAD_ISSUE(c, l.op_mul, brows(m.b_attn, T), brows(m.b_gate, T), brows(m.b_attn, T)); - if (m.iq8r) l.ro.step(c, m.a_attn, m.b_h, T); + if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, T); + if (m.rotated_i8) l.ro.step(c, m.a_attn, m.b_h, T); else l.lo.step(c, m.b_attn, m.b_h, T); if (l.op_ar) RAD_ISSUE_N(c, l.op_ar, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE); RAD_ISSUE(c, l.op_post, brows(m.b_h, T), RAD_W(l.w_post), brows(m.b_h, T)); @@ -1210,7 +1216,8 @@ static void step(RadCtx* c, const RadBatch* batch) { /* -- feed-forward. */ if (l.nq_ffn.op) l.nq_ffn.step(c, T); else RAD_ISSUE(c, l.op_fnorm, brows(m.b_x, T), RAD_W(l.w_fnorm), brows(m.b_h, T)); - if (m.iq8r) { + if (l.cs_mlp >= 0) m.calib.tap(c, (size_t)l.cs_mlp, T); + if (m.rotated_i8) { l.rgu.step(c, m.a_h, m.b_gu, T); if (l.gq_ffn.op) l.gq_ffn.step(c, m.b_gu, T); else RAD_ISSUE(c, l.op_act, brows(m.b_gu, T), brows(m.b_ffn, T)); @@ -1220,6 +1227,7 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_ISSUE(c, l.op_act, brows(m.b_gu, T), brows(m.b_ffn, T)); l.ldown.step(c, m.b_ffn, m.b_h, T); } + if (l.cs_down >= 0) m.calib.tap(c, (size_t)l.cs_down, T); if (l.op_far) RAD_ISSUE_N(c, l.op_far, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE); RAD_ISSUE(c, l.op_fpost, brows(m.b_h, T), RAD_W(l.w_fpost), brows(m.b_h, T)); RAD_ISSUE(c, l.op_fadd, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); @@ -1230,6 +1238,7 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_ISSUE(c, m.op_final_norm, brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok)); + if (m.cs_head >= 0) m.calib.tap(c, (size_t)m.cs_head, T); m.calib.after_step(c, T); /* The lm_head runs only on the rows the sampler asked for; a mid-prompt prefill chunk has @@ -1254,6 +1263,12 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; if (MuseTower::present(meta)) out->enc_merge = 4; /* The drafter denoises `block_size` positions, the anchor row proposes nothing. */ + if (muse_draft_is_dflash2(meta)) { + const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 16); + out->draft_depth = bs > 1 ? (int)(bs - 1) : 15; + out->draft_depth_fixed = 1; + return RAD_OK; + } const long long bs = rad_meta_geti(meta, "draft.block_size", 0); if (bs > 1) { out->draft_depth = (int)(bs - 1); @@ -1274,9 +1289,9 @@ RAD_ARCH_PROBE(museglimmer_ct) RAD_ARCH_MULTI_INSTANCE() RAD_ARCH_PLUGIN(museglimmer_ct, "museglimmer", "compressed-tensors", "0.1.0", "Meta Muse Glimmer 30B dense under compressed-tensors: encoding-aware trunk " - "linears (plain bf16, asymmetric int4/int5 a 128, int8 a 128, or an IQ8R trunk: " - "rotated int8 a 256), gated attention " - "alternating sliding-window (rotary) and NoPE full-attention layers, Gemma-2 " - "style double norms, a bf16 vision tower") + "linears (bf16, asymmetric/symmetric integer, IQ8R, or fwht128 computed-MAD " + "IQR-V4 at i8a8h), gated attention alternating sliding-window (rotary) and NoPE " + "full-attention layers, Gemma-2 style double norms, bf16 vision tower, and DFlash " + "or DFlash2 drafter") RAD_ARCH_CHAT_FORMAT(museglimmer_ct) #endif diff --git a/data/recipes/museglimmer-30b-iq4r-v4.recipe b/data/recipes/museglimmer-30b-iq4r-v4.recipe new file mode 100644 index 00000000..c2333dd6 --- /dev/null +++ b/data/recipes/museglimmer-30b-iq4r-v4.recipe @@ -0,0 +1,34 @@ +# museglimmer-30b-iq4r-v4.recipe -- Muse Glimmer 30B computed-trellis IQR-V4 trunk. +# +# Convert from the BF16 Muse release and local DFlash2 (this selects museglimmer_ct): +# CALIB=/path/to/RADGRAM2 rad-convert \ +# --draft-model \ +# --tokenizer /tokenizer.json \ +# --chat-template /chat_template.jinja \ +# --recipe data/recipes/museglimmer-30b-iq4r-v4.recipe \ +# --set quantization_config.quant_method=compressed-tensors \ +# -o muse-glimmer-30b-iq4r-v4-df2.rad +# +# The seven trunk projections use 128-wide FWHT and computed-MAD trellis codes, read at i8a8h. +# Reuse the existing Muse CalibFull data for MLP gate/up and down only; convert its +# safetensors to RADGRAM2 first. That capture has no attention Hessians, so attention GPTQ uses +# its documented nearest-round fallback. DFlash2 has no tapped Hessians either, so its dense +# linears use the same no-Gram fallback: U3 for the large MLPs and U4 for attention/fc. Keep the +# target head, embedding, norms, vision tower, selector, convolution weights and codebooks +# unchanged. K/V use tcq_rows=128 for TP2's local KV head. + +blk.*.attn_q.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=1024 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 tcq_order=1 +blk.*.attn_gate.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=1024 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 tcq_order=1 +blk.*.attn_k.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=128 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 tcq_order=1 +blk.*.attn_v.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=128 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 tcq_order=1 +blk.*.attn_output.weight gptq codes=u5 tcq=16 tcq_code=mad tcq_rows=256 group=128 scale=bf16 dyn=1 transform=fwht128 tcq_gain=1.20 damp=0.01 +blk.*.ffn_gate_up.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=512 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 calib=$CALIB tcq_order=1 +blk.*.ffn_down.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 calib=$CALIB tcq_order=1 + +dflash.fc.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 +dflash.blk.*.attn_q.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 +dflash.blk.*.attn_k.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 +dflash.blk.*.attn_v.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 +dflash.blk.*.attn_output.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 tcq_gain=1.12 damp=0.01 +dflash.blk.*.ffn_gate_up.weight gptq codes=u3 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 tcq_gain=1.08 damp=0.01 +dflash.blk.*.ffn_down.weight gptq codes=u3 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 tcq_gain=1.08 damp=0.01 diff --git a/libr4d/r4d_nemotron_bf16.hip b/libr4d/r4d_nemotron_bf16.hip index 3d259d89..f68c561e 100644 --- a/libr4d/r4d_nemotron_bf16.hip +++ b/libr4d/r4d_nemotron_bf16.hip @@ -221,9 +221,10 @@ __global__ __launch_bounds__(32) void attention(const uint16_t* q, const uint16_ out[(int64_t)(begin + qi) * ol + head * D + t * 16 + h * 8 + e] = f32_to_bf16(acc[t][e]); } -// Pixtral's RGB 14x14 patch projection has K=588, outside the existing K%16 GEMMs. -// Keep the oracle's ordered f32 dot for this small stem: a WMMA reduction can cross a BF16 -// rounding midpoint. No existing GEMM row accepts this geometry, so no old row is replaced. +// Pixtral's RGB 14x14 patch projection has K=588; Muse Glimmer's temporal-2 stem is 1176. +// Both sit outside the existing K%16 GEMMs. Keep the oracle's ordered f32 dot for this small +// stem: a WMMA reduction can cross a BF16 rounding midpoint. +template __global__ __launch_bounds__(NT) void patch_projection(const uint16_t* a, const uint16_t* w, uint16_t* y, int M, int N, int64_t al, int64_t wl, int64_t yl) { @@ -231,7 +232,7 @@ __global__ __launch_bounds__(NT) void patch_projection(const uint16_t* a, const if (n >= N) return; for (int64_t r = blockIdx.y; r < M; r += gridDim.y) { float sum = 0; - for (int d = 0; d < 588; ++d) + for (int d = 0; d < K; ++d) sum += bf2f(a[r * al + d]) * bf2f(w[(int64_t)n * wl + d]); y[r * yl + n] = f32_to_bf16(sum); } @@ -420,13 +421,19 @@ extern "C" int r4d_rad_pixtral_patch(const RadArgs* a, RadStream stream) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const auto &x = a->t[0], &w = a->t[1], &y = a->t[2]; const int64_t M = x.rank == 2 ? x.shape[0] : 0, N = r4d_geti_or(a, "N", 0); + const int64_t K = r4d_geti_or(a, "K", 0); if (M <= 0 || M > INT_MAX || M > r4d_geti_or(a, "M", 0) || N <= 0 || N > INT_MAX || - r4d_geti_or(a, "K", 0) != 588 || !matrix(x, M, 588) || !matrix(w, N, 588) || - !matrix(y, M, N) || x.stride[1] != 1 || w.stride[1] != 1 || y.stride[1] != 1) + (K != 588 && K != 1176) || !matrix(x, M, K) || !matrix(w, N, K) || !matrix(y, M, N) || + x.stride[1] != 1 || w.stride[1] != 1 || y.stride[1] != 1) return RAD_E_SHAPE; - hipLaunchKernelGGL(patch_projection, dim3((N + NT - 1) / NT, std::min(M, 65535)), - dim3(NT), 0, (hipStream_t)stream, (const uint16_t*)x.data, - (const uint16_t*)w.data, (uint16_t*)y.data, (int)M, (int)N, x.stride[0], - w.stride[0], y.stride[0]); + const dim3 grid((unsigned)((N + NT - 1) / NT), (unsigned)std::min(M, 65535)); + if (K == 588) + hipLaunchKernelGGL((patch_projection<588>), grid, dim3(NT), 0, (hipStream_t)stream, + (const uint16_t*)x.data, (const uint16_t*)w.data, (uint16_t*)y.data, + (int)M, (int)N, x.stride[0], w.stride[0], y.stride[0]); + else + hipLaunchKernelGGL((patch_projection<1176>), grid, dim3(NT), 0, (hipStream_t)stream, + (const uint16_t*)x.data, (const uint16_t*)w.data, (uint16_t*)y.data, + (int)M, (int)N, x.stride[0], w.stride[0], y.stride[0]); return finish(); } diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 569f11e8..3b2835d3 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -6061,6 +6061,7 @@ static const RadConstraint cVsa[] = { static const RadConstraint cQuantCols[] = { C_DIV("n", 8), C_IN("dtype", "bf16") }; static const RadConstraint cPixtralPatch[] = { C_IN("dtype","bf16"), C_EQ("K",588), C_GE("M",1), C_LE("M",2147483647), C_GE("N",1), C_LE("N",2147483647) }; +static const RadConstraint cMusePatch[] = { C_IN("dtype","bf16"), C_EQ("K",1176), C_GE("M",1), C_LE("M",2147483647), C_GE("N",1), C_LE("N",2147483647) }; static const RadConstraint cNemotron[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 2147483647) }; static const RadConstraint cNemotronMerge[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 2147483647), C_EQ("merge",2) }; static const RadConstraint cNemotronRope64[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 2147483647), C_EQ("head_dim",64) }; @@ -6072,6 +6073,10 @@ static const RadKernelInfo kKernels[] = { "K=588, M<=INT_MAX, N<=INT_MAX, pitched bf16 rows", "bf16", RAD_DOMAIN_DEVICE, 10, ROW(cPixtralPatch), NOTUNE, nullptr, nullptr, r4d_rad_pixtral_patch }, +{ "gemm_bf16_muse_patch", "gemm_nt", "gemm", "Muse Glimmer RGB 14x14x2 patch projection", + "K=1176, M<=INT_MAX, N<=INT_MAX, pitched bf16 rows", "bf16", + RAD_DOMAIN_DEVICE, 10, ROW(cMusePatch), NOTUNE, + nullptr, nullptr, r4d_rad_pixtral_patch }, { "position_scale_bf16", "position_scale", "attn", "Ministral rounded query scale", "pitched active rows, nonnegative i32 positions", "bf16", RAD_DOMAIN_DEVICE, 50, ROW(cNemotron), NOTUNE, nullptr, nullptr, r4d_rad_position_scale, r4d_nemotron_scratch }, diff --git a/tests/museglimmer_test.cpp b/tests/museglimmer_test.cpp index fbdd6ca8..452f7271 100644 --- a/tests/museglimmer_test.cpp +++ b/tests/museglimmer_test.cpp @@ -1258,6 +1258,97 @@ MetaKV muse_meta_iq8r() { return k; } +/* Muse IQ4R-V4's computed trellis: 128-wide FWHT, unsigned codes, the MAD plane, and either + * one f32 scale a row plus a shared f32 column factor or a bf16 block scale (the 5-bit o_proj). */ +RadEncoding muse_iqr_v4_enc(uint32_t codes, int64_t tcq_rows, bool row_scale = true) { + RadEncoding e{}; + rad_enc_clear(&e); + rad_enc_copy_str(e.scheme, "trellis"); + rad_enc_add_plane(&e, "codes", codes, 1, 1); + if (row_scale) { + rad_enc_add_plane(&e, "scale", RAD_F32, 1, 0); + rad_enc_add_plane(&e, "scale.col", RAD_F32, 0, 128); + } else { + rad_enc_add_plane(&e, "scale", RAD_BF16, 1, 128); + } + const int t = rad_enc_add_table(&e, "trellis", RAD_I8, (int64_t)1 << 16, 1); + e.plane[t].block[0] = tcq_rows; + e.plane[t].block[1] = 1; + rad_enc_add_table(&e, "trellis.mad", RAD_U32, 2, 1); + rad_enc_copy_str(e.transform, "fwht128"); + return e; +} + +std::vector> muse_iqr_v4_encs() { + return { { "attn_q.", muse_iqr_v4_enc(RAD_U4, 1024) }, + { "attn_gate.", muse_iqr_v4_enc(RAD_U4, 1024) }, + { "attn_k.", muse_iqr_v4_enc(RAD_U4, 128) }, + { "attn_v.", muse_iqr_v4_enc(RAD_U4, 128) }, + { "attn_output.", muse_iqr_v4_enc(RAD_U5, 256, false) }, + { "ffn_gate_up.", muse_iqr_v4_enc(RAD_U4, 512) }, + { "ffn_down.", muse_iqr_v4_enc(RAD_U4, 1024) } }; +} + +MetaKV muse_meta_iqr_v4() { + MetaKV k = muse_meta(); + RadModelMeta m = *k.meta(); + m.n_embd = 256; + m.n_head = 2; + m.n_head_kv = 2; + m.head_dim = 128; + m.n_ff = 512; + k = MetaKV(m); + return k; +} + +MetaKV muse_dflash2_meta() { + MetaKV k = muse_meta_iqr_v4(); + k.set("draft.architectures", "DFlash2DraftModel") + .set("draft.num_hidden_layers", "2") + .set("draft.head_dim", "128") + .set("draft.num_attention_heads", "2") + .set("draft.num_key_value_heads", "2") + .set("draft.hidden_size", "256") + .set("draft.intermediate_size", "512") + .set("draft.rms_norm_eps", "1e-5") + .set("draft.rope_theta", "500000") + .set("draft.vocab_size", "512") + .set("draft.use_sliding_window", "1") + .set("draft.sliding_window", "4") + .set("draft.dflash_config.input_embedding_scale", "1") + .set("draft.dflash_config.output_multiplier", "0.19611613513818404") + .set("draft.dflash_config.final_logit_softcapping", "20") + .set("draft.dflash_config.target_layer_ids", "1 3") + .set("draft.dflash_config.block_size", "4") + .set("draft.dflash_config.mask_token_id", "511") + .set("draft.dflash_config.selector_rank", "64") + .set("draft.dflash_config.selector_top_k", "8") + .set("draft.dflash_config.conv_kernel_size", "2") + .set("draft.dflash_config.conv_group_size", "16"); + return k; +} + +std::vector> muse_dflash2_iqr_encs(bool include_trunk) { + std::vector> encs; + auto add = [&](const std::string& name, uint32_t codes, int64_t rows) { + encs.push_back({name, muse_iqr_v4_enc(codes, rows)}); + }; + add("dflash.fc.", RAD_U4, 256); + encs.push_back({ "dflash.draft_head.", rad_enc_plain(RAD_BF16) }); + for (int l = 0; l < 2; ++l) { + const std::string p = "dflash.blk." + std::to_string(l) + "."; + for (const char* n : { "attn_q.", "attn_k.", "attn_v.", "attn_output." }) + add(p + n, RAD_U4, 256); + add(p + "ffn_gate_up.", RAD_U3, 256); + add(p + "ffn_down.", RAD_U3, 256); + } + if (include_trunk) { + const auto trunk = muse_iqr_v4_encs(); + encs.insert(encs.end(), trunk.begin(), trunk.end()); + } + return encs; +} + /* The op that writes buffer `buf` first among the ops named `name`. */ const RecOp* writer_of(const RadBuilder& b, const char* name, rad_buf buf) { for (const RecOp& o : b.ops) @@ -1267,6 +1358,46 @@ const RecOp* writer_of(const RadBuilder& b, const char* name, rad_buf buf) { } /* namespace */ +/* Computed-MAD IQ4R-V4: the full trunk is on the 128-wide rotated activation grid, including + * centered norm and gated-product producers; q/k/v/gate share a pair, output and down have their + * own. Check decode and prefill graph lint at TP1 and TP2, including the skinny KV shard. */ +TEST(museglimmer_ct_serves_an_iq4r_v4_trunk) { + for (int world : { 1, 2 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + b.encs = muse_iqr_v4_encs(); + RadBuildCtx ctx = muse_ctx(rank, world); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_iqr_v4().meta(), &ctx), RAD_OK); + const museglimmer_ct::Model& m = museglimmer_ct::g_model[rad_build_slot(&ctx)]; + CHECK(m.iqr_v4); + CHECK(!m.iq8r); + CHECK(m.rotated_i8); + CHECK_EQ(m.rot_group, 128); + CHECK(m.a_h.q8_fed); + CHECK(m.a_ffn.q8_fed); + CHECK(!m.a_attn.q8_fed); + CHECK_EQ(count_op(b, "gemm_nt_q"), 56); + CHECK_EQ(count_op(b, "gemm_nt"), 0); + for (const RecOp& o : b.ops) + if (o.op == "gemm_nt_q") { + CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h")); + CHECK_EQ(pint(&o, "group"), 128); + } + for (int pass = 0; pass < 2; ++pass) { + auto k = pass == 0 ? kit(b, { 1, 1, 1, 1 }, {}) : kit(b, {}, { 200 }); + auto v = run_passes(b, museglimmer_ct::step, { k.get() }, rank, world); + CHECK_PASSES(b, v); + CHECK_LINT(b, v[0].get()); + CHECK(v[0]->step_fail.empty()); + const auto is = issued_ops(b, *v[0]); + CHECK_EQ(count_issued(is, "gemm_nt_q"), 56); + CHECK_EQ(count_issued(is, "rmsnorm_had_quant_i8g"), 16); + CHECK_EQ(count_issued(is, "gated_had_quant_i8g"), 8); + CHECK_EQ(count_issued(is, "had_quant_act_i8g"), 8); + } + } +} + /* The IQ8R container at one rank and at two: every trunk linear gemm_nt_q at i8a8h, group 256, over * the codes view (i8 [N, K]) and one "scale,scale.1" u8 view at the logical [N, K]; both pre-norms * rmsnorm_had_quant_i8g (centered, at rms_norm_eps, no residual, no all-reduce form at two ranks: @@ -1641,6 +1772,74 @@ TEST(muse_dflash_reduces_the_sharded_embedding_before_the_block) { } } +/* DFlash2 recognizes its own config fields, probes the IQR fc before declaring activation pairs, + * and serves its U3/U4 linears on the same 128-wide rotated grid. Its 202048-row production head + * is unsupported by tiled 2-bit/int8 head kernels, so retain a BF16 head and apply Muse's own + * multiplier and softcap in the draft graph. */ +TEST(muse_dflash2_serves_a_rotated_iqr_drafter) { + MetaKV mk = muse_dflash2_meta(); + RadBuilder b; + b.encs = muse_dflash2_iqr_encs(false); + RadBuildCtx ctx = spec_ctx(0, 1, 3); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + const museglimmer::Model& m = museglimmer::g_model[rad_build_slot(&ctx)]; + CHECK(m.have_df2); + CHECK(!m.have_df); + CHECK(m.df2.cfg.act_i8); + CHECK_EQ(m.df2.cfg.act_g8, 128); + CHECK(near(m.df2.cfg.omul, 0.19611613513818404, 1e-12)); + CHECK_EQ(m.df2.cfg.scap, 20.0); + CHECK_EQ(find_b(b, "df_srcq")->d.dtype, (uint32_t)RAD_I8); + CHECK_EQ(find_b(b, "df_h2q")->d.dtype, (uint32_t)RAD_I8); + CHECK_EQ(find_b(b, "df_ats")->d.shape[1], 2); + const RecWeight* fc = find_w(b, "dflash.fc.weight"); + REQUIRE(fc != nullptr); + CHECK_EQ(fc->d.dtype, (uint32_t)RAD_U4); + CHECK_EQ(std::string(fc->d.planes), std::string("codes,trellis,trellis.mad")); + const RecWeight* gu = find_w(b, "dflash.blk.0.ffn_gate_up.weight"); + REQUIRE(gu != nullptr); + CHECK_EQ(gu->d.dtype, (uint32_t)RAD_U3); + const RecWeight* head = find_w(b, "dflash.draft_head.weight"); + REQUIRE(head != nullptr); + CHECK_EQ(head->d.dtype, (uint32_t)RAD_BF16); + CHECK_EQ(count_op(b, "logit_softcap"), 2); /* target head and DFlash2 head */ + bool bf16_draft_head = false; + for (const RecOp& o : b.ops) + if (o.op == "gemm_nt" && pint(&o, "N") == 512 && + in(o.w, (rad_weight)w_h(b, "dflash.draft_head.weight"))) + bf16_draft_head = true; + CHECK(bf16_draft_head); + + auto trunk = kit(b, { 1, 1 }, {}); + auto hp = context_pass(b, *trunk); + auto qp = query_pass(b, 1, 4, 3); + auto v = run_passes(b, museglimmer::step, { trunk.get(), hp.get(), qp.get() }, 0, 1); + CHECK_PASSES(b, v); + for (const auto& pass : v) CHECK(pass->step_fail.empty()); + CHECK_EQ(count_issued(issued_ops(b, *v[1]), "had_quant_act_i8g"), 2); + CHECK_EQ(count_issued(issued_ops(b, *v[2]), "had_quant_act_i8g"), 8); + CHECK_EQ(count_issued(issued_ops(b, *v[2]), "gemm_nt_q"), 12); + + /* Exercise the same rotated drafter next to the actual compressed-tensors trunk path. */ + RadBuilder ct; + ct.encs = muse_dflash2_iqr_encs(true); + RadBuildCtx cctx = spec_ctx(0, 1, 3); + REQUIRE_EQ(museglimmer_ct::declare(&ct, mk.meta(), &cctx), RAD_OK); + const museglimmer_ct::Model& cm = museglimmer_ct::g_model[rad_build_slot(&cctx)]; + CHECK(cm.iqr_v4); + CHECK(cm.have_df2); + CHECK(cm.df2.cfg.act_i8); + CHECK_EQ(cm.df2.cfg.act_g8, 128); + auto ctrunk = kit(ct, { 1, 1 }, {}); + auto chp = context_pass(ct, *ctrunk); + auto cqp = query_pass(ct, 1, 4, 3); + auto cv = run_passes(ct, museglimmer_ct::step, { ctrunk.get(), chp.get(), cqp.get() }, 0, 1); + CHECK_PASSES(ct, cv); + for (const auto& pass : cv) CHECK(pass->step_fail.empty()); + CHECK_EQ(count_issued(issued_ops(ct, *cv[0]), "gemm_nt_q"), 56); + CHECK_EQ(count_issued(issued_ops(ct, *cv[2]), "gemm_nt_q"), 12); +} + /* A drafter converted to block fp8 attention and MXFP4 MLPs (the grid of the NVFP4 release's * conversion) is refused with the trunk at declare: neither form is served. */ TEST(muse_dflash_refuses_a_block_fp8_and_mxfp4_drafter) { diff --git a/tests/recipe_test.cpp b/tests/recipe_test.cpp index e3f6417f..bb38cb07 100644 --- a/tests/recipe_test.cpp +++ b/tests/recipe_test.cpp @@ -343,6 +343,67 @@ TEST(the_museglimmer_iq8r_recipe_decides_the_model_it_was_written_for) { CHECK(r.match(n) == nullptr); } +/* Muse Glimmer IQ4R-V4 uses computed-MAD trellises across the trunk and a compact U3/U4 + * DFlash2. The target head, embedding, norms, vision, selector and convolutions remain BF16. */ +TEST(the_museglimmer_iq4r_v4_recipe_selects_the_trellis_trunk) { + const std::string dir = std::string(__FILE__).substr( + 0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes"; + std::ifstream in(dir + "/museglimmer-30b-iq4r-v4.recipe"); + REQUIRE(in.good()); + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + Recipe r; + std::string why; + const char* old_calib = std::getenv("CALIB"); + const std::string saved_calib = old_calib ? old_calib : ""; + setenv("CALIB", "/tmp/muse-glimmer-calib", 1); + const int parse_rc = r.add_text(text, "museglimmer-30b-iq4r-v4.recipe", &why); + if (old_calib) setenv("CALIB", saved_calib.c_str(), 1); + else unsetenv("CALIB"); + REQUIRE_EQ(parse_rc, RAD_OK); + CHECK_EQ(r.rules().size(), (size_t)14); + for (const char* n : { "blk.0.attn_q.weight", "blk.51.attn_gate.weight", + "blk.12.attn_k.weight", "blk.12.attn_v.weight", + "blk.0.ffn_gate_up.weight", "blk.51.ffn_down.weight" }) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK_EQ(m->quantizer, std::string("gptq")); + CHECK(has_opt(m, "tcq", "16")); + CHECK(has_opt(m, "tcq_code", "mad")); + CHECK(has_opt(m, "transform", "fwht128")); + if (std::string(n).find("ffn_") != std::string::npos) + CHECK(has_opt(m, "calib", "/tmp/muse-glimmer-calib")); + else + CHECK(!has_opt(m, "calib", "$CALIB")); + CHECK(has_opt(m, "tcq_order", "1")); + } + const RecipeRule* kv = r.match("blk.1.attn_k.weight"); + REQUIRE(kv != nullptr); + CHECK(has_opt(kv, "tcq_rows", "128")); + for (const char* n : { "dflash.fc.weight", "dflash.blk.0.attn_q.weight", + "dflash.blk.4.attn_output.weight", "dflash.blk.0.ffn_gate_up.weight", + "dflash.blk.4.ffn_down.weight" }) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK_EQ(m->quantizer, std::string("gptq")); + CHECK(has_opt(m, "tcq", "16")); + CHECK(has_opt(m, "tcq_code", "mad")); + CHECK(has_opt(m, "tcq_rows", "256")); + CHECK(has_opt(m, "transform", "fwht128")); + CHECK(!has_opt(m, "calib", "$CALIB")); + } + CHECK(has_opt(r.match("dflash.blk.0.ffn_down.weight"), "codes", "u3")); + CHECK(has_opt(r.match("dflash.blk.0.attn_q.weight"), "codes", "u4")); + const RecipeRule* o = r.match("blk.3.attn_output.weight"); + REQUIRE(o != nullptr); + CHECK(has_opt(o, "codes", "u5")); + CHECK(has_opt(o, "scale", "bf16")); + CHECK(!has_opt(o, "tcq_order", "1")); + for (const char* n : { "output.weight", "token_embd.weight", "blk.3.attn_norm.weight", + "dflash.blk.0.attn_norm.weight", "dflash.sel_pred", "v.proj.weight", + "dspark.fc.weight" }) + CHECK(r.match(n) == nullptr); +} + /* The Flint recipes as they ship, over arch/flint's declared names. flint-iq8r: every trunk linear * (attention, the two dense layers, the shared expert's gate/up) IQ8R, the routed experts and the * shared expert's down projection rotated int8 at a bf16 scale a (row, 128 of K), the head plain