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