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