char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Yaniss Amazouzmodel: add NVIDIA Nemotron-3-Puzzle-75B-A9B (NemotronHPuzzle) support (#25444)c61b98b87

char/aliceai-t5-moe
17.9 KiB390 linesraw
1#include "models.h"
2
3void llama_model_hy_v3::load_arch_hparams(llama_model_loader & ml) {
4    ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,       hparams.f_norm_rms_eps);
5    ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all);
6    ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
7    ml.get_key(LLM_KV_EXPERT_GATING_FUNC,                hparams.expert_gating_func, false);
8    ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE,              hparams.expert_weights_scale, false);
9    ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM,               hparams.expert_weights_norm, false);
10
11    // HY V3 uses a sigmoid router with expert selection bias by default
12    if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_NONE) {
13        hparams.expert_gating_func = LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID;
14    }
15
16    switch (hparams.n_layer()) {
17        case 48: type = LLM_TYPE_30B_A3B; break;
18        default: type = LLM_TYPE_UNKNOWN;
19    }
20}
21
22void llama_model_hy_v3::load_arch_tensors(llama_model_loader & ml) {
23    LLAMA_LOAD_LOCALS;
24
25    const bool mtp_only = (hparams.n_layer_nextn > 0) && (ml.get_weight("blk.0.attn_norm.weight") == nullptr);
26    // Trunk-only: the GGUF declares MTP layers in metadata but the actual MTP
27    // tensors live in a separate file (e.g. user split target/draft). Mark
28    // MTP tensors NOT_REQUIRED so the trunk loads cleanly.
29    const std::string mtp_probe = "blk." + std::to_string(n_layer) + ".nextn.eh_proj.weight";
30    const bool trunk_only = (hparams.n_layer_nextn > 0) && (ml.get_weight(mtp_probe.c_str()) == nullptr);
31    const int trunk_flags = mtp_only   ? TENSOR_NOT_REQUIRED : 0;
32    int mtp_flags         = trunk_only ? TENSOR_NOT_REQUIRED : 0;
33
34    if (!ml.load_mtp) {
35        mtp_flags |= TENSOR_SKIP;
36    }
37
38    tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
39
40    output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
41    output      = create_tensor(tn(LLM_TENSOR_OUTPUT,      "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
42    if (output == NULL) {
43        output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
44    }
45
46    auto load_block = [&](int i, int flags) {
47        auto & layer = layers[i];
48        const int64_t n_ff_exp   = hparams.n_ff_exp() ? hparams.n_ff_exp() : n_ff / (n_expert_used > 0 ? n_expert_used : 1);
49        const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff_exp;
50
51        layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, flags);
52
53        create_tensor_qkv(layer, i, n_embd, n_embd_head_k * n_head, n_embd_k_gqa, n_embd_v_gqa, flags);
54        layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, flags);
55
56        layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k}, flags);
57        layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k}, flags);
58
59        layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, flags);
60
61        // dense FFN (leading dense blocks, first_k_dense_replace)
62        layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, TENSOR_NOT_REQUIRED);
63        layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, TENSOR_NOT_REQUIRED);
64        layer.ffn_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", i), {n_embd, n_ff}, TENSOR_NOT_REQUIRED);
65
66        // MoE routed experts (sigmoid router + expert selection bias)
67        layer.ffn_gate_inp    = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP,    "weight", i), {n_embd, n_expert}, TENSOR_NOT_REQUIRED);
68        layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B,           i), {n_expert}, TENSOR_NOT_REQUIRED);
69        layer.ffn_down_exps   = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS,   "weight", i), {n_ff_exp, n_embd, n_expert}, TENSOR_NOT_REQUIRED);
70        create_tensor_gate_up_exps(layer, i, n_embd, n_ff_exp, n_expert, TENSOR_NOT_REQUIRED);
71
72        // shared expert (always active, no gate)
73        layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_shexp}, TENSOR_NOT_REQUIRED);
74        layer.ffn_up_shexp   = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP,   "weight", i), {n_embd, n_ff_shexp}, TENSOR_NOT_REQUIRED);
75        layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, TENSOR_NOT_REQUIRED);
76    };
77
78    for (int i = 0; i < n_layer; ++i) {
79        load_block(i, trunk_flags);
80    }
81
82    // NextN/MTP block(s): a full hy_v3 decoder block plus the NextN projections.
83    for (int i = n_layer; i < n_layer_all; ++i) {
84        auto & layer = layers[i];
85
86        load_block(i, mtp_flags);
87
88        layer.nextn.eh_proj          = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ,          "weight", i), { 2 * n_embd, n_embd }, mtp_flags);
89        layer.nextn.enorm            = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM,            "weight", i), { n_embd },             mtp_flags);
90        layer.nextn.hnorm            = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM,            "weight", i), { n_embd },             mtp_flags);
91        layer.nextn.embed_tokens     = create_tensor(tn(LLM_TENSOR_NEXTN_EMBED_TOKENS,     "weight", i), { n_embd, n_vocab },    TENSOR_NOT_REQUIRED);
92        layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab },    TENSOR_NOT_REQUIRED);
93        // hy_v3 stores the MTP block's trailing final_layernorm here (applied
94        // after the decoder block, before the shared LM head).
95        layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd },             TENSOR_NOT_REQUIRED);
96    }
97}
98
99std::unique_ptr<llm_graph_context> llama_model_hy_v3::build_arch_graph(const llm_graph_params & params) const {
100    if (params.gtype == LLM_GRAPH_TYPE_DECODER_MTP) {
101        return std::make_unique<graph_mtp>(*this, params);
102    }
103    return std::make_unique<graph>(*this, params);
104}
105
106llama_model_hy_v3::graph::graph(const llama_model & model, const llm_graph_params & params) : llm_graph_context(params) {
107    const int64_t n_embd_head = hparams.n_embd_head_v();
108
109    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
110    GGML_ASSERT(n_embd_head == n_rot);
111
112    ggml_tensor * cur;
113    ggml_tensor * inpL;
114
115    inpL = build_inp_embd(model.tok_embd);
116    ggml_tensor * inp_pos = build_inp_pos();
117    auto * inp_attn = build_attn_inp_kv();
118    ggml_tensor * inp_out_ids = build_inp_out_ids();
119
120    const float kq_scale = 1.0f / sqrtf(float(n_embd_head));
121
122    // MTP/NextN layers are loaded as extra decoder blocks but not executed in the main pass.
123    for (int il = 0; il < n_layer; ++il) {
124        ggml_tensor * inpSA = inpL;
125
126        cur = build_norm(inpL, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il);
127        cb(cur, "attn_norm", il);
128
129        // self-attention
130        {
131            ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);
132
133            auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, n_head, n_head_kv, il);
134
135            Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, nullptr, LLM_NORM_RMS, il);
136            Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, nullptr, LLM_NORM_RMS, il);
137
138            Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, rope_factors,
139                    n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
140                    ext_factor, attn_factor, beta_fast, beta_slow);
141            Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, rope_factors,
142                    n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
143                    ext_factor, attn_factor, beta_fast, beta_slow);
144
145            cur = build_attn(inp_attn,
146                    model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
147                    Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
148            cb(cur, "attn_out", il);
149        }
150
151        if (il == n_layer - 1 && inp_out_ids && cparams.embeddings_nextn_masked) {
152            cur   = ggml_get_rows(ctx0,   cur, inp_out_ids);
153            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
154        }
155
156        ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
157        cb(ffn_inp, "ffn_inp", il);
158
159        cur = build_norm(ffn_inp, model.layers[il].ffn_norm, nullptr, LLM_NORM_RMS, il);
160        cb(cur, "ffn_norm", il);
161
162        if (model.layers[il].ffn_gate_inp == nullptr) {
163            // dense FFN (leading dense blocks)
164            cur = build_ffn(cur,
165                    model.layers[il].ffn_up,   model.layers[il].ffn_up_b,   model.layers[il].ffn_up_s,
166                    model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, model.layers[il].ffn_gate_s,
167                    model.layers[il].ffn_down, model.layers[il].ffn_down_b, model.layers[il].ffn_down_s,
168                    nullptr,
169                    LLM_FFN_SILU, LLM_FFN_PAR, il);
170            cb(cur, "ffn_dense_out", il);
171        } else {
172            // MoE routed experts (sigmoid gating + expert selection bias)
173            ggml_tensor * moe_out = build_moe_ffn(cur,
174                    model.layers[il].ffn_gate_inp,
175                    model.layers[il].ffn_up_exps,
176                    model.layers[il].ffn_gate_exps,
177                    model.layers[il].ffn_down_exps,
178                    model.layers[il].ffn_exp_probs_b,
179                    n_expert, n_expert_used,
180                    LLM_FFN_SILU,
181                    hparams.expert_weights_norm,
182                    hparams.expert_weights_scale,
183                    (llama_expert_gating_func_type) hparams.expert_gating_func,
184                    il,
185                    nullptr, model.layers[il].ffn_gate_up_exps,
186                    model.layers[il].ffn_up_exps_s,
187                    model.layers[il].ffn_gate_exps_s,
188                    model.layers[il].ffn_down_exps_s);
189            cb(moe_out, "ffn_moe_out", il);
190
191            // shared expert (always active, no gate)
192            ggml_tensor * sh_out = build_ffn(cur,
193                    model.layers[il].ffn_up_shexp,   nullptr, model.layers[il].ffn_up_shexp_s,
194                    model.layers[il].ffn_gate_shexp, nullptr, model.layers[il].ffn_gate_shexp_s,
195                    model.layers[il].ffn_down_shexp, nullptr, model.layers[il].ffn_down_shexp_s,
196                    nullptr,
197                    LLM_FFN_SILU, LLM_FFN_PAR, il);
198            cb(sh_out, "ffn_shared_out", il);
199
200            cur = ggml_add(ctx0, moe_out, sh_out);
201            cb(cur, "ffn_out", il);
202        }
203
204        cur = ggml_add(ctx0, cur, ffn_inp);
205        cur = build_cvec(cur, il);
206        cb(cur, "l_out", il);
207
208        inpL = cur;
209    }
210
211    cur = build_norm(inpL, model.output_norm, nullptr, LLM_NORM_RMS, -1);
212
213    // Post-final-norm hidden state: what the MTP draft head's hnorm consumes.
214    // vLLM feeds the target model's normed output states, and the MTP layer
215    // itself returns final_layernorm(h), so the chained state is post-norm.
216    cb(cur, "h_nextn", -1);
217    res->t_h_nextn = cur;
218
219    if (!cparams.embeddings_nextn_masked && inp_out_ids) {
220        cur = ggml_get_rows(ctx0, cur, inp_out_ids);
221    }
222
223    cb(cur, "result_norm", -1);
224    res->t_embd = cur;
225
226    cur = build_lora_mm(model.output, cur, model.output_s);
227    cb(cur, "result_output", -1);
228    res->t_logits = cur;
229
230    ggml_build_forward_expand(gf, cur);
231}
232
233// LLM_GRAPH_TYPE_DECODER_MTP draft head for HY V3 (MoE).
234// Semantics mirror vLLM's HYV3MultiTokenPredictorLayer (hy_v3_mtp.py):
235//   enorm(embed) + hnorm(prev_hidden) -> concat(e, h) -> eh_proj ->
236//   hy_v3 decoder block -> final_layernorm (stored as nextn.shared_head_norm) ->
237//   shared LM head (the main model's lm_head; the checkpoint has no separate
238//   MTP head or MTP embeddings).
239llama_model_hy_v3::graph_mtp::graph_mtp(const llama_model & model, const llm_graph_params & params)
240    : llm_graph_context(params) {
241    GGML_ASSERT(hparams.n_layer_nextn > 0 && "HY_V3 MTP requires n_layer_nextn > 0");
242
243    const int64_t n_embd_head = hparams.n_embd_head_v();
244    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
245    GGML_ASSERT(n_embd_head == n_rot);
246
247    const int il = hparams.n_layer() + cparams.nextn_layer_offset;
248    GGML_ASSERT(cparams.nextn_layer_offset >= 0 &&
249                cparams.nextn_layer_offset < (int) hparams.n_layer_nextn &&
250                "nextn_layer_offset out of range [0, n_layer_nextn)");
251    const auto & layer = model.layers[il];
252
253    GGML_ASSERT(layer.nextn.eh_proj && "MTP block missing nextn.eh_proj");
254    GGML_ASSERT(layer.nextn.enorm   && "MTP block missing nextn.enorm");
255    GGML_ASSERT(layer.nextn.hnorm   && "MTP block missing nextn.hnorm");
256
257    auto inp = std::make_unique<llm_graph_input_embd>(hparams.n_embd);
258
259    inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
260    ggml_set_input(inp->tokens);
261
262    inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, hparams.n_embd, n_tokens);
263    ggml_set_input(inp->embd);
264    ggml_set_name(inp->embd, "mtp_h_input");
265
266    ggml_tensor * tok_embd_w = layer.nextn.embed_tokens ? layer.nextn.embed_tokens : model.tok_embd;
267
268    ggml_tensor * h_input  = inp->embd;
269    ggml_tensor * tok_embd = ggml_get_rows(ctx0, tok_embd_w, inp->tokens);
270    cb(tok_embd, "mtp_tok_embd", il);
271
272    res->add_input(std::move(inp));
273
274    ggml_tensor * inp_pos     = build_inp_pos();
275    ggml_tensor * inp_out_ids = build_inp_out_ids();
276    auto * inp_attn           = build_attn_inp_kv();
277
278    ggml_tensor * h_norm = build_norm(h_input, layer.nextn.hnorm, nullptr, LLM_NORM_RMS, il);
279    cb(h_norm, "mtp_hnorm", il);
280
281    ggml_tensor * e_norm = build_norm(tok_embd, layer.nextn.enorm, nullptr, LLM_NORM_RMS, il);
282    cb(e_norm, "mtp_enorm", il);
283
284    ggml_tensor * concat = ggml_concat(ctx0, e_norm, h_norm, /*dim=*/ 0);
285    cb(concat, "mtp_concat", il);
286
287    ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat);
288    cb(cur, "mtp_eh_proj", il);
289
290    ggml_tensor * inpSA = cur;
291
292    // mtp_block: a full hy_v3 decoder layer (mirrors the trunk graph)
293    cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il);
294    cb(cur, "mtp_attn_norm", il);
295
296    {
297        ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);
298
299        auto [Qcur, Kcur, Vcur] = build_qkv(layer, cur, n_embd_head, n_head, n_head_kv, il);
300
301        Qcur = build_norm(Qcur, layer.attn_q_norm, nullptr, LLM_NORM_RMS, il);
302        Kcur = build_norm(Kcur, layer.attn_k_norm, nullptr, LLM_NORM_RMS, il);
303
304        Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, rope_factors,
305                n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
306                ext_factor, attn_factor, beta_fast, beta_slow);
307        Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, rope_factors,
308                n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
309                ext_factor, attn_factor, beta_fast, beta_slow);
310
311        const float kq_scale = 1.0f / sqrtf(float(n_embd_head));
312
313        cur = build_attn(inp_attn,
314                layer.wo, layer.wo_b, layer.wo_s,
315                Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
316        cb(cur, "mtp_attn_out", il);
317    }
318
319    ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
320    cb(ffn_inp, "mtp_ffn_inp", il);
321
322    cur = build_norm(ffn_inp, layer.ffn_norm, nullptr, LLM_NORM_RMS, il);
323    cb(cur, "mtp_ffn_norm", il);
324
325    if (layer.ffn_gate_inp == nullptr) {
326        cur = build_ffn(cur,
327                layer.ffn_up,   layer.ffn_up_b,   layer.ffn_up_s,
328                layer.ffn_gate, layer.ffn_gate_b, layer.ffn_gate_s,
329                layer.ffn_down, layer.ffn_down_b, layer.ffn_down_s,
330                nullptr,
331                LLM_FFN_SILU, LLM_FFN_PAR, il);
332        cb(cur, "mtp_ffn_dense_out", il);
333    } else {
334        ggml_tensor * moe_out = build_moe_ffn(cur,
335                layer.ffn_gate_inp,
336                layer.ffn_up_exps,
337                layer.ffn_gate_exps,
338                layer.ffn_down_exps,
339                layer.ffn_exp_probs_b,
340                n_expert, n_expert_used,
341                LLM_FFN_SILU,
342                hparams.expert_weights_norm,
343                hparams.expert_weights_scale,
344                (llama_expert_gating_func_type) hparams.expert_gating_func,
345                il,
346                nullptr, layer.ffn_gate_up_exps,
347                layer.ffn_up_exps_s,
348                layer.ffn_gate_exps_s,
349                layer.ffn_down_exps_s);
350        cb(moe_out, "mtp_ffn_moe_out", il);
351
352        ggml_tensor * sh_out = build_ffn(cur,
353                layer.ffn_up_shexp,   nullptr, layer.ffn_up_shexp_s,
354                layer.ffn_gate_shexp, nullptr, layer.ffn_gate_shexp_s,
355                layer.ffn_down_shexp, nullptr, layer.ffn_down_shexp_s,
356                nullptr,
357                LLM_FFN_SILU, LLM_FFN_PAR, il);
358        cb(sh_out, "mtp_ffn_shared_out", il);
359
360        cur = ggml_add(ctx0, moe_out, sh_out);
361        cb(cur, "mtp_ffn_out", il);
362    }
363
364    cur = ggml_add(ctx0, cur, ffn_inp);
365    cb(cur, "mtp_post_ffn", il);
366
367    // final_layernorm applied after the decoder block, before the shared head.
368    // The post-norm hidden state seeds the next MTP step (matches vLLM, where
369    // HYV3MultiTokenPredictorLayer returns final_layernorm(h)).
370    ggml_tensor * head_norm_w = layer.nextn.shared_head_norm
371            ? layer.nextn.shared_head_norm
372            : model.output_norm;
373    GGML_ASSERT(head_norm_w && "HY_V3 MTP: missing both nextn.shared_head_norm and output_norm");
374    cur = build_norm(cur, head_norm_w, nullptr, LLM_NORM_RMS, -1);
375
376    cb(cur, "h_nextn", -1);
377    res->t_h_nextn = cur;
378
379    cur = ggml_get_rows(ctx0, cur, inp_out_ids);
380    cb(cur, "mtp_shared_head_norm", -1);
381
382    ggml_tensor * head_w = layer.nextn.shared_head_head ? layer.nextn.shared_head_head : model.output;
383    ggml_tensor * head_s = layer.nextn.shared_head_head ? layer.nextn.shared_head_head_s : model.output_s;
384    GGML_ASSERT(head_w && "HY_V3 MTP: missing LM head (nextn.shared_head_head or model.output)");
385    cur = build_lora_mm(head_w, cur, head_s);
386    cb(cur, "result_output", -1);
387
388    res->t_logits = cur;
389    ggml_build_forward_expand(gf, cur);
390}