char-fork/llama.cpp

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

PikaPikachuconvert : add `--fuse-qkv` flag to fuse Q/K/V into QKV during HF-to-GGUF conversion (#22780)465e49b9c

char/aliceai-t5-moe
31.1 KiB713 linesraw
1#include "models.h"
2
3void llama_model_deepseek2::load_arch_hparams(llama_model_loader & ml) {
4    uint32_t n_vocab = 0;
5    ml.get_key(LLM_KV_VOCAB_SIZE, n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, n_vocab, false);
6
7    // lite variants include DeepSeek-V2-Lite, GigaChat3-10B-A1.8B, Kanana-2-30B-A3B
8    const bool is_lite = (hparams.n_layer() == 27 || hparams.n_layer() == 26 || (hparams.n_layer() == 48 && n_vocab == 128256));
9
10    ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
11    ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT,   hparams.n_layer_dense_lead, false);
12    if (!is_lite) {
13        ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
14    }
15    ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK,     hparams.n_lora_kv);
16    ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA,   hparams.n_embd_head_k_mla_impl, false);
17    ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, hparams.n_embd_head_v_mla_impl, false);
18    ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all);
19    ml.get_key(LLM_KV_EXPERT_SHARED_COUNT,        hparams.n_expert_shared);
20    ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE,       hparams.expert_weights_scale, false);
21    ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM,        hparams.expert_weights_norm, false);
22    ml.get_key(LLM_KV_EXPERT_GATING_FUNC,         hparams.expert_gating_func, false);
23    if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_NONE) {
24        // for compatibility with existing DeepSeek V2 and V2.5 GGUFs
25        // that have no expert_gating_func model parameter set
26        if ((hparams.n_layer() == 47 || hparams.n_layer() == 48) && n_vocab == 154880) {
27            // GLM 4.7 Lite
28            hparams.expert_gating_func = LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID;
29        } else {
30            hparams.expert_gating_func = LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX;
31        }
32    }
33
34    if (ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul, false)) {
35        // [TAG_DEEPSEEK2_YARN_LOG_MUL_FIX]
36        // cancel the factor from the convert script
37        hparams.rope_yarn_log_mul /= 0.1f;
38    }
39
40    // (optional) temperature tuning - used by mistral-large
41    ml.get_key(LLM_KV_ATTENTION_TEMPERATURE_SCALE,  hparams.f_attn_temp_scale,       false);
42    ml.get_key(LLM_KV_ATTENTION_TEMPERATURE_LENGTH, hparams.n_attn_temp_floor_scale, false); // FIXME why not use temperature_length?
43
44    hparams.f_attn_temp_offset = 0.0f;
45
46    switch (hparams.n_layer()) {
47        case 27: type = LLM_TYPE_16B; break;
48        case 47: type = LLM_TYPE_30B_A3B; break;
49        case 60: type = LLM_TYPE_236B; break;
50        case 61: type = LLM_TYPE_671B; break;
51        default: type = LLM_TYPE_UNKNOWN;
52    }
53}
54
55void llama_model_deepseek2::load_arch_tensors(llama_model_loader & ml) {
56    LLAMA_LOAD_LOCALS;
57    const int64_t n_expert_shared = hparams.n_expert_shared;
58
59    const bool mtp_only = (hparams.n_layer_nextn > 0) && (ml.get_weight("blk.0.attn_norm.weight") == nullptr);
60    const std::string mtp_probe = "blk." + std::to_string(n_layer) + ".nextn.eh_proj.weight";
61    const bool trunk_only = (hparams.n_layer_nextn > 0) && (ml.get_weight(mtp_probe.c_str()) == nullptr);
62    const int trunk_flags = mtp_only  ? TENSOR_NOT_REQUIRED : 0;
63    int       mtp_flags   = trunk_only ? TENSOR_NOT_REQUIRED : 0;
64
65    if (!ml.load_mtp) {
66        mtp_flags |= TENSOR_SKIP;
67    }
68
69    const bool is_mla = hparams.is_mla();
70
71    // note: these are the actual head sizes you get when treating as MHA or after "decompression" using wv_b for MLA
72    const int64_t n_embd_head_k_mla = hparams.n_embd_head_k_mla();
73    const int64_t n_embd_head_v_mla = hparams.n_embd_head_v_mla();
74
75    const int64_t n_embd_head_qk_rope = hparams.n_rot();
76    const int64_t n_embd_head_qk_nope = n_embd_head_k_mla - n_embd_head_qk_rope;
77    GGML_ASSERT(n_embd_head_qk_nope >= 1);
78
79    const int64_t q_lora_rank  = hparams.n_lora_q;
80    const int64_t kv_lora_rank = hparams.n_lora_kv;
81
82    const int64_t n_ff_exp        = hparams.n_ff_exp();
83
84    tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
85
86    // output
87    output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
88    // try to load output.weight, if not found, use token_embd (tied embeddings)
89    output      = create_tensor(tn(LLM_TENSOR_OUTPUT,      "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
90    if (!output) {
91        output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
92    }
93
94    for (int i = 0; i < n_layer_all; ++i) {
95        auto & layer = layers[i];
96        const int flags = i < n_layer ? trunk_flags : mtp_flags;
97
98        layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, flags);
99        if (q_lora_rank > 0) {
100            layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, flags);
101        }
102
103        layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, flags);
104
105        if (q_lora_rank > 0) {
106            layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, flags);
107            layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head * n_embd_head_k_mla}, flags);
108        } else {
109            layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_head * n_embd_head_k_mla}, flags);
110        }
111
112        layer.wkv_a_mqa = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + n_embd_head_qk_rope}, flags);
113
114        // note: only old legacy GGUF files will have the unsplit wkv_b tensor in
115        if (is_mla) {
116            layer.wk_b = create_tensor(tn(LLM_TENSOR_ATTN_K_B, "weight", i), {n_embd_head_qk_nope, kv_lora_rank, n_head}, flags);
117            layer.wv_b = create_tensor(tn(LLM_TENSOR_ATTN_V_B, "weight", i), {kv_lora_rank, n_embd_head_v_mla, n_head}, flags);
118        } else {
119            layer.wkv_b = create_tensor(tn(LLM_TENSOR_ATTN_KV_B, "weight", i), {kv_lora_rank, n_head * (n_embd_head_qk_nope + n_embd_head_v_mla)}, flags);
120        }
121
122        layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head * n_embd_head_v_mla, n_embd}, flags);
123
124        layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, flags);
125
126        if (i < (int) hparams.n_layer_dense_lead) {
127            layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd,   n_ff}, flags);
128            layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {  n_ff, n_embd}, flags);
129            layer.ffn_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", i), {n_embd,   n_ff}, flags);
130        } else {
131            layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, flags);
132            layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED | flags);
133
134            if (n_expert == 0) {
135                throw std::runtime_error("n_expert must be > 0");
136            }
137            if (n_expert_used == 0) {
138                throw std::runtime_error("n_expert_used must be > 0");
139            }
140
141            // MoE branch
142            layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp,   n_embd, n_expert}, flags);
143            create_tensor_gate_up_exps(layer, i, n_embd, n_ff_exp, n_expert, flags);
144
145            // Shared expert branch
146            layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, flags);
147            layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {        n_ff_exp * n_expert_shared, n_embd}, flags);
148            layer.ffn_up_shexp   = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP,   "weight", i), {n_embd, n_ff_exp * n_expert_shared}, flags);
149        }
150
151        // NextN/MTP tensors
152        if (i >= n_layer) {
153            layer.nextn.eh_proj          = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ, "weight", i), { 2 * n_embd, n_embd }, mtp_flags);
154            layer.nextn.enorm            = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM, "weight", i), { n_embd }, mtp_flags);
155            layer.nextn.hnorm            = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM, "weight", i), { n_embd }, mtp_flags);
156            layer.nextn.embed_tokens     = create_tensor(tn(LLM_TENSOR_NEXTN_EMBED_TOKENS, "weight", i), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED | flags);
157            layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED | flags);
158            layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd }, TENSOR_NOT_REQUIRED | flags);
159        }
160    }
161}
162
163std::unique_ptr<llm_graph_context> llama_model_deepseek2::build_arch_graph(const llm_graph_params & params) const {
164    if (params.gtype == LLM_GRAPH_TYPE_DECODER_MTP) {
165        return std::make_unique<graph_mtp>(*this, params);
166    }
167    return std::make_unique<graph>(*this, params);
168}
169
170llama_model_deepseek2::graph_mtp::graph_mtp(const llama_model & model, const llm_graph_params & params) :
171    llm_graph_context(params) {
172    GGML_ASSERT(hparams.n_layer_nextn > 0 && "GLM4 MTP requires n_layer_nextn > 0");
173    GGML_ASSERT(hparams.n_layer_nextn == 1 && "GLM4 MTP currently only supports a single MTP block");
174    GGML_ASSERT(hparams.is_mla() && "GLM4 MTP requires MLA");
175    GGML_ASSERT(hparams.f_attn_temp_scale == 0.0f && "GLM4 MTP does not support attention temperature scaling");
176
177    // The appended MTP block is stored immediately after the main decoder layers.
178    const int il = hparams.n_layer();
179    const auto & layer = model.layers[il];
180
181    GGML_ASSERT(layer.nextn.eh_proj && "MTP block missing nextn.eh_proj");
182    GGML_ASSERT(layer.nextn.enorm   && "MTP block missing nextn.enorm");
183    GGML_ASSERT(layer.nextn.hnorm   && "MTP block missing nextn.hnorm");
184
185    GGML_ASSERT((uint32_t) il >= hparams.n_layer_dense_lead && "GLM4 MTP block expected to use MoE FFN");
186
187    const int64_t n_embd_head_k_mla   = hparams.n_embd_head_k_mla();
188    const int64_t n_embd_head_qk_rope = hparams.n_rot();
189    const int64_t n_embd_head_qk_nope = n_embd_head_k_mla - n_embd_head_qk_rope;
190    const int64_t kv_lora_rank        = hparams.n_lora_kv;
191
192    GGML_ASSERT(n_embd_head_qk_nope >= 1);
193    GGML_ASSERT(hparams.n_lora_q > 0);
194    GGML_ASSERT(layer.wq_a);
195    GGML_ASSERT(layer.attn_q_a_norm);
196    GGML_ASSERT(layer.wq_b);
197    GGML_ASSERT(layer.wkv_a_mqa);
198    GGML_ASSERT(layer.attn_kv_a_norm);
199    GGML_ASSERT(layer.wk_b);
200
201    const bool has_split_exps =
202            layer.ffn_up_exps   != nullptr &&
203            layer.ffn_gate_exps != nullptr;
204
205    const bool has_fused_exps = layer.ffn_gate_up_exps != nullptr;
206
207    GGML_ASSERT(has_split_exps || has_fused_exps);
208    GGML_ASSERT(layer.ffn_norm);
209    GGML_ASSERT(layer.ffn_gate_inp);
210    GGML_ASSERT(layer.ffn_down_exps);
211    GGML_ASSERT(layer.ffn_gate_shexp);
212    GGML_ASSERT(layer.ffn_down_shexp);
213    GGML_ASSERT(layer.ffn_up_shexp);
214
215    auto inp = std::make_unique<llm_graph_input_embd_h>(hparams.n_embd);
216
217    inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
218    ggml_set_input(inp->tokens);
219
220    inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, hparams.n_embd_inp(), n_tokens);
221    ggml_set_input(inp->embd);
222
223    ggml_tensor * tok_embd;
224    if (ubatch.token) {
225        ggml_tensor * tok_embd_w = layer.nextn.embed_tokens
226                ? layer.nextn.embed_tokens
227                : model.tok_embd;
228
229        tok_embd = ggml_get_rows(ctx0, tok_embd_w, inp->tokens);
230    } else {
231        tok_embd = inp->embd;
232    }
233    cb(tok_embd, "mtp_tok_embd", il);
234
235    inp->h = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, hparams.n_embd, n_tokens);
236    ggml_set_input(inp->h);
237    ggml_set_name(inp->h, "mtp_h_input");
238
239    ggml_tensor * h_embd = inp->h;
240
241    res->add_input(std::move(inp));
242
243    ggml_tensor * inp_pos     = build_inp_pos();
244    ggml_tensor * inp_out_ids = build_inp_out_ids();
245
246    auto * inp_attn_k = build_attn_inp_k();
247
248    ggml_tensor * h_norm = build_norm(h_embd, layer.nextn.hnorm, nullptr, LLM_NORM_RMS, il);
249    cb(h_norm, "mtp_hnorm", il);
250
251    ggml_tensor * e_norm = build_norm(tok_embd, layer.nextn.enorm, nullptr, LLM_NORM_RMS, il);
252    cb(e_norm, "mtp_enorm", il);
253
254    ggml_tensor * concat = ggml_concat(ctx0, e_norm, h_norm, 0);
255    cb(concat, "mtp_concat", il);
256
257    ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat, layer.nextn.eh_proj_s);
258    cb(cur, "mtp_eh_proj", il);
259
260    ggml_tensor * inpSA = cur;
261
262    cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il);
263    cb(cur, "mtp_attn_norm", il);
264
265    ggml_tensor * q = ggml_mul_mat(ctx0, layer.wq_a, cur);
266    cb(q, "mtp_q_a", il);
267
268    q = build_norm(q, layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il);
269    cb(q, "mtp_q_a_norm", il);
270
271    q = ggml_mul_mat(ctx0, layer.wq_b, q);
272    cb(q, "mtp_q_b", il);
273
274    ggml_tensor * q_nope =
275        ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
276                ggml_row_size(q->type, n_embd_head_k_mla),
277                ggml_row_size(q->type, n_embd_head_k_mla) * n_head, 0);
278    cb(q_nope, "mtp_q_nope", il);
279
280    ggml_tensor * q_pe =
281        ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
282                ggml_row_size(q->type, n_embd_head_k_mla),
283                ggml_row_size(q->type, n_embd_head_k_mla) * n_head,
284                ggml_row_size(q->type, n_embd_head_qk_nope));
285    cb(q_pe, "mtp_q_pe", il);
286
287    ggml_tensor * kv_cmpr_pe = ggml_mul_mat(ctx0, layer.wkv_a_mqa, cur);
288    cb(kv_cmpr_pe, "mtp_kv_cmpr_pe", il);
289
290    ggml_tensor * kv_cmpr =
291        ggml_view_2d(ctx0, kv_cmpr_pe, kv_lora_rank, n_tokens,
292                ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), 0);
293    cb(kv_cmpr, "mtp_kv_cmpr", il);
294
295    ggml_tensor * k_pe =
296        ggml_view_3d(ctx0, kv_cmpr_pe, n_embd_head_qk_rope, 1, n_tokens,
297                ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope),
298                ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope),
299                ggml_row_size(kv_cmpr_pe->type, kv_lora_rank));
300    cb(k_pe, "mtp_k_pe", il);
301
302    kv_cmpr = build_norm(kv_cmpr, layer.attn_kv_a_norm, nullptr, LLM_NORM_RMS, il);
303    cb(kv_cmpr, "mtp_kv_cmpr_norm", il);
304
305    GGML_ASSERT(ext_factor >= 0.0f);
306
307    const float attn_factor_org =
308            attn_factor * (1.0f + 0.1f * logf(1.0f / freq_scale));
309
310    const float mscale =
311            attn_factor_org * (1.0f + 0.1f * hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
312
313    const float kq_scale =
314            1.0f * mscale * mscale / sqrtf(float(n_embd_head_k_mla));
315
316    q_pe = ggml_rope_ext(ctx0, q_pe, inp_pos, nullptr,
317            n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
318            ext_factor, attn_factor, beta_fast, beta_slow);
319    cb(q_pe, "mtp_q_pe_rope", il);
320
321    k_pe = ggml_rope_ext(ctx0, k_pe, inp_pos, nullptr,
322            n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
323            ext_factor, attn_factor, beta_fast, beta_slow);
324    cb(k_pe, "mtp_k_pe_rope", il);
325
326    q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
327    cb(q_nope, "mtp_q_nope_perm", il);
328
329    ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, layer.wk_b, q_nope);
330    cb(q_nope_absorbed, "mtp_q_nope_absorbed", il);
331
332    q_nope_absorbed = ggml_permute(ctx0, q_nope_absorbed, 0, 2, 1, 3);
333    cb(q_nope_absorbed, "mtp_q_nope_absorbed_perm", il);
334
335    ggml_tensor * Qcur = ggml_concat(ctx0, q_nope_absorbed, q_pe, 0);
336    cb(Qcur, "mtp_Qcur", il);
337
338    kv_cmpr = ggml_reshape_3d(ctx0, kv_cmpr, hparams.n_lora_kv, 1, n_tokens);
339    cb(kv_cmpr, "mtp_kv_cmpr_reshape", il);
340
341    ggml_tensor * Kcur = ggml_concat(ctx0, kv_cmpr, k_pe, 0);
342    cb(Kcur, "mtp_Kcur", il);
343
344    ggml_tensor * Vcur = kv_cmpr;
345    cb(Vcur, "mtp_Vcur", il);
346
347    cur = build_attn(inp_attn_k,
348            layer.wo, nullptr, layer.wo_s,
349            Qcur, Kcur, Vcur, nullptr, nullptr, layer.wv_b, kq_scale, il);
350    cb(cur, "mtp_attn_out", il);
351
352    ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
353    cb(ffn_inp, "mtp_ffn_inp", il);
354
355    cur = build_norm(ffn_inp, layer.ffn_norm, nullptr, LLM_NORM_RMS, il);
356    cb(cur, "mtp_ffn_norm", il);
357
358    ggml_tensor * moe_out = build_moe_ffn(cur,
359            layer.ffn_gate_inp,
360            layer.ffn_up_exps,
361            layer.ffn_gate_exps,
362            layer.ffn_down_exps,
363            layer.ffn_exp_probs_b,
364            n_expert, n_expert_used,
365            LLM_FFN_SILU, hparams.expert_weights_norm,
366            hparams.expert_weights_scale,
367            (llama_expert_gating_func_type) hparams.expert_gating_func,
368            il,
369            nullptr,
370            layer.ffn_gate_up_exps);
371    cb(moe_out, "mtp_ffn_moe_out", il);
372
373    ggml_tensor * ffn_shexp = build_ffn(cur,
374            layer.ffn_up_shexp, nullptr, nullptr,
375            layer.ffn_gate_shexp, nullptr, nullptr,
376            layer.ffn_down_shexp, nullptr, nullptr,
377            nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
378    cb(ffn_shexp, "mtp_ffn_shexp", il);
379
380    cur = ggml_add(ctx0, moe_out, ffn_shexp);
381    cb(cur, "mtp_ffn_out", il);
382
383    cur = ggml_add(ctx0, cur, ffn_inp);
384    cb(cur, "mtp_post_ffn", il);
385
386    ggml_tensor * head_norm_w = layer.nextn.shared_head_norm
387            ? layer.nextn.shared_head_norm
388            : model.output_norm;
389    GGML_ASSERT(head_norm_w && "GLM4 MTP: missing both nextn.shared_head_norm and output_norm");
390
391    cur = build_norm(cur, head_norm_w, nullptr, LLM_NORM_RMS, -1);
392    cb(cur, "h_nextn", -1);
393    res->t_h_nextn = cur;
394
395    if (inp_out_ids) {
396        cur = ggml_get_rows(ctx0, cur, inp_out_ids);
397    }
398    cb(cur, "mtp_shared_head_norm", -1);
399
400    ggml_tensor * head_w = layer.nextn.shared_head_head
401            ? layer.nextn.shared_head_head
402            : model.output;
403
404    ggml_tensor * head_s = layer.nextn.shared_head_head
405            ? layer.nextn.shared_head_head_s
406            : model.output_s;
407
408    GGML_ASSERT(head_w && "GLM4 MTP: missing LM head (nextn.shared_head_head or model.output)");
409
410    cur = build_lora_mm(head_w, cur, head_s);
411    cb(cur, "result_output", -1);
412
413    res->t_logits = cur;
414    ggml_build_forward_expand(gf, cur);
415}
416
417llama_model_deepseek2::graph::graph(const llama_model & model, const llm_graph_params & params) :
418    llm_graph_context(params) {
419    // lite variants include DeepSeek-V2-Lite, GigaChat3-10B-A1.8B
420    bool is_ocr = model.arch == LLM_ARCH_DEEPSEEK2OCR;
421
422    const bool is_mla = hparams.is_mla();
423
424    // note: these are the actual head sizes you get when treating as MHA or after "decompression" using wv_b for MLA
425    const int64_t n_embd_head_k = hparams.n_embd_head_k_mla();
426    const int64_t n_embd_head_v = hparams.n_embd_head_v_mla();
427
428    const int64_t n_embd_head_qk_rope = hparams.n_rot();
429    const int64_t n_embd_head_qk_nope = n_embd_head_k - n_embd_head_qk_rope;
430
431    const uint32_t kv_lora_rank = hparams.n_lora_kv;
432
433    // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
434    // See https://github.com/ggml-org/llama.cpp/discussions/7416 for detailed explanation.
435    // And also: https://github.com/ggml-org/llama.cpp/pull/17945 [TAG_DEEPSEEK2_YARN_LOG_MUL_FIX]
436
437    // first cancel the adjustment from llama_hparams::yarn_attn_factor_adjust to get the original attn_factor
438    GGML_ASSERT(ext_factor >= 0.0f);
439    const float attn_factor_org = attn_factor * (1.0f + 0.1f * logf(1.0f / freq_scale));
440
441    // use the original attn_factor to pre-scale the kq_scale
442    const float mscale   = attn_factor_org * (1.0f + 0.1f * hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
443    const float kq_scale = 1.0f * mscale * mscale / sqrtf(float(n_embd_head_k));
444
445    ggml_tensor * cur;
446    ggml_tensor * inpL;
447
448    // {n_embd, n_tokens}
449    inpL = build_inp_embd(model.tok_embd);
450
451    // (optional) temperature tuning - used by mistral-large
452    ggml_tensor * inp_attn_scale = nullptr;
453    if (hparams.f_attn_temp_scale != 0.0f) {
454        inp_attn_scale = build_inp_attn_scale();
455    }
456
457    // inp_pos - contains the positions
458    ggml_tensor * inp_pos = build_inp_pos();
459
460    auto * inp_attn_kv = !is_mla ? build_attn_inp_kv() : nullptr;
461    auto * inp_attn_k  =  is_mla ? build_attn_inp_k()  : nullptr;
462
463    ggml_tensor * inp_out_ids = build_inp_out_ids();
464
465    for (int il = 0; il < n_layer; ++il) {
466        ggml_tensor * inpSA = inpL;
467
468        // norm
469        cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il);
470        cb(cur, "attn_norm", il);
471
472        // self_attention
473        if (is_ocr) {
474            const int n_embed_head = hparams.n_embd / hparams.n_head();
475            const int ocr_rope_type = GGML_ROPE_TYPE_NEOX;
476            GGML_ASSERT(n_embed_head == n_embd_head_k && n_embed_head == n_embd_head_v);
477
478            auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur,
479                    n_embed_head, n_head, n_head, il);
480            cb(Qcur, "q", il);
481            cb(Kcur, "k", il);
482            cb(Vcur, "v", il);
483
484            GGML_ASSERT(fabs(freq_base - 10000.0) < 1e-4);
485            Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr, n_embed_head, ocr_rope_type, 0, freq_base, 1, 0, 1, 0, 0);
486            Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr, n_embed_head, ocr_rope_type, 0, freq_base, 1, 0, 1, 0, 0);
487            cb(Qcur, "q_pe", il);
488            cb(Kcur, "k_pe", il);
489
490            cur = build_attn(inp_attn_kv,
491                        model.layers[il].wo, NULL, model.layers[il].wo_s,
492                        Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
493            cb(cur, "attn_out", il);
494        }
495        else {
496            ggml_tensor * q = NULL;
497
498            const bool is_lite = model.layers[il].wq;
499
500            if (!is_lite) {
501                q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
502                cb(q, "q", il);
503
504                q = build_norm(q, model.layers[il].attn_q_a_norm, nullptr, LLM_NORM_RMS, il);
505                cb(q, "q", il);
506
507                q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
508                cb(q, "q", il);
509            } else {
510                q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
511                cb(q, "q", il);
512            }
513            // {n_embd_head_k, n_head, n_tokens}
514            q = ggml_reshape_3d(ctx0, q, n_embd_head_k, n_head, n_tokens);
515            cb(q, "q", il);
516
517            ggml_tensor * kv_cmpr_pe = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
518            cb(kv_cmpr_pe, "kv_cmpr_pe", il);
519
520            // split into {kv_lora_rank, n_tokens}
521            ggml_tensor * kv_cmpr =
522                ggml_view_2d(ctx0, kv_cmpr_pe, kv_lora_rank, n_tokens,
523                             ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), 0);
524            cb(kv_cmpr, "kv_cmpr", il);
525
526            // and {n_embd_head_qk_rope, 1, n_tokens}
527            ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_cmpr_pe, n_embd_head_qk_rope, 1, n_tokens,
528                                              ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope),
529                                              ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope),
530                                              ggml_row_size(kv_cmpr_pe->type, kv_lora_rank));
531            cb(k_pe, "k_pe", il);
532
533            k_pe = ggml_rope_ext(ctx0, k_pe, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
534                                 ext_factor, attn_factor, beta_fast, beta_slow);
535            cb(k_pe, "k_pe", il);
536
537            kv_cmpr = build_norm(kv_cmpr, model.layers[il].attn_kv_a_norm, nullptr, LLM_NORM_RMS, il);
538            cb(kv_cmpr, "kv_cmpr", il);
539
540            if (is_mla) {
541                // split into {n_embd_head_qk_nope, n_head, n_tokens}
542                ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
543                                                    q->nb[1], q->nb[2], 0);
544                cb(q_nope, "q_nope", il);
545
546                // and {n_embd_head_qk_rope, n_head, n_tokens}
547                ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
548                                                  q->nb[1], q->nb[2], ggml_row_size(q->type, n_embd_head_qk_nope));
549                cb(q_pe, "q_pe", il);
550
551                q_pe = ggml_rope_ext(ctx0, q_pe, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
552                                     ext_factor, attn_factor, beta_fast, beta_slow);
553                cb(q_pe, "q_pe", il);
554
555                // {n_embd_head_qk_nope, n_tokens, n_head}
556                q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
557                cb(q_nope, "q_nope_perm", il);
558
559                // {n_embd_head_qk_nope, kv_lora_rank, n_head} x {n_embd_head_qk_nope, n_tokens, n_head}
560                ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, model.layers[il].wk_b, q_nope);
561                cb(q_nope_absorbed, "q_nope_absorbed", il);
562
563                // {kv_lora_rank, n_head, n_tokens}
564                q_nope_absorbed = ggml_permute(ctx0, q_nope_absorbed, 0, 2, 1, 3);
565                cb(q_nope_absorbed, "q_nope_absorbed_perm", il);
566
567                // {n_embd_head_qk_rope + kv_lora_rank, n_head, n_tokens}
568                // note: rope must go first for in-place context shifting in build_rope_shift()
569                ggml_tensor * Qcur = ggml_concat(ctx0, q_nope_absorbed, q_pe, 0);
570                cb(Qcur, "Qcur", il);
571
572                kv_cmpr = ggml_reshape_3d(ctx0, kv_cmpr, kv_lora_rank, 1, n_tokens);
573                cb(kv_cmpr, "kv_cmpr_reshape", il);
574
575                // {n_embd_head_qk_rope + kv_lora_rank, 1, n_tokens}
576                ggml_tensor * Kcur = ggml_concat(ctx0, kv_cmpr, k_pe, 0);
577                cb(Kcur, "Kcur", il);
578
579                // {kv_lora_rank, 1, n_tokens}
580                ggml_tensor * Vcur = kv_cmpr;
581                cb(Vcur, "Vcur", il);
582
583                if (inp_attn_scale) {
584                    // apply llama 4 temperature scaling
585                    Qcur = ggml_mul(ctx0, Qcur, inp_attn_scale);
586                    cb(Qcur, "Qcur_attn_temp_scaled", il);
587                }
588
589                // note: MLA with the absorption optimization converts into MQA (ie: GQA with 1 group)
590                cur = build_attn(inp_attn_k,
591                        model.layers[il].wo, NULL, model.layers[il].wo_s,
592                        Qcur, Kcur, Vcur, nullptr, nullptr, model.layers[il].wv_b, kq_scale, il);
593            } else {
594                ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_cmpr);
595                cb(kv, "kv", il);
596
597                // split into {n_embd_head_qk_nope, n_head, n_tokens}
598                ggml_tensor * k_nope =
599                    ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
600                                 ggml_row_size(kv->type, n_embd_head_qk_nope + n_embd_head_v),
601                                 ggml_row_size(kv->type, n_embd_head_qk_nope + n_embd_head_v) * n_head, 0);
602                cb(k_nope, "k_nope_view", il);
603
604                // and {n_embd_head_v, n_head, n_tokens}
605                ggml_tensor * Vcur = ggml_view_3d(ctx0, kv, n_embd_head_v, n_head, n_tokens,
606                                                  ggml_row_size(kv->type, n_embd_head_qk_nope + n_embd_head_v),
607                                                  ggml_row_size(kv->type, n_embd_head_qk_nope + n_embd_head_v) * n_head,
608                                                  ggml_row_size(kv->type, n_embd_head_qk_nope));
609                cb(Vcur, "Vcur_view", il);
610
611                Vcur = ggml_cont(ctx0, Vcur);
612                cb(Vcur, "Vcur_cont", il);
613
614                // RoPE is applied to the trailing dims only
615                ggml_tensor * Qcur = ggml_rope_ext(ctx0, q, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
616                                                   freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
617                Qcur = ggml_rope_set_offset(Qcur, n_embd_head_qk_nope);
618                cb(Qcur, "Qcur", il);
619
620                ggml_tensor * Kcur = ggml_concat(ctx0, k_nope,
621                        ggml_repeat_4d(ctx0, k_pe, n_embd_head_qk_rope, n_head, n_tokens, 1), 0);
622                cb(Kcur, "Kcur", il);
623
624                if (inp_attn_scale) {
625                    // apply llama 4 temperature scaling
626                    Qcur = ggml_mul(ctx0, Qcur, inp_attn_scale);
627                    cb(Qcur, "Qcur_attn_temp_scaled", il);
628                }
629
630                // note: MLA without the absorption optimization converts into MHA (ie: GQA with full n_head groups)
631                cur = build_attn(inp_attn_kv,
632                            model.layers[il].wo, NULL, model.layers[il].wo_s,
633                            Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
634            }
635        }
636        if (il == n_layer - 1 && inp_out_ids && (!cparams.embeddings_nextn || cparams.embeddings_nextn_masked)) {
637            cur   = ggml_get_rows(ctx0, cur, inp_out_ids);
638            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
639        }
640        ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
641        cb(ffn_inp, "ffn_inp", il);
642
643        cur = build_norm(ffn_inp, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il);
644        cb(cur, "ffn_norm", il);
645
646        if ((uint32_t) il < hparams.n_layer_dense_lead) {
647            cur = build_ffn(cur,
648                model.layers[il].ffn_up, NULL, NULL,
649                model.layers[il].ffn_gate, NULL, NULL,
650                model.layers[il].ffn_down, NULL, NULL,
651                NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
652            cb(cur, "ffn_out", il);
653        } else {
654            // MoE branch
655            ggml_tensor * moe_out = build_moe_ffn(cur,
656                model.layers[il].ffn_gate_inp,
657                model.layers[il].ffn_up_exps,
658                model.layers[il].ffn_gate_exps,
659                model.layers[il].ffn_down_exps,
660                model.layers[il].ffn_exp_probs_b,
661                n_expert, n_expert_used,
662                LLM_FFN_SILU, hparams.expert_weights_norm,
663                hparams.expert_weights_scale,
664                (llama_expert_gating_func_type) hparams.expert_gating_func,
665                il,
666                nullptr,
667                model.layers[il].ffn_gate_up_exps);
668            cb(moe_out, "ffn_moe_out", il);
669
670            // FFN shared expert
671            {
672                ggml_tensor * ffn_shexp =
673                    build_ffn(cur,
674                        model.layers[il].ffn_up_shexp, NULL, NULL,
675                        model.layers[il].ffn_gate_shexp, NULL, NULL,
676                        model.layers[il].ffn_down_shexp, NULL, NULL,
677                        NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
678                cb(ffn_shexp, "ffn_shexp", il);
679
680                cur = ggml_add(ctx0, moe_out, ffn_shexp);
681                cb(cur, "ffn_out", il);
682            }
683        }
684        cur = ggml_add(ctx0, cur, ffn_inp);
685
686        cur = build_cvec(cur, il);
687        cb(cur, "l_out", il);
688
689        // input for next layer
690        inpL = cur;
691    }
692    cur = inpL;
693
694    cur = build_norm(cur, model.output_norm, NULL, LLM_NORM_RMS, -1);
695
696    cb(cur, "h_nextn", -1);
697    res->t_h_nextn = cur;
698
699    if (cparams.embeddings_nextn && !cparams.embeddings_nextn_masked && inp_out_ids) {
700        cur = ggml_get_rows(ctx0, cur, inp_out_ids);
701    }
702
703    cb(cur, "result_norm", -1);
704    res->t_embd = cur;
705
706    // lm_head
707    cur = ggml_mul_mat(ctx0, model.output, cur);
708
709    cb(cur, "result_output", -1);
710    res->t_logits = cur;
711
712    ggml_build_forward_expand(gf, cur);
713}