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