char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
163a40796
char/aliceai-t5-moe
1#include "llama-hparams.h" 2#include "models.h" 3 4#include "llama-kv-cache-dsv4.h" 5 6#include <algorithm> 7#include <cmath> 8#include <stdexcept> 9#include <string> 10 11static float dsv4_rope_attn_factor (float freq_scale ,float ext_factor ) { 12if (ext_factor == 0.0f ) { 13return 1.0f ; 14 } 15 16return 1.0f / (1.0f + 0.1f * logf (1.0f /freq_scale )); 17} 18 19void llama_model_deepseek4::load_arch_hparams (llama_model_loader & ml ) { 20if (hparams .n_layer_nextn > 0 ) { 21const uint32_t n_layer_main = hparams .n_layer_all - hparams .n_layer_nextn ; 22const std::string mtp_probe = "blk." + std::to_string (n_layer_main )+ ".nextn.eh_proj.weight" ; 23if (ml .get_weight (mtp_probe .c_str ())== nullptr ) { 24hparams .n_layer_nextn = 0 ; 25 } 26 } 27 28ml .get_key (LLM_KV_ATTENTION_LAYERNORM_RMS_EPS ,hparams .f_norm_rms_eps ); 29ml .get_key (LLM_KV_ATTENTION_Q_LORA_RANK ,hparams .n_lora_q ); 30ml .get_key (LLM_KV_ATTENTION_SLIDING_WINDOW ,hparams .n_swa ); 31 32ml .get_key_or_arr (LLM_KV_EXPERT_FEED_FORWARD_LENGTH ,hparams .n_ff_exp_arr ,hparams .n_layer_all ); 33ml .get_key (LLM_KV_EXPERT_SHARED_COUNT ,hparams .n_expert_shared ); 34ml .get_key (LLM_KV_EXPERT_WEIGHTS_SCALE ,hparams .expert_weights_scale ); 35ml .get_key (LLM_KV_EXPERT_WEIGHTS_NORM ,hparams .expert_weights_norm ); 36ml .get_key_or_arr (LLM_KV_SWIGLU_CLAMP_EXP ,hparams .swiglu_clamp_exp ,hparams .n_layer_all ); 37if (!ml .get_key_or_arr (LLM_KV_SWIGLU_CLAMP_SHEXP ,hparams .swiglu_clamp_shexp ,hparams .n_layer_all ,0 )) { 38hparams .swiglu_clamp_shexp = hparams .swiglu_clamp_exp ; 39 } 40 41ml .get_key (LLM_KV_ATTENTION_INDEXER_HEAD_COUNT ,hparams .indexer_n_head ); 42ml .get_key (LLM_KV_ATTENTION_INDEXER_KEY_LENGTH ,hparams .indexer_head_size ); 43ml .get_key (LLM_KV_ATTENTION_INDEXER_TOP_K ,hparams .indexer_top_k ); 44 45ml .get_key (LLM_KV_ATTENTION_OUTPUT_GROUP_COUNT ,hparams .dsv4_o_group_count ); 46ml .get_key (LLM_KV_ATTENTION_OUTPUT_LORA_RANK ,hparams .dsv4_o_lora_rank ); 47ml .get_key (LLM_KV_ATTENTION_COMPRESS_ROPE_FREQ_BASE ,hparams .dsv4_compress_rope_base ); 48ml .get_key (LLM_KV_HYPER_CONNECTION_COUNT ,hparams .dsv4_hc_mult ); 49ml .get_key (LLM_KV_HYPER_CONNECTION_SINKHORN_ITERATIONS ,hparams .dsv4_hc_sinkhorn_iters ); 50ml .get_key (LLM_KV_HYPER_CONNECTION_EPSILON ,hparams .dsv4_hc_eps ); 51ml .get_key (LLM_KV_HASH_LAYER_COUNT ,hparams .dsv4_hash_layer_count ); 52 53hparams .n_embd_out_impl = hparams .dsv4_hc_mult * hparams .n_embd ; 54 55uint32_t n_compress_ratios = 0 ; 56ml .get_arr_n (LLM_KV_ATTENTION_COMPRESS_RATIOS ,n_compress_ratios ); 57if (n_compress_ratios < hparams .n_layer_all ) { 58throw std::runtime_error ("DeepSeek-V4 compress_ratios is shorter than block_count" ); 59 } 60GGML_ASSERT (n_compress_ratios <=LLAMA_MAX_LAYERS ); 61ml .get_arr (LLM_KV_ATTENTION_COMPRESS_RATIOS ,hparams .dsv4_compress_ratios ); 62 63ml .get_key (LLM_KV_EXPERT_GATING_FUNC ,hparams .expert_gating_func ); 64if (hparams .expert_gating_func != LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS ) { 65throw std::runtime_error ("DeepSeek-V4 loader currently expects sqrtsoftplus MoE scoring" ); 66 } 67hparams .swa_type = LLAMA_SWA_TYPE_STANDARD ; 68hparams .set_swa_pattern (0 ); 69// tokens of an image span attend bidirectionally to the whole span, the window only applies to older tokens 70// ref: get_window_topk_idxs_visible in the reference impl 71hparams .non_causal_type = LLAMA_NON_CAUSAL_TYPE_SWA_FULL ; 72for (uint32_t il = hparams .n_layer ();il < hparams .n_layer_all ;++ il ) { 73hparams .is_swa_impl [il ]= true; 74 } 75 76switch (hparams .n_layer ()) { 77case 43 :type = LLM_TYPE_UNKNOWN ;break ; 78default :type = LLM_TYPE_UNKNOWN ; 79 } 80} 81 82void llama_model_deepseek4::load_arch_tensors (llama_model_loader & ml ) { 83LLAMA_LOAD_LOCALS ; 84 85const int64_t q_lora_rank = hparams .n_lora_q ; 86const int64_t n_ff_exp = hparams .n_ff_exp (); 87const int64_t n_expert_shared = hparams .n_expert_shared ; 88 89const int64_t n_embd_head = hparams .n_embd_head_k (); 90const int64_t o_groups = hparams .dsv4_o_group_count ; 91const int64_t o_lora_rank = hparams .dsv4_o_lora_rank ; 92const int64_t hc_mult = hparams .dsv4_hc_mult ; 93const int64_t hc_dim = hc_mult * n_embd ; 94const int64_t hc_mix_dim = (2 + hc_mult )* hc_mult ; 95 96const bool mtp_only = (n_layer_nextn > 0 )&& (ml .get_weight ("blk.0.attn_norm.weight" )== nullptr ); 97const int trunk_flags = mtp_only ?TENSOR_NOT_REQUIRED :0 ; 98const int mtp_flags = ml .load_mtp ?0 :TENSOR_SKIP ; 99 100tok_embd = create_tensor (tn (LLM_TENSOR_TOKEN_EMBD ,"weight" ), {n_embd ,n_vocab },0 ); 101 102output_norm = create_tensor (tn (LLM_TENSOR_OUTPUT_NORM ,"weight" ), {n_embd },0 ); 103output = create_tensor (tn (LLM_TENSOR_OUTPUT ,"weight" ), {n_embd ,n_vocab },0 ); 104 105hc_head_fn = create_tensor (tn (LLM_TENSOR_HC_HEAD_FN ,"weight" ), {hc_dim ,hc_mult },0 ); 106hc_head_base = create_tensor (tn (LLM_TENSOR_HC_HEAD_BASE ,"weight" ), {hc_mult },0 ); 107hc_head_scale = create_tensor (tn (LLM_TENSOR_HC_HEAD_SCALE ,"weight" ), {1 },0 ); 108 109for (int i = 0 ;i < n_layer_all ;++ i ) { 110auto & layer = layers [i ]; 111const int flags = i < n_layer ?trunk_flags :mtp_flags ; 112 113layer .attn_norm = create_tensor (tn (LLM_TENSOR_ATTN_NORM ,"weight" ,i ), {n_embd },flags ); 114layer .attn_sinks = create_tensor (tn (LLM_TENSOR_ATTN_SINKS ,"weight" ,i ), {n_head },flags ); 115layer .wq_a = create_tensor (tn (LLM_TENSOR_ATTN_Q_A ,"weight" ,i ), {n_embd ,q_lora_rank },flags ); 116layer .attn_q_a_norm = create_tensor (tn (LLM_TENSOR_ATTN_Q_A_NORM ,"weight" ,i ), {q_lora_rank },flags ); 117layer .wq_b = create_tensor (tn (LLM_TENSOR_ATTN_Q_B ,"weight" ,i ), {q_lora_rank ,n_head * n_embd_head },flags ); 118layer .wkv = create_tensor (tn (LLM_TENSOR_ATTN_KV ,"weight" ,i ), {n_embd ,n_embd_head },flags ); 119layer .attn_kv_norm = create_tensor (tn (LLM_TENSOR_ATTN_KV_NORM ,"weight" ,i ), {n_embd_head },flags ); 120// for wo_a, the shape in the file is (n_head * n_embd_head / o_groups, o_lora_rank*o_groups) 121// so we reshape here, to avoid reshaping the tensor in the graph 122layer .wo_a = create_tensor (tn (LLM_TENSOR_ATTN_OUT_A ,"weight" ,i ), {n_head * n_embd_head /o_groups ,o_lora_rank ,o_groups },flags |TENSOR_ALLOW_RESHAPE ); 123layer .wo_b = create_tensor (tn (LLM_TENSOR_ATTN_OUT_B ,"weight" ,i ), {o_groups * o_lora_rank ,n_embd },flags ); 124 125layer .hc_attn_fn = create_tensor (tn (LLM_TENSOR_HC_ATTN_FN ,"weight" ,i ), {hc_dim ,hc_mix_dim },flags ); 126layer .hc_attn_base = create_tensor (tn (LLM_TENSOR_HC_ATTN_BASE ,"weight" ,i ), {hc_mix_dim },flags ); 127layer .hc_attn_scale = create_tensor (tn (LLM_TENSOR_HC_ATTN_SCALE ,"weight" ,i ), {3 },flags ); 128layer .hc_ffn_fn = create_tensor (tn (LLM_TENSOR_HC_FFN_FN ,"weight" ,i ), {hc_dim ,hc_mix_dim },flags ); 129layer .hc_ffn_base = create_tensor (tn (LLM_TENSOR_HC_FFN_BASE ,"weight" ,i ), {hc_mix_dim },flags ); 130layer .hc_ffn_scale = create_tensor (tn (LLM_TENSOR_HC_FFN_SCALE ,"weight" ,i ), {3 },flags ); 131 132const int64_t ratio = hparams .dsv4_compress_ratios [i ]; 133if (ratio != 0 ) { 134const int64_t coff = ratio == 4 ?2 :1 ; 135 136layer .attn_comp_wkv = create_tensor (tn (LLM_TENSOR_ATTN_COMPRESSOR_WKV ,"weight" ,i ), {n_embd ,coff * n_embd_head },flags ); 137layer .attn_comp_wgate = create_tensor (tn (LLM_TENSOR_ATTN_COMPRESSOR_WGATE ,"weight" ,i ), {n_embd ,coff * n_embd_head },flags ); 138layer .attn_comp_ape = create_tensor (tn (LLM_TENSOR_ATTN_COMPRESSOR_APE ,"weight" ,i ), {coff * n_embd_head ,ratio },flags ); 139layer .attn_comp_norm = create_tensor (tn (LLM_TENSOR_ATTN_COMPRESSOR_NORM ,"weight" ,i ), {n_embd_head },flags ); 140 141if (ratio == 4 ) { 142const int64_t n_embd_indexer = hparams .indexer_head_size ; 143 144layer .indexer_proj = create_tensor (tn (LLM_TENSOR_INDEXER_PROJ ,"weight" ,i ), {n_embd ,hparams .indexer_n_head },flags ); 145layer .indexer_attn_q_b = create_tensor (tn (LLM_TENSOR_INDEXER_ATTN_Q_B ,"weight" ,i ), {q_lora_rank ,hparams .indexer_n_head * n_embd_indexer },flags ); 146 147layer .indexer_comp_wkv = create_tensor (tn (LLM_TENSOR_INDEXER_COMPRESSOR_WKV ,"weight" ,i ), {n_embd ,2 * n_embd_indexer },flags ); 148layer .indexer_comp_wgate = create_tensor (tn (LLM_TENSOR_INDEXER_COMPRESSOR_WGATE ,"weight" ,i ), {n_embd ,2 * n_embd_indexer },flags ); 149layer .indexer_comp_ape = create_tensor (tn (LLM_TENSOR_INDEXER_COMPRESSOR_APE ,"weight" ,i ), {2 * n_embd_indexer ,ratio },flags ); 150layer .indexer_comp_norm = create_tensor (tn (LLM_TENSOR_INDEXER_COMPRESSOR_NORM ,"weight" ,i ), {n_embd_indexer },flags ); 151 }else if (ratio != 128 ) { 152throw std::runtime_error ("DeepSeek-V4 loader only supports compression ratios 0, 4, and 128" ); 153 } 154 } 155 156layer .ffn_gate_inp = create_tensor (tn (LLM_TENSOR_FFN_GATE_INP ,"weight" ,i ), {n_embd ,n_expert },flags ); 157if ((uint32_t )i < hparams .dsv4_hash_layer_count ) { 158layer .ffn_gate_tid2eid = create_tensor (tn (LLM_TENSOR_FFN_GATE_TID2EID ,"weight" ,i ), {n_expert_used ,n_vocab },flags ); 159 }else { 160layer .ffn_exp_probs_b = create_tensor (tn (LLM_TENSOR_FFN_EXP_PROBS_B ,"bias" ,i ), {n_expert },flags ); 161 } 162// vision variant only: routing bias for image tokens 163layer .ffn_exp_probs_b_vl = create_tensor (tn (LLM_TENSOR_FFN_EXP_PROBS_B_VL ,"bias" ,i ), {n_expert },flags |TENSOR_NOT_REQUIRED ); 164layer .ffn_norm = create_tensor (tn (LLM_TENSOR_FFN_NORM ,"weight" ,i ), {n_embd },flags ); 165 166layer .ffn_gate_exps = create_tensor (tn (LLM_TENSOR_FFN_GATE_EXPS ,"weight" ,i ), {n_embd ,n_ff_exp ,n_expert },flags ); 167layer .ffn_down_exps = create_tensor (tn (LLM_TENSOR_FFN_DOWN_EXPS ,"weight" ,i ), {n_ff_exp ,n_embd ,n_expert },flags ); 168layer .ffn_up_exps = create_tensor (tn (LLM_TENSOR_FFN_UP_EXPS ,"weight" ,i ), {n_embd ,n_ff_exp ,n_expert },flags ); 169 170layer .ffn_gate_shexp = create_tensor (tn (LLM_TENSOR_FFN_GATE_SHEXP ,"weight" ,i ), {n_embd ,n_ff_exp * n_expert_shared },flags ); 171layer .ffn_down_shexp = create_tensor (tn (LLM_TENSOR_FFN_DOWN_SHEXP ,"weight" ,i ), {n_ff_exp * n_expert_shared ,n_embd },flags ); 172layer .ffn_up_shexp = create_tensor (tn (LLM_TENSOR_FFN_UP_SHEXP ,"weight" ,i ), {n_embd ,n_ff_exp * n_expert_shared },flags ); 173 174if (i >=n_layer ) { 175layer .nextn .eh_proj = create_tensor (tn (LLM_TENSOR_NEXTN_EH_PROJ ,"weight" ,i ), {2 * n_embd ,n_embd },flags ); 176layer .nextn .enorm = create_tensor (tn (LLM_TENSOR_NEXTN_ENORM ,"weight" ,i ), {n_embd },flags ); 177layer .nextn .hnorm = create_tensor (tn (LLM_TENSOR_NEXTN_HNORM ,"weight" ,i ), {n_embd },flags ); 178layer .nextn .embed_tokens = create_tensor (tn (LLM_TENSOR_NEXTN_EMBED_TOKENS ,"weight" ,i ), {n_embd ,n_vocab },TENSOR_NOT_REQUIRED |flags ); 179layer .nextn .shared_head_head = create_tensor (tn (LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD ,"weight" ,i ), {n_embd ,n_vocab },TENSOR_NOT_REQUIRED |flags ); 180layer .nextn .shared_head_norm = create_tensor (tn (LLM_TENSOR_NEXTN_SHARED_HEAD_NORM ,"weight" ,i ), {n_embd },TENSOR_NOT_REQUIRED |flags ); 181 } 182 } 183} 184 185std::unique_ptr < llm_graph_context > llama_model_deepseek4::build_arch_graph (const llm_graph_params & params )const { 186if (params .gtype == LLM_GRAPH_TYPE_DECODER_MTP ) { 187return std::make_unique < graph_mtp > (* this ,params ); 188 } 189return std::make_unique < graph > (* this ,params ); 190} 191 192static size_t dsv4_elem_offset (const ggml_tensor * t ,int64_t i ) { 193return ggml_row_size (t -> type ,i ); 194} 195 196static ggml_tensor * dsv4_view_1d (ggml_context * ctx ,ggml_tensor * t ,int64_t ne0 ,int64_t i0 ) { 197return ggml_view_1d (ctx ,t ,ne0 ,dsv4_elem_offset (t ,i0 )); 198} 199 200static ggml_tensor * dsv4_view_2d ( 201ggml_context * ctx , 202ggml_tensor * t , 203int64_t ne0 , 204int64_t ne1 , 205int64_t i0 ) { 206return ggml_view_2d (ctx ,t ,ne0 ,ne1 ,t -> nb [1 ],dsv4_elem_offset (t ,i0 )); 207} 208 209static ggml_tensor * dsv4_append_zero_row (ggml_context * ctx ,ggml_tensor * t ,bool neg_inf ) { 210ggml_tensor * row = ggml_view_1d (ctx ,t ,t -> ne [0 ],0 ); 211row = neg_inf ?ggml_scale_bias (ctx ,row ,0.0f ,- INFINITY ) :ggml_scale (ctx ,row ,0.0f ); 212row = ggml_reshape_2d (ctx ,row ,t -> ne [0 ],1 ); 213 214return ggml_concat (ctx ,t ,row ,1 ); 215} 216 217struct dsv4_state_tensors { 218ggml_tensor * kv ; 219ggml_tensor * score ; 220}; 221 222static dsv4_state_tensors dsv4_build_state_restore ( 223ggml_context * ctx , 224const llm_graph_input_dsv4::comp_input & inp , 225const llama_dsv4_comp_state * state , 226int32_t il ) { 227dsv4_state_tensors restored = { 228state -> get_kv_all (ctx ,il ), 229state -> get_score_all (ctx ,il ), 230 }; 231 232if (inp .state_restore_src_idxs == nullptr || inp .state_restore_dst_idxs == nullptr ) { 233return restored ; 234 } 235 236ggml_tensor * kv_rows = ggml_get_rows (ctx ,restored .kv ,inp .state_restore_src_idxs ); 237restored .kv = state -> cpy_kv (ctx ,kv_rows ,inp .state_restore_dst_idxs ,il ); 238 239ggml_tensor * score_rows = ggml_get_rows (ctx ,restored .score ,inp .state_restore_src_idxs ); 240restored .score = state -> cpy_score (ctx ,score_rows ,inp .state_restore_dst_idxs ,il ); 241 242return restored ; 243} 244 245static dsv4_state_tensors dsv4_build_state_snapshot ( 246ggml_context * ctx , 247const llm_graph_input_dsv4::comp_input & inp , 248const llama_dsv4_comp_state * state , 249ggml_tensor * source_kv , 250ggml_tensor * source_score , 251int32_t il ) { 252if (inp .state_snapshot_src_idxs == nullptr || inp .state_snapshot_dst_idxs == nullptr || 253source_kv == nullptr || source_score == nullptr ) { 254return {}; 255 } 256 257ggml_tensor * kv_rows = ggml_get_rows (ctx ,source_kv ,inp .state_snapshot_src_idxs ); 258ggml_tensor * kv = state -> cpy_kv (ctx ,kv_rows ,inp .state_snapshot_dst_idxs ,il ); 259 260ggml_tensor * score_rows = ggml_get_rows (ctx ,source_score ,inp .state_snapshot_src_idxs ); 261ggml_tensor * score = state -> cpy_score (ctx ,score_rows ,inp .state_snapshot_dst_idxs ,il ); 262 263return {kv ,score }; 264} 265 266static constexpr int64_t DSV4_CSA_RATIO = 4 ; 267static constexpr int64_t DSV4_HCA_RATIO = 128 ; 268 269// mean over the hyper-connection streams: [n_embd, hc, n_tokens] -> [n_embd, n_tokens] 270static ggml_tensor * dsv4_hc_mean (ggml_context * ctx ,ggml_tensor * x ) { 271const int64_t hc = x -> ne [1 ]; 272 273ggml_tensor * acc = ggml_view_2d (ctx ,x ,x -> ne [0 ],x -> ne [2 ],x -> nb [2 ],0 ); 274for (int64_t s = 1 ;s < hc ;++ s ) { 275acc = ggml_add (ctx ,acc ,ggml_view_2d (ctx ,x ,x -> ne [0 ],x -> ne [2 ],x -> nb [2 ],s * x -> nb [1 ])); 276 } 277return ggml_scale (ctx ,acc ,1.0f /hc ); 278} 279 280static ggml_tensor * dsv4_hc_affine ( 281ggml_context * ctx , 282ggml_tensor * x , 283ggml_tensor * scale , 284ggml_tensor * base ) { 285x = ggml_mul (ctx ,x ,scale ); 286x = ggml_add (ctx ,x ,base ); 287return x ; 288} 289 290ggml_tensor * llama_model_deepseek4::graph::build_hc_pre ( 291ggml_tensor * x , 292ggml_tensor * weights , 293int il )const { 294GGML_ASSERT (x -> ne [0 ]== n_embd ); 295GGML_ASSERT (x -> ne [1 ]== hparams .dsv4_hc_mult ); 296 297const int64_t hc = hparams .dsv4_hc_mult ; 298const int64_t nt = x -> ne [2 ]; 299 300if (cparams .fused_dsv4_hc_pre && il >=0 ) { 301ggml_tensor * result = ggml_dsv4_hc_pre (ctx0 ,x ,weights ); 302res -> add_fused_node ({LLM_FUSED_OP_DSV4_HC_PRE ,result ,il }); 303return result ; 304 } 305 306ggml_tensor * result = nullptr ; 307for (int64_t ih = 0 ;ih < hc ;++ ih ) { 308ggml_tensor * xh = ggml_view_2d (ctx0 ,x ,n_embd ,nt ,x -> nb [2 ],ih * x -> nb [1 ]); 309ggml_tensor * wh = ggml_view_2d (ctx0 ,weights ,1 ,nt ,weights -> nb [1 ],ih * weights -> nb [0 ]); 310ggml_tensor * cur = ggml_mul (ctx0 ,xh ,wh ); 311result = result ?ggml_add (ctx0 ,result ,cur ) :cur ; 312 } 313 314return result ; 315} 316 317ggml_tensor * llama_model_deepseek4::graph::build_hc_sinkhorn ( 318ggml_tensor * comb , 319int il )const { 320GGML_UNUSED (il ); 321 322// comb is [dst_hc, src_hc, n_tokens]. Sinkhorn follows the reference: 323// row softmax over dst, one column normalization, then repeated row/column normalization. 324comb = ggml_soft_max (ctx0 ,comb ); 325 326ggml_tensor * eps = ggml_new_tensor_1d (ctx0 ,GGML_TYPE_F32 ,1 ); 327eps = ggml_fill (ctx0 ,eps ,hparams .dsv4_hc_eps ); 328 329comb = ggml_add (ctx0 ,comb ,eps ); 330 331auto norm_cols = [& ]() { 332ggml_tensor * comb_src_dst = ggml_cont (ctx0 ,ggml_permute (ctx0 ,comb ,1 ,0 ,2 ,3 )); 333ggml_tensor * col_sum = ggml_sum_rows (ctx0 ,comb_src_dst ); 334col_sum = ggml_add (ctx0 ,col_sum ,eps ); 335col_sum = ggml_permute (ctx0 ,col_sum ,1 ,0 ,2 ,3 ); 336comb = ggml_div (ctx0 ,comb ,col_sum ); 337 }; 338 339auto norm_rows = [& ]() { 340ggml_tensor * row_sum = ggml_sum_rows (ctx0 ,comb ); 341row_sum = ggml_add (ctx0 ,row_sum ,eps ); 342comb = ggml_div (ctx0 ,comb ,row_sum ); 343 }; 344 345norm_cols (); 346for (uint32_t i = 1 ;i < hparams .dsv4_hc_sinkhorn_iters ;++ i ) { 347norm_rows (); 348norm_cols (); 349 } 350 351return comb ; 352} 353 354ggml_tensor * llama_model_deepseek4::graph::build_hc_pre ( 355ggml_tensor * x , 356ggml_tensor * hc_fn , 357ggml_tensor * hc_scale , 358ggml_tensor * hc_base , 359ggml_tensor ** post , 360ggml_tensor ** comb , 361int il )const { 362const int64_t hc = hparams .dsv4_hc_mult ; 363const int64_t hc_dim = hc * n_embd ; 364const int64_t hc_mix_dim = (2 + hc )* hc ; 365const int64_t nt = x -> ne [2 ]; 366 367GGML_ASSERT (hc == 4 ); 368GGML_ASSERT (hc_fn -> ne [1 ]== hc_mix_dim ); 369 370ggml_tensor * flat = ggml_reshape_2d (ctx0 ,x ,hc_dim ,nt ); 371ggml_tensor * flat_norm = ggml_rms_norm (ctx0 ,flat ,norm_rms_eps ); 372ggml_tensor * mixes = ggml_mul_mat (ctx0 ,hc_fn ,flat_norm ); 373cb (mixes ,"hc_mixes" ,il ); 374 375ggml_tensor * scale_pre = dsv4_view_1d (ctx0 ,hc_scale ,1 ,0 ); 376ggml_tensor * scale_post = dsv4_view_1d (ctx0 ,hc_scale ,1 ,1 ); 377 378ggml_tensor * base_pre = dsv4_view_1d (ctx0 ,hc_base ,hc ,0 ); 379ggml_tensor * base_post = dsv4_view_1d (ctx0 ,hc_base ,hc ,hc ); 380 381ggml_tensor * pre = dsv4_view_2d (ctx0 ,mixes ,hc ,nt ,0 ); 382pre = dsv4_hc_affine (ctx0 ,pre ,scale_pre ,base_pre ); 383pre = ggml_sigmoid (ctx0 ,pre ); 384pre = ggml_scale_bias (ctx0 ,pre ,1.0f ,hparams .dsv4_hc_eps ); 385cb (pre ,"hc_pre" ,il ); 386 387* post = dsv4_view_2d (ctx0 ,mixes ,hc ,nt ,hc ); 388* post = dsv4_hc_affine (ctx0 ,* post ,scale_post ,base_post ); 389* post = ggml_sigmoid (ctx0 ,* post ); 390* post = ggml_scale (ctx0 ,* post ,2.0f ); 391cb (* post ,"hc_post" ,il ); 392 393if (cparams .fused_dsv4_hc_comb ) { 394* comb = ggml_dsv4_hc_comb (ctx0 ,mixes ,hc_scale ,hc_base ,hparams .dsv4_hc_eps , 395 (int32_t )hparams .dsv4_hc_sinkhorn_iters ); 396res -> add_fused_node ({LLM_FUSED_OP_DSV4_HC_COMB ,* comb ,il }); 397 }else { 398ggml_tensor * scale_comb = dsv4_view_1d (ctx0 ,hc_scale ,1 ,2 ); 399ggml_tensor * base_comb = dsv4_view_1d (ctx0 ,hc_base ,hc * hc ,2 * hc ); 400 401* comb = dsv4_view_2d (ctx0 ,mixes ,hc * hc ,nt ,2 * hc ); 402* comb = dsv4_hc_affine (ctx0 ,* comb ,scale_comb ,base_comb ); 403* comb = ggml_reshape_3d (ctx0 ,* comb ,hc ,hc ,nt ); 404* comb = build_hc_sinkhorn (* comb ,il ); 405 } 406cb (* comb ,"hc_comb" ,il ); 407 408ggml_tensor * result = build_hc_pre (x ,pre ,il ); 409return result ; 410} 411 412ggml_tensor * llama_model_deepseek4::graph::build_hc_post ( 413ggml_tensor * x , 414ggml_tensor * residual , 415ggml_tensor * post , 416ggml_tensor * comb , 417int il )const { 418GGML_ASSERT (x -> ne [0 ]== n_embd ); 419GGML_ASSERT (residual -> ne [1 ]== hparams .dsv4_hc_mult ); 420 421if (cparams .fused_dsv4_hc_post ) { 422ggml_tensor * result = ggml_dsv4_hc_post (ctx0 ,x ,residual ,post ,comb ); 423res -> add_fused_node ({LLM_FUSED_OP_DSV4_HC_POST ,result ,il }); 424return result ; 425 } 426 427const int64_t hc = hparams .dsv4_hc_mult ; 428const int64_t nt = x -> ne [1 ]; 429 430ggml_tensor * out = nullptr ; 431for (int64_t dst = 0 ;dst < hc ;++ dst ) { 432ggml_tensor * post_dst = ggml_view_2d (ctx0 ,post ,1 ,nt ,post -> nb [1 ],dst * post -> nb [0 ]); 433ggml_tensor * cur = ggml_mul (ctx0 ,x ,post_dst ); 434 435for (int64_t src = 0 ;src < hc ;++ src ) { 436ggml_tensor * res_src = ggml_view_2d (ctx0 ,residual ,n_embd ,nt ,residual -> nb [2 ],src * residual -> nb [1 ]); 437ggml_tensor * comb_src_dst = ggml_view_2d (ctx0 ,comb ,1 ,nt ,comb -> nb [2 ], 438dst * comb -> nb [0 ]+ src * comb -> nb [1 ]); 439cur = ggml_add (ctx0 ,cur ,ggml_mul (ctx0 ,res_src ,comb_src_dst )); 440 } 441 442cur = ggml_reshape_3d (ctx0 ,cur ,n_embd ,1 ,nt ); 443out = out ?ggml_concat (ctx0 ,out ,cur ,1 ) :cur ; 444 } 445 446return out ; 447} 448 449ggml_tensor * llama_model_deepseek4::graph::build_hc_head ( 450ggml_tensor * x , 451ggml_tensor * hc_fn , 452ggml_tensor * hc_scale , 453ggml_tensor * hc_base )const { 454const int64_t hc = hparams .dsv4_hc_mult ; 455const int64_t hc_dim = hc * n_embd ; 456const int64_t nt = x -> ne [2 ]; 457 458ggml_tensor * flat = ggml_reshape_2d (ctx0 ,x ,hc_dim ,nt ); 459ggml_tensor * flat_norm = ggml_rms_norm (ctx0 ,flat ,norm_rms_eps ); 460ggml_tensor * mixes = ggml_mul_mat (ctx0 ,hc_fn ,flat_norm ); 461cb (mixes ,"hc_head_mixes" ,-1 ); 462 463ggml_tensor * pre = dsv4_hc_affine (ctx0 ,mixes ,hc_scale ,hc_base ); 464pre = ggml_sigmoid (ctx0 ,pre ); 465pre = ggml_scale_bias (ctx0 ,pre ,1.0f ,hparams .dsv4_hc_eps ); 466cb (pre ,"hc_head_pre" ,-1 ); 467 468return build_hc_pre (x ,pre ,-1 ); 469} 470 471ggml_tensor * llama_model_deepseek4::graph::build_hca_compressed_kv_from_state ( 472ggml_tensor * kv_state , 473ggml_tensor * score_state , 474ggml_tensor * state_read_idxs , 475ggml_tensor * comp_pos , 476ggml_tensor * norm , 477int64_t n_embd_head , 478const char * name , 479int il )const { 480const int64_t n_embd_head_rope = hparams .n_rot (); 481const int64_t n_embd_head_nope = n_embd_head - n_embd_head_rope ; 482const int64_t n_blocks = comp_pos ?comp_pos -> ne [0 ] :0 ; 483 484GGML_ASSERT (n_blocks > 0 ); 485GGML_ASSERT (state_read_idxs ); 486GGML_ASSERT (state_read_idxs -> ne [0 ]== DSV4_HCA_RATIO * n_blocks ); 487GGML_ASSERT (n_embd_head >=n_embd_head_rope ); 488 489ggml_tensor * kv = ggml_get_rows (ctx0 ,kv_state ,state_read_idxs ); 490kv = ggml_reshape_3d (ctx0 ,kv ,n_embd_head ,DSV4_HCA_RATIO ,n_blocks ); 491cb (kv ,name ,il ); 492 493ggml_tensor * score = ggml_get_rows (ctx0 ,score_state ,state_read_idxs ); 494score = ggml_reshape_3d (ctx0 ,score ,n_embd_head ,DSV4_HCA_RATIO ,n_blocks ); 495cb (score ,name ,il ); 496 497ggml_tensor * values = ggml_cont (ctx0 ,ggml_permute (ctx0 ,kv ,1 ,0 ,2 ,3 )); 498ggml_tensor * scores = ggml_cont (ctx0 ,ggml_permute (ctx0 ,score ,1 ,0 ,2 ,3 )); 499 500ggml_tensor * weights = ggml_soft_max (ctx0 ,scores ); 501ggml_tensor * comp = ggml_mul (ctx0 ,values ,weights ); 502comp = ggml_sum_rows (ctx0 ,comp ); 503comp = ggml_cont (ctx0 ,ggml_permute (ctx0 ,comp ,1 ,0 ,2 ,3 )); 504cb (comp ,name ,il ); 505 506comp = build_norm (comp ,norm ,nullptr ,LLM_NORM_RMS ,il ); 507cb (comp ,name ,il ); 508 509comp = ggml_rope_ext (ctx0 ,comp ,comp_pos ,nullptr ,n_embd_head_rope ,rope_type ,n_ctx_orig , 510hparams .dsv4_compress_rope_base ,freq_scale ,ext_factor , 511dsv4_rope_attn_factor (freq_scale ,ext_factor ),beta_fast ,beta_slow ); 512comp = ggml_rope_set_offset (comp ,n_embd_head_nope ); 513cb (comp ,name ,il ); 514 515return comp ; 516} 517 518ggml_tensor * llama_model_deepseek4::graph::build_overlap_compressed_kv_from_state ( 519ggml_tensor * kv_state , 520ggml_tensor * score_state , 521ggml_tensor * state_read_idxs , 522ggml_tensor * comp_pos , 523ggml_tensor * norm , 524int64_t ratio , 525int64_t n_embd_head , 526const char * name , 527int il )const { 528const int64_t n_embd_head_rope = hparams .n_rot (); 529const int64_t n_embd_head_nope = n_embd_head - n_embd_head_rope ; 530const int64_t n_blocks = comp_pos ?comp_pos -> ne [0 ] :0 ; 531 532GGML_ASSERT (n_blocks > 0 ); 533GGML_ASSERT (state_read_idxs ); 534GGML_ASSERT (state_read_idxs -> ne [0 ]== 2 * ratio * n_blocks ); 535GGML_ASSERT (kv_state -> ne [0 ]== 2 * n_embd_head ); 536GGML_ASSERT (score_state -> ne [0 ]== 2 * n_embd_head ); 537GGML_ASSERT (n_embd_head >=n_embd_head_rope ); 538 539kv_state = dsv4_append_zero_row (ctx0 ,kv_state , false); 540score_state = dsv4_append_zero_row (ctx0 ,score_state , true); 541 542const int64_t n_read = ratio * n_blocks ; 543 544ggml_tensor * kv_rows = ggml_get_rows (ctx0 ,kv_state ,state_read_idxs ); 545ggml_tensor * score_rows = ggml_get_rows (ctx0 ,score_state ,state_read_idxs ); 546 547ggml_tensor * kv_prev = ggml_cont (ctx0 , 548ggml_view_2d (ctx0 ,kv_rows ,n_embd_head ,n_read ,kv_rows -> nb [1 ],0 )); 549kv_prev = ggml_reshape_3d (ctx0 ,kv_prev ,n_embd_head ,ratio ,n_blocks ); 550cb (kv_prev ,name ,il ); 551 552ggml_tensor * score_prev = ggml_cont (ctx0 , 553ggml_view_2d (ctx0 ,score_rows ,n_embd_head ,n_read ,score_rows -> nb [1 ],0 )); 554score_prev = ggml_reshape_3d (ctx0 ,score_prev ,n_embd_head ,ratio ,n_blocks ); 555cb (score_prev ,name ,il ); 556 557ggml_tensor * kv_cur = ggml_cont (ctx0 , 558ggml_view_2d (ctx0 ,kv_rows ,n_embd_head ,n_read ,kv_rows -> nb [1 ], 559n_read * kv_rows -> nb [1 ]+ ggml_row_size (kv_rows -> type ,n_embd_head ))); 560kv_cur = ggml_reshape_3d (ctx0 ,kv_cur ,n_embd_head ,ratio ,n_blocks ); 561 562ggml_tensor * score_cur = ggml_cont (ctx0 , 563ggml_view_2d (ctx0 ,score_rows ,n_embd_head ,n_read ,score_rows -> nb [1 ], 564n_read * score_rows -> nb [1 ]+ ggml_row_size (score_rows -> type ,n_embd_head ))); 565score_cur = ggml_reshape_3d (ctx0 ,score_cur ,n_embd_head ,ratio ,n_blocks ); 566 567ggml_tensor * values = ggml_concat (ctx0 ,kv_prev ,kv_cur ,1 ); 568ggml_tensor * scores = ggml_concat (ctx0 ,score_prev ,score_cur ,1 ); 569 570values = ggml_cont (ctx0 ,ggml_permute (ctx0 ,values ,1 ,0 ,2 ,3 )); 571scores = ggml_cont (ctx0 ,ggml_permute (ctx0 ,scores ,1 ,0 ,2 ,3 )); 572 573ggml_tensor * weights = ggml_soft_max (ctx0 ,scores ); 574ggml_tensor * comp = ggml_mul (ctx0 ,values ,weights ); 575comp = ggml_sum_rows (ctx0 ,comp ); 576comp = ggml_cont (ctx0 ,ggml_permute (ctx0 ,comp ,1 ,0 ,2 ,3 )); 577cb (comp ,name ,il ); 578 579comp = build_norm (comp ,norm ,nullptr ,LLM_NORM_RMS ,il ); 580cb (comp ,name ,il ); 581 582comp = ggml_rope_ext (ctx0 ,comp ,comp_pos ,nullptr ,n_embd_head_rope ,rope_type ,n_ctx_orig , 583hparams .dsv4_compress_rope_base ,freq_scale ,ext_factor , 584dsv4_rope_attn_factor (freq_scale ,ext_factor ),beta_fast ,beta_slow ); 585comp = ggml_rope_set_offset (comp ,n_embd_head_nope ); 586cb (comp ,name ,il ); 587 588return comp ; 589} 590 591ggml_tensor * llama_model_deepseek4::graph::build_lid_top_k ( 592const llama_model & model , 593llm_graph_input_dsv4 * inp_dsv4 , 594ggml_tensor * qr , 595ggml_tensor * cur , 596ggml_tensor * inp_pos , 597int il )const { 598const auto & layer = model .layers [il ]; 599const auto & inp_lid = inp_dsv4 -> get_lid (); 600const int64_t n_embd_indexer_head = hparams .indexer_head_size ; 601const int64_t n_embd_indexer_head_rope = hparams .n_rot (); 602const int64_t n_embd_indexer_head_nope = n_embd_indexer_head - n_embd_indexer_head_rope ; 603const int64_t n_indexer_head = hparams .indexer_n_head ; 604const int64_t nt = cur -> ne [1 ]; 605 606GGML_ASSERT (inp_lid .kq_mask ); 607GGML_ASSERT (inp_lid .k_rot ); 608GGML_ASSERT (n_embd_indexer_head >=n_embd_indexer_head_rope ); 609 610ggml_tensor * indexer_q = build_lora_mm (layer .indexer_attn_q_b ,qr ); 611indexer_q = ggml_reshape_3d (ctx0 ,indexer_q ,n_embd_indexer_head ,n_indexer_head ,nt ); 612cb (indexer_q ,"lid_q" ,il ); 613 614indexer_q = ggml_rope_ext (ctx0 ,indexer_q ,inp_pos ,nullptr ,n_embd_indexer_head_rope , 615rope_type ,n_ctx_orig ,hparams .dsv4_compress_rope_base ,freq_scale , 616ext_factor ,dsv4_rope_attn_factor (freq_scale ,ext_factor ),beta_fast ,beta_slow ); 617indexer_q = ggml_rope_set_offset (indexer_q ,n_embd_indexer_head_nope ); 618cb (indexer_q ,"lid_q_rope" ,il ); 619 620indexer_q = llama_mul_mat_hadamard (ctx0 ,indexer_q ,inp_lid .k_rot ); 621cb (indexer_q ,"lid_q_rot" ,il ); 622 623ggml_tensor * indexer_weights = build_lora_mm (layer .indexer_proj ,cur ); 624indexer_weights = ggml_scale (ctx0 ,indexer_weights ,1.0f /sqrtf (float (n_embd_indexer_head * n_indexer_head ))); 625cb (indexer_weights ,"lid_weights" ,il ); 626 627ggml_tensor * indexer_k = inp_dsv4 -> mctx -> get_lid ()-> get_k (ctx0 ,il ); 628const int64_t n_lid = inp_lid .kq_mask -> ne [0 ]; 629GGML_ASSERT (n_lid > 0 ); 630GGML_ASSERT (n_lid <=indexer_k -> ne [2 ]); 631 632indexer_k = ggml_view_4d (ctx0 ,indexer_k , 633indexer_k -> ne [0 ],indexer_k -> ne [1 ],n_lid ,indexer_k -> ne [3 ], 634indexer_k -> nb [1 ],indexer_k -> nb [2 ],indexer_k -> nb [3 ],0 ); 635cb (indexer_k ,"lid_k" ,il ); 636 637const int64_t n_stream = indexer_k -> ne [3 ]; 638indexer_q = ggml_view_4d (ctx0 ,indexer_q , 639indexer_q -> ne [0 ],indexer_q -> ne [1 ],indexer_q -> ne [2 ]/n_stream ,n_stream , 640indexer_q -> nb [1 ],indexer_q -> nb [2 ],indexer_q -> nb [3 ]/n_stream ,0 ); 641indexer_weights = ggml_view_4d (ctx0 ,indexer_weights , 642indexer_weights -> ne [0 ],indexer_weights -> ne [1 ]/n_stream ,indexer_weights -> ne [2 ],n_stream , 643indexer_weights -> nb [1 ],indexer_weights -> nb [2 ]/n_stream ,indexer_weights -> nb [3 ]/n_stream ,0 ); 644 645ggml_tensor * indexer_score = nullptr ; 646if (cparams .fused_lid ) { 647indexer_score = ggml_lightning_indexer (ctx0 ,indexer_q ,indexer_k ,indexer_weights ,inp_lid .kq_mask ); 648cb (indexer_score ,"lid_score_masked" ,il ); 649res -> add_fused_node ({LLM_FUSED_OP_LIGHTNING_INDEXER ,indexer_score ,il }); 650 }else { 651indexer_q = ggml_permute (ctx0 ,indexer_q ,0 ,2 ,1 ,3 ); 652cb (indexer_q ,"lid_q" ,il ); 653indexer_k = ggml_permute (ctx0 ,indexer_k ,0 ,2 ,1 ,3 ); 654cb (indexer_k ,"lid_k" ,il ); 655 656ggml_tensor * indexer_kq = ggml_mul_mat (ctx0 ,indexer_k ,indexer_q ); 657cb (indexer_kq ,"lid_kq" ,il ); 658 659indexer_kq = ggml_cont (ctx0 ,ggml_permute (ctx0 ,indexer_kq ,2 ,1 ,0 ,3 )); 660cb (indexer_kq ,"lid_kq" ,il ); 661 662indexer_score = ggml_relu (ctx0 ,indexer_kq ); 663indexer_score = ggml_mul (ctx0 ,indexer_score ,indexer_weights ); 664indexer_score = ggml_sum_rows (ctx0 ,indexer_score ); 665indexer_score = ggml_cont (ctx0 ,ggml_permute (ctx0 ,indexer_score ,2 ,1 ,0 ,3 )); 666cb (indexer_score ,"lid_score" ,il ); 667 668indexer_score = ggml_add (ctx0 ,indexer_score ,inp_lid .kq_mask ); 669cb (indexer_score ,"lid_score_masked" ,il ); 670 } 671 672const uint32_t n_top_k = indexer_score -> ne [0 ]< hparams .indexer_top_k ?indexer_score -> ne [0 ] :hparams .indexer_top_k ; 673ggml_tensor * top_k = ggml_cont (ctx0 ,ggml_top_k (ctx0 ,indexer_score ,n_top_k )); 674cb (top_k ,"lid_top_k" ,il ); 675 676return top_k ; 677} 678 679ggml_tensor * llama_model_deepseek4::graph::build_top_k_mask ( 680ggml_tensor * kq_mask , 681ggml_tensor * top_k , 682const char * name , 683int il )const { 684GGML_ASSERT (kq_mask ); 685GGML_ASSERT (top_k ); 686 687ggml_tensor * kq_mask_all = ggml_fill (ctx0 ,kq_mask ,- INFINITY ); 688kq_mask_all = ggml_view_4d (ctx0 ,kq_mask_all ,1 ,kq_mask_all -> ne [0 ],kq_mask_all -> ne [1 ],kq_mask_all -> ne [3 ], 689kq_mask_all -> nb [0 ],kq_mask_all -> nb [1 ],kq_mask_all -> nb [2 ],0 ); 690 691ggml_tensor * top_k_3d = ggml_view_4d (ctx0 ,top_k ,top_k -> ne [0 ],top_k -> ne [1 ],top_k -> ne [3 ],1 , 692top_k -> nb [1 ],top_k -> nb [2 ],top_k -> ne [3 ]* top_k -> nb [3 ],0 ); 693 694ggml_tensor * zeros = ggml_new_tensor_4d (ctx0 ,cparams .flash_attn ?GGML_TYPE_F16 :GGML_TYPE_F32 ,1 ,top_k_3d -> ne [0 ],top_k_3d -> ne [1 ],top_k_3d -> ne [2 ]); 695zeros = ggml_fill (ctx0 ,zeros ,0.0f ); 696 697ggml_tensor * kq_mask_top_k = ggml_set_rows (ctx0 ,kq_mask_all ,zeros ,top_k_3d ); 698kq_mask_top_k = ggml_view_4d (ctx0 ,kq_mask_top_k , 699kq_mask_top_k -> ne [1 ],kq_mask_top_k -> ne [2 ],1 ,kq_mask_top_k -> ne [3 ], 700kq_mask_top_k -> nb [2 ],kq_mask_top_k -> nb [3 ],kq_mask_top_k -> nb [3 ],0 ); 701 702kq_mask_top_k = ggml_add (ctx0 ,kq_mask_top_k ,kq_mask ); 703cb (kq_mask_top_k ,name ,il ); 704 705return kq_mask_top_k ; 706} 707 708ggml_tensor * llama_model_deepseek4::graph::build_csa_lid_attention ( 709const llama_model & model , 710llm_graph_input_dsv4 * inp_dsv4 , 711llm_graph_input_dsv4_raw * inp_attn , 712ggml_tensor * q , 713ggml_tensor * kv , 714ggml_tensor * qr , 715ggml_tensor * cur , 716ggml_tensor * inp_pos , 717ggml_tensor * sinks , 718float kq_scale , 719int il )const { 720const auto & inp_csa = inp_dsv4 -> get_csa (); 721GGML_ASSERT (inp_csa .kq_mask ); 722 723ggml_tensor * top_k = build_lid_top_k (model ,inp_dsv4 ,qr ,cur ,inp_pos ,il ); 724 725ggml_tensor * k_rot = inp_attn -> self_k_rot ; 726if (k_rot ) { 727q = llama_mul_mat_hadamard (ctx0 ,q ,k_rot ); 728kv = llama_mul_mat_hadamard (ctx0 ,kv ,k_rot ); 729 } 730 731ggml_build_forward_expand (gf ,q ); 732ggml_build_forward_expand (gf ,kv ); 733 734const llama_kv_cache_dsv4_raw_context * mctx_raw = inp_attn -> mctx ; 735 736ggml_build_forward_expand (gf ,mctx_raw -> cpy_k (ctx0 ,kv ,inp_attn -> get_k_idxs (),il )); 737 738ggml_tensor * raw_k = mctx_raw -> get_k (ctx0 ,il ); 739cb (raw_k ,"csa_raw_k" ,il ); 740 741ggml_tensor * csa_k = inp_dsv4 -> mctx -> get_csa ()-> get_k (ctx0 ,il ); 742const int64_t n_csa = inp_csa .kq_mask -> ne [0 ]; 743GGML_ASSERT (n_csa > 0 ); 744GGML_ASSERT (n_csa <=csa_k -> ne [2 ]); 745 746csa_k = ggml_view_4d (ctx0 ,csa_k , 747csa_k -> ne [0 ],csa_k -> ne [1 ],n_csa ,csa_k -> ne [3 ], 748csa_k -> nb [1 ],csa_k -> nb [2 ],csa_k -> nb [3 ],0 ); 749cb (csa_k ,"csa_comp_k" ,il ); 750 751ggml_tensor * k_all = ggml_concat (ctx0 ,raw_k ,csa_k ,2 ); 752cb (k_all ,"csa_k_all" ,il ); 753 754ggml_tensor * raw_mask = inp_attn -> get_kq_mask (); 755ggml_tensor * csa_mask = build_top_k_mask (inp_csa .kq_mask ,top_k ,"csa_top_k_mask" ,il ); 756 757ggml_tensor * kq_mask = ggml_concat (ctx0 ,raw_mask ,csa_mask ,0 ); 758cb (kq_mask ,"csa_lid_kq_mask" ,il ); 759 760const int64_t n_kv_max = std::min < int64_t > (raw_mask -> ne [0 ],hparams .n_swa )+ top_k -> ne [0 ]; 761ggml_tensor * out = build_attn_mha (q ,k_all ,k_all ,nullptr ,kq_mask ,sinks ,nullptr ,n_kv_max ,kq_scale ,il ); 762if (k_rot ) { 763out = llama_mul_mat_hadamard (ctx0 ,out ,k_rot ); 764 } 765cb (out ,"attn_csa_lid" ,il ); 766 767return out ; 768} 769 770ggml_tensor * llama_model_deepseek4::graph::build_hca_attention ( 771llm_graph_input_dsv4 * inp_dsv4 , 772llm_graph_input_dsv4_raw * inp_attn , 773ggml_tensor * q , 774ggml_tensor * kv , 775ggml_tensor * sinks , 776float kq_scale , 777int il )const { 778const auto & inp_hca = inp_dsv4 -> get_hca (); 779GGML_ASSERT (inp_hca .kq_mask ); 780 781ggml_tensor * k_rot = inp_attn -> self_k_rot ; 782if (k_rot ) { 783q = llama_mul_mat_hadamard (ctx0 ,q ,k_rot ); 784kv = llama_mul_mat_hadamard (ctx0 ,kv ,k_rot ); 785 } 786 787ggml_build_forward_expand (gf ,q ); 788ggml_build_forward_expand (gf ,kv ); 789 790const llama_kv_cache_dsv4_raw_context * mctx_raw = inp_attn -> mctx ; 791 792ggml_build_forward_expand (gf ,mctx_raw -> cpy_k (ctx0 ,kv ,inp_attn -> get_k_idxs (),il )); 793 794ggml_tensor * raw_k = mctx_raw -> get_k (ctx0 ,il ); 795cb (raw_k ,"hca_raw_k" ,il ); 796 797ggml_tensor * hca_k = inp_dsv4 -> mctx -> get_hca ()-> get_k (ctx0 ,il ); 798const int64_t n_hca = inp_hca .kq_mask -> ne [0 ]; 799GGML_ASSERT (n_hca > 0 ); 800GGML_ASSERT (n_hca <=hca_k -> ne [2 ]); 801 802hca_k = ggml_view_4d (ctx0 ,hca_k , 803hca_k -> ne [0 ],hca_k -> ne [1 ],n_hca ,hca_k -> ne [3 ], 804hca_k -> nb [1 ],hca_k -> nb [2 ],hca_k -> nb [3 ],0 ); 805cb (hca_k ,"hca_comp_k" ,il ); 806 807ggml_tensor * k_all = ggml_concat (ctx0 ,raw_k ,hca_k ,2 ); 808cb (k_all ,"hca_k_all" ,il ); 809 810ggml_tensor * raw_mask = inp_attn -> get_kq_mask (); 811ggml_tensor * hca_mask = inp_hca .kq_mask ; 812 813ggml_tensor * kq_mask = ggml_concat (ctx0 ,raw_mask ,hca_mask ,0 ); 814cb (kq_mask ,"hca_kq_mask" ,il ); 815 816ggml_tensor * out = build_attn_mha (q ,k_all ,k_all ,nullptr ,kq_mask ,sinks ,nullptr ,0 ,kq_scale ,il ); 817if (k_rot ) { 818out = llama_mul_mat_hadamard (ctx0 ,out ,k_rot ); 819 } 820cb (out ,"attn_hca" ,il ); 821 822return out ; 823} 824 825ggml_tensor * llama_model_deepseek4::graph::build_raw_attention ( 826llm_graph_input_dsv4_raw * inp_attn , 827ggml_tensor * q , 828ggml_tensor * kv , 829ggml_tensor * sinks , 830float kq_scale , 831int il )const { 832GGML_ASSERT (hparams .is_swa (il )); 833 834ggml_tensor * k_rot = inp_attn -> self_k_rot ; 835 836if (k_rot ) { 837q = llama_mul_mat_hadamard (ctx0 ,q ,k_rot ); 838kv = llama_mul_mat_hadamard (ctx0 ,kv ,k_rot ); 839 } 840 841ggml_build_forward_expand (gf ,q ); 842ggml_build_forward_expand (gf ,kv ); 843 844const llama_kv_cache_dsv4_raw_context * mctx_cur = inp_attn -> mctx ; 845 846ggml_build_forward_expand (gf ,mctx_cur -> cpy_k (ctx0 ,kv ,inp_attn -> get_k_idxs (),il )); 847 848ggml_tensor * kq_mask = inp_attn -> get_kq_mask (); 849 850ggml_tensor * k = mctx_cur -> get_k (ctx0 ,il ); 851 852ggml_tensor * out = build_attn_mha (q ,k ,k ,nullptr ,kq_mask ,sinks ,nullptr ,0 ,kq_scale ,il ); 853if (k_rot ) { 854out = llama_mul_mat_hadamard (ctx0 ,out ,k_rot ); 855 } 856cb (out ,"attn_raw" ,il ); 857 858return out ; 859} 860 861ggml_tensor * llama_model_deepseek4::graph::build_attention ( 862const llama_model & model , 863llm_graph_input_dsv4 * inp_dsv4 , 864ggml_tensor * cur , 865ggml_tensor * inp_pos , 866int il )const { 867return build_attention_impl (model ,inp_dsv4 ,nullptr ,cur ,inp_pos ,il ); 868} 869 870ggml_tensor * llama_model_deepseek4::graph::build_attention ( 871const llama_model & model , 872llm_graph_input_attn_k_iswa * inp_mtp , 873ggml_tensor * cur , 874ggml_tensor * inp_pos , 875int il )const { 876return build_attention_impl (model ,nullptr ,inp_mtp ,cur ,inp_pos ,il ); 877} 878 879ggml_tensor * llama_model_deepseek4::graph::build_attention_impl ( 880const llama_model & model , 881llm_graph_input_dsv4 * inp_dsv4 , 882llm_graph_input_attn_k_iswa * inp_mtp , 883ggml_tensor * cur , 884ggml_tensor * inp_pos , 885int il )const { 886GGML_ASSERT ((inp_dsv4 == nullptr )!= (inp_mtp == nullptr )); 887 888const auto & layer = model .layers [il ]; 889llm_graph_input_dsv4_raw * inp_attn = inp_dsv4 ?inp_dsv4 -> get_raw () :nullptr ; 890 891const int64_t n_embd_head = hparams .n_embd_head_k (); 892const int64_t n_embd_head_rope = hparams .n_rot (); 893const int64_t n_embd_head_nope = n_embd_head - n_embd_head_rope ; 894const int64_t n_groups = hparams .dsv4_o_group_count ; 895const int64_t n_heads_group = n_head /n_groups ; 896const int64_t o_lora_rank = hparams .dsv4_o_lora_rank ; 897const int64_t o_group_dim = n_heads_group * n_embd_head ; 898const int64_t nt = cur -> ne [1 ]; 899 900GGML_ASSERT (n_embd_head == n_embd_head_v ); 901GGML_ASSERT (n_head %n_groups == 0 ); 902 903const bool use_compress_rope = hparams .dsv4_compress_ratios [il ]!= 0 ; 904const float freq_base_l = use_compress_rope ?hparams .dsv4_compress_rope_base :freq_base ; 905const float freq_scale_l = use_compress_rope ?freq_scale :1.0f ; 906const float ext_factor_l = use_compress_rope ?ext_factor :0.0f ; 907const float attn_factor_l = dsv4_rope_attn_factor (freq_scale_l ,ext_factor_l ); 908const float beta_fast_l = use_compress_rope ?beta_fast :0.0f ; 909const float beta_slow_l = use_compress_rope ?beta_slow :0.0f ; 910const int32_t n_ctx_orig_l = use_compress_rope ?n_ctx_orig :0 ; 911 912ggml_tensor * qr = build_lora_mm (layer .wq_a ,cur ); 913cb (qr ,"qr" ,il ); 914 915qr = build_norm (qr ,layer .attn_q_a_norm ,nullptr ,LLM_NORM_RMS ,il ); 916cb (qr ,"qr_norm" ,il ); 917 918ggml_tensor * q = build_lora_mm (layer .wq_b ,qr ); 919q = ggml_reshape_3d (ctx0 ,q ,n_embd_head ,n_head ,nt ); 920q = ggml_rms_norm (ctx0 ,q ,norm_rms_eps ); 921cb (q ,"q_norm" ,il ); 922 923q = ggml_rope_ext (ctx0 ,q ,inp_pos ,nullptr ,n_embd_head_rope ,rope_type ,n_ctx_orig_l , 924freq_base_l ,freq_scale_l ,ext_factor_l ,attn_factor_l ,beta_fast_l ,beta_slow_l ); 925q = ggml_rope_set_offset (q ,n_embd_head_nope ); 926cb (q ,"q" ,il ); 927 928ggml_tensor * kv = build_lora_mm (layer .wkv ,cur ); 929kv = build_norm (kv ,layer .attn_kv_norm ,nullptr ,LLM_NORM_RMS ,il ); 930kv = ggml_reshape_3d (ctx0 ,kv ,n_embd_head ,1 ,nt ); 931cb (kv ,"kv_norm" ,il ); 932 933kv = ggml_rope_ext (ctx0 ,kv ,inp_pos ,nullptr ,n_embd_head_rope ,rope_type ,n_ctx_orig_l , 934freq_base_l ,freq_scale_l ,ext_factor_l ,attn_factor_l ,beta_fast_l ,beta_slow_l ); 935kv = ggml_rope_set_offset (kv ,n_embd_head_nope ); 936cb (kv ,"kv" ,il ); 937 938const int64_t ratio = hparams .dsv4_compress_ratios [il ]; 939GGML_ASSERT (inp_dsv4 || ratio == 0 ); 940 941ggml_tensor * hca_state_kv = nullptr ; 942ggml_tensor * hca_state_score = nullptr ; 943ggml_tensor * hca_source_kv = nullptr ; 944ggml_tensor * hca_source_score = nullptr ; 945if (ratio == DSV4_HCA_RATIO && inp_dsv4 -> get_hca ().state_pos ) { 946hca_state_kv = build_lora_mm (layer .attn_comp_wkv ,cur ); 947cb (hca_state_kv ,"hca_state_kv" ,il ); 948 949hca_state_score = build_lora_mm (layer .attn_comp_wgate ,cur ); 950cb (hca_state_score ,"hca_state_score" ,il ); 951 952ggml_tensor * ape = layer .attn_comp_ape ; 953 954ggml_tensor * ape_rows = ggml_get_rows (ctx0 ,ape ,inp_dsv4 -> get_hca ().state_pos ); 955hca_state_score = ggml_add (ctx0 ,hca_state_score ,ape_rows ); 956cb (hca_state_score ,"hca_state_score_ape" ,il ); 957 958 } 959 960if (ratio == DSV4_CSA_RATIO && inp_dsv4 -> get_csa ().state_pos ) { 961ggml_tensor * csa_state_kv = build_lora_mm (layer .attn_comp_wkv ,cur ); 962cb (csa_state_kv ,"csa_state_kv" ,il ); 963 964ggml_tensor * csa_state_score = build_lora_mm (layer .attn_comp_wgate ,cur ); 965cb (csa_state_score ,"csa_state_score" ,il ); 966 967ggml_tensor * csa_ape = layer .attn_comp_ape ; 968 969ggml_tensor * csa_ape_rows = ggml_get_rows (ctx0 ,csa_ape ,inp_dsv4 -> get_csa ().state_pos ); 970csa_state_score = ggml_add (ctx0 ,csa_state_score ,csa_ape_rows ); 971cb (csa_state_score ,"csa_state_score_ape" ,il ); 972 973GGML_ASSERT (inp_dsv4 -> get_csa ().state_write_idxs ); 974 975const auto * csa_state = inp_dsv4 -> mctx -> get_csa_state (); 976const dsv4_state_tensors csa_restored = dsv4_build_state_restore ( 977ctx0 ,inp_dsv4 -> get_csa (),csa_state ,il ); 978ggml_tensor * csa_base_kv = dsv4_view_2d ( 979ctx0 ,csa_restored .kv ,csa_restored .kv -> ne [0 ],csa_state -> get_n_rows (),0 ); 980ggml_tensor * csa_base_score = dsv4_view_2d ( 981ctx0 ,csa_restored .score ,csa_restored .score -> ne [0 ],csa_state -> get_n_rows (),0 ); 982 983ggml_tensor * csa_source_kv = ggml_concat (ctx0 ,csa_base_kv ,csa_state_kv ,1 ); 984ggml_tensor * csa_source_score = ggml_concat (ctx0 ,csa_base_score ,csa_state_score ,1 ); 985 986ggml_tensor * kv_comp_csa_state = build_overlap_compressed_kv_from_state ( 987csa_source_kv , 988csa_source_score , 989inp_dsv4 -> get_csa ().state_read_idxs , 990inp_dsv4 -> get_csa ().state_write_pos , 991layer .attn_comp_norm , 992DSV4_CSA_RATIO , 993n_embd_head , 994"csa_state_compress" , 995il ); 996 997if (inp_dsv4 -> get_csa ().k_rot ) { 998kv_comp_csa_state = llama_mul_mat_hadamard (ctx0 ,kv_comp_csa_state ,inp_dsv4 -> get_csa ().k_rot ); 999cb (kv_comp_csa_state ,"csa_state_compress_rot" ,il ); 1000 } 1001 1002ggml_build_forward_expand (gf ,inp_dsv4 -> mctx -> get_csa ()-> cpy_k (ctx0 , 1003kv_comp_csa_state ,inp_dsv4 -> get_csa ().state_write_idxs ,il )); 1004 1005ggml_tensor * csa_snapshot_source_kv = ggml_concat (ctx0 , 1006csa_restored .kv ,csa_state_kv ,1 ); 1007ggml_tensor * csa_snapshot_source_score = ggml_concat (ctx0 , 1008csa_restored .score ,csa_state_score ,1 ); 1009 1010const dsv4_state_tensors csa_snapshot = dsv4_build_state_snapshot ( 1011ctx0 ,inp_dsv4 -> get_csa (),csa_state ,csa_snapshot_source_kv ,csa_snapshot_source_score ,il ); 1012if (csa_snapshot .kv != nullptr ) { 1013ggml_build_forward_expand (gf ,csa_snapshot .kv ); 1014 } 1015if (csa_snapshot .score != nullptr ) { 1016ggml_build_forward_expand (gf ,csa_snapshot .score ); 1017 } 1018 1019ggml_tensor * csa_persist_kv = ggml_get_rows (ctx0 ,csa_state_kv ,inp_dsv4 -> get_csa ().state_persist_src_idxs ); 1020ggml_tensor * csa_persist_score = ggml_get_rows (ctx0 ,csa_state_score ,inp_dsv4 -> get_csa ().state_persist_src_idxs ); 1021 1022csa_state_kv = inp_dsv4 -> mctx -> get_csa_state ()-> cpy_kv (ctx0 , 1023csa_persist_kv ,inp_dsv4 -> get_csa ().state_persist_dst_idxs ,il ); 1024csa_state_score = inp_dsv4 -> mctx -> get_csa_state ()-> cpy_score (ctx0 , 1025csa_persist_score ,inp_dsv4 -> get_csa ().state_persist_dst_idxs ,il ); 1026 1027ggml_build_forward_expand (gf ,csa_state_kv ); 1028ggml_build_forward_expand (gf ,csa_state_score ); 1029 1030ggml_tensor * lid_state_kv = build_lora_mm (layer .indexer_comp_wkv ,cur ); 1031cb (lid_state_kv ,"lid_state_kv" ,il ); 1032 1033ggml_tensor * lid_state_score = build_lora_mm (layer .indexer_comp_wgate ,cur ); 1034cb (lid_state_score ,"lid_state_score" ,il ); 1035 1036ggml_tensor * lid_ape = layer .indexer_comp_ape ; 1037 1038ggml_tensor * lid_ape_rows = ggml_get_rows (ctx0 ,lid_ape ,inp_dsv4 -> get_lid ().state_pos ); 1039lid_state_score = ggml_add (ctx0 ,lid_state_score ,lid_ape_rows ); 1040cb (lid_state_score ,"lid_state_score_ape" ,il ); 1041 1042GGML_ASSERT (inp_dsv4 -> get_lid ().state_write_idxs ); 1043 1044const auto * lid_state = inp_dsv4 -> mctx -> get_lid_state (); 1045const dsv4_state_tensors lid_restored = dsv4_build_state_restore ( 1046ctx0 ,inp_dsv4 -> get_lid (),lid_state ,il ); 1047ggml_tensor * lid_base_kv = dsv4_view_2d ( 1048ctx0 ,lid_restored .kv ,lid_restored .kv -> ne [0 ],lid_state -> get_n_rows (),0 ); 1049ggml_tensor * lid_base_score = dsv4_view_2d ( 1050ctx0 ,lid_restored .score ,lid_restored .score -> ne [0 ],lid_state -> get_n_rows (),0 ); 1051 1052ggml_tensor * lid_source_kv = ggml_concat (ctx0 ,lid_base_kv ,lid_state_kv ,1 ); 1053ggml_tensor * lid_source_score = ggml_concat (ctx0 ,lid_base_score ,lid_state_score ,1 ); 1054 1055ggml_tensor * kv_comp_lid_state = build_overlap_compressed_kv_from_state ( 1056lid_source_kv , 1057lid_source_score , 1058inp_dsv4 -> get_lid ().state_read_idxs , 1059inp_dsv4 -> get_lid ().state_write_pos , 1060layer .indexer_comp_norm , 1061DSV4_CSA_RATIO , 1062hparams .indexer_head_size , 1063"lid_state_compress" , 1064il ); 1065 1066if (inp_dsv4 -> get_lid ().k_rot ) { 1067kv_comp_lid_state = llama_mul_mat_hadamard (ctx0 ,kv_comp_lid_state ,inp_dsv4 -> get_lid ().k_rot ); 1068cb (kv_comp_lid_state ,"lid_state_compress_rot" ,il ); 1069 } 1070 1071ggml_build_forward_expand (gf ,inp_dsv4 -> mctx -> get_lid ()-> cpy_k (ctx0 , 1072kv_comp_lid_state ,inp_dsv4 -> get_lid ().state_write_idxs ,il )); 1073 1074ggml_tensor * lid_snapshot_source_kv = ggml_concat (ctx0 , 1075lid_restored .kv ,lid_state_kv ,1 ); 1076ggml_tensor * lid_snapshot_source_score = ggml_concat (ctx0 , 1077lid_restored .score ,lid_state_score ,1 ); 1078 1079const dsv4_state_tensors lid_snapshot = dsv4_build_state_snapshot ( 1080ctx0 ,inp_dsv4 -> get_lid (),lid_state ,lid_snapshot_source_kv ,lid_snapshot_source_score ,il ); 1081if (lid_snapshot .kv != nullptr ) { 1082ggml_build_forward_expand (gf ,lid_snapshot .kv ); 1083 } 1084if (lid_snapshot .score != nullptr ) { 1085ggml_build_forward_expand (gf ,lid_snapshot .score ); 1086 } 1087 1088ggml_tensor * lid_persist_kv = ggml_get_rows (ctx0 ,lid_state_kv ,inp_dsv4 -> get_lid ().state_persist_src_idxs ); 1089ggml_tensor * lid_persist_score = ggml_get_rows (ctx0 ,lid_state_score ,inp_dsv4 -> get_lid ().state_persist_src_idxs ); 1090 1091lid_state_kv = inp_dsv4 -> mctx -> get_lid_state ()-> cpy_kv (ctx0 , 1092lid_persist_kv ,inp_dsv4 -> get_lid ().state_persist_dst_idxs ,il ); 1093lid_state_score = inp_dsv4 -> mctx -> get_lid_state ()-> cpy_score (ctx0 , 1094lid_persist_score ,inp_dsv4 -> get_lid ().state_persist_dst_idxs ,il ); 1095 1096ggml_build_forward_expand (gf ,lid_state_kv ); 1097ggml_build_forward_expand (gf ,lid_state_score ); 1098 } 1099 1100const llama_dsv4_comp_state * hca_state = nullptr ; 1101dsv4_state_tensors hca_restored = {}; 1102if (ratio == DSV4_HCA_RATIO && inp_dsv4 -> get_hca ().state_write_idxs ) { 1103GGML_ASSERT (hca_state_kv ); 1104GGML_ASSERT (hca_state_score ); 1105 1106hca_state = inp_dsv4 -> mctx -> get_hca_state (); 1107hca_restored = dsv4_build_state_restore (ctx0 ,inp_dsv4 -> get_hca (),hca_state ,il ); 1108ggml_tensor * hca_base_kv = dsv4_view_2d ( 1109ctx0 ,hca_restored .kv ,hca_restored .kv -> ne [0 ],hca_state -> get_n_rows (),0 ); 1110ggml_tensor * hca_base_score = dsv4_view_2d ( 1111ctx0 ,hca_restored .score ,hca_restored .score -> ne [0 ],hca_state -> get_n_rows (),0 ); 1112 1113hca_source_kv = ggml_concat (ctx0 ,hca_base_kv ,hca_state_kv ,1 ); 1114hca_source_score = ggml_concat (ctx0 ,hca_base_score ,hca_state_score ,1 ); 1115 1116ggml_tensor * kv_comp_hca = build_hca_compressed_kv_from_state ( 1117hca_source_kv , 1118hca_source_score , 1119inp_dsv4 -> get_hca ().state_read_idxs , 1120inp_dsv4 -> get_hca ().state_write_pos , 1121layer .attn_comp_norm , 1122n_embd_head , 1123"hca_state_compress" , 1124il ); 1125 1126if (inp_dsv4 -> get_hca ().k_rot ) { 1127kv_comp_hca = llama_mul_mat_hadamard (ctx0 ,kv_comp_hca ,inp_dsv4 -> get_hca ().k_rot ); 1128cb (kv_comp_hca ,"hca_state_compress_rot" ,il ); 1129 } 1130 1131ggml_build_forward_expand (gf ,inp_dsv4 -> mctx -> get_hca ()-> cpy_k (ctx0 , 1132kv_comp_hca ,inp_dsv4 -> get_hca ().state_write_idxs ,il )); 1133 } 1134 1135if (ratio == DSV4_HCA_RATIO && inp_dsv4 -> get_hca ().state_pos ) { 1136GGML_ASSERT (hca_state_kv ); 1137GGML_ASSERT (hca_state_score ); 1138 1139if (hca_state == nullptr ) { 1140hca_state = inp_dsv4 -> mctx -> get_hca_state (); 1141 } 1142if (hca_restored .kv == nullptr ) { 1143hca_restored = dsv4_build_state_restore (ctx0 ,inp_dsv4 -> get_hca (),hca_state ,il ); 1144 } 1145if (hca_source_kv == nullptr || hca_source_score == nullptr ) { 1146ggml_tensor * hca_base_kv = dsv4_view_2d ( 1147ctx0 ,hca_restored .kv ,hca_restored .kv -> ne [0 ],hca_state -> get_n_rows (),0 ); 1148ggml_tensor * hca_base_score = dsv4_view_2d ( 1149ctx0 ,hca_restored .score ,hca_restored .score -> ne [0 ],hca_state -> get_n_rows (),0 ); 1150 1151hca_source_kv = ggml_concat (ctx0 ,hca_base_kv ,hca_state_kv ,1 ); 1152hca_source_score = ggml_concat (ctx0 ,hca_base_score ,hca_state_score ,1 ); 1153 } 1154 1155ggml_tensor * hca_snapshot_source_kv = ggml_concat (ctx0 , 1156hca_restored .kv ,hca_state_kv ,1 ); 1157ggml_tensor * hca_snapshot_source_score = ggml_concat (ctx0 , 1158hca_restored .score ,hca_state_score ,1 ); 1159 1160const dsv4_state_tensors hca_snapshot = dsv4_build_state_snapshot ( 1161ctx0 ,inp_dsv4 -> get_hca (),hca_state ,hca_snapshot_source_kv ,hca_snapshot_source_score ,il ); 1162if (hca_snapshot .kv != nullptr ) { 1163ggml_build_forward_expand (gf ,hca_snapshot .kv ); 1164 } 1165if (hca_snapshot .score != nullptr ) { 1166ggml_build_forward_expand (gf ,hca_snapshot .score ); 1167 } 1168 1169ggml_tensor * hca_persist_kv = ggml_get_rows (ctx0 ,hca_state_kv ,inp_dsv4 -> get_hca ().state_persist_src_idxs ); 1170ggml_tensor * hca_persist_score = ggml_get_rows (ctx0 ,hca_state_score ,inp_dsv4 -> get_hca ().state_persist_src_idxs ); 1171 1172hca_state_kv = inp_dsv4 -> mctx -> get_hca_state ()-> cpy_kv (ctx0 , 1173hca_persist_kv ,inp_dsv4 -> get_hca ().state_persist_dst_idxs ,il ); 1174hca_state_score = inp_dsv4 -> mctx -> get_hca_state ()-> cpy_score (ctx0 , 1175hca_persist_score ,inp_dsv4 -> get_hca ().state_persist_dst_idxs ,il ); 1176 1177ggml_build_forward_expand (gf ,hca_state_kv ); 1178ggml_build_forward_expand (gf ,hca_state_score ); 1179 } 1180 1181ggml_tensor * out = nullptr ; 1182if (inp_mtp ) { 1183out = build_attn (inp_mtp , 1184nullptr ,nullptr ,nullptr , 1185q ,kv ,kv , 1186nullptr ,layer .attn_sinks ,nullptr , 11871.0f /sqrtf (float (n_embd_head )),il ); 1188cb (out ,"attn_raw" ,il ); 1189 }else if (ratio == DSV4_CSA_RATIO && 1190inp_dsv4 -> get_csa ().kq_mask && 1191inp_dsv4 -> get_lid ().kq_mask && 1192inp_dsv4 -> get_lid ().k_rot ) { 1193out = build_csa_lid_attention (model ,inp_dsv4 ,inp_attn ,q ,kv ,qr ,cur ,inp_pos ,layer .attn_sinks , 11941.0f /sqrtf (float (n_embd_head )),il ); 1195 }else if (ratio == DSV4_HCA_RATIO && 1196inp_dsv4 -> get_hca ().kq_mask ) { 1197out = build_hca_attention (inp_dsv4 ,inp_attn ,q ,kv ,layer .attn_sinks , 11981.0f /sqrtf (float (n_embd_head )),il ); 1199 }else { 1200out = build_raw_attention (inp_attn ,q ,kv ,layer .attn_sinks , 12011.0f /sqrtf (float (n_embd_head )),il ); 1202 } 1203 1204out = ggml_reshape_3d (ctx0 ,out ,n_embd_head ,n_head ,nt ); 1205out = ggml_rope_ext_back (ctx0 ,out ,inp_pos ,nullptr ,n_embd_head_rope ,rope_type ,n_ctx_orig_l , 1206freq_base_l ,freq_scale_l ,ext_factor_l ,attn_factor_l ,beta_fast_l ,beta_slow_l ); 1207out = ggml_rope_set_offset (out ,n_embd_head_nope ); 1208cb (out ,"attn_derope" ,il ); 1209 1210out = ggml_reshape_3d (ctx0 ,out ,o_group_dim ,n_groups ,nt ); 1211out = ggml_permute (ctx0 ,out ,0 ,2 ,1 ,3 ); 1212ggml_tensor * oa = ggml_mul_mat (ctx0 ,layer .wo_a ,out ); 1213cb (oa ,"attn_wo_a" ,il ); 1214oa = ggml_permute (ctx0 ,oa ,0 ,2 ,1 ,3 ); 1215oa = ggml_cont_2d (ctx0 ,oa ,o_lora_rank * n_groups ,nt ); 1216 1217out = build_lora_mm (layer .wo_b ,oa ); 1218cb (out ,"attn_out" ,il ); 1219 1220return out ; 1221} 1222 1223llama_model_deepseek4::graph::graph (const llama_model & model ,const llm_graph_params & params ) : 1224llm_graph_context (params ) { 1225ggml_tensor * cur ; 1226 1227ggml_tensor * inp = build_inp_embd (model .tok_embd ); 1228ggml_tensor * inp_pos = build_inp_pos (); 1229ggml_tensor * inp_out_ids = build_inp_out_ids (); 1230llm_graph_input_dsv4 * inp_dsv4 = build_inp_dsv4 (); 1231llm_graph_input_dsv4_raw * inp_attn = inp_dsv4 -> get_raw (); 1232ggml_build_forward_expand (gf ,inp_attn -> self_kq_mask ); 1233 1234const int64_t hc = hparams .dsv4_hc_mult ; 1235ggml_tensor * inpL = ggml_reshape_3d (ctx0 ,inp ,n_embd ,1 ,n_tokens ); 1236inpL = ggml_repeat_4d (ctx0 ,inpL ,n_embd ,hc ,n_tokens ,1 ); 1237cb (inpL ,"hc_init" ,-1 ); 1238 1239for (int il = 0 ;il < n_layer ;++ il ) { 1240if ((size_t )il < cparams .embeddings_layer_inp .size ()&& cparams .embeddings_layer_inp [il ]) { 1241res -> t_layer_inp [il ]= dsv4_hc_mean (ctx0 ,inpL ); 1242cb (res -> t_layer_inp [il ],"layer_inp" ,il ); 1243ggml_build_forward_expand (gf ,res -> t_layer_inp [il ]); 1244 } 1245 1246ggml_tensor * residual = inpL ; 1247ggml_tensor * post = nullptr ; 1248ggml_tensor * comb = nullptr ; 1249 1250cur = build_hc_pre (inpL , 1251model .layers [il ].hc_attn_fn , 1252model .layers [il ].hc_attn_scale , 1253model .layers [il ].hc_attn_base , 1254& post ,& comb ,il ); 1255cb (cur ,"hc_attn_pre" ,il ); 1256 1257cur = build_norm (cur ,model .layers [il ].attn_norm ,nullptr ,LLM_NORM_RMS ,il ); 1258cb (cur ,"attn_norm" ,il ); 1259 1260cur = build_attention (model ,inp_dsv4 ,cur ,inp_pos ,il ); 1261 1262inpL = build_hc_post (cur ,residual ,post ,comb ,il ); 1263cb (inpL ,"hc_attn_post" ,il ); 1264 1265residual = inpL ; 1266cur = build_hc_pre (inpL , 1267model .layers [il ].hc_ffn_fn , 1268model .layers [il ].hc_ffn_scale , 1269model .layers [il ].hc_ffn_base , 1270& post ,& comb ,il ); 1271cb (cur ,"hc_ffn_pre" ,il ); 1272 1273ggml_build_forward_expand (gf ,residual ); 1274ggml_build_forward_expand (gf ,post ); 1275ggml_build_forward_expand (gf ,comb ); 1276 1277cur = build_norm (cur ,model .layers [il ].ffn_norm ,nullptr ,LLM_NORM_RMS ,il ); 1278cb (cur ,"ffn_norm" ,il ); 1279 1280const auto & layer = model .layers [il ]; 1281ggml_tensor * selected_experts = nullptr ; 1282ggml_tensor * exp_probs_b = layer .ffn_exp_probs_b ; 1283 1284// may apply exp_probs_b_vl is input is from mtmd 1285const bool is_media = ubatch .embd != nullptr ; 1286if (is_media ) { 1287if (layer .ffn_exp_probs_b_vl ) { 1288exp_probs_b = layer .ffn_exp_probs_b_vl ; 1289 } 1290 }else if ((uint32_t )il < hparams .dsv4_hash_layer_count ) { 1291selected_experts = ggml_get_rows (ctx0 ,layer .ffn_gate_tid2eid ,res -> t_inp_tokens ); 1292exp_probs_b = nullptr ; 1293 } 1294 1295ggml_tensor * moe_out = build_moe_ffn (cur , 1296layer .ffn_gate_inp , 1297layer .ffn_up_exps , 1298layer .ffn_gate_exps , 1299layer .ffn_down_exps , 1300exp_probs_b , 1301n_expert ,hparams .n_expert_used (), 1302LLM_FFN_SILU ,hparams .expert_weights_norm , 1303hparams .expert_weights_scale , 1304 (llama_expert_gating_func_type )hparams .expert_gating_func , 1305il , 1306nullptr , 1307nullptr , 1308nullptr , 1309nullptr , 1310nullptr , 1311selected_experts ); 1312cb (moe_out ,"ffn_moe_out" ,il ); 1313 1314ggml_tensor * ffn_shexp = build_ffn (cur , 1315layer .ffn_up_shexp ,nullptr ,nullptr , 1316layer .ffn_gate_shexp ,nullptr ,nullptr , 1317layer .ffn_down_shexp ,nullptr ,nullptr , 1318nullptr ,LLM_FFN_SILU ,LLM_FFN_PAR ,il ); 1319cb (ffn_shexp ,"ffn_shexp" ,il ); 1320 1321cur = ggml_add (ctx0 ,moe_out ,ffn_shexp ); 1322cb (cur ,"ffn_out" ,il ); 1323 1324inpL = build_hc_post (cur ,residual ,post ,comb ,il ); 1325inpL = build_cvec (inpL ,il ); 1326cb (inpL ,"l_last" ,il ); 1327 } 1328 1329if ((size_t )n_layer < cparams .embeddings_layer_inp .size ()&& cparams .embeddings_layer_inp [n_layer ]) { 1330res -> t_layer_inp [n_layer ]= dsv4_hc_mean (ctx0 ,inpL ); 1331cb (res -> t_layer_inp [n_layer ],"layer_inp" ,n_layer ); 1332ggml_build_forward_expand (gf ,res -> t_layer_inp [n_layer ]); 1333 } 1334 1335ggml_tensor * flat = ggml_reshape_2d (ctx0 ,inpL ,n_embd * hc ,n_tokens ); 1336ggml_tensor * flat_out = inp_out_ids ?ggml_get_rows (ctx0 ,flat ,inp_out_ids ) :flat ; 1337 1338if (cparams .embeddings_nextn ) { 1339ggml_tensor * h_nextn = cparams .embeddings_nextn_masked ?flat_out :inpL ; 1340cb (h_nextn ,"h_nextn" ,-1 ); 1341res -> t_h_nextn = h_nextn ; 1342 } 1343 1344if (inp_out_ids ) { 1345inpL = ggml_reshape_3d (ctx0 ,flat_out ,n_embd ,hc ,n_outputs ); 1346 } 1347 1348cur = build_hc_head (inpL ,model .hc_head_fn ,model .hc_head_scale ,model .hc_head_base ); 1349cb (cur ,"hc_head" ,-1 ); 1350 1351cur = build_norm (cur ,model .output_norm ,nullptr ,LLM_NORM_RMS ,-1 ); 1352cb (cur ,"result_norm" ,-1 ); 1353res -> t_embd = cur ; 1354 1355cur = ggml_mul_mat (ctx0 ,model .output ,cur ); 1356cb (cur ,"result_output" ,-1 ); 1357res -> t_logits = cur ; 1358 1359ggml_build_forward_expand (gf ,cur ); 1360} 1361 1362 1363llama_model_deepseek4::graph_mtp::graph_mtp (const llama_model & model ,const llm_graph_params & params ) : 1364graph (params ) { 1365GGML_ASSERT (hparams .n_layer_nextn > 0 && "DEEPSEEK4 MTP requires n_layer_nextn > 0" ); 1366GGML_ASSERT (hparams .n_layer_nextn == 1 && "DEEPSEEK4 MTP currently only supports a single MTP block" ); 1367GGML_ASSERT (cparams .nextn_layer_offset >=0 && 1368cparams .nextn_layer_offset < (int )hparams .n_layer_nextn && 1369"nextn_layer_offset out of range [0, n_layer_nextn)" ); 1370GGML_ASSERT (ubatch .token && "DEEPSEEK4 MTP requires token input" ); 1371 1372const int64_t hc = hparams .dsv4_hc_mult ; 1373GGML_ASSERT (hparams .n_embd_out ()== (uint32_t ) (n_embd * hc )&& "DEEPSEEK4 MTP hidden width mismatch" ); 1374 1375const int il = hparams .n_layer ()+ cparams .nextn_layer_offset ; 1376const auto & layer = model .layers [il ]; 1377 1378GGML_ASSERT (layer .nextn .eh_proj && "MTP block missing nextn.eh_proj" ); 1379GGML_ASSERT (layer .nextn .enorm && "MTP block missing nextn.enorm" ); 1380GGML_ASSERT (layer .nextn .hnorm && "MTP block missing nextn.hnorm" ); 1381 1382auto inp = std::make_unique < llm_graph_input_embd_h > (hparams .n_embd_out ()); 1383 1384inp -> tokens = ggml_new_tensor_1d (ctx0 ,GGML_TYPE_I32 ,n_tokens ); 1385ggml_set_input (inp -> tokens ); 1386 1387inp -> embd = ggml_new_tensor_2d (ctx0 ,GGML_TYPE_F32 ,hparams .n_embd_out (),n_tokens ); 1388ggml_set_input (inp -> embd ); 1389 1390inp -> h = ggml_new_tensor_2d (ctx0 ,GGML_TYPE_F32 ,hparams .n_embd_out (),n_tokens ); 1391ggml_set_input (inp -> h ); 1392ggml_set_name (inp -> h ,"mtp_h_input" ); 1393 1394ggml_tensor * tok_embd_w = layer .nextn .embed_tokens ?layer .nextn .embed_tokens :model .tok_embd ; 1395ggml_tensor * tok_embd = ggml_get_rows (ctx0 ,tok_embd_w ,inp -> tokens ); 1396cb (tok_embd ,"mtp_tok_embd" ,il ); 1397 1398ggml_tensor * h_state = ggml_reshape_3d (ctx0 ,inp -> h ,n_embd ,hc ,n_tokens ); 1399cb (h_state ,"mtp_h_state" ,il ); 1400 1401res -> add_input (std::move (inp )); 1402 1403ggml_tensor * inp_pos = build_inp_pos (); 1404ggml_tensor * inp_out_ids = build_inp_out_ids (); 1405llm_graph_input_attn_k_iswa * inp_attn = build_attn_inp_k_iswa (); 1406 1407ggml_tensor * h_norm = build_norm (h_state ,layer .nextn .hnorm ,nullptr ,LLM_NORM_RMS ,il ); 1408cb (h_norm ,"mtp_hnorm" ,il ); 1409 1410ggml_tensor * e_norm = build_norm (tok_embd ,layer .nextn .enorm ,nullptr ,LLM_NORM_RMS ,il ); 1411e_norm = ggml_reshape_3d (ctx0 ,e_norm ,n_embd ,1 ,n_tokens ); 1412e_norm = ggml_repeat_4d (ctx0 ,e_norm ,n_embd ,hc ,n_tokens ,1 ); 1413cb (e_norm ,"mtp_enorm" ,il ); 1414 1415ggml_tensor * concat = ggml_concat (ctx0 ,e_norm ,h_norm ,0 ); 1416cb (concat ,"mtp_concat" ,il ); 1417 1418ggml_tensor * inpL = build_lora_mm (layer .nextn .eh_proj ,concat ,layer .nextn .eh_proj_s ); 1419cb (inpL ,"mtp_eh_proj" ,il ); 1420 1421ggml_tensor * residual = inpL ; 1422ggml_tensor * post = nullptr ; 1423ggml_tensor * comb = nullptr ; 1424 1425ggml_tensor * cur = build_hc_pre (inpL , 1426layer .hc_attn_fn , 1427layer .hc_attn_scale , 1428layer .hc_attn_base , 1429& post ,& comb ,il ); 1430cb (cur ,"mtp_hc_attn_pre" ,il ); 1431 1432cur = build_norm (cur ,layer .attn_norm ,nullptr ,LLM_NORM_RMS ,il ); 1433cb (cur ,"mtp_attn_norm" ,il ); 1434 1435cur = build_attention (model ,inp_attn ,cur ,inp_pos ,il ); 1436 1437inpL = build_hc_post (cur ,residual ,post ,comb ,il ); 1438cb (inpL ,"mtp_hc_attn_post" ,il ); 1439 1440residual = inpL ; 1441cur = build_hc_pre (inpL , 1442layer .hc_ffn_fn , 1443layer .hc_ffn_scale , 1444layer .hc_ffn_base , 1445& post ,& comb ,il ); 1446cb (cur ,"mtp_hc_ffn_pre" ,il ); 1447 1448cur = build_norm (cur ,layer .ffn_norm ,nullptr ,LLM_NORM_RMS ,il ); 1449cb (cur ,"mtp_ffn_norm" ,il ); 1450 1451GGML_ASSERT ((uint32_t )il >=hparams .dsv4_hash_layer_count && "DEEPSEEK4 MTP does not support hash-routed MTP blocks" ); 1452ggml_tensor * moe_out = build_moe_ffn (cur , 1453layer .ffn_gate_inp , 1454layer .ffn_up_exps , 1455layer .ffn_gate_exps , 1456layer .ffn_down_exps , 1457layer .ffn_exp_probs_b , 1458n_expert ,hparams .n_expert_used (), 1459LLM_FFN_SILU ,hparams .expert_weights_norm , 1460hparams .expert_weights_scale , 1461 (llama_expert_gating_func_type )hparams .expert_gating_func , 1462il ); 1463cb (moe_out ,"mtp_ffn_moe_out" ,il ); 1464 1465ggml_tensor * ffn_shexp = build_ffn (cur , 1466layer .ffn_up_shexp ,nullptr ,nullptr , 1467layer .ffn_gate_shexp ,nullptr ,nullptr , 1468layer .ffn_down_shexp ,nullptr ,nullptr , 1469nullptr ,LLM_FFN_SILU ,LLM_FFN_PAR ,il ); 1470cb (ffn_shexp ,"mtp_ffn_shexp" ,il ); 1471 1472cur = ggml_add (ctx0 ,moe_out ,ffn_shexp ); 1473cb (cur ,"mtp_ffn_out" ,il ); 1474 1475inpL = build_hc_post (cur ,residual ,post ,comb ,il ); 1476inpL = build_cvec (inpL ,il ); 1477cb (inpL ,"mtp_l_out" ,il ); 1478 1479ggml_tensor * flat = ggml_reshape_2d (ctx0 ,inpL ,n_embd * hc ,n_tokens ); 1480ggml_tensor * h_nextn = ggml_get_rows (ctx0 ,flat ,inp_out_ids ); 1481cb (h_nextn ,"h_nextn" ,-1 ); 1482res -> t_h_nextn = h_nextn ; 1483 1484inpL = ggml_reshape_3d (ctx0 ,h_nextn ,n_embd ,hc ,n_outputs ); 1485 1486cur = build_hc_head (inpL ,model .hc_head_fn ,model .hc_head_scale ,model .hc_head_base ); 1487cb (cur ,"mtp_hc_head" ,-1 ); 1488 1489ggml_tensor * head_norm_w = layer .nextn .shared_head_norm ?layer .nextn .shared_head_norm :model .output_norm ; 1490GGML_ASSERT (head_norm_w && "DEEPSEEK4 MTP missing shared head norm" ); 1491cur = build_norm (cur ,head_norm_w ,nullptr ,LLM_NORM_RMS ,-1 ); 1492cb (cur ,"mtp_shared_head_norm" ,-1 ); 1493res -> t_embd = cur ; 1494 1495ggml_tensor * head_w = layer .nextn .shared_head_head ?layer .nextn .shared_head_head :model .output ; 1496GGML_ASSERT (head_w && "DEEPSEEK4 MTP missing LM head" ); 1497cur = ggml_mul_mat (ctx0 ,head_w ,cur ); 1498cb (cur ,"result_output" ,-1 ); 1499 1500res -> t_logits = cur ; 1501ggml_build_forward_expand (gf ,cur ); 1502}