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
36.4 KiB822 linesraw
1#include "models.h"
2#include "llama-memory-recurrent.h"
3
4void llama_model_qwen3next::load_arch_hparams(llama_model_loader & ml) {
5    ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all, false);
6    ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
7    ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,       hparams.f_norm_rms_eps);
8
9    // Load linear attention (gated delta net) parameters
10    ml.get_key(LLM_KV_SSM_CONV_KERNEL,    hparams.ssm_d_conv);
11    ml.get_key(LLM_KV_SSM_INNER_SIZE,     hparams.ssm_d_inner);
12    ml.get_key(LLM_KV_SSM_STATE_SIZE,     hparams.ssm_d_state);
13    ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
14    ml.get_key(LLM_KV_SSM_GROUP_COUNT,    hparams.ssm_n_group);
15
16    // Mark recurrent layers (linear attention layers).
17    if (!ml.get_key_or_arr(LLM_KV_ATTENTION_RECURRENT_LAYERS, hparams.is_recr_impl, hparams.n_layer_all, false)) {
18        uint32_t full_attn_interval = 4;
19        ml.get_key(LLM_KV_FULL_ATTENTION_INTERVAL, full_attn_interval, false);
20        for (uint32_t i = 0; i < hparams.n_layer_all; ++i) {
21            hparams.is_recr_impl[i] = (i < hparams.n_layer()) && ((i + 1) % full_attn_interval != 0);
22        }
23    }
24
25    switch (hparams.n_layer()) {
26        case 48: type = LLM_TYPE_80B_A3B; break;
27        default: type = LLM_TYPE_UNKNOWN;
28    }
29}
30
31void llama_model_qwen3next::load_arch_tensors(llama_model_loader & ml) {
32    LLAMA_LOAD_LOCALS;
33
34    if (n_expert == 0) {
35        throw std::runtime_error(arch_name() + " model cannot have zero experts");
36    }
37
38    const bool mtp_only = (hparams.n_layer_nextn > 0) && (ml.get_weight("blk.0.attn_norm.weight") == nullptr);
39    const int trunk_flags = mtp_only ? TENSOR_NOT_REQUIRED : 0;
40    int mtp_flags = !ml.load_mtp ? TENSOR_SKIP : 0;
41
42    tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, 0);
43
44    // output
45    output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd }, 0);
46    output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED);
47
48    // if output is NULL, init from the input tok embed
49    if (output == NULL) {
50        output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, TENSOR_DUPLICATED);
51    }
52
53    const int64_t n_ff_exp = hparams.n_ff_exp() ? hparams.n_ff_exp() : n_ff / n_expert_used;
54
55    // Calculate dimensions from hyperparameters
56    const int64_t head_k_dim = hparams.ssm_d_state;
57    const int64_t head_v_dim = hparams.ssm_d_state;
58    const int64_t n_k_heads  = hparams.ssm_n_group;
59    const int64_t n_v_heads  = hparams.ssm_dt_rank;
60    const int64_t key_dim    = head_k_dim * n_k_heads;
61    const int64_t value_dim  = head_v_dim * n_v_heads;
62    const int64_t conv_dim   = key_dim * 2 + value_dim;
63
64    // Calculate projection sizes
65    const int64_t qkvz_dim = key_dim * 2 + value_dim * 2;
66    const int64_t ba_dim   = n_v_heads * 2;
67
68    auto load_block_trunk = [&](int il, int flags) {
69        auto & layer = layers[il];
70        const uint32_t n_ff_shexp = hparams.n_ff_shexp > 0 ? hparams.n_ff_shexp : hparams.n_ff(il);
71
72        layer.attn_norm      = create_tensor(tn(LLM_TENSOR_ATTN_NORM,      "weight", il), { n_embd }, flags);
73        layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", il), { n_embd }, flags);
74
75        if (!hparams.is_recr(il)) {
76            // Attention layers
77            create_tensor_qkv(layer, il, n_embd, n_embd_head_k * n_head * 2, n_embd_k_gqa, n_embd_v_gqa, flags);
78            layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", il), { n_embd_head_k * n_head, n_embd }, flags);
79            // Q/K normalization for attention layers
80            layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", il), { n_embd_head_k }, flags);
81            layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", il), { n_embd_head_k }, flags);
82        } else {
83            // Linear attention (gated delta net) specific tensors
84            // Create tensors with calculated dimensions
85            // note: ssm_in is used by legacy GGUF
86            layer.ssm_in         = create_tensor(tn(LLM_TENSOR_SSM_IN,         "weight", il), { n_embd, qkvz_dim }, TENSOR_NOT_REQUIRED | flags);
87            layer.wqkv           = create_tensor(tn(LLM_TENSOR_ATTN_QKV,       "weight", il), { n_embd, key_dim * 2 + value_dim }, TENSOR_NOT_REQUIRED | flags);
88            layer.wqkv_gate      = create_tensor(tn(LLM_TENSOR_ATTN_GATE,      "weight", il), { n_embd, value_dim }, TENSOR_NOT_REQUIRED | flags);
89            layer.ssm_conv1d     = create_tensor(tn(LLM_TENSOR_SSM_CONV1D,     "weight", il), { hparams.ssm_d_conv, conv_dim }, flags);
90            layer.ssm_dt         = create_tensor(tn(LLM_TENSOR_SSM_DT,         "bias",   il), { hparams.ssm_dt_rank }, flags);
91            layer.ssm_a          = create_tensor(tn(LLM_TENSOR_SSM_A_NOSCAN,             il), { hparams.ssm_dt_rank }, flags);
92            layer.ssm_beta_alpha = create_tensor(tn(LLM_TENSOR_SSM_BETA_ALPHA, "weight", il), { n_embd, ba_dim }, flags);
93            layer.ssm_norm       = create_tensor(tn(LLM_TENSOR_SSM_NORM,       "weight", il), { head_v_dim }, flags);
94            layer.ssm_out        = create_tensor(tn(LLM_TENSOR_SSM_OUT,        "weight", il), { value_dim, n_embd }, flags);
95        }
96
97        layer.ffn_gate_inp  = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP,  "weight", il), { n_embd, n_expert }, flags);
98        layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", il), { n_ff_exp, n_embd, n_expert }, flags);
99        create_tensor_gate_up_exps(layer, il, n_embd, n_ff_exp, n_expert, flags);
100
101        // Shared experts
102        layer.ffn_gate_inp_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", il), { n_embd }, flags);
103        layer.ffn_gate_shexp     = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP,     "weight", il), { n_embd, n_ff_shexp }, flags);
104        layer.ffn_up_shexp       = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP,       "weight", il), { n_embd, n_ff_shexp }, flags);
105        layer.ffn_down_shexp     = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP,     "weight", il), { n_ff_shexp, n_embd }, flags);
106    };
107
108    auto load_block_mtp = [&](int il) {
109        // MTP head is identical to the trunk block (full attention + FFN)
110        load_block_trunk(il, mtp_flags);
111
112        auto & layer = layers[il];
113
114        // NextN-specific tensors that define the MTP block.
115        layer.nextn.eh_proj          = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ,          "weight", il), { 2 * n_embd, n_embd }, mtp_flags);
116        layer.nextn.enorm            = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM,            "weight", il), { n_embd },             mtp_flags);
117        layer.nextn.hnorm            = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM,            "weight", il), { n_embd },             mtp_flags);
118        layer.nextn.embed_tokens     = create_tensor(tn(LLM_TENSOR_NEXTN_EMBED_TOKENS,     "weight", il), { n_embd, n_vocab },    mtp_flags | TENSOR_NOT_REQUIRED);
119        layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", il), { n_embd, n_vocab },    mtp_flags | TENSOR_NOT_REQUIRED);
120        layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", il), { n_embd },             mtp_flags | TENSOR_NOT_REQUIRED);
121    };
122
123    for (int i = 0; i < n_layer; i++) {
124        load_block_trunk(i, trunk_flags);
125    }
126    for (int i = n_layer; i < n_layer_all; i++) {
127        load_block_mtp(i);
128    }
129}
130
131std::unique_ptr<llm_graph_context> llama_model_qwen3next::build_arch_graph(const llm_graph_params & params) const {
132    if (params.gtype == LLM_GRAPH_TYPE_DECODER_MTP) {
133        return std::make_unique<graph_mtp>(*this, params);
134    }
135    return std::make_unique<graph>(*this, params);
136}
137
138llama_model_qwen3next::graph::graph(const llama_model & model, const llm_graph_params & params) :
139    llm_build_delta_net_base(params), model(model) {
140    ggml_tensor * cur;
141    ggml_tensor * inpL;
142
143    inpL = build_inp_embd(model.tok_embd);
144    cb(inpL, "model.embed_tokens", -1);
145
146    auto * inp = build_inp_mem_hybrid();
147
148    ggml_tensor * inp_pos     = build_inp_pos();
149    ggml_tensor * inp_out_ids = build_inp_out_ids();
150
151    // MTP/NextN layers are loaded as extra decoder blocks but not executed in the main pass.
152    for (int il = 0; il < n_layer; ++il) {
153        res->t_layer_inp[il] = inpL;
154
155        ggml_tensor * inpSA = inpL;
156
157        cur = build_norm(inpL, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il);
158        cb(cur, "attn_norm", il);
159
160        ggml_build_forward_expand(gf, cur);
161
162        // Determine layer type and build appropriate attention mechanism
163        if (hparams.is_recr(il)) {
164            // Linear attention layer (gated delta net)
165            cur = build_layer_attn_linear(inp->get_recr(), cur, il);
166        } else {
167            // Full attention layer
168            cur = build_layer_attn(inp->get_attn(), cur, inp_pos, il);
169        }
170
171        if (il == n_layer - 1 && inp_out_ids && cparams.embeddings_nextn_masked) {
172            cur   = ggml_get_rows(ctx0, cur, inp_out_ids);
173            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
174        }
175
176        // Residual connection
177        cur = ggml_add(ctx0, cur, inpSA);
178        cb(cur, "attn_residual", il);
179
180        // Save the tensor before post-attention norm for residual connection
181        ggml_tensor * ffn_residual = cur;
182
183        // Post-attention norm
184        ggml_tensor * attn_post_norm = build_norm(cur, model.layers[il].attn_post_norm, nullptr, LLM_NORM_RMS, il);
185        cb(attn_post_norm, "attn_post_norm", il);
186
187        // FFN layer (MoE or dense) - without residual connection
188        cur = build_layer_ffn(attn_post_norm, il);
189        cb(cur, "ffn_out", il);
190
191        // Residual connection for FFN - add to the tensor from before post_attention_layernorm
192        cur = ggml_add(ctx0, cur, ffn_residual);
193        cb(cur, "post_moe", il);
194
195        cur = build_cvec(cur, il);
196        cb(cur, "l_out", il);
197
198        // Input for next layer
199        inpL = cur;
200    }
201    cur = inpL;
202
203    // post-norm hidden state is input to both the LM head and the MTP head
204    cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1);
205
206    cb(cur, "h_nextn", -1);
207    res->t_h_nextn = cur;
208
209    if (!cparams.embeddings_nextn_masked && inp_out_ids) {
210        cur = ggml_get_rows(ctx0, cur, inp_out_ids);
211    }
212
213    cb(cur, "result_norm", -1);
214    res->t_embd = cur;
215
216    // LM head
217    cur = build_lora_mm(model.output, cur, model.output_s);
218
219    cb(cur, "result_output", -1);
220    res->t_logits = cur;
221
222    ggml_build_forward_expand(gf, cur);
223}
224
225ggml_tensor * llama_model_qwen3next::graph::build_norm_gated(
226        ggml_tensor * input,
227        ggml_tensor * weights,
228        ggml_tensor * gate,
229        int           layer) {
230    ggml_tensor * normalized = build_norm(input, weights, nullptr, LLM_NORM_RMS, layer);
231    ggml_tensor * gated_silu = ggml_silu(ctx0, gate);
232
233    return ggml_mul(ctx0, normalized, gated_silu);
234}
235
236ggml_tensor * llama_model_qwen3next::graph::build_layer_attn(
237        llm_graph_input_attn_kv * inp,
238        ggml_tensor *             cur,
239        ggml_tensor *             inp_pos,
240        int                       il) {
241    const int64_t n_embd_head = hparams.n_embd_head_v();
242    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
243
244    // Order: joint QG projection, QG split, Q norm, KV projection, K norm, RoPE, attention
245
246    // Qwen3Next uses a single Q projection that outputs query + gate
247    auto [Qcur_full, Kcur, Vcur] = build_qkv(model.layers[il], cur,
248            n_embd_head * 2, n_head,
249            n_embd_head,     n_head_kv,
250            n_embd_head,     n_head_kv,
251            il, false);
252    cb(Qcur_full, "Qcur_full", il);
253    cb(Kcur, "Kcur", il);
254    cb(Vcur, "Vcur", il);
255
256    Qcur_full = ggml_reshape_4d(ctx0, Qcur_full, n_embd_head * 2, n_head, n_tokens, 1);
257
258    // Split Q projection into query and gate
259    // The split should be along dimension 0 (the feature dimension)
260    ggml_tensor * Qcur = ggml_view_4d(ctx0, Qcur_full, n_embd_head, n_head, n_tokens, 1,
261                                            Qcur_full->nb[1], Qcur_full->nb[2], Qcur_full->nb[3], 0);
262    cb(Qcur, "Qcur_view", il);
263
264    ggml_tensor * gate =
265        ggml_view_4d(ctx0, Qcur_full, n_embd_head, n_head, n_tokens, 1,
266                     Qcur_full->nb[1], Qcur_full->nb[2], Qcur_full->nb[3], n_embd_head * ggml_element_size(Qcur_full));
267    cb(gate, "gate", il);
268
269    Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
270    Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens);
271
272    Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, nullptr, LLM_NORM_RMS, il);
273    cb(Qcur, "Qcur_normed", il);
274
275    Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, nullptr, LLM_NORM_RMS, il);
276    cb(Kcur, "Kcur_normed", il);
277
278    Qcur = ggml_rope_ext(
279            ctx0, Qcur, inp_pos, nullptr,
280            n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
281            ext_factor, attn_factor, beta_fast, beta_slow);
282
283    Kcur = ggml_rope_ext(
284            ctx0, Kcur, inp_pos, nullptr,
285            n_rot, rope_type, n_ctx_orig, freq_base,
286            freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
287
288    cb(Qcur, "Qcur", il);
289    cb(Kcur, "Kcur", il);
290    cb(Vcur, "Vcur", il);
291
292    const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f / sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
293
294    cur = build_attn(inp,
295                nullptr, nullptr, nullptr,
296                Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
297    cb(cur, "attn_pregate", il);
298
299    // TODO: CUDA is missing non-contiguous unary ops. when implemented: remove this cont
300    gate = ggml_cont_2d(ctx0, gate, n_embd_head * n_head, n_tokens);
301
302    gate = ggml_sigmoid(ctx0, gate);
303    cb(gate, "gate_sigmoid", il);
304
305    cur = ggml_mul(ctx0, cur, gate);
306    cb(cur, "attn_gated", il);
307
308    cur = build_lora_mm(model.layers[il].wo, cur, model.layers[il].wo_s);
309    cb(cur, "attn_output", il);
310
311    return cur;
312}
313
314std::pair<ggml_tensor *, ggml_tensor *> llama_model_qwen3next::graph::build_qkvz(
315                ggml_tensor * input,
316                        int   il) {
317    const int64_t d_inner      = hparams.ssm_d_inner;
318    const int64_t n_seqs       = ubatch.n_seqs;
319    const int64_t head_k_dim   = hparams.ssm_d_state;
320    const int64_t num_k_heads  = hparams.ssm_n_group;
321    const int64_t num_v_heads  = hparams.ssm_dt_rank;
322    const int64_t head_v_dim   = d_inner / num_v_heads;
323    const int64_t n_seq_tokens = ubatch.n_seq_tokens;
324
325    if (model.layers[il].wqkv) {
326        // optimized path
327        ggml_tensor * qkv_mixed = build_lora_mm(model.layers[il].wqkv, input);
328        qkv_mixed = ggml_reshape_3d(ctx0, qkv_mixed, qkv_mixed->ne[0], n_seq_tokens, n_seqs);
329        cb(qkv_mixed, "linear_attn_qkv_mixed", il);
330
331        ggml_tensor * z = build_lora_mm(model.layers[il].wqkv_gate, input);
332        cb(z, "z", il);
333
334        return { qkv_mixed, z };
335    } else {
336        // legacy (slower) path
337        ggml_tensor * mixed_qkvz = build_lora_mm(model.layers[il].ssm_in, input);
338        cb(mixed_qkvz, "linear_attn_mixed_qkvz", il);
339
340        int64_t       qkvz_new_dim        = 2 * head_k_dim + 2 * head_v_dim * (num_v_heads / num_k_heads);
341        ggml_tensor * mixed_qkvz_reshaped = ggml_reshape_4d(ctx0, mixed_qkvz, qkvz_new_dim, num_k_heads, n_seq_tokens, n_seqs);
342
343        // Split mixed_qkvz into query, key, value, z
344        int64_t split_sizes_qkvz[4] = {
345            head_k_dim,                              // query size
346            head_k_dim,                              // key size
347            head_v_dim * num_v_heads / num_k_heads,  // value size
348            head_v_dim * num_v_heads / num_k_heads   // z size
349        };
350
351        ggml_tensor * query =
352            ggml_view_4d(ctx0, mixed_qkvz_reshaped, split_sizes_qkvz[0], num_k_heads, n_seq_tokens, n_seqs,
353                        mixed_qkvz_reshaped->nb[1], mixed_qkvz_reshaped->nb[2], mixed_qkvz_reshaped->nb[3], 0);
354        cb(query, "q", il);
355
356        ggml_tensor * key = ggml_view_4d(ctx0, mixed_qkvz_reshaped, split_sizes_qkvz[1], num_k_heads, n_seq_tokens, n_seqs,
357                                        mixed_qkvz_reshaped->nb[1], mixed_qkvz_reshaped->nb[2], mixed_qkvz_reshaped->nb[3],
358                                        split_sizes_qkvz[0] * ggml_element_size(mixed_qkvz_reshaped));
359        cb(key, "k", il);
360
361        ggml_tensor * value =
362            ggml_view_4d(ctx0, mixed_qkvz_reshaped, split_sizes_qkvz[2], num_k_heads, n_seq_tokens, n_seqs,
363                        mixed_qkvz_reshaped->nb[1], mixed_qkvz_reshaped->nb[2], mixed_qkvz_reshaped->nb[3],
364                        (split_sizes_qkvz[0] + split_sizes_qkvz[1]) * ggml_element_size(mixed_qkvz_reshaped));
365        cb(value, "v", il);
366
367        ggml_tensor * z = ggml_view_4d(ctx0, mixed_qkvz_reshaped, split_sizes_qkvz[3], num_k_heads, n_seq_tokens, n_seqs,
368                                    mixed_qkvz_reshaped->nb[1], mixed_qkvz_reshaped->nb[2], mixed_qkvz_reshaped->nb[3],
369                                    (split_sizes_qkvz[0] + split_sizes_qkvz[1] + split_sizes_qkvz[2]) * ggml_element_size(mixed_qkvz_reshaped));
370        z = ggml_cont(ctx0, z);
371        cb(z, "z", il);
372
373        // After creating query, key, and value_reshaped, reshape each to flatten the head dimensions
374        // query: [head_k_dim, num_k_heads, n_tokens, n_seqs] -> [head_k_dim * num_k_heads, n_tokens, n_seqs]
375        ggml_tensor * query_flat = ggml_cont_3d(ctx0, query, head_k_dim * num_k_heads, n_seq_tokens, n_seqs);
376        cb(query_flat, "query_flat", il);
377
378        // key: [head_k_dim, num_k_heads, n_tokens, n_seqs] -> [head_k_dim * num_k_heads, n_tokens, n_seqs]
379        ggml_tensor * key_flat = ggml_cont_3d(ctx0, key, head_k_dim * num_k_heads, n_seq_tokens, n_seqs);
380        cb(key_flat, "key_flat", il);
381
382        // value_reshaped: [head_v_dim, num_v_heads, n_tokens, n_seqs] -> [head_v_dim * num_v_heads, n_tokens, n_seqs]
383        ggml_tensor * value_flat = ggml_cont_3d(ctx0, value, head_v_dim * num_v_heads, n_seq_tokens, n_seqs);
384        cb(value_flat, "value_flat", il);
385
386        // Now concatenate along the feature dimension (dim 0) to get [conv_dim, n_tokens, n_seqs]
387        ggml_tensor * qkv_mixed = ggml_concat(ctx0, query_flat, key_flat, 0);
388        qkv_mixed               = ggml_concat(ctx0, qkv_mixed, value_flat, 0);
389        cb(qkv_mixed, "qkv_mixed", il);
390
391        return { qkv_mixed, z };
392    }
393}
394
395ggml_tensor * llama_model_qwen3next::graph::build_layer_attn_linear(
396        llm_graph_input_rs * inp,
397        ggml_tensor *        cur,
398        int                  il) {
399    const auto * mctx_cur = inp->mctx;
400
401    const int64_t d_inner      = hparams.ssm_d_inner;
402    const int64_t n_seqs       = ubatch.n_seqs;
403    const int64_t head_k_dim   = hparams.ssm_d_state;
404    const int64_t num_k_heads  = hparams.ssm_n_group;
405    const int64_t num_v_heads  = hparams.ssm_dt_rank;
406    const int64_t head_v_dim   = d_inner / num_v_heads;
407    const int64_t n_seq_tokens = ubatch.n_seq_tokens;
408
409    GGML_ASSERT(n_seqs != 0);
410    GGML_ASSERT(ubatch.equal_seqs());
411    GGML_ASSERT(ubatch.n_tokens == n_seq_tokens * n_seqs);
412
413    // Input projections
414    auto qkvz = build_qkvz(cur, il);
415    ggml_tensor * qkv_mixed = qkvz.first;
416    ggml_tensor * z         = qkvz.second;
417
418    ggml_tensor * mixed_ba = build_lora_mm(model.layers[il].ssm_beta_alpha, cur);
419    cb(mixed_ba, "linear_attn_mixed_ba", il);
420
421    // Reshape mixed_ba: [batch, seq_len, hidden_size] -> [batch, seq_len, num_k_heads, 2*num_v_heads/num_k_heads]
422    int64_t       ba_new_dim        = 2 * num_v_heads / num_k_heads;
423    ggml_tensor * mixed_ba_reshaped = ggml_reshape_4d(ctx0, mixed_ba, ba_new_dim, num_k_heads, n_seq_tokens, n_seqs);
424
425    // Split mixed_ba into b and a (beta and alpha parameters)
426    int64_t split_sizes_ba[2] = {
427        num_v_heads / num_k_heads,  // beta size
428        num_v_heads / num_k_heads   // alpha size
429    };
430
431    ggml_tensor * b = ggml_view_4d(ctx0, mixed_ba_reshaped, split_sizes_ba[0], num_k_heads, n_seq_tokens, n_seqs,
432                                   mixed_ba_reshaped->nb[1], mixed_ba_reshaped->nb[2], mixed_ba_reshaped->nb[3], 0);
433    cb(b, "b", il);
434
435    ggml_tensor * a = ggml_view_4d(ctx0, mixed_ba_reshaped, split_sizes_ba[1], num_k_heads, n_seq_tokens, n_seqs,
436                                   mixed_ba_reshaped->nb[1], mixed_ba_reshaped->nb[2], mixed_ba_reshaped->nb[3],
437                                   split_sizes_ba[0] * ggml_element_size(mixed_ba_reshaped));
438    cb(a, "a", il);
439
440    // TODO: CUDA is missing non-contiguous unary ops. when implemented: remove this cont
441    b = ggml_cont(ctx0, b);
442
443    ggml_tensor * beta = ggml_sigmoid(ctx0, b);
444
445    // Reshape a to merge head dimensions: [batch, seq_len, num_k_heads, num_v_heads/num_k_heads] -> [batch, seq_len, num_v_heads]
446    ggml_tensor * alpha = ggml_cont_3d(ctx0, a, num_v_heads, n_seq_tokens, n_seqs);
447
448    ggml_tensor * alpha_biased   = ggml_add(ctx0, alpha, model.layers[il].ssm_dt);
449    ggml_tensor * alpha_softplus = ggml_softplus(ctx0, alpha_biased);
450    cb(alpha_softplus, "a_softplus", il);
451
452    ggml_tensor * gate = ggml_mul(ctx0, alpha_softplus, model.layers[il].ssm_a);  // -A_log.exp() * softplus
453    cb(gate, "gate", il);
454
455    beta = ggml_reshape_4d(ctx0, beta, 1, num_v_heads, n_seq_tokens, n_seqs);
456    gate = ggml_reshape_4d(ctx0, gate, 1, num_v_heads, n_seq_tokens, n_seqs);
457
458    ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
459    ggml_tensor * ssm_states_all  = mctx_cur->get_s_l(il);
460
461    ggml_tensor * conv_kernel      = model.layers[il].ssm_conv1d;
462    const int64_t conv_kernel_size = conv_kernel->ne[0];
463    const int64_t conv_channels    = d_inner + 2 * hparams.ssm_n_group * hparams.ssm_d_state;
464
465    ggml_tensor * conv_input = build_conv_state(inp, conv_states_all, qkv_mixed, conv_kernel_size, conv_channels, il);
466
467    ggml_tensor * state = build_rs(inp, ssm_states_all, hparams.n_embd_s(), n_seqs);
468    state = ggml_reshape_4d(ctx0, state, head_v_dim, head_v_dim, num_v_heads, n_seqs);
469    cb(state, "state_predelta", il);
470
471    ggml_tensor * conv_output_proper = ggml_ssm_conv(ctx0, conv_input, conv_kernel);
472    cb(conv_output_proper, "conv_output_raw", il);
473
474    ggml_tensor * conv_output_silu = ggml_silu(ctx0, conv_output_proper);
475    cb(conv_output_silu, "conv_output_silu", il);
476
477    ggml_tensor * conv_qkv_mix = conv_output_silu;
478
479    // Calculate the total conv dimension
480    int64_t qkv_dim = head_k_dim * num_k_heads * 2 + head_v_dim * num_v_heads;
481    int64_t nb1_qkv = ggml_row_size(conv_qkv_mix->type, qkv_dim);
482
483    // Extract the convolved Q, K, V from conv_output
484    ggml_tensor * q_conv = ggml_view_4d(ctx0, conv_qkv_mix, head_k_dim, num_k_heads, n_seq_tokens, n_seqs,
485            ggml_row_size(conv_qkv_mix->type, head_k_dim),
486            nb1_qkv,
487            nb1_qkv * n_seq_tokens,
488            0);
489
490    ggml_tensor * k_conv = ggml_view_4d(ctx0, conv_qkv_mix, head_k_dim, num_k_heads, n_seq_tokens, n_seqs,
491            ggml_row_size(conv_qkv_mix->type, head_k_dim),
492            nb1_qkv,
493            nb1_qkv * n_seq_tokens,
494            head_k_dim * num_k_heads * ggml_element_size(conv_qkv_mix));
495
496    ggml_tensor * v_conv = ggml_view_4d(ctx0, conv_qkv_mix, head_v_dim, num_v_heads, n_seq_tokens, n_seqs,
497            ggml_row_size(conv_qkv_mix->type, head_v_dim),
498            nb1_qkv,
499            nb1_qkv * n_seq_tokens,
500            ggml_row_size(conv_qkv_mix->type, 2 * head_k_dim * num_k_heads));
501
502    cb(q_conv, "q_conv", il);
503    cb(k_conv, "k_conv", il);
504    cb(v_conv, "v_conv", il);
505
506
507    const float eps_norm = hparams.f_norm_rms_eps;
508
509    q_conv = build_gdn_l2_norm(ctx0, q_conv, eps_norm);
510    k_conv = build_gdn_l2_norm(ctx0, k_conv, eps_norm);
511
512    //q_conv = ggml_cont_4d(ctx0, q_conv, head_k_dim, num_k_heads, n_seq_tokens, n_seqs);
513    //k_conv = ggml_cont_4d(ctx0, k_conv, head_k_dim, num_k_heads, n_seq_tokens, n_seqs);
514    //v_conv = ggml_cont_4d(ctx0, v_conv, head_v_dim, num_v_heads, n_seq_tokens, n_seqs);
515
516    // if head keys and value keys are different, repeat to force tensors into matching shapes
517    // TODO: avoid repeats for fused GDN, needs broadcast configuration for GDN op [TAG_GGML_GDN_BCAST]
518    if (num_k_heads != num_v_heads) {
519        GGML_ASSERT(num_v_heads % num_k_heads == 0);
520        int64_t repeat_factor = num_v_heads / num_k_heads;
521
522        // repeat interleave: reshape to (repeat part, 1, remaining part...), do repeat, then reshape back
523        ggml_tensor * q_reshaped = ggml_reshape_4d(ctx0, q_conv, head_k_dim, 1, num_k_heads, n_seq_tokens * n_seqs);
524        ggml_tensor * k_reshaped = ggml_reshape_4d(ctx0, k_conv, head_k_dim, 1, num_k_heads, n_seq_tokens * n_seqs);
525
526        // Repeat along the third dimension (the new dimension with size 1)
527        ggml_tensor * q_repeated =
528            ggml_repeat_4d(ctx0, q_reshaped, head_k_dim, repeat_factor, num_k_heads, n_seq_tokens * n_seqs);
529        ggml_tensor * k_repeated =
530            ggml_repeat_4d(ctx0, k_reshaped, head_k_dim, repeat_factor, num_k_heads, n_seq_tokens * n_seqs);
531
532        // Reshape back to merge the head and repeat dimensions
533        // From [head_dim, repeat_factor, num_k_heads, n_seq_tokens * n_seqs]
534        // Back to [head_dim, repeat_factor * num_k_heads, n_seq_tokens, n_seqs]
535        q_conv = ggml_reshape_4d(ctx0, q_repeated, head_k_dim, num_k_heads * repeat_factor, n_seq_tokens, n_seqs);
536        k_conv = ggml_reshape_4d(ctx0, k_repeated, head_k_dim, num_k_heads * repeat_factor, n_seq_tokens, n_seqs);
537    }
538
539    cb(q_conv, "q_conv_predelta", il);
540    cb(k_conv, "k_conv_predelta", il);
541    cb(v_conv, "v_conv_predelta", il);
542
543    ggml_tensor * output = build_recurrent_attn(inp, ssm_states_all, q_conv, k_conv, v_conv, gate, beta, state, il);
544
545    // z: [head_dim, n_heads, n_tokens, n_seqs] -> [n_heads * n_tokens * n_seqs, head_dim]
546    ggml_tensor * z_2d = ggml_reshape_4d(ctx0, z, head_v_dim, num_v_heads, n_seq_tokens, n_seqs);
547
548    // Apply gated normalization: self.norm(core_attn_out, z)
549    ggml_tensor * attn_out_norm = build_norm_gated(output, model.layers[il].ssm_norm, z_2d, il);
550
551    // Final reshape: [head_dim, n_heads, n_tokens, n_seqs] -> [n_tokens, n_seqs, n_heads * head_dim]
552    ggml_tensor * final_output = ggml_reshape_3d(ctx0, attn_out_norm, head_v_dim * num_v_heads, n_seq_tokens, n_seqs);
553    cb(final_output, "final_output", il);
554
555    // Output projection
556    cur = build_lora_mm(model.layers[il].ssm_out, final_output);
557    cb(cur, "linear_attn_out", il);
558
559    // Reshape back to original dimensions
560    cur = ggml_reshape_2d(ctx0, cur, n_embd, n_seq_tokens * n_seqs);
561
562    return cur;
563}
564
565ggml_tensor * llama_model_qwen3next::graph::build_layer_ffn(ggml_tensor * cur, const int il) {
566    // Check if this is an MoE layer
567    if (model.layers[il].ffn_gate_inp != nullptr) {
568        // MoE branch
569        ggml_tensor * moe_out =
570            build_moe_ffn(cur,
571                model.layers[il].ffn_gate_inp,
572                model.layers[il].ffn_up_exps,
573                model.layers[il].ffn_gate_exps,
574                model.layers[il].ffn_down_exps,
575                nullptr,
576                n_expert, n_expert_used,
577                LLM_FFN_SILU, true,
578                hparams.expert_weights_scale,
579                LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il,
580                nullptr, model.layers[il].ffn_gate_up_exps,
581                model.layers[il].ffn_up_exps_s,
582                model.layers[il].ffn_gate_exps_s,
583                model.layers[il].ffn_down_exps_s);
584        cb(moe_out, "ffn_moe_out", il);
585
586        // Add shared experts if present - following Qwen3Next reference implementation
587        if (model.layers[il].ffn_up_shexp != nullptr) {
588            ggml_tensor * ffn_shexp =
589                build_ffn(cur,
590                    model.layers[il].ffn_up_shexp,   NULL, model.layers[il].ffn_up_shexp_s,
591                    model.layers[il].ffn_gate_shexp, NULL, model.layers[il].ffn_gate_shexp_s,
592                    model.layers[il].ffn_down_shexp, NULL, model.layers[il].ffn_down_shexp_s,
593                    NULL,
594                    LLM_FFN_SILU, LLM_FFN_PAR, il);
595            cb(ffn_shexp, "ffn_shexp", il);
596
597            // Apply shared expert gating as in the reference implementation
598            // The shared expert has its own gate that is sigmoided
599            // Note: ffn_gate_inp_shexp is the shared expert gate (outputs 1 value per token)
600            ggml_tensor * shared_gate = build_lora_mm(model.layers[il].ffn_gate_inp_shexp, cur);
601            cb(shared_gate, "shared_expert_gate", il);
602
603            shared_gate = ggml_sigmoid(ctx0, shared_gate);
604            cb(shared_gate, "shared_expert_gate_sigmoid", il);
605
606            ffn_shexp = ggml_mul(ctx0, ffn_shexp, shared_gate);
607            cb(ffn_shexp, "ffn_shexp_gated", il);
608
609            cur = ggml_add(ctx0, moe_out, ffn_shexp);
610            cb(cur, "ffn_out", il);
611        } else {
612            cur = moe_out;
613        }
614    } else {
615        // Dense FFN branch (not currently used I believe)
616        cur = build_ffn(cur,
617            model.layers[il].ffn_up, NULL, NULL,
618            model.layers[il].ffn_gate, NULL, NULL,
619            model.layers[il].ffn_down, NULL, NULL,
620            NULL,
621            LLM_FFN_SILU, LLM_FFN_PAR, il);
622        cb(cur, "ffn_out", il);
623    }
624    return cur;
625}
626
627// LLM_GRAPH_TYPE_DECODER_MTP draft head for Qwen3-Next
628llama_model_qwen3next::graph_mtp::graph_mtp(const llama_model & model, const llm_graph_params & params)
629    : llm_graph_context(params) {
630    GGML_ASSERT(hparams.n_layer_nextn > 0 && "QWEN3NEXT MTP requires n_layer_nextn > 0");
631    GGML_ASSERT(hparams.n_layer_nextn == 1 && "QWEN3NEXT MTP currently only supports a single MTP block");
632
633    const int64_t n_embd_head = hparams.n_embd_head_v();
634    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
635
636    const int il = hparams.n_layer();
637    const auto & layer = model.layers[il];
638
639    GGML_ASSERT(layer.nextn.eh_proj    && "MTP block missing nextn.eh_proj");
640    GGML_ASSERT(layer.nextn.enorm      && "MTP block missing nextn.enorm");
641    GGML_ASSERT(layer.nextn.hnorm      && "MTP block missing nextn.hnorm");
642    GGML_ASSERT(layer.ffn_gate_inp     && "MTP block missing ffn_gate_inp");
643
644    // TODO: extract in a common llm_graph_context::build_inp_embd_h()
645    auto inp = std::make_unique<llm_graph_input_embd_h>(hparams.n_embd);
646
647    inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
648    ggml_set_input(inp->tokens);
649
650    inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, hparams.n_embd_inp(), n_tokens);
651    ggml_set_input(inp->embd);
652
653    // TODO: make static using `ggml_build_forward_select()`
654    //       see llm_graph_context::build_inp_embd() for reference
655    ggml_tensor * tok_embd;
656    if (ubatch.token) {
657        ggml_tensor * tok_embd_w = layer.nextn.embed_tokens ? layer.nextn.embed_tokens : model.tok_embd;
658
659        tok_embd = ggml_get_rows(ctx0, tok_embd_w, inp->tokens);
660    } else {
661        tok_embd = inp->embd;
662    }
663    cb(tok_embd, "mtp_tok_embd", il);
664
665    inp->h = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, hparams.n_embd, n_tokens);
666    ggml_set_input(inp->h);
667    ggml_set_name(inp->h, "mtp_h_input");
668
669    ggml_tensor * h_embd = inp->h;
670
671    res->add_input(std::move(inp));
672
673    ggml_tensor * inp_pos     = build_inp_pos();
674    ggml_tensor * inp_out_ids = build_inp_out_ids();
675
676    auto * inp_attn = build_attn_inp_kv();
677
678    ggml_tensor * h_norm = build_norm(h_embd, layer.nextn.hnorm, nullptr, LLM_NORM_RMS, il);
679    cb(h_norm, "mtp_hnorm", il);
680
681    ggml_tensor * e_norm = build_norm(tok_embd, layer.nextn.enorm, nullptr, LLM_NORM_RMS, il);
682    cb(e_norm, "mtp_enorm", il);
683
684    ggml_tensor * concat = ggml_concat(ctx0, e_norm, h_norm, /*dim=*/ 0);
685    cb(concat, "mtp_concat", il);
686
687    ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat, layer.nextn.eh_proj_s);
688    cb(cur, "mtp_eh_proj", il);
689
690    ggml_tensor * inpSA = cur;
691
692    cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il);
693    cb(cur, "mtp_attn_norm", il);
694
695    auto [Qcur_full, Kcur, Vcur] = build_qkv(layer, cur,
696            n_embd_head * 2, n_head,
697            n_embd_head,     n_head_kv,
698            n_embd_head,     n_head_kv,
699            il, false);
700    cb(Qcur_full, "mtp_Qcur_full", il);
701
702    ggml_tensor * Qcur = ggml_view_3d(ctx0, Qcur_full,
703            n_embd_head, n_head, n_tokens,
704            ggml_element_size(Qcur_full) * n_embd_head * 2,
705            ggml_element_size(Qcur_full) * n_embd_head * 2 * n_head,
706            0);
707    Qcur = build_norm(Qcur, layer.attn_q_norm, nullptr, LLM_NORM_RMS, il);
708    cb(Qcur, "mtp_Qcur_normed", il);
709
710    Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
711    Kcur = build_norm(Kcur, layer.attn_k_norm, nullptr, LLM_NORM_RMS, il);
712    cb(Kcur, "mtp_Kcur_normed", il);
713
714    Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens);
715
716    Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr,
717            n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
718            ext_factor, attn_factor, beta_fast, beta_slow);
719    Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr,
720            n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
721            ext_factor, attn_factor, beta_fast, beta_slow);
722
723    cb(Qcur, "mtp_Qcur", il);
724    cb(Kcur, "mtp_Kcur", il);
725    cb(Vcur, "mtp_Vcur", il);
726
727    const float kq_scale = hparams.f_attention_scale == 0.0f
728            ? 1.0f / sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
729
730    cur = build_attn(inp_attn,
731            nullptr, nullptr, nullptr,
732            Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
733    cb(cur, "mtp_attn_pregate", il);
734
735    ggml_tensor * gate = ggml_view_3d(ctx0, Qcur_full,
736            n_embd_head, n_head, n_tokens,
737            ggml_element_size(Qcur_full) * n_embd_head * 2,
738            ggml_element_size(Qcur_full) * n_embd_head * 2 * n_head,
739            ggml_element_size(Qcur_full) * n_embd_head);
740
741    // TODO: CUDA is missing non-contiguous unary ops. when implemented: remove this cont
742    gate = ggml_cont_2d(ctx0, gate, n_embd_head * n_head, n_tokens);
743    cb(gate, "mtp_gate", il);
744
745    cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, gate));
746    cur = build_lora_mm(layer.wo, cur, layer.wo_s);
747    cb(cur, "mtp_attn_out", il);
748
749    if (inp_out_ids) {
750        cur   = ggml_get_rows(ctx0, cur,   inp_out_ids);
751        inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
752    }
753
754    cur = ggml_add(ctx0, cur, inpSA);
755    cb(cur, "mtp_attn_residual", il);
756
757    ggml_tensor * ffn_residual = cur;
758    cur = build_norm(cur, layer.attn_post_norm, nullptr, LLM_NORM_RMS, il);
759    cb(cur, "mtp_attn_post_norm", il);
760
761    // MoE FFN — routed experts plus gated shared expert (mirrors the trunk).
762    ggml_tensor * moe_out =
763        build_moe_ffn(cur,
764            layer.ffn_gate_inp,
765            layer.ffn_up_exps,
766            layer.ffn_gate_exps,
767            layer.ffn_down_exps,
768            nullptr,
769            n_expert, n_expert_used,
770            LLM_FFN_SILU, true,
771            hparams.expert_weights_scale,
772            LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il,
773            nullptr, layer.ffn_gate_up_exps,
774            layer.ffn_up_exps_s,
775            layer.ffn_gate_exps_s,
776            layer.ffn_down_exps_s);
777    cb(moe_out, "mtp_ffn_moe_out", il);
778
779    if (layer.ffn_up_shexp != nullptr) {
780        ggml_tensor * ffn_shexp =
781            build_ffn(cur,
782                layer.ffn_up_shexp,   nullptr, layer.ffn_up_shexp_s,
783                layer.ffn_gate_shexp, nullptr, layer.ffn_gate_shexp_s,
784                layer.ffn_down_shexp, nullptr, layer.ffn_down_shexp_s,
785                nullptr,
786                LLM_FFN_SILU, LLM_FFN_PAR, il);
787        cb(ffn_shexp, "mtp_ffn_shexp", il);
788
789        ggml_tensor * shared_gate = build_lora_mm(layer.ffn_gate_inp_shexp, cur);
790        shared_gate = ggml_sigmoid(ctx0, shared_gate);
791        cb(shared_gate, "mtp_shared_expert_gate_sigmoid", il);
792
793        ffn_shexp = ggml_mul(ctx0, ffn_shexp, shared_gate);
794        cb(ffn_shexp, "mtp_ffn_shexp_gated", il);
795
796        cur = ggml_add(ctx0, moe_out, ffn_shexp);
797    } else {
798        cur = moe_out;
799    }
800    cb(cur, "mtp_ffn_out", il);
801
802    cur = ggml_add(ctx0, cur, ffn_residual);
803    cb(cur, "mtp_post_ffn", il);
804
805    ggml_tensor * head_norm_w = layer.nextn.shared_head_norm
806            ? layer.nextn.shared_head_norm
807            : model.output_norm;
808    GGML_ASSERT(head_norm_w && "QWEN3NEXT MTP: missing both nextn.shared_head_norm and output_norm");
809    cur = build_norm(cur, head_norm_w, nullptr, LLM_NORM_RMS, -1);
810
811    cb(cur, "h_nextn", -1);
812    res->t_h_nextn = cur;
813
814    ggml_tensor * head_w = layer.nextn.shared_head_head ? layer.nextn.shared_head_head : model.output;
815    ggml_tensor * head_s = layer.nextn.shared_head_head ? layer.nextn.shared_head_head_s : model.output_s;
816    GGML_ASSERT(head_w && "QWEN3NEXT MTP: missing LM head (nextn.shared_head_head or model.output)");
817    cur = build_lora_mm(head_w, cur, head_s);
818    cb(cur, "result_output", -1);
819
820    res->t_logits = cur;
821    ggml_build_forward_expand(gf, cur);
822}