char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
465e49b9c
char/aliceai-t5-moe
1#include "models.h" 2#include "llama-memory-recurrent.h" 3 4void llama_model_qwen35::load_arch_hparams (llama_model_loader & ml ) { 5ml .get_key (LLM_KV_ATTENTION_LAYERNORM_RMS_EPS ,hparams .f_norm_rms_eps ); 6ml .get_key_or_arr (LLM_KV_ROPE_DIMENSION_SECTIONS ,hparams .rope_sections ,4 , true); 7 8// Load linear attention (gated delta net) parameters 9ml .get_key (LLM_KV_SSM_CONV_KERNEL ,hparams .ssm_d_conv ); 10ml .get_key (LLM_KV_SSM_INNER_SIZE ,hparams .ssm_d_inner ); 11ml .get_key (LLM_KV_SSM_STATE_SIZE ,hparams .ssm_d_state ); 12ml .get_key (LLM_KV_SSM_TIME_STEP_RANK ,hparams .ssm_dt_rank ); 13ml .get_key (LLM_KV_SSM_GROUP_COUNT ,hparams .ssm_n_group ); 14 15// Mark recurrent layers (linear attention layers). MTP layers are dense 16// attention-only and must be flagged non-recurrent. 17if (!ml .get_key_or_arr (LLM_KV_ATTENTION_RECURRENT_LAYERS ,hparams .is_recr_impl ,hparams .n_layer_all , false)) { 18uint32_t full_attn_interval = 4 ; 19ml .get_key (LLM_KV_FULL_ATTENTION_INTERVAL ,full_attn_interval , false); 20for (uint32_t i = 0 ;i < hparams .n_layer_all ;++ i ) { 21hparams .is_recr_impl [i ]= (i < hparams .n_layer ())&& ((i + 1 ) %full_attn_interval != 0 ); 22 } 23 } 24 25switch (hparams .n_layer ()) { 26case 24 :type = hparams .n_embd == 1024 ?LLM_TYPE_0_8B :LLM_TYPE_2B ;break ; 27case 32 :type = hparams .n_embd == 2560 ?LLM_TYPE_4B :LLM_TYPE_9B ;break ; 28case 64 :type = LLM_TYPE_27B ;break ; 29default :type = LLM_TYPE_UNKNOWN ; 30 } 31} 32 33void llama_model_qwen35::load_arch_tensors (llama_model_loader & ml ) { 34LLAMA_LOAD_LOCALS ; 35 36const bool mtp_only = (hparams .n_layer_nextn > 0 )&& (ml .get_weight ("blk.0.attn_norm.weight" )== nullptr ); 37const int trunk_flags = mtp_only ?TENSOR_NOT_REQUIRED :0 ; 38int mtp_flags = !ml .load_mtp ?TENSOR_SKIP :0 ; 39 40tok_embd = create_tensor (tn (LLM_TENSOR_TOKEN_EMBD ,"weight" ), {n_embd ,n_vocab },0 ); 41 42// output 43output_norm = create_tensor (tn (LLM_TENSOR_OUTPUT_NORM ,"weight" ), {n_embd },0 ); 44output = create_tensor (tn (LLM_TENSOR_OUTPUT ,"weight" ), {n_embd ,n_vocab },TENSOR_NOT_REQUIRED ); 45 46// if output is NULL, init from the input tok embed 47if (output == NULL ) { 48output = create_tensor (tn (LLM_TENSOR_TOKEN_EMBD ,"weight" ), {n_embd ,n_vocab },TENSOR_DUPLICATED ); 49 } 50 51auto load_block_trunk = [& ](int il ,int flags ) { 52auto & layer = layers [il ]; 53 54// Calculate dimensions from hyperparameters 55const int64_t head_k_dim = hparams .ssm_d_state ; 56const int64_t head_v_dim = hparams .ssm_d_state ; 57const int64_t n_k_heads = hparams .ssm_n_group ; 58const int64_t n_v_heads = hparams .ssm_dt_rank ; 59const int64_t key_dim = head_k_dim * n_k_heads ; 60const int64_t value_dim = head_v_dim * n_v_heads ; 61const int64_t conv_dim = key_dim * 2 + value_dim ; 62 63layer .attn_norm = create_tensor (tn (LLM_TENSOR_ATTN_NORM ,"weight" ,il ), {n_embd },flags ); 64layer .attn_post_norm = create_tensor (tn (LLM_TENSOR_ATTN_POST_NORM ,"weight" ,il ), {n_embd },flags ); 65 66if (!hparams .is_recr (il )) { 67// Attention layers 68create_tensor_qkv (layer ,il ,n_embd ,n_embd_head_k * n_head * 2 ,n_embd_k_gqa ,n_embd_v_gqa ,flags ); 69layer .wo = create_tensor (tn (LLM_TENSOR_ATTN_OUT ,"weight" ,il ), {n_embd_head_k * n_head ,n_embd },flags ); 70 71// Q/K normalization for attention layers 72layer .attn_q_norm = create_tensor (tn (LLM_TENSOR_ATTN_Q_NORM ,"weight" ,il ), {n_embd_head_k },flags ); 73layer .attn_k_norm = create_tensor (tn (LLM_TENSOR_ATTN_K_NORM ,"weight" ,il ), {n_embd_head_k },flags ); 74 }else { 75// Linear attention (gated delta net) specific tensors 76// Create tensors with calculated dimensions 77layer .wqkv = create_tensor (tn (LLM_TENSOR_ATTN_QKV ,"weight" ,il ), {n_embd ,key_dim * 2 + value_dim },TENSOR_NOT_REQUIRED ); 78layer .wqkv_gate = create_tensor (tn (LLM_TENSOR_ATTN_GATE ,"weight" ,il ), {n_embd ,value_dim },TENSOR_NOT_REQUIRED ); 79layer .ssm_conv1d = create_tensor (tn (LLM_TENSOR_SSM_CONV1D ,"weight" ,il ), {hparams .ssm_d_conv ,conv_dim },flags ); 80layer .ssm_dt = create_tensor (tn (LLM_TENSOR_SSM_DT ,"bias" ,il ), {hparams .ssm_dt_rank },flags ); 81layer .ssm_a = create_tensor (tn (LLM_TENSOR_SSM_A_NOSCAN ,il ), {hparams .ssm_dt_rank },flags ); 82layer .ssm_beta = create_tensor (tn (LLM_TENSOR_SSM_BETA ,"weight" ,il ), {n_embd ,n_v_heads },flags ); 83layer .ssm_alpha = create_tensor (tn (LLM_TENSOR_SSM_ALPHA ,"weight" ,il ), {n_embd ,n_v_heads },flags ); 84layer .ssm_norm = create_tensor (tn (LLM_TENSOR_SSM_NORM ,"weight" ,il ), {head_v_dim },flags ); 85layer .ssm_out = create_tensor (tn (LLM_TENSOR_SSM_OUT ,"weight" ,il ), {value_dim ,n_embd },flags ); 86 } 87 88layer .ffn_gate = create_tensor (tn (LLM_TENSOR_FFN_GATE ,"weight" ,il ), {n_embd ,n_ff },flags ); 89layer .ffn_down = create_tensor (tn (LLM_TENSOR_FFN_DOWN ,"weight" ,il ), {n_ff ,n_embd },flags ); 90layer .ffn_up = create_tensor (tn (LLM_TENSOR_FFN_UP ,"weight" ,il ), {n_embd ,n_ff },flags ); 91 }; 92 93auto load_block_mtp = [& ](int il ) { 94auto & layer = layers [il ]; 95 96// MTP block looks like a full-attention Qwen3.5 decoder block. 97layer .attn_norm = create_tensor (tn (LLM_TENSOR_ATTN_NORM ,"weight" ,il ), {n_embd },mtp_flags ); 98layer .attn_post_norm = create_tensor (tn (LLM_TENSOR_ATTN_POST_NORM ,"weight" ,il ), {n_embd },mtp_flags ); 99 100create_tensor_qkv (layer ,il ,n_embd ,n_embd_head_k * n_head * 2 ,n_embd_k_gqa ,n_embd_v_gqa ,mtp_flags ); 101layer .wo = create_tensor (tn (LLM_TENSOR_ATTN_OUT ,"weight" ,il ), {n_embd_head_k * n_head ,n_embd },mtp_flags ); 102layer .attn_q_norm = create_tensor (tn (LLM_TENSOR_ATTN_Q_NORM ,"weight" ,il ), {n_embd_head_k },mtp_flags ); 103layer .attn_k_norm = create_tensor (tn (LLM_TENSOR_ATTN_K_NORM ,"weight" ,il ), {n_embd_head_k },mtp_flags ); 104 105layer .ffn_gate = create_tensor (tn (LLM_TENSOR_FFN_GATE ,"weight" ,il ), {n_embd ,n_ff },mtp_flags ); 106layer .ffn_down = create_tensor (tn (LLM_TENSOR_FFN_DOWN ,"weight" ,il ), {n_ff ,n_embd },mtp_flags ); 107layer .ffn_up = create_tensor (tn (LLM_TENSOR_FFN_UP ,"weight" ,il ), {n_embd ,n_ff },mtp_flags ); 108 109// NextN-specific tensors that define the MTP block. 110layer .nextn .eh_proj = create_tensor (tn (LLM_TENSOR_NEXTN_EH_PROJ ,"weight" ,il ), {2 * n_embd ,n_embd },mtp_flags ); 111layer .nextn .enorm = create_tensor (tn (LLM_TENSOR_NEXTN_ENORM ,"weight" ,il ), {n_embd },mtp_flags ); 112layer .nextn .hnorm = create_tensor (tn (LLM_TENSOR_NEXTN_HNORM ,"weight" ,il ), {n_embd },mtp_flags ); 113layer .nextn .embed_tokens = create_tensor (tn (LLM_TENSOR_NEXTN_EMBED_TOKENS ,"weight" ,il ), {n_embd ,n_vocab },mtp_flags |TENSOR_NOT_REQUIRED ); 114layer .nextn .shared_head_head = create_tensor (tn (LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD ,"weight" ,il ), {n_embd ,n_vocab },mtp_flags |TENSOR_NOT_REQUIRED ); 115layer .nextn .shared_head_norm = create_tensor (tn (LLM_TENSOR_NEXTN_SHARED_HEAD_NORM ,"weight" ,il ), {n_embd },mtp_flags |TENSOR_NOT_REQUIRED ); 116 }; 117 118for (int i = 0 ;i < n_layer ;++ i ) { 119load_block_trunk (i ,trunk_flags ); 120 } 121for (int i = n_layer ;i < n_layer_all ;++ i ) { 122load_block_mtp (i ); 123 } 124} 125 126std::unique_ptr < llm_graph_context > llama_model_qwen35::build_arch_graph (const llm_graph_params & params )const { 127if (params .gtype == LLM_GRAPH_TYPE_DECODER_MTP ) { 128return std::make_unique < graph_mtp > (* this ,params ); 129 } 130return std::make_unique < graph > (* this ,params ); 131} 132 133llama_model_qwen35::graph::graph (const llama_model & model ,const llm_graph_params & params ) : 134llm_build_delta_net_base (params ),model (model ) { 135const int64_t n_embd_head = hparams .n_embd_head_v (); 136 137GGML_ASSERT (n_embd_head == hparams .n_embd_head_k ()); 138 139int sections [4 ]; 140 std::copy (std::begin (hparams .rope_sections ), std::begin (hparams .rope_sections )+ 4 ,sections ); 141 142ggml_tensor * cur ; 143ggml_tensor * inpL ; 144 145inpL = build_inp_embd (model .tok_embd ); 146 147cb (inpL ,"model.input_embed" ,-1 ); 148 149auto * inp = build_inp_mem_hybrid (); 150 151ggml_tensor * inp_pos = build_inp_pos (); 152ggml_tensor * inp_out_ids = build_inp_out_ids (); 153 154// MTP/NextN layers are loaded as extra decoder blocks but not executed in the main pass. 155for (int il = 0 ;il < n_layer ;++ il ) { 156res -> t_layer_inp [il ]= inpL ; 157 158ggml_tensor * inpSA = inpL ; 159 160cur = build_norm (inpL ,model .layers [il ].attn_norm ,nullptr ,LLM_NORM_RMS ,il ); 161cb (cur ,"attn_norm" ,il ); 162 163ggml_build_forward_expand (gf ,cur ); 164 165// Determine layer type and build appropriate attention mechanism 166if (hparams .is_recr (il )) { 167// Linear attention layer (gated delta net) 168cur = build_layer_attn_linear (inp -> get_recr (),cur ,il ); 169 }else { 170// Full attention layer 171cur = build_layer_attn (inp -> get_attn (),cur ,inp_pos ,sections ,il ); 172 } 173 174if (il == n_layer - 1 && inp_out_ids && cparams .embeddings_nextn_masked ) { 175cur = ggml_get_rows (ctx0 ,cur ,inp_out_ids ); 176inpSA = ggml_get_rows (ctx0 ,inpSA ,inp_out_ids ); 177 } 178 179// Residual connection 180cur = ggml_add (ctx0 ,cur ,inpSA ); 181cb (cur ,"attn_residual" ,il ); 182 183// Save the tensor before post-attention norm for residual connection 184ggml_tensor * ffn_residual = cur ; 185 186// Post-attention norm 187ggml_tensor * attn_post_norm = build_norm (cur ,model .layers [il ].attn_post_norm ,nullptr ,LLM_NORM_RMS ,il ); 188cb (attn_post_norm ,"attn_post_norm" ,il ); 189 190// Dense FFN layer - without residual connection 191cur = build_layer_ffn (attn_post_norm ,il ); 192cb (cur ,"ffn_out" ,il ); 193 194// Residual connection for FFN - add to the tensor from before post_attention_layernorm 195cur = ggml_add (ctx0 ,cur ,ffn_residual ); 196cb (cur ,"post_ffn" ,il ); 197 198cur = build_cvec (cur ,il ); 199cb (cur ,"l_out" ,il ); 200 201// Input for next layer 202inpL = cur ; 203 } 204cur = inpL ; 205 206cur = build_norm (cur ,model .output_norm ,nullptr ,LLM_NORM_RMS ,-1 ); 207 208cb (cur ,"h_nextn" ,-1 ); 209res -> t_h_nextn = cur ; 210 211if (!cparams .embeddings_nextn_masked && inp_out_ids ) { 212cur = ggml_get_rows (ctx0 ,cur ,inp_out_ids ); 213 } 214 215cb (cur ,"result_norm" ,-1 ); 216res -> t_embd = cur ; 217 218// LM head 219cur = build_lora_mm (model .output ,cur ,model .output_s ); 220 221cb (cur ,"result_output" ,-1 ); 222res -> t_logits = cur ; 223 224ggml_build_forward_expand (gf ,cur ); 225} 226 227std::pair < ggml_tensor * ,ggml_tensor *> llama_model_qwen35::graph::build_qkvz ( 228ggml_tensor * input , 229int il ) { 230const int64_t n_seqs = ubatch .n_seqs ; 231const int64_t n_seq_tokens = ubatch .n_seq_tokens ; 232 233ggml_tensor * qkv_mixed = build_lora_mm (model .layers [il ].wqkv ,input ,model .layers [il ].wqkv_s ); 234qkv_mixed = ggml_reshape_3d (ctx0 ,qkv_mixed ,qkv_mixed -> ne [0 ],n_seq_tokens ,n_seqs ); 235cb (qkv_mixed ,"linear_attn_qkv_mixed" ,il ); 236 237ggml_tensor * z = build_lora_mm (model .layers [il ].wqkv_gate ,input ,model .layers [il ].wqkv_gate_s ); 238cb (z ,"z" ,il ); 239 240return {qkv_mixed ,z }; 241} 242 243ggml_tensor * llama_model_qwen35::graph::build_norm_gated ( 244ggml_tensor * input , 245ggml_tensor * weights , 246ggml_tensor * gate , 247int layer ) { 248ggml_tensor * normalized = build_norm (input ,weights ,nullptr ,LLM_NORM_RMS ,layer ); 249ggml_tensor * gated_silu = ggml_silu (ctx0 ,gate ); 250 251return ggml_mul (ctx0 ,normalized ,gated_silu ); 252} 253 254ggml_tensor * llama_model_qwen35::graph::build_layer_attn ( 255llm_graph_input_attn_kv * inp , 256ggml_tensor * cur , 257ggml_tensor * inp_pos , 258int * sections , 259int il ) { 260const int64_t n_embd_head = hparams .n_embd_head_v (); 261GGML_ASSERT (n_embd_head == hparams .n_embd_head_k ()); 262 263// Order: joint QG projection, QG split, Q norm, KV projection, K norm, RoPE, attention 264 265// Qwen3Next uses a single Q projection that outputs query + gate 266auto [Qcur_full ,Kcur ,Vcur ]= build_qkv (model .layers [il ],cur , 267n_embd_head * 2 ,n_head , 268n_embd_head ,n_head_kv , 269n_embd_head ,n_head_kv , 270il , false); 271cb (Qcur_full ,"Qcur_full" ,il ); 272cb (Kcur ,"Kcur" ,il ); 273cb (Vcur ,"Vcur" ,il ); 274 275ggml_tensor * Qcur = ggml_view_3d (ctx0 ,Qcur_full ,n_embd_head ,n_head ,n_tokens , 276ggml_element_size (Qcur_full )* n_embd_head * 2 , 277ggml_element_size (Qcur_full )* n_embd_head * 2 * n_head ,0 ); 278cb (Qcur ,"Qcur_reshaped" ,il ); 279 280// Apply Q normalization 281Qcur = build_norm (Qcur ,model .layers [il ].attn_q_norm ,nullptr ,LLM_NORM_RMS ,il ); 282cb (Qcur ,"Qcur_normed" ,il ); 283 284// Apply K normalization 285Kcur = ggml_reshape_3d (ctx0 ,Kcur ,n_embd_head ,n_head_kv ,n_tokens ); 286Kcur = build_norm (Kcur ,model .layers [il ].attn_k_norm ,nullptr ,LLM_NORM_RMS ,il ); 287cb (Kcur ,"Kcur_normed" ,il ); 288 289ggml_tensor * gate = ggml_view_3d (ctx0 ,Qcur_full ,n_embd_head ,n_head ,n_tokens , 290ggml_element_size (Qcur_full )* n_embd_head * 2 , 291ggml_element_size (Qcur_full )* n_embd_head * 2 * n_head , 292ggml_element_size (Qcur_full )* n_embd_head ); 293gate = ggml_cont_2d (ctx0 ,gate ,n_embd_head * n_head ,n_tokens ); 294cb (gate ,"gate_reshaped" ,il ); 295 296Vcur = ggml_reshape_3d (ctx0 ,Vcur ,n_embd_head ,n_head_kv ,n_tokens ); 297 298// Apply MRoPE 299Qcur = ggml_rope_multi ( 300ctx0 ,Qcur ,inp_pos ,nullptr , 301n_rot ,sections ,rope_type ,n_ctx_orig ,freq_base ,freq_scale , 302ext_factor ,attn_factor ,beta_fast ,beta_slow 303 ); 304 305Kcur = ggml_rope_multi ( 306ctx0 ,Kcur ,inp_pos ,nullptr , 307n_rot ,sections ,rope_type ,n_ctx_orig ,freq_base ,freq_scale , 308ext_factor ,attn_factor ,beta_fast ,beta_slow 309 ); 310 311cb (Qcur ,"Qcur" ,il ); 312cb (Kcur ,"Kcur" ,il ); 313cb (Vcur ,"Vcur" ,il ); 314 315// Attention computation 316const float kq_scale = hparams .f_attention_scale == 0.0f ?1.0f /sqrtf (float (n_embd_head )) :hparams .f_attention_scale ; 317 318cur = build_attn (inp , 319nullptr ,nullptr ,nullptr , 320Qcur ,Kcur ,Vcur ,nullptr ,nullptr ,nullptr ,kq_scale ,il ); 321cb (cur ,"attn_pregate" ,il ); 322 323ggml_tensor * gate_sigmoid = ggml_sigmoid (ctx0 ,gate ); 324cb (gate_sigmoid ,"gate_sigmoid" ,il ); 325 326cur = ggml_mul (ctx0 ,cur ,gate_sigmoid ); 327cb (cur ,"attn_gated" ,il ); 328 329cur = build_lora_mm (model .layers [il ].wo ,cur ,model .layers [il ].wo_s ); 330cb (cur ,"attn_output" ,il ); 331 332return cur ; 333} 334 335ggml_tensor * llama_model_qwen35::graph::build_layer_attn_linear ( 336llm_graph_input_rs * inp , 337ggml_tensor * cur , 338int il ) { 339const auto * mctx_cur = inp -> mctx ; 340 341const int64_t d_inner = hparams .ssm_d_inner ; 342const int64_t n_seqs = ubatch .n_seqs ; 343const int64_t head_k_dim = hparams .ssm_d_state ; 344const int64_t num_k_heads = hparams .ssm_n_group ; 345const int64_t num_v_heads = hparams .ssm_dt_rank ; 346const int64_t head_v_dim = d_inner /num_v_heads ; 347const int64_t n_seq_tokens = ubatch .n_seq_tokens ; 348 349GGML_ASSERT (n_seqs != 0 ); 350GGML_ASSERT (ubatch .equal_seqs ()); 351GGML_ASSERT (ubatch .n_tokens == n_seq_tokens * n_seqs ); 352 353// Input projections 354auto qkvz = build_qkvz (cur ,il ); 355ggml_tensor * qkv_mixed = qkvz .first ; 356ggml_tensor * z = qkvz .second ; 357 358ggml_tensor * beta = build_lora_mm (model .layers [il ].ssm_beta ,cur ,model .layers [il ].ssm_beta_s ); 359beta = ggml_reshape_4d (ctx0 ,beta ,1 ,num_v_heads ,n_seq_tokens ,n_seqs ); 360cb (beta ,"beta" ,il ); 361 362beta = ggml_sigmoid (ctx0 ,beta ); 363cb (beta ,"beta_sigmoid" ,il ); 364 365ggml_tensor * alpha = build_lora_mm (model .layers [il ].ssm_alpha ,cur ,model .layers [il ].ssm_alpha_s ); 366alpha = ggml_reshape_3d (ctx0 ,alpha ,num_v_heads ,n_seq_tokens ,n_seqs ); 367cb (alpha ,"alpha" ,il ); 368 369ggml_tensor * alpha_biased = ggml_add (ctx0 ,alpha ,model .layers [il ].ssm_dt ); 370ggml_tensor * alpha_softplus = ggml_softplus (ctx0 ,alpha_biased ); 371cb (alpha_softplus ,"a_softplus" ,il ); 372 373ggml_tensor * gate = ggml_mul (ctx0 ,alpha_softplus ,model .layers [il ].ssm_a );// -A_log.exp() * softplus 374cb (gate ,"gate" ,il ); 375 376gate = ggml_reshape_4d (ctx0 ,gate ,1 ,num_v_heads ,n_seq_tokens ,n_seqs ); 377 378ggml_tensor * conv_states_all = mctx_cur -> get_r_l (il ); 379ggml_tensor * ssm_states_all = mctx_cur -> get_s_l (il ); 380 381ggml_tensor * conv_kernel = model .layers [il ].ssm_conv1d ; 382const int64_t conv_kernel_size = conv_kernel -> ne [0 ]; 383const int64_t conv_channels = d_inner + 2 * hparams .ssm_n_group * hparams .ssm_d_state ; 384 385ggml_tensor * conv_input = build_conv_state (inp ,conv_states_all ,qkv_mixed ,conv_kernel_size ,conv_channels ,il ); 386 387ggml_tensor * state = build_rs (inp ,ssm_states_all ,hparams .n_embd_s (),n_seqs ); 388state = ggml_reshape_4d (ctx0 ,state ,head_v_dim ,head_v_dim ,num_v_heads ,n_seqs ); 389cb (state ,"state_predelta" ,il ); 390 391ggml_tensor * conv_output_proper = ggml_ssm_conv (ctx0 ,conv_input ,conv_kernel ); 392cb (conv_output_proper ,"conv_output_raw" ,il ); 393 394ggml_tensor * conv_output_silu = ggml_silu (ctx0 ,conv_output_proper ); 395cb (conv_output_silu ,"conv_output_silu" ,il ); 396 397ggml_tensor * conv_qkv_mix = conv_output_silu ; 398 399// Calculate the total conv dimension 400int64_t qkv_dim = head_k_dim * num_k_heads * 2 + head_v_dim * num_v_heads ; 401int64_t nb1_qkv = ggml_row_size (conv_qkv_mix -> type ,qkv_dim ); 402 403// Extract the convolved Q, K, V from conv_output 404ggml_tensor * q_conv = ggml_view_4d (ctx0 ,conv_qkv_mix ,head_k_dim ,num_k_heads ,n_seq_tokens ,n_seqs , 405ggml_row_size (conv_qkv_mix -> type ,head_k_dim ), 406nb1_qkv , 407nb1_qkv * n_seq_tokens , 4080 ); 409 410ggml_tensor * k_conv = ggml_view_4d (ctx0 ,conv_qkv_mix ,head_k_dim ,num_k_heads ,n_seq_tokens ,n_seqs , 411ggml_row_size (conv_qkv_mix -> type ,head_k_dim ), 412nb1_qkv , 413nb1_qkv * n_seq_tokens , 414head_k_dim * num_k_heads * ggml_element_size (conv_qkv_mix )); 415 416ggml_tensor * v_conv = ggml_view_4d (ctx0 ,conv_qkv_mix ,head_v_dim ,num_v_heads ,n_seq_tokens ,n_seqs , 417ggml_row_size (conv_qkv_mix -> type ,head_v_dim ), 418nb1_qkv , 419nb1_qkv * n_seq_tokens , 420ggml_row_size (conv_qkv_mix -> type ,2 * head_k_dim * num_k_heads )); 421 422cb (q_conv ,"q_conv" ,il ); 423cb (k_conv ,"k_conv" ,il ); 424cb (v_conv ,"v_conv" ,il ); 425 426 427const float eps_norm = hparams .f_norm_rms_eps ; 428 429q_conv = build_gdn_l2_norm (ctx0 ,q_conv ,eps_norm ); 430k_conv = build_gdn_l2_norm (ctx0 ,k_conv ,eps_norm ); 431 432//q_conv = ggml_cont_4d(ctx0, q_conv, head_k_dim, num_k_heads, n_seq_tokens, n_seqs); 433//k_conv = ggml_cont_4d(ctx0, k_conv, head_k_dim, num_k_heads, n_seq_tokens, n_seqs); 434//v_conv = ggml_cont_4d(ctx0, v_conv, head_v_dim, num_v_heads, n_seq_tokens, n_seqs); 435 436// if head keys and value keys are different, repeat to force tensors into matching shapes 437// note: need explicit repeat only if we are not using the fused GDN. 438if (num_k_heads != num_v_heads && (!cparams .fused_gdn_ar || !cparams .fused_gdn_ch )) { 439GGML_ASSERT (num_v_heads %num_k_heads == 0 ); 440q_conv = ggml_repeat_4d (ctx0 ,q_conv ,head_k_dim ,num_v_heads ,n_seq_tokens ,n_seqs ); 441k_conv = ggml_repeat_4d (ctx0 ,k_conv ,head_k_dim ,num_v_heads ,n_seq_tokens ,n_seqs ); 442 } 443 444cb (q_conv ,"q_conv_predelta" ,il ); 445cb (k_conv ,"k_conv_predelta" ,il ); 446cb (v_conv ,"v_conv_predelta" ,il ); 447 448ggml_tensor * output = build_recurrent_attn (inp ,ssm_states_all ,q_conv ,k_conv ,v_conv ,gate ,beta ,state ,il ); 449 450// z: [head_dim, n_heads, n_tokens, n_seqs] -> [n_heads * n_tokens * n_seqs, head_dim] 451ggml_tensor * z_2d = ggml_reshape_4d (ctx0 ,z ,head_v_dim ,num_v_heads ,n_seq_tokens ,n_seqs ); 452 453// Apply gated normalization: self.norm(core_attn_out, z) 454ggml_tensor * attn_out_norm = build_norm_gated (output ,model .layers [il ].ssm_norm ,z_2d ,il ); 455 456// Final reshape: [head_dim, n_heads, n_tokens, n_seqs] -> [n_tokens, n_seqs, n_heads * head_dim] 457ggml_tensor * final_output = ggml_reshape_3d (ctx0 ,attn_out_norm ,head_v_dim * num_v_heads ,n_seq_tokens ,n_seqs ); 458cb (final_output ,"final_output" ,il ); 459 460// Output projection 461cur = build_lora_mm (model .layers [il ].ssm_out ,final_output ,model .layers [il ].ssm_out_s ); 462cb (cur ,"linear_attn_out" ,il ); 463 464// Reshape back to original dimensions 465cur = ggml_reshape_2d (ctx0 ,cur ,n_embd ,n_seq_tokens * n_seqs ); 466 467return cur ; 468} 469 470ggml_tensor * llama_model_qwen35::graph::build_layer_ffn (ggml_tensor * cur ,const int il ) { 471// Qwen3.5 does not use MoE FFN 472GGML_ASSERT (model .layers [il ].ffn_gate_inp == nullptr ); 473 474cur = build_ffn (cur , 475model .layers [il ].ffn_up ,NULL ,model .layers [il ].ffn_up_s , 476model .layers [il ].ffn_gate ,NULL ,model .layers [il ].ffn_gate_s , 477model .layers [il ].ffn_down ,NULL ,model .layers [il ].ffn_down_s , 478NULL , 479LLM_FFN_SILU ,LLM_FFN_PAR ,il ); 480cb (cur ,"ffn_out" ,il ); 481 482return cur ; 483} 484 485// LLM_GRAPH_TYPE_DECODER_MTP draft head for Qwen3.5/3.6 dense series 486llama_model_qwen35::graph_mtp::graph_mtp (const llama_model & model ,const llm_graph_params & params ) 487 :llm_graph_context (params ) { 488GGML_ASSERT (hparams .n_layer_nextn > 0 && "QWEN35 MTP requires n_layer_nextn > 0" ); 489GGML_ASSERT (hparams .n_layer_nextn == 1 && "QWEN35 MTP currently only supports a single MTP block" ); 490 491const int64_t n_embd_head = hparams .n_embd_head_v (); 492GGML_ASSERT (n_embd_head == hparams .n_embd_head_k ()); 493 494// hparams.n_layer includes both main model layers and MTP layers. The MTP 495// layer is stored immediately after the main layers in model.layers[]. 496const int il = hparams .n_layer (); 497const auto & layer = model .layers [il ]; 498 499GGML_ASSERT (layer .nextn .eh_proj && "MTP block missing nextn.eh_proj" ); 500GGML_ASSERT (layer .nextn .enorm && "MTP block missing nextn.enorm" ); 501GGML_ASSERT (layer .nextn .hnorm && "MTP block missing nextn.hnorm" ); 502 503int sections [4 ]; 504 std::copy (std::begin (hparams .rope_sections ), std::begin (hparams .rope_sections )+ 4 ,sections ); 505 506// TODO: extract in a common llm_graph_context::build_inp_embd_h() 507auto inp = std::make_unique < llm_graph_input_embd_h > (hparams .n_embd ); 508 509inp -> tokens = ggml_new_tensor_1d (ctx0 ,GGML_TYPE_I32 ,n_tokens ); 510ggml_set_input (inp -> tokens ); 511 512inp -> embd = ggml_new_tensor_2d (ctx0 ,GGML_TYPE_F32 ,hparams .n_embd_inp (),n_tokens ); 513ggml_set_input (inp -> embd ); 514 515// TODO: make static using `ggml_build_forward_select()` 516// see llm_graph_context::build_inp_embd() for reference 517ggml_tensor * tok_embd ; 518if (ubatch .token ) { 519ggml_tensor * tok_embd_w = layer .nextn .embed_tokens ?layer .nextn .embed_tokens :model .tok_embd ; 520 521tok_embd = ggml_get_rows (ctx0 ,tok_embd_w ,inp -> tokens ); 522 }else { 523tok_embd = inp -> embd ; 524 } 525cb (tok_embd ,"mtp_tok_embd" ,il ); 526 527inp -> h = ggml_new_tensor_2d (ctx0 ,GGML_TYPE_F32 ,hparams .n_embd ,n_tokens ); 528ggml_set_input (inp -> h ); 529ggml_set_name (inp -> h ,"mtp_h_input" ); 530 531ggml_tensor * h_embd = inp -> h ; 532 533res -> add_input (std::move (inp )); 534 535ggml_tensor * inp_pos = build_inp_pos (); 536ggml_tensor * inp_out_ids = build_inp_out_ids (); 537 538auto * inp_attn = build_attn_inp_kv (); 539 540ggml_tensor * h_norm = build_norm (h_embd ,layer .nextn .hnorm ,nullptr ,LLM_NORM_RMS ,il ); 541cb (h_norm ,"mtp_hnorm" ,il ); 542 543ggml_tensor * e_norm = build_norm (tok_embd ,layer .nextn .enorm ,nullptr ,LLM_NORM_RMS ,il ); 544cb (e_norm ,"mtp_enorm" ,il ); 545 546ggml_tensor * concat = ggml_concat (ctx0 ,e_norm ,h_norm ,/*dim=*/ 0 ); 547cb (concat ,"mtp_concat" ,il ); 548 549ggml_tensor * cur = build_lora_mm (layer .nextn .eh_proj ,concat ,layer .nextn .eh_proj_s ); 550cb (cur ,"mtp_eh_proj" ,il ); 551 552ggml_tensor * inpSA = cur ; 553 554cur = build_norm (cur ,layer .attn_norm ,nullptr ,LLM_NORM_RMS ,il ); 555cb (cur ,"mtp_attn_norm" ,il ); 556 557auto [Qcur_full ,Kcur ,Vcur ]= build_qkv (layer ,cur , 558n_embd_head * 2 ,n_head , 559n_embd_head ,n_head_kv , 560n_embd_head ,n_head_kv , 561il , false); 562cb (Qcur_full ,"mtp_Qcur_full" ,il ); 563 564ggml_tensor * Qcur = ggml_view_3d (ctx0 ,Qcur_full , 565n_embd_head ,n_head ,n_tokens , 566ggml_element_size (Qcur_full )* n_embd_head * 2 , 567ggml_element_size (Qcur_full )* n_embd_head * 2 * n_head , 5680 ); 569Qcur = build_norm (Qcur ,layer .attn_q_norm ,nullptr ,LLM_NORM_RMS ,il ); 570cb (Qcur ,"mtp_Qcur_normed" ,il ); 571 572ggml_tensor * gate = ggml_view_3d (ctx0 ,Qcur_full , 573n_embd_head ,n_head ,n_tokens , 574ggml_element_size (Qcur_full )* n_embd_head * 2 , 575ggml_element_size (Qcur_full )* n_embd_head * 2 * n_head , 576ggml_element_size (Qcur_full )* n_embd_head ); 577gate = ggml_cont_2d (ctx0 ,gate ,n_embd_head * n_head ,n_tokens ); 578cb (gate ,"mtp_gate" ,il ); 579 580Kcur = ggml_reshape_3d (ctx0 ,Kcur ,n_embd_head ,n_head_kv ,n_tokens ); 581Kcur = build_norm (Kcur ,layer .attn_k_norm ,nullptr ,LLM_NORM_RMS ,il ); 582cb (Kcur ,"mtp_Kcur_normed" ,il ); 583 584Vcur = ggml_reshape_3d (ctx0 ,Vcur ,n_embd_head ,n_head_kv ,n_tokens ); 585cb (Vcur ,"mtp_Vcur" ,il ); 586 587Qcur = ggml_rope_multi (ctx0 ,Qcur ,inp_pos ,nullptr , 588n_rot ,sections ,rope_type ,n_ctx_orig ,freq_base ,freq_scale , 589ext_factor ,attn_factor ,beta_fast ,beta_slow ); 590Kcur = ggml_rope_multi (ctx0 ,Kcur ,inp_pos ,nullptr , 591n_rot ,sections ,rope_type ,n_ctx_orig ,freq_base ,freq_scale , 592ext_factor ,attn_factor ,beta_fast ,beta_slow ); 593 594const float kq_scale = hparams .f_attention_scale == 0.0f 595 ?1.0f /sqrtf (float (n_embd_head )) :hparams .f_attention_scale ; 596 597cur = build_attn (inp_attn , 598nullptr ,nullptr ,nullptr , 599Qcur ,Kcur ,Vcur ,nullptr ,nullptr ,nullptr ,kq_scale ,il ); 600cb (cur ,"mtp_attn_pregate" ,il ); 601 602cur = ggml_mul (ctx0 ,cur ,ggml_sigmoid (ctx0 ,gate )); 603cur = build_lora_mm (layer .wo ,cur ,layer .wo_s ); 604cb (cur ,"mtp_attn_out" ,il ); 605 606cur = ggml_add (ctx0 ,cur ,inpSA ); 607cb (cur ,"mtp_attn_residual" ,il ); 608 609ggml_tensor * ffn_residual = cur ; 610cur = build_norm (cur ,layer .attn_post_norm ,nullptr ,LLM_NORM_RMS ,il ); 611cb (cur ,"mtp_attn_post_norm" ,il ); 612 613cur = build_ffn (cur , 614layer .ffn_up ,nullptr ,layer .ffn_up_s , 615layer .ffn_gate ,nullptr ,layer .ffn_gate_s , 616layer .ffn_down ,nullptr ,layer .ffn_down_s , 617nullptr , 618LLM_FFN_SILU ,LLM_FFN_PAR ,il ); 619cb (cur ,"mtp_ffn_out" ,il ); 620 621cur = ggml_add (ctx0 ,cur ,ffn_residual ); 622cb (cur ,"mtp_post_ffn" ,il ); 623 624ggml_tensor * head_norm_w = layer .nextn .shared_head_norm 625 ?layer .nextn .shared_head_norm 626 :model .output_norm ; 627GGML_ASSERT (head_norm_w && "QWEN35 MTP: missing both nextn.shared_head_norm and output_norm" ); 628cur = build_norm (cur ,head_norm_w ,nullptr ,LLM_NORM_RMS ,-1 ); 629 630cb (cur ,"h_nextn" ,-1 ); 631res -> t_h_nextn = cur ; 632 633cur = ggml_get_rows (ctx0 ,cur ,inp_out_ids ); 634cb (cur ,"mtp_shared_head_norm" ,-1 ); 635 636ggml_tensor * head_w = layer .nextn .shared_head_head ?layer .nextn .shared_head_head :model .output ; 637ggml_tensor * head_s = layer .nextn .shared_head_head ?layer .nextn .shared_head_head_s :model .output_s ; 638GGML_ASSERT (head_w && "QWEN35 MTP: missing LM head (nextn.shared_head_head or model.output)" ); 639cur = build_lora_mm (head_w ,cur ,head_s ); 640cb (cur ,"result_output" ,-1 ); 641 642res -> t_logits = cur ; 643ggml_build_forward_expand (gf ,cur ); 644}