char-fork/llama.cpp

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

Yaniss Amazouzmodels : guard the expert FFN size fallback in nemotron-h against a zero divisor (#28779)e49d2c276

char/aliceai-t5-moe
16.4 KiB336 linesraw
1#include "models.h"
2
3#include <algorithm> // std::max
4
5void llama_model_nemotron_h::load_arch_hparams(llama_model_loader & ml) {
6    ml.get_key(LLM_KV_SSM_CONV_KERNEL,    hparams.ssm_d_conv);
7    ml.get_key(LLM_KV_SSM_INNER_SIZE,     hparams.ssm_d_inner);
8    ml.get_key(LLM_KV_SSM_STATE_SIZE,     hparams.ssm_d_state);
9    ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
10    ml.get_key(LLM_KV_SSM_GROUP_COUNT,    hparams.ssm_n_group);
11
12    // A layer is recurrent IFF the n_head_kv value is set to 0 and
13    // the n_ff value is set to 0. Appended MTP blocks are dense (non-recurrent)
14    for (uint32_t i = 0; i < hparams.n_layer_all; ++i) {
15        hparams.is_recr_impl[i] = i < hparams.n_layer() && hparams.n_head_kv(i) == 0 && hparams.n_ff(i) == 0;
16    }
17
18    ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
19    ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS,     hparams.f_norm_eps); // MTP head final_layernorm
20
21    // Puzzle models set a different expert FFN size per layer
22    ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all, false);
23    ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp,      false);
24    ml.get_key(LLM_KV_EXPERT_SHARED_COUNT,               hparams.n_expert_shared, false);
25    ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM,               hparams.expert_weights_norm, false);
26    ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE,              hparams.expert_weights_scale, false);
27    ml.get_key(LLM_KV_MOE_LATENT_SIZE,                   hparams.moe_latent_size, false);
28
29    switch (hparams.n_layer()) {
30        case 52: type = LLM_TYPE_31B_A3_5B; break; // Nemotron-H_MOE 31B
31        case 56: type = LLM_TYPE_9B; break;
32        case 88:
33            {
34                // Nemotron 3 Super (uniform MoE) and Nemotron 3 Puzzle (per-layer
35                // heterogeneous MoE) both have 88 layers; the per-layer top-k array
36                // is the discriminator.
37                bool heterogeneous = false;
38                for (uint32_t i = 1; i < hparams.n_layer(); ++i) {
39                    heterogeneous |= hparams.n_expert_used_arr[i] != hparams.n_expert_used_arr[0];
40                }
41                type = heterogeneous ? LLM_TYPE_75B_A9B : LLM_TYPE_120B_A12B;
42            } break;
43        default: type = LLM_TYPE_UNKNOWN;
44    }
45}
46
47void llama_model_nemotron_h::load_arch_tensors(llama_model_loader & ml) {
48    LLAMA_LOAD_LOCALS;
49
50    const bool mtp_only    = hparams.n_layer_nextn > 0 && ml.get_weight("blk.0.attn_norm.weight") == nullptr;
51    const int  trunk_flags = mtp_only ? TENSOR_NOT_REQUIRED : 0;
52    const int  mtp_flags   = !ml.load_mtp ? TENSOR_SKIP : 0;
53
54    // mamba2 Mixer SSM params
55    // NOTE: int64_t for tensor dimensions
56    const int64_t d_conv     = hparams.ssm_d_conv;
57    const int64_t d_inner    = hparams.ssm_d_inner;
58    const int64_t d_state    = hparams.ssm_d_state;
59    const int64_t n_ssm_head = hparams.ssm_dt_rank;
60    const int64_t n_group    = hparams.ssm_n_group;
61    const int64_t d_in_proj  = 2*d_inner + 2*n_group*d_state + n_ssm_head;
62    const int64_t moe_n_embd = hparams.moe_latent_size > 0 ? hparams.moe_latent_size : n_embd;
63
64    // embeddings
65    tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
66
67    // output
68    {
69        output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
70        output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
71        // if output is NULL, init from the input tok embed, duplicated to allow offloading
72        if (output == NULL) {
73            output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
74        }
75    }
76
77    for (int i = 0; i < n_layer; ++i) {
78        auto & layer = layers[i];
79
80        // all blocks use the attn norm
81        layer.attn_norm  = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, trunk_flags);
82
83        if (hparams.is_recr(i)) {
84            // ssm layers
85            layer.ssm_in = create_tensor(tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, d_in_proj}, trunk_flags);
86
87            layer.ssm_conv1d = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner + 2*n_group*d_state}, trunk_flags);
88            layer.ssm_conv1d_b = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner + 2*n_group*d_state}, TENSOR_NOT_REQUIRED);
89
90            layer.ssm_dt_b = create_tensor(tn(LLM_TENSOR_SSM_DT, "bias", i), {n_ssm_head}, trunk_flags);
91
92            // no "weight" suffix for these
93            layer.ssm_a = create_tensor(tn(LLM_TENSOR_SSM_A, i), {1, n_ssm_head}, trunk_flags);
94            layer.ssm_d = create_tensor(tn(LLM_TENSOR_SSM_D, i), {1, n_ssm_head}, trunk_flags);
95
96            layer.ssm_norm = create_tensor(tn(LLM_TENSOR_SSM_NORM, "weight", i), {d_inner / n_group, n_group}, trunk_flags);
97
98            // out_proj
99            layer.ssm_out = create_tensor(tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd}, trunk_flags);
100        } else if (hparams.n_ff(i) == 0) {
101            // attention layers (with optional bias)
102            const int64_t n_head_i = hparams.n_head(i);
103            const int64_t n_embd_k_gqa_i = hparams.n_embd_k_gqa(i);
104            const int64_t n_embd_v_gqa_i = hparams.n_embd_v_gqa(i);
105            create_tensor_qkv(layer, i, n_embd, n_embd_head_k * n_head_i, n_embd_k_gqa_i, n_embd_v_gqa_i, trunk_flags);
106            layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head_i, n_embd}, trunk_flags);
107            layer.wo_b = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, TENSOR_NOT_REQUIRED);
108        }  else {
109            if (n_expert != 0) {
110                // Use per-layer n_ff_exp; fall back to n_ff/n_expert_used if absent (existing GGUFs).
111                const int64_t n_ff_exp_i = hparams.n_ff_exp(i)
112                    ? (int64_t)hparams.n_ff_exp(i)
113                    : hparams.n_ff(i) / (int64_t)hparams.n_expert_used(i);
114                const int64_t n_ff_shexp = hparams.n_ff_shexp;
115
116                layer.ffn_gate_inp    = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP,  "weight", i), { n_embd, n_expert}, trunk_flags);
117                layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert         }, trunk_flags);
118
119                // MoE branch
120                layer.ffn_latent_down = create_tensor(tn(LLM_TENSOR_FFN_LATENT_DOWN, "weight", i), {n_embd, moe_n_embd}, TENSOR_NOT_REQUIRED);
121                layer.ffn_latent_up   = create_tensor(tn(LLM_TENSOR_FFN_LATENT_UP,   "weight", i), {moe_n_embd, n_embd}, TENSOR_NOT_REQUIRED);
122
123                layer.ffn_down_exps   = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp_i,   moe_n_embd, n_expert}, trunk_flags);
124                layer.ffn_up_exps     = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS,   "weight", i), {moe_n_embd, n_ff_exp_i, n_expert}, trunk_flags);
125
126                // Shared expert branch
127                layer.ffn_down_shexp  = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, trunk_flags);
128                layer.ffn_up_shexp    = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP,   "weight", i), {n_embd, n_ff_shexp}, trunk_flags);
129
130            } else {
131                // mlp layers
132                layer.ffn_down   = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {  hparams.n_ff(i), n_embd}, trunk_flags);
133                layer.ffn_up     = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", i), {n_embd,   hparams.n_ff(i)}, trunk_flags);
134                layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias",   i), {n_embd}, TENSOR_NOT_REQUIRED);
135                layer.ffn_up_b   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "bias",   i), {hparams.n_ff(i)}, TENSOR_NOT_REQUIRED);
136            }
137        }
138    }
139
140    // NextN/MTP draft head: each predict layer folds an attention sub-layer and a MoE
141    // sub-layer into a single trailing block
142    for (int i = n_layer; i < n_layer_all; ++i) {
143        auto & layer = layers[i];
144
145        const int64_t n_head_i       = hparams.n_head(i);
146        const int64_t n_embd_k_gqa_i = hparams.n_embd_k_gqa(i);
147        const int64_t n_embd_v_gqa_i = hparams.n_embd_v_gqa(i);
148        const int64_t n_expert_used_i = hparams.n_expert_used(i);
149        const int64_t n_ff_exp_i      = hparams.n_ff_exp(i);
150        if (n_ff_exp_i == 0 && n_expert_used_i == 0) {
151            throw std::runtime_error(format("%s: layer %d declares neither expert_feed_forward_length nor expert_used_count, "
152                                            "cannot determine the expert FFN size", __func__, i));
153        }
154        const int64_t n_ff_exp   = n_ff_exp_i ? n_ff_exp_i : n_ff / n_expert_used_i;
155        const int64_t n_ff_shexp = hparams.n_ff_shexp;
156
157        // NextN input-fusion tensors
158        layer.nextn.enorm            = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM,            "weight", i), {n_embd}, mtp_flags);
159        layer.nextn.hnorm            = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM,            "weight", i), {n_embd}, mtp_flags);
160        layer.nextn.eh_proj          = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ,          "weight", i), {2*n_embd, n_embd}, mtp_flags);
161        layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), {n_embd}, mtp_flags);
162
163        // attention sub-layer
164        layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, mtp_flags);
165        create_tensor_qkv(layer, i, n_embd, n_embd_head_k * n_head_i, n_embd_k_gqa_i, n_embd_v_gqa_i, mtp_flags);
166        layer.wo   = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head_i, n_embd}, mtp_flags);
167        layer.wo_b = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias",   i), {n_embd}, mtp_flags | TENSOR_NOT_REQUIRED);
168
169        // MoE sub-layer
170        layer.attn_post_norm  = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM,  "weight", i), {n_embd}, mtp_flags);
171        layer.ffn_gate_inp    = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP,    "weight", i), {n_embd, n_expert}, mtp_flags);
172        layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias",   i), {n_expert}, mtp_flags);
173        layer.ffn_down_exps   = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS,   "weight", i), {n_ff_exp,   moe_n_embd, n_expert}, mtp_flags);
174        layer.ffn_up_exps     = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS,     "weight", i), {moe_n_embd, n_ff_exp,   n_expert}, mtp_flags);
175        layer.ffn_down_shexp  = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP,  "weight", i), {n_ff_shexp, n_embd}, mtp_flags);
176        layer.ffn_up_shexp    = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP,    "weight", i), {n_embd, n_ff_shexp}, mtp_flags);
177    }
178}
179
180std::unique_ptr<llm_graph_context> llama_model_nemotron_h::build_arch_graph(const llm_graph_params & params) const {
181    return std::make_unique<graph>(*this, params);
182}
183
184llama_model_nemotron_h::graph::graph(const llama_model & model, const llm_graph_params & params) :
185    llm_build_mamba_base(params) {
186    const int64_t n_embd_head = hparams.n_embd_head_v();
187    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
188
189    ggml_tensor * cur;
190    ggml_tensor * inpL;
191
192    inpL = build_inp_embd(model.tok_embd);
193    ggml_build_forward_expand(gf, inpL);
194
195    auto * inp = build_inp_mem_hybrid();
196
197    ggml_tensor * inp_out_ids = build_inp_out_ids();
198    const bool extract_final_inp = (size_t) n_layer < cparams.embeddings_layer_inp.size() && cparams.embeddings_layer_inp[n_layer];
199
200    for (int il = 0; il < n_layer; ++il) {
201        res->t_layer_inp[il] = inpL;
202
203        struct ggml_tensor * inpSA = inpL;
204
205        // norm
206        cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il);
207        cb(cur, "attn_norm", il);
208
209        if (hparams.is_recr(il)) {
210            // ssm layer //
211            cur = build_mamba2_layer(inp->get_recr(), cur, model, ubatch, il);
212        } else if (hparams.n_ff(il) == 0) {
213            // attention layer //
214            cur = build_attention_layer(cur, inp->get_attn(), model, n_embd_head, il);
215        } else {
216            cur = build_ffn_layer(cur, model, il);
217        }
218
219        if (il == n_layer - 1 && inp_out_ids && cparams.embeddings_nextn_masked && !extract_final_inp) {
220            cur   = ggml_get_rows(ctx0, cur, inp_out_ids);
221            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
222        }
223
224        // add residual
225        cur = ggml_add(ctx0, cur, inpSA);
226        cb(cur, "nemotron_h_block_out", il);
227
228        // input for next layer
229        inpL = cur;
230    }
231
232    cur = inpL;
233    if (extract_final_inp) {
234        res->t_layer_inp[n_layer] = cur;
235
236        if (inp_out_ids && cparams.embeddings_nextn_masked) {
237            cur = ggml_get_rows(ctx0, cur, inp_out_ids);
238        }
239    }
240
241    cur = build_norm(cur, model.output_norm, NULL, LLM_NORM_RMS, -1);
242
243    // seed for the MTP/NextN draft head
244    cb(cur, "h_nextn", -1);
245    res->t_h_nextn = cur;
246
247    if (!cparams.embeddings_nextn_masked && inp_out_ids) {
248        cur = ggml_get_rows(ctx0, cur, inp_out_ids);
249    }
250
251    cb(cur, "result_norm", -1);
252    res->t_embd = cur;
253
254    // lm_head
255    cur = build_lora_mm(model.output, cur, model.output_s);
256    cb(cur, "result_output", -1);
257    res->t_logits = cur;
258
259    ggml_build_forward_expand(gf, cur);
260}
261
262ggml_tensor * llama_model_nemotron_h::graph::build_attention_layer(ggml_tensor *             cur,
263                                                          llm_graph_input_attn_kv * inp_attn,
264                                                          const llama_model &       model,
265                                                                int64_t             n_embd_head,
266                                                                int                 il) {
267    auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, hparams.n_head(il), hparams.n_head_kv(il), il);
268
269    const float kq_scale =
270        hparams.f_attention_scale == 0.0f ? 1.0f / sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
271    cur = build_attn(inp_attn,
272            model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
273            Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
274    cb(cur, "attn_out", il);
275    return cur;
276}
277
278ggml_tensor * llama_model_nemotron_h::graph::build_ffn_layer(ggml_tensor * cur, const llama_model & model, int il) {
279    if (model.layers[il].ffn_gate_inp == nullptr) {
280        cur = build_ffn(cur,
281                model.layers[il].ffn_up,   model.layers[il].ffn_up_b,   model.layers[il].ffn_up_s,
282                NULL,                      NULL,                        NULL,
283                model.layers[il].ffn_down, model.layers[il].ffn_down_b, model.layers[il].ffn_down_s,
284                NULL,
285                LLM_FFN_RELU_SQR, LLM_FFN_PAR, il);
286        cb(cur, "ffn_out", il);
287    } else {
288        ggml_tensor * inp_emb    = cur;
289        ggml_tensor * inp_latent = cur;
290
291        if (model.layers[il].ffn_latent_down) {
292            inp_latent = ggml_mul_mat(ctx0, model.layers[il].ffn_latent_down, cur);
293        }
294
295        ggml_tensor * router_logits = build_lora_mm(model.layers[il].ffn_gate_inp, cur);
296        cb(router_logits, "ffn_moe_logits", il);
297
298        ggml_tensor * moe_out =
299            build_moe_ffn(inp_latent,
300                    model.layers[il].ffn_gate_inp,
301                    model.layers[il].ffn_up_exps,
302                    nullptr, // no gate
303                    model.layers[il].ffn_down_exps,
304                    model.layers[il].ffn_exp_probs_b,
305                    n_expert, (int64_t)hparams.n_expert_used(il),
306                    LLM_FFN_RELU_SQR, hparams.expert_weights_norm,
307                    hparams.expert_weights_scale,
308                    LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID,
309                    il,
310                    router_logits, nullptr,
311                    model.layers[il].ffn_up_exps_s,
312                    nullptr, // no gate
313                    model.layers[il].ffn_down_exps_s);
314        cb(moe_out, "ffn_moe_out", il);
315
316        if (model.layers[il].ffn_latent_up) {
317            moe_out = ggml_mul_mat(ctx0, model.layers[il].ffn_latent_up, moe_out);
318        }
319
320        ggml_tensor * ffn_shexp = build_ffn(inp_emb,
321                    model.layers[il].ffn_up_shexp,   NULL, model.layers[il].ffn_up_shexp_s,
322                    NULL /* no gate */           ,   NULL, NULL,
323                    model.layers[il].ffn_down_shexp, NULL, model.layers[il].ffn_down_shexp_s,
324                    NULL,
325                    LLM_FFN_RELU_SQR, LLM_FFN_PAR, il);
326        cb(ffn_shexp, "ffn_shexp", il);
327
328        cur = ggml_add(ctx0, moe_out, ffn_shexp);
329        cb(cur, "ffn_out", il);
330    }
331
332    cur = build_cvec(cur, il);
333    cb(cur, "l_out", il);
334
335    return cur;
336}