okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2de2641f
main
1#include "llama-graph.h" 2 3#include "llama-impl.h" 4#include "llama-model.h" 5#include "llama-batch.h" 6#include "llama-cparams.h" 7#include "llama-sampler.h" 8 9#include "llama-kv-cache.h" 10#include "llama-kv-cache-iswa.h" 11#include "llama-kv-cache-dsa.h" 12#include "llama-kv-cache-dsa-iswa.h" 13#include "llama-kv-cache-msa.h" 14#include "llama-kv-cache-dsv4.h" 15#include "llama-memory-hybrid.h" 16#include "llama-memory-hybrid-iswa.h" 17#include "llama-memory-recurrent.h" 18 19#include <cassert> 20#include <cmath> 21#include <cstring> 22#include <numeric> 23#include <sstream> 24#include <string> 25#include <unordered_set> 26 27// dedup helpers 28 29static ggml_tensor * build_attn_inp_kq_mask ( 30ggml_context * ctx , 31const llama_kv_cache_context * mctx , 32const llama_ubatch & ubatch , 33const llama_cparams & cparams ) { 34const auto n_kv = mctx -> get_n_kv (); 35const auto n_tokens = ubatch .n_tokens ; 36const auto n_stream = cparams .kv_unified ?1 :ubatch .n_seqs_unq ; 37 38// flash attention requires an f16 mask 39const auto type = cparams .flash_attn ?GGML_TYPE_F16 :GGML_TYPE_F32 ; 40 41ggml_tensor * res = ggml_new_tensor_4d (ctx ,type ,n_kv ,n_tokens /n_stream ,1 ,n_stream ); 42ggml_set_input (res ); 43ggml_set_name (res ,"attn_inp_kq_mask" ); 44 45return res ; 46} 47 48static bool can_reuse_kq_mask ( 49ggml_tensor * kq_mask , 50const llama_kv_cache_context * mctx , 51const llama_ubatch & ubatch , 52const llama_cparams & cparams ) { 53const auto n_kv = mctx -> get_n_kv (); 54const auto n_tokens = ubatch .n_tokens ; 55const auto n_stream = cparams .kv_unified ?1 :ubatch .n_seqs_unq ; 56 57bool res = true; 58 59res &= (kq_mask -> ne [0 ]== n_kv ); 60res &= (kq_mask -> ne [1 ]== n_tokens /n_stream ); 61res &= (kq_mask -> ne [2 ]== 1 ); 62res &= (kq_mask -> ne [3 ]== n_stream ); 63 64return res ; 65} 66 67// impl 68 69void llm_graph_input_embd::set_input (const llama_ubatch * ubatch ) { 70if (ubatch -> token ) { 71const int64_t n_tokens = ubatch -> n_tokens ; 72 73ggml_backend_tensor_set (tokens ,ubatch -> token ,0 ,n_tokens * ggml_element_size (tokens )); 74 } 75 76if (ubatch -> embd ) { 77GGML_ASSERT (n_embd == embd -> ne [0 ]); 78 79const int64_t n_tokens = ubatch -> n_tokens ; 80 81ggml_backend_tensor_set (embd ,ubatch -> embd ,0 ,n_tokens * n_embd * ggml_element_size (embd )); 82 } 83} 84 85bool llm_graph_input_embd::can_reuse (const llm_graph_params & params ) { 86bool res = true; 87 88res &= (!params .ubatch .token )|| (tokens && tokens -> ne [0 ]== params .ubatch .n_tokens ); 89res &= (!params .ubatch .embd )|| (embd && embd -> ne [1 ]== params .ubatch .n_tokens ); 90 91return res ; 92} 93 94void llm_graph_input_embd_h::set_input (const llama_ubatch * ubatch ) { 95const int64_t n_tokens = ubatch -> n_tokens ; 96 97if (ubatch -> token ) { 98ggml_backend_tensor_set (tokens ,ubatch -> token ,0 ,n_tokens * ggml_element_size (tokens )); 99 }else { 100// note: mtmd embedding input goes through here 101GGML_ASSERT (ubatch -> embd ); 102GGML_ASSERT (n_embd == embd -> ne [0 ]); 103 104ggml_backend_tensor_set (embd ,ubatch -> embd ,0 ,n_tokens * n_embd * ggml_element_size (h )); 105 } 106 107// TODO: extend llama_ubatch to differentiate between token embeddings and hidden states 108// for now, we assume that the hidden state is always provided as an embedding 109// ref: https://github.com/ggml-org/llama.cpp/pull/23643 110if (ubatch -> embd ) { 111GGML_ASSERT (n_embd == h -> ne [0 ]); 112 113ggml_backend_tensor_set (h ,ubatch -> embd ,0 ,n_tokens * n_embd * ggml_element_size (h )); 114 } 115} 116 117bool llm_graph_input_embd_h::can_reuse (const llm_graph_params & params ) { 118bool res = true; 119 120res &= (!params .ubatch .token )|| (tokens && tokens -> ne [0 ]== params .ubatch .n_tokens ); 121res &= (!params .ubatch .embd )|| (embd && embd -> ne [1 ]== params .ubatch .n_tokens ); 122res &= (!params .ubatch .embd )|| (h && h -> ne [1 ]== params .ubatch .n_tokens ); 123 124return res ; 125} 126 127void llm_graph_input_pos::set_input (const llama_ubatch * ubatch ) { 128if (ubatch -> pos && pos ) { 129const int64_t n_tokens = ubatch -> n_tokens ; 130 131if (ubatch -> token && n_pos_per_embd == 4 ) { 132// in case we're using M-RoPE with text tokens, convert the 1D positions to 4D 133// the 3 first dims are the same, and 4th dim is all 0 134 std::vector < llama_pos > pos_data (n_tokens * n_pos_per_embd ); 135// copy the first dimension 136for (int i = 0 ;i < n_tokens ;++ i ) { 137pos_data [i ]= ubatch -> pos [i ]; 138pos_data [n_tokens + i ]= ubatch -> pos [i ]; 139pos_data [2 * n_tokens + i ]= ubatch -> pos [i ]; 140pos_data [3 * n_tokens + i ]= 0 ;// 4th dim is 0 141 } 142ggml_backend_tensor_set (pos ,pos_data .data (),0 ,pos_data .size ()* ggml_element_size (pos )); 143 }else { 144ggml_backend_tensor_set (pos ,ubatch -> pos ,0 ,n_tokens * n_pos_per_embd * ggml_element_size (pos )); 145 } 146 } 147} 148 149bool llm_graph_input_pos::can_reuse (const llm_graph_params & params ) { 150bool res = true; 151 152res &=pos -> ne [0 ]== params .ubatch .n_tokens * n_pos_per_embd ; 153 154return res ; 155} 156 157void llm_graph_input_attn_temp::set_input (const llama_ubatch * ubatch ) { 158if (ubatch -> pos && attn_scale ) { 159const int64_t n_tokens = ubatch -> n_tokens ; 160 161GGML_ASSERT (f_attn_temp_scale != 0.0f ); 162GGML_ASSERT (n_attn_temp_floor_scale != 0 ); 163 164 std::vector < float > attn_scale_data (n_tokens ,0.0f ); 165for (int i = 0 ;i < n_tokens ;++ i ) { 166const float pos = ubatch -> pos [i ]; 167attn_scale_data [i ]= std::log ( 168 std::floor ((pos + f_attn_temp_offset ) /n_attn_temp_floor_scale )+ 1.0 169 )* f_attn_temp_scale + 1.0 ; 170 } 171 172ggml_backend_tensor_set (attn_scale ,attn_scale_data .data (),0 ,n_tokens * ggml_element_size (attn_scale )); 173 } 174} 175 176void llm_graph_input_pos_bucket::set_input (const llama_ubatch * ubatch ) { 177if (pos_bucket ) { 178const int64_t n_tokens = ubatch -> n_tokens ; 179 180GGML_ASSERT (ggml_backend_buffer_is_host (pos_bucket -> buffer )); 181GGML_ASSERT (!ubatch -> equal_seqs ());// TODO: use ubatch->n_seqs instead of failing 182 183int32_t * data = (int32_t * )pos_bucket -> data ; 184 185for (int j = 0 ;j < n_tokens ;++ j ) { 186for (int i = 0 ;i < n_tokens ;++ i ) { 187data [j * n_tokens + i ]= llama_relative_position_bucket (ubatch -> pos [i ],ubatch -> pos [j ],hparams .n_rel_attn_bkts , true); 188 } 189 } 190 } 191} 192 193void llm_graph_input_pos_bucket_kv::set_input (const llama_ubatch * ubatch ) { 194if (pos_bucket ) { 195mctx -> set_input_pos_bucket (pos_bucket ,ubatch ); 196 } 197} 198 199void llm_graph_input_out_ids::set_input (const llama_ubatch * ubatch ) { 200GGML_ASSERT (out_ids ); 201 202const int64_t n_tokens = ubatch -> n_tokens ; 203 204GGML_ASSERT (ggml_backend_buffer_is_host (out_ids -> buffer )); 205int32_t * data = (int32_t * )out_ids -> data ; 206 207if (n_outputs == n_tokens ) { 208for (int i = 0 ;i < n_tokens ;++ i ) { 209data [i ]= i ; 210 } 211 212return ; 213 } 214 215GGML_ASSERT (ubatch -> output ); 216 217int n_outputs = 0 ; 218 219for (int i = 0 ;i < n_tokens ;++ i ) { 220if (ubatch -> output [i ]) { 221data [n_outputs ++ ]= i ; 222 } 223 } 224} 225 226bool llm_graph_input_out_ids::can_reuse (const llm_graph_params & params ) { 227bool res = true; 228 229res &=n_outputs == params .n_outputs ; 230 231return res ; 232} 233 234void llm_graph_input_mean::set_input (const llama_ubatch * ubatch ) { 235if (cparams .embeddings && 236 (cparams .pooling_type == LLAMA_POOLING_TYPE_MEAN || 237cparams .pooling_type == LLAMA_POOLING_TYPE_RANK )) { 238 239const int64_t n_tokens = ubatch -> n_tokens ; 240const int64_t n_seq_tokens = ubatch -> n_seq_tokens ; 241const int64_t n_seqs_unq = ubatch -> n_seqs_unq ; 242 243GGML_ASSERT (mean ); 244GGML_ASSERT (ggml_backend_buffer_is_host (mean -> buffer )); 245 246float * data = (float * )mean -> data ; 247memset (mean -> data ,0 ,n_tokens * n_seqs_unq * ggml_element_size (mean )); 248 249 std::vector < uint64_t > sums (n_seqs_unq ,0 ); 250for (int i = 0 ;i < n_tokens ;i += n_seq_tokens ) { 251for (int s = 0 ;s < ubatch -> n_seq_id [i ];++ s ) { 252const llama_seq_id seq_id = ubatch -> seq_id [i ][s ]; 253const int32_t seq_idx = ubatch -> seq_idx [seq_id ]; 254 255sums [seq_idx ]+= ubatch -> n_seq_tokens ; 256 } 257 } 258 259 std::vector < float > div (n_seqs_unq ,0.0f ); 260for (int s = 0 ;s < n_seqs_unq ;++ s ) { 261const uint64_t sum = sums [s ]; 262if (sum > 0 ) { 263div [s ]= 1.0f /float (sum ); 264 } 265 } 266 267for (int i = 0 ;i < n_tokens ;i += n_seq_tokens ) { 268for (int s = 0 ;s < ubatch -> n_seq_id [i ];++ s ) { 269const llama_seq_id seq_id = ubatch -> seq_id [i ][s ]; 270const int32_t seq_idx = ubatch -> seq_idx [seq_id ]; 271 272for (int j = 0 ;j < n_seq_tokens ;++ j ) { 273data [seq_idx * n_tokens + i + j ]= div [seq_idx ]; 274 } 275 } 276 } 277 } 278} 279 280void llm_graph_input_cls::set_input (const llama_ubatch * ubatch ) { 281const int64_t n_tokens = ubatch -> n_tokens ; 282const int64_t n_seqs_unq = ubatch -> n_seqs_unq ; 283 284if (cparams .embeddings && ( 285cparams .pooling_type == LLAMA_POOLING_TYPE_CLS || 286cparams .pooling_type == LLAMA_POOLING_TYPE_RANK || 287cparams .pooling_type == LLAMA_POOLING_TYPE_LAST 288 )) { 289GGML_ASSERT (cls ); 290GGML_ASSERT (ggml_backend_buffer_is_host (cls -> buffer )); 291 292uint32_t * data = (uint32_t * )cls -> data ; 293memset (cls -> data ,0 ,n_seqs_unq * ggml_element_size (cls )); 294 295 std::vector < int > target_pos (n_seqs_unq ,-1 ); 296 std::vector < int > target_row (n_seqs_unq ,-1 ); 297 298const bool last = ( 299cparams .pooling_type == LLAMA_POOLING_TYPE_LAST || 300 (cparams .pooling_type == LLAMA_POOLING_TYPE_RANK && (arch == LLM_ARCH_QWEN3 || arch == LLM_ARCH_QWEN3VL ))// qwen3 reranking & embedding models use last token 301 ); 302 303for (int i = 0 ;i < n_tokens ;++ i ) { 304const llama_pos pos = ubatch -> pos [i ]; 305 306for (int s = 0 ;s < ubatch -> n_seq_id [i ];++ s ) { 307const llama_seq_id seq_id = ubatch -> seq_id [i ][s ]; 308const int32_t seq_idx = ubatch -> seq_idx [seq_id ]; 309 310if ( 311 (target_pos [seq_idx ]== -1 )|| 312 (last && pos >=target_pos [seq_idx ])|| 313 (!last && pos < target_pos [seq_idx ]) 314 ) { 315target_pos [seq_idx ]= pos ; 316target_row [seq_idx ]= i ; 317 } 318 } 319 } 320 321for (int s = 0 ;s < n_seqs_unq ;++ s ) { 322if (target_row [s ] >=0 ) { 323data [s ]= target_row [s ]; 324 } 325 } 326 } 327} 328 329void llm_graph_input_rs::set_input (const llama_ubatch * ubatch ) { 330GGML_UNUSED (ubatch ); 331 332const int64_t n_rs = mctx -> get_n_rs (); 333 334if (s_copy ) { 335GGML_ASSERT (ggml_backend_buffer_is_host (s_copy -> buffer )); 336int32_t * data = (int32_t * )s_copy -> data ; 337 338// assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n 339for (uint32_t i = 0 ;i < n_rs ;++ i ) { 340data [i ]= mctx -> s_copy (i ); 341 } 342 } 343} 344 345bool llm_graph_input_rs::can_reuse (const llm_graph_params & params ) { 346const auto * mctx = static_cast < const llama_memory_recurrent_context *> (params .mctx ); 347 348this -> mctx = mctx ; 349 350bool res = true; 351 352res &=s_copy -> ne [0 ]== mctx -> get_n_rs (); 353 354res &=s_copy_main -> ne [0 ]== params .ubatch .n_seqs ; 355res &=s_copy_extra -> ne [0 ]== mctx -> get_n_rs ()- params .ubatch .n_seqs ; 356 357res &=head == mctx -> get_head (); 358res &=rs_z == mctx -> get_rs_z (); 359 360return res ; 361} 362 363void llm_graph_input_cross_embd::set_input (const llama_ubatch * ubatch ) { 364GGML_UNUSED (ubatch ); 365 366if (cross_embd && !cross -> v_embd .empty ()) { 367assert (cross_embd -> type == GGML_TYPE_F32 ); 368 369ggml_backend_tensor_set (cross_embd ,cross -> v_embd .data (),0 ,ggml_nbytes (cross_embd )); 370 } 371} 372 373template < typename T > 374static void print_mask (const T * data ,int64_t n_tokens ,int64_t n_kv ,int64_t n_swa ,llama_swa_type swa_type ) { 375LLAMA_LOG_DEBUG ("%s: === Attention mask ===\n" ,__func__ ); 376const char * swa_type_str = "unknown" ; 377 378switch (swa_type ) { 379case LLAMA_SWA_TYPE_NONE :swa_type_str = "LLAMA_SWA_TYPE_NONE" ;break ; 380case LLAMA_SWA_TYPE_STANDARD :swa_type_str = "LLAMA_SWA_TYPE_STANDARD" ;break ; 381case LLAMA_SWA_TYPE_CHUNKED :swa_type_str = "LLAMA_SWA_TYPE_CHUNKED" ;break ; 382case LLAMA_SWA_TYPE_SYMMETRIC :swa_type_str = "LLAMA_SWA_TYPE_SYMMETRIC" ;break ; 383 }; 384 385LLAMA_LOG_DEBUG ("%s: n_swa : %d, n_kv: %d, swa_type: %s\n" ,__func__ , (int )n_swa , (int )n_kv ,swa_type_str ); 386LLAMA_LOG_DEBUG ("%s: '0' = can attend, '∞' = masked\n" ,__func__ ); 387LLAMA_LOG_DEBUG ("%s: Rows = query tokens, Columns = key/value tokens\n\n" ,__func__ ); 388 389LLAMA_LOG_DEBUG (" " ); 390for (int j = 0 ;j < std::min ((int64_t )20 ,n_kv );++ j ) { 391LLAMA_LOG_DEBUG ("%2d" ,j ); 392 } 393LLAMA_LOG_DEBUG ("\n" ); 394 395for (int i = 0 ;i < std::min ((int64_t )20 ,n_tokens );++ i ) { 396LLAMA_LOG_DEBUG (" %2d " ,i ); 397for (int j = 0 ;j < std::min ((int64_t )20 ,n_kv );++ j ) { 398float val = llama_cast < float > (data [i * n_kv + j ]); 399if (val == - INFINITY ) { 400LLAMA_LOG_DEBUG (" ∞" ); 401 }else { 402LLAMA_LOG_DEBUG (" 0" ); 403 } 404 } 405LLAMA_LOG_DEBUG ("\n" ); 406 } 407} 408 409void llm_graph_input_attn_no_cache::set_input (const llama_ubatch * ubatch ) { 410const int64_t n_kv = ubatch -> n_tokens ; 411const int64_t n_tokens = ubatch -> n_tokens ; 412 413const auto fill_mask = [& ](auto * data ,int64_t ne ,int n_swa ,llama_swa_type swa_type ) { 414using T = std::remove_reference_t < decltype(* data )> ; 415 std::fill (data ,data + ne ,llama_cast < T > (- INFINITY )); 416 417for (int i1 = 0 ;i1 < n_tokens ;++ i1 ) { 418const llama_seq_id s1 = ubatch -> seq_id [i1 ][0 ]; 419const llama_pos p1 = ubatch -> pos [i1 ]; 420 421const uint64_t idst = i1 * n_kv ; 422 423for (int i0 = 0 ;i0 < n_tokens ;++ i0 ) { 424const llama_seq_id s0 = ubatch -> seq_id [i0 ][0 ]; 425const llama_pos p0 = ubatch -> pos [i0 ]; 426 427// mask different sequences 428if (s0 != s1 ) { 429continue ; 430 } 431 432// mask future tokens 433if (cparams .causal_attn && p0 > p1 ) { 434continue ; 435 } 436 437// apply SWA if any 438if (llama_hparams::is_masked_swa (n_swa ,swa_type ,p0 ,p1 )) { 439continue ; 440 } 441 442data [idst + i0 ]= llama_cast < T > (hparams .use_alibi ?- std::abs (p0 - p1 ) :0.0f ); 443 } 444 } 445 446if (debug ) { 447print_mask (data ,n_tokens ,n_kv ,n_swa ,swa_type ); 448 } 449 }; 450 451GGML_ASSERT (self_kq_mask ); 452GGML_ASSERT (ggml_backend_buffer_is_host (self_kq_mask -> buffer )); 453if (self_kq_mask -> type == GGML_TYPE_F16 ) { 454fill_mask ((ggml_fp16_t * )self_kq_mask -> data ,ggml_nelements (self_kq_mask ),0 ,LLAMA_SWA_TYPE_NONE ); 455 }else { 456fill_mask ((float * )self_kq_mask -> data ,ggml_nelements (self_kq_mask ),0 ,LLAMA_SWA_TYPE_NONE ); 457 } 458 459if (hparams .swa_type != LLAMA_SWA_TYPE_NONE ) { 460GGML_ASSERT (self_kq_mask_swa ); 461GGML_ASSERT (ggml_backend_buffer_is_host (self_kq_mask_swa -> buffer )); 462if (self_kq_mask_swa -> type == GGML_TYPE_F16 ) { 463fill_mask ((ggml_fp16_t * )self_kq_mask_swa -> data ,ggml_nelements (self_kq_mask_swa ),hparams .n_swa ,hparams .swa_type ); 464 }else { 465fill_mask ((float * )self_kq_mask_swa -> data ,ggml_nelements (self_kq_mask_swa ),hparams .n_swa ,hparams .swa_type ); 466 } 467 } 468} 469 470void llm_graph_input_attn_kv::set_input (const llama_ubatch * ubatch ) { 471mctx -> set_input_k_idxs (self_k_idxs ,ubatch ); 472mctx -> set_input_v_idxs (self_v_idxs ,ubatch ); 473 474// the mask is left unallocated when the graph only stores K/V without attending 475// (e.g. DFlash's KV-injection pass) 476if (self_kq_mask && self_kq_mask -> buffer ) { 477mctx -> set_input_kq_mask (self_kq_mask ,ubatch ,cparams .causal_attn ); 478 } 479 480if (self_k_rot && self_k_rot -> buffer ) { 481mctx -> set_input_k_rot (self_k_rot ); 482 } 483 484if (self_v_rot && self_v_rot -> buffer ) { 485mctx -> set_input_v_rot (self_v_rot ); 486 } 487} 488 489bool llm_graph_input_attn_kv::can_reuse (const llm_graph_params & params ) { 490const auto * mctx = static_cast < const llama_kv_cache_context *> (params .mctx ); 491 492this -> mctx = mctx ; 493 494bool res = true; 495 496res &=self_k_idxs -> ne [0 ]== params .ubatch .n_tokens ; 497//res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there 498 499res &=can_reuse_kq_mask (self_kq_mask ,mctx ,params .ubatch ,params .cparams ); 500 501return res ; 502} 503 504void llm_graph_input_attn_k::set_input (const llama_ubatch * ubatch ) { 505mctx -> set_input_k_idxs (self_k_idxs ,ubatch ); 506 507mctx -> set_input_kq_mask (self_kq_mask ,ubatch ,cparams .causal_attn ); 508} 509 510bool llm_graph_input_attn_k::can_reuse (const llm_graph_params & params ) { 511mctx = static_cast < const llama_kv_cache_context *> (params .mctx ); 512 513return can_reuse_impl (params ); 514} 515 516bool llm_graph_input_attn_k::can_reuse_impl (const llm_graph_params & params ) { 517bool res = true; 518 519res &=self_k_idxs -> ne [0 ]== params .ubatch .n_tokens ; 520 521res &=can_reuse_kq_mask (self_kq_mask ,mctx ,params .ubatch ,params .cparams ); 522 523return res ; 524} 525 526llm_graph_input_attn_kv_msa::llm_graph_input_attn_kv_msa ( 527const llama_hparams & hparams , 528const llama_cparams & cparams , 529const llama_kv_cache_msa_context * mctx ) : 530llm_graph_input_attn_kv (hparams ,cparams ,mctx -> get_base ()), 531mctx_msa (mctx ) { 532} 533 534void llm_graph_input_attn_kv_msa::set_input (const llama_ubatch * ubatch ) { 535 llm_graph_input_attn_kv::set_input (ubatch ); 536 537if (self_k_idxs_idx ) { 538mctx_msa -> get_idx ()-> set_input_k_idxs (self_k_idxs_idx ,ubatch ); 539 } 540} 541 542bool llm_graph_input_attn_kv_msa::can_reuse (const llm_graph_params & params ) { 543mctx_msa = static_cast < const llama_kv_cache_msa_context *> (params .mctx ); 544 545// the parent class operates on the base cache context 546this -> mctx = mctx_msa -> get_base (); 547 548bool res = true; 549 550res &=self_k_idxs -> ne [0 ]== params .ubatch .n_tokens ; 551if (self_k_idxs_idx ) { 552res &=self_k_idxs_idx -> ne [0 ]== params .ubatch .n_tokens ; 553 } 554 555res &=can_reuse_kq_mask (self_kq_mask ,this -> mctx ,params .ubatch ,params .cparams ); 556 557return res ; 558} 559 560void llm_graph_input_attn_k_dsa::set_input (const llama_ubatch * ubatch ) { 561mctx -> get_mla ()-> set_input_k_idxs (self_k_idxs_mla ,ubatch ); 562 563mctx -> get_mla ()-> set_input_kq_mask (self_kq_mask_mla ,ubatch ,cparams .causal_attn ); 564 565mctx -> get_lid ()-> set_input_k_idxs (self_k_idxs_lid ,ubatch ); 566 567mctx -> get_lid ()-> set_input_kq_mask (self_kq_mask_lid ,ubatch ,cparams .causal_attn ); 568 569// left unallocated when the indexer does not use the rotation 570if (self_k_rot_lid && self_k_rot_lid -> buffer ) { 571mctx -> get_lid ()-> set_input_k_rot (self_k_rot_lid ); 572 } 573} 574 575bool llm_graph_input_attn_k_dsa::can_reuse (const llm_graph_params & params ) { 576mctx = static_cast < const llama_kv_cache_dsa_context *> (params .mctx ); 577 578return can_reuse_impl (params ); 579} 580 581bool llm_graph_input_attn_k_dsa::can_reuse_impl (const llm_graph_params & params ) { 582bool res = true; 583 584res &=self_k_idxs_mla -> ne [0 ]== params .ubatch .n_tokens ; 585res &=self_k_idxs_lid -> ne [0 ]== params .ubatch .n_tokens ; 586 587res &=can_reuse_kq_mask (self_kq_mask_mla ,mctx -> get_mla (),params .ubatch ,params .cparams ); 588res &=can_reuse_kq_mask (self_kq_mask_lid ,mctx -> get_lid (),params .ubatch ,params .cparams ); 589 590return res ; 591} 592 593void llm_graph_input_attn_k_dsa_iswa::set_input (const llama_ubatch * ubatch ) { 594inp_dsa -> set_input (ubatch ); 595inp_swa -> set_input (ubatch ); 596} 597 598bool llm_graph_input_attn_k_dsa_iswa::can_reuse (const llm_graph_params & params ) { 599mctx = static_cast < const llama_kv_cache_dsa_iswa_context *> (params .mctx ); 600 601inp_dsa -> mctx = mctx -> get_dsa (); 602inp_swa -> mctx = mctx -> get_swa (); 603 604bool res = true; 605 606res &=inp_dsa -> can_reuse_impl (params ); 607res &=inp_swa -> can_reuse_impl (params ); 608 609return res ; 610} 611 612void llm_graph_input_attn_kv_iswa::set_input (const llama_ubatch * ubatch ) { 613// base tensors may not be allocated if there are no non-SWA attention layers 614if (self_k_idxs && self_k_idxs -> buffer ) { 615mctx -> get_base ()-> set_input_k_idxs (self_k_idxs ,ubatch ); 616if (self_v_idxs ) { 617mctx -> get_base ()-> set_input_v_idxs (self_v_idxs ,ubatch ); 618 } 619 } 620 621// the kq mask guards on its own buffer: shared cells leave idxs unbacked while the mask stays live 622if (self_kq_mask && self_kq_mask -> buffer ) { 623mctx -> get_base ()-> set_input_kq_mask (self_kq_mask ,ubatch ,cparams .causal_attn ); 624 } 625 626// swa tensors may not be allocated if there are no SWA attention layers 627if (self_k_idxs_swa && self_k_idxs_swa -> buffer ) { 628mctx -> get_swa ()-> set_input_k_idxs (self_k_idxs_swa ,ubatch ); 629if (self_v_idxs_swa ) { 630mctx -> get_swa ()-> set_input_v_idxs (self_v_idxs_swa ,ubatch ); 631 } 632 } 633 634if (self_kq_mask_swa && self_kq_mask_swa -> buffer ) { 635mctx -> get_swa ()-> set_input_kq_mask (self_kq_mask_swa ,ubatch ,cparams .causal_attn ); 636 } 637 638if (self_k_rot && self_k_rot -> buffer ) { 639mctx -> get_base ()-> set_input_k_rot (self_k_rot ); 640 } 641 642if (self_v_rot && self_v_rot -> buffer ) { 643mctx -> get_base ()-> set_input_v_rot (self_v_rot ); 644 } 645 646if (self_k_rot_swa && self_k_rot_swa -> buffer ) { 647mctx -> get_swa ()-> set_input_k_rot (self_k_rot_swa ); 648 } 649 650if (self_v_rot_swa && self_v_rot_swa -> buffer ) { 651mctx -> get_swa ()-> set_input_v_rot (self_v_rot_swa ); 652 } 653} 654 655bool llm_graph_input_attn_kv_iswa::can_reuse (const llm_graph_params & params ) { 656const auto * mctx = static_cast < const llama_kv_cache_iswa_context *> (params .mctx ); 657 658this -> mctx = mctx ; 659 660bool res = true; 661 662// base tensors may not be allocated if there are no non-SWA attention layers 663if (self_k_idxs && self_k_idxs -> buffer ) { 664res &=self_k_idxs -> ne [0 ]== params .ubatch .n_tokens ; 665//res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there 666 } 667 668if (self_kq_mask && self_kq_mask -> buffer ) { 669res &=can_reuse_kq_mask (self_kq_mask ,mctx -> get_base (),params .ubatch ,params .cparams ); 670 } 671 672// swa tensors may not be allocated if there are no SWA attention layers 673if (self_k_idxs_swa && self_k_idxs_swa -> buffer ) { 674res &=self_k_idxs_swa -> ne [0 ]== params .ubatch .n_tokens ; 675//res &= self_v_idxs_swa->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there 676 } 677 678if (self_kq_mask_swa && self_kq_mask_swa -> buffer ) { 679res &=can_reuse_kq_mask (self_kq_mask_swa ,mctx -> get_swa (),params .ubatch ,params .cparams ); 680 } 681 682return res ; 683} 684 685void llm_graph_input_attn_k_iswa::set_input (const llama_ubatch * ubatch ) { 686// base tensors may not be allocated if there are no non-SWA attention layers 687if (self_k_idxs && self_k_idxs -> buffer ) { 688mctx -> get_base ()-> set_input_k_idxs (self_k_idxs ,ubatch ); 689 } 690 691// the kq mask guards on its own buffer: shared cells leave idxs unbacked while the mask stays live 692if (self_kq_mask && self_kq_mask -> buffer ) { 693mctx -> get_base ()-> set_input_kq_mask (self_kq_mask ,ubatch ,cparams .causal_attn ); 694 } 695 696// swa tensors may not be allocated if there are no SWA attention layers 697if (self_k_idxs_swa && self_k_idxs_swa -> buffer ) { 698mctx -> get_swa ()-> set_input_k_idxs (self_k_idxs_swa ,ubatch ); 699 } 700 701if (self_kq_mask_swa && self_kq_mask_swa -> buffer ) { 702mctx -> get_swa ()-> set_input_kq_mask (self_kq_mask_swa ,ubatch ,cparams .causal_attn ); 703 } 704 705if (self_k_rot && self_k_rot -> buffer ) { 706mctx -> get_base ()-> set_input_k_rot (self_k_rot ); 707 } 708 709if (self_k_rot_swa && self_k_rot_swa -> buffer ) { 710mctx -> get_swa ()-> set_input_k_rot (self_k_rot_swa ); 711 } 712} 713 714bool llm_graph_input_attn_k_iswa::can_reuse (const llm_graph_params & params ) { 715const auto * mctx = static_cast < const llama_kv_cache_iswa_context *> (params .mctx ); 716 717this -> mctx = mctx ; 718 719bool res = true; 720 721// base tensors may not be allocated if there are no non-SWA attention layers 722if (self_k_idxs && self_k_idxs -> buffer ) { 723res &=self_k_idxs -> ne [0 ]== params .ubatch .n_tokens ; 724 } 725 726if (self_kq_mask && self_kq_mask -> buffer ) { 727res &=can_reuse_kq_mask (self_kq_mask ,mctx -> get_base (),params .ubatch ,params .cparams ); 728 } 729 730// swa tensors may not be allocated if there are no SWA attention layers 731if (self_k_idxs_swa && self_k_idxs_swa -> buffer ) { 732res &=self_k_idxs_swa -> ne [0 ]== params .ubatch .n_tokens ; 733 } 734 735if (self_kq_mask_swa && self_kq_mask_swa -> buffer ) { 736res &=can_reuse_kq_mask (self_kq_mask_swa ,mctx -> get_swa (),params .ubatch ,params .cparams ); 737 } 738 739return res ; 740} 741 742static void dsv4_set_i64 (ggml_tensor * dst ,const std::vector < int64_t > & src ) { 743if (!dst || !dst -> buffer ) { 744return ; 745 } 746 747GGML_ASSERT (dst -> ne [0 ]== (int64_t )src .size ()); 748ggml_backend_tensor_set (dst ,src .data (),0 ,src .size ()* ggml_element_size (dst )); 749} 750 751static void dsv4_set_i32 (ggml_tensor * dst ,const std::vector < int32_t > & src ) { 752if (!dst || !dst -> buffer ) { 753return ; 754 } 755 756GGML_ASSERT (dst -> ne [0 ]== (int64_t )src .size ()); 757ggml_backend_tensor_set (dst ,src .data (),0 ,src .size ()* ggml_element_size (dst )); 758} 759 760static void dsv4_set_kq_mask ( 761ggml_tensor * dst , 762const llama_kv_cache_dsv4_context::comp_plan & plan , 763uint32_t n_tokens , 764int64_t n_stream ) { 765if (!dst || !dst -> buffer ) { 766return ; 767 } 768 769GGML_ASSERT (dst -> type == GGML_TYPE_F32 || dst -> type == GGML_TYPE_F16 ); 770GGML_ASSERT (n_stream > 0 ); 771GGML_ASSERT (n_tokens %n_stream == 0 ); 772GGML_ASSERT (dst -> ne [0 ]== plan .n_kv ); 773GGML_ASSERT (dst -> ne [1 ]== (int64_t )n_tokens /n_stream ); 774GGML_ASSERT (dst -> ne [2 ]== 1 ); 775GGML_ASSERT (dst -> ne [3 ]== n_stream ); 776GGML_ASSERT ((int64_t )plan .n_visible .size ()== (int64_t )n_tokens ); 777GGML_ASSERT (ggml_backend_buffer_is_host (dst -> buffer )); 778 779if (dst -> type == GGML_TYPE_F32 ) { 780float * data = (float * )dst -> data ; 781 782for (int64_t i = 0 ;i < (int64_t )n_tokens ;++ i ) { 783const int32_t n_visible = plan .n_visible [i ]; 784 785for (int64_t j = 0 ;j < dst -> ne [0 ];++ j ) { 786data [i * dst -> ne [0 ]+ j ]= j < n_visible ?0.0f :- INFINITY ; 787 } 788 } 789 }else if (dst -> type == GGML_TYPE_F16 ) { 790ggml_fp16_t * data = (ggml_fp16_t * )dst -> data ; 791const ggml_fp16_t fp16_ninf = llama_cast < ggml_fp16_t > (- INFINITY ); 792const ggml_fp16_t fp16_zero = llama_cast < ggml_fp16_t > (0.0f ); 793 794for (int64_t i = 0 ;i < (int64_t )n_tokens ;++ i ) { 795const int32_t n_visible = plan .n_visible [i ]; 796 797for (int64_t j = 0 ;j < dst -> ne [0 ];++ j ) { 798data [i * dst -> ne [0 ]+ j ]= j < n_visible ?fp16_zero :fp16_ninf ; 799 } 800 } 801 } 802} 803 804static ggml_tensor * dsv4_build_raw_kq_mask ( 805ggml_context * ctx , 806const llama_kv_cache_dsv4_raw_context * mctx , 807const llama_ubatch & ubatch , 808const llama_cparams & cparams , 809int64_t n_stream ) { 810const auto n_kv = mctx -> get_n_kv (); 811const auto n_tokens = ubatch .n_tokens ; 812 813GGML_ASSERT (n_stream > 0 ); 814GGML_ASSERT (n_tokens %n_stream == 0 ); 815 816const auto type = cparams .flash_attn ?GGML_TYPE_F16 :GGML_TYPE_F32 ; 817 818ggml_tensor * res = ggml_new_tensor_4d (ctx ,type ,n_kv ,n_tokens /n_stream ,1 ,n_stream ); 819ggml_set_input (res ); 820ggml_set_name (res ,"attn_inp_kq_mask" ); 821 822return res ; 823} 824 825static bool dsv4_can_reuse_raw_kq_mask ( 826ggml_tensor * kq_mask , 827const llama_kv_cache_dsv4_raw_context * mctx , 828const llama_ubatch & ubatch , 829int64_t n_stream ) { 830const auto n_kv = mctx -> get_n_kv (); 831const auto n_tokens = ubatch .n_tokens ; 832 833GGML_ASSERT (n_stream > 0 ); 834 835bool res = true; 836 837res &= (kq_mask -> ne [0 ]== n_kv ); 838res &= (kq_mask -> ne [1 ]== n_tokens /n_stream ); 839res &= (kq_mask -> ne [2 ]== 1 ); 840res &= (kq_mask -> ne [3 ]== n_stream ); 841 842return res ; 843} 844 845static std::string dsv4_plan_positions (const std::vector < int32_t > & values ) { 846 std::ostringstream ss ; 847ss <<"[" ; 848for (size_t i = 0 ;i < values .size ();++ i ) { 849if (i > 0 ) { 850ss <<", " ; 851 } 852ss <<values [i ]; 853 } 854ss <<"]" ; 855return ss .str (); 856} 857 858static bool dsv4_compress_debug () { 859static const bool debug = []() { 860const char * env = getenv ("LLAMA_DSV4_COMPRESS_DEBUG" ); 861return env && atoi (env )> 0 ; 862 }(); 863 864return debug ; 865} 866 867static void dsv4_set_comp_inputs ( 868const llm_graph_input_dsv4::comp_input & inp , 869const llama_kv_cache_dsv4_context::comp_plan & plan , 870const char * name , 871bool debug , 872uint32_t n_tokens , 873int64_t n_stream ) { 874dsv4_set_i32 (inp .state_pos ,plan .state_pos ); 875dsv4_set_i32 (inp .state_persist_src_idxs ,plan .state_persist_src_idxs ); 876dsv4_set_i32 (inp .state_persist_dst_idxs ,plan .state_persist_dst_idxs ); 877dsv4_set_i32 (inp .state_restore_src_idxs ,plan .state_restore_src_idxs ); 878dsv4_set_i32 (inp .state_restore_dst_idxs ,plan .state_restore_dst_idxs ); 879dsv4_set_i32 (inp .state_snapshot_src_idxs ,plan .state_snapshot_src_idxs ); 880dsv4_set_i32 (inp .state_snapshot_dst_idxs ,plan .state_snapshot_dst_idxs ); 881dsv4_set_i32 (inp .state_read_idxs ,plan .state_read_idxs ); 882dsv4_set_i64 (inp .state_write_idxs ,plan .state_write_idxs ); 883dsv4_set_i32 (inp .state_write_pos ,plan .state_write_pos ); 884dsv4_set_kq_mask (inp .kq_mask ,plan ,n_tokens ,n_stream ); 885 886if (debug || dsv4_compress_debug ()) { 887LLAMA_LOG_INFO ("%s: %s n_tokens=%u, n_stream=%d, state_persist_dst=%s, state_write_pos=%s\n" , 888__func__ ,name ,n_tokens , (int )n_stream , 889dsv4_plan_positions (plan .state_persist_dst_idxs ).c_str (), 890dsv4_plan_positions (plan .state_write_pos ).c_str ()); 891 } 892} 893 894static bool dsv4_can_reuse_tensor_1d (ggml_tensor * t ,int64_t ne0 ) { 895return (t == nullptr && ne0 == 0 )|| (t != nullptr && t -> ne [0 ]== ne0 ); 896} 897 898static bool dsv4_can_reuse_kq_mask ( 899ggml_tensor * t , 900const llama_kv_cache_dsv4_context::comp_plan & plan , 901uint32_t n_tokens , 902int64_t n_stream ) { 903if (plan .n_kv == 0 ) { 904return t == nullptr ; 905 } 906 907GGML_ASSERT (n_stream > 0 ); 908 909return t != nullptr && 910t -> ne [0 ]== plan .n_kv && 911t -> ne [1 ]== (int64_t )n_tokens /n_stream && 912t -> ne [2 ]== 1 && 913t -> ne [3 ]== n_stream ; 914} 915 916static bool dsv4_can_reuse_comp_input ( 917const llm_graph_input_dsv4::comp_input & inp , 918const llama_kv_cache_dsv4_context::comp_plan & plan , 919uint32_t n_tokens , 920int64_t n_stream ) { 921bool res = true; 922res &=dsv4_can_reuse_tensor_1d (inp .state_pos ,plan .state_pos .size ()); 923res &=dsv4_can_reuse_tensor_1d (inp .state_persist_src_idxs ,plan .state_persist_src_idxs .size ()); 924res &=dsv4_can_reuse_tensor_1d (inp .state_persist_dst_idxs ,plan .state_persist_dst_idxs .size ()); 925res &=dsv4_can_reuse_tensor_1d (inp .state_restore_src_idxs ,plan .state_restore_src_idxs .size ()); 926res &=dsv4_can_reuse_tensor_1d (inp .state_restore_dst_idxs ,plan .state_restore_dst_idxs .size ()); 927res &=dsv4_can_reuse_tensor_1d (inp .state_snapshot_src_idxs ,plan .state_snapshot_src_idxs .size ()); 928res &=dsv4_can_reuse_tensor_1d (inp .state_snapshot_dst_idxs ,plan .state_snapshot_dst_idxs .size ()); 929res &=dsv4_can_reuse_tensor_1d (inp .state_read_idxs ,plan .state_read_idxs .size ()); 930res &=dsv4_can_reuse_tensor_1d (inp .state_write_idxs ,plan .state_write_idxs .size ()); 931res &=dsv4_can_reuse_tensor_1d (inp .state_write_pos ,plan .state_write_pos .size ()); 932res &=dsv4_can_reuse_kq_mask (inp .kq_mask ,plan ,n_tokens ,n_stream ); 933 934return res ; 935} 936 937static ggml_tensor * dsv4_build_input_1d ( 938ggml_context * ctx , 939ggml_type type , 940int64_t ne0 , 941const std::string & name ) { 942if (ne0 == 0 ) { 943return nullptr ; 944 } 945 946ggml_tensor * res = ggml_new_tensor_1d (ctx ,type ,ne0 ); 947ggml_set_input (res ); 948ggml_set_name (res ,name .c_str ()); 949 950return res ; 951} 952 953static void dsv4_build_comp_inputs ( 954ggml_context * ctx , 955 llm_graph_input_dsv4::comp_input & inp , 956const llama_kv_cache_dsv4_context::comp_plan & plan , 957const char * name , 958const llama_cparams & cparams , 959int64_t n_stream ) { 960inp .state_pos = dsv4_build_input_1d (ctx ,GGML_TYPE_I32 ,plan .state_pos .size (), std::string ("dsv4_" )+ name + "_state_pos" ); 961inp .state_persist_src_idxs = dsv4_build_input_1d (ctx ,GGML_TYPE_I32 ,plan .state_persist_src_idxs .size (), std::string ("dsv4_" )+ name + "_state_persist_src_idxs" ); 962inp .state_persist_dst_idxs = dsv4_build_input_1d (ctx ,GGML_TYPE_I32 ,plan .state_persist_dst_idxs .size (), std::string ("dsv4_" )+ name + "_state_persist_dst_idxs" ); 963inp .state_restore_src_idxs = dsv4_build_input_1d (ctx ,GGML_TYPE_I32 ,plan .state_restore_src_idxs .size (), std::string ("dsv4_" )+ name + "_state_restore_src_idxs" ); 964inp .state_restore_dst_idxs = dsv4_build_input_1d (ctx ,GGML_TYPE_I32 ,plan .state_restore_dst_idxs .size (), std::string ("dsv4_" )+ name + "_state_restore_dst_idxs" ); 965inp .state_snapshot_src_idxs = dsv4_build_input_1d (ctx ,GGML_TYPE_I32 ,plan .state_snapshot_src_idxs .size (), std::string ("dsv4_" )+ name + "_state_snapshot_src_idxs" ); 966inp .state_snapshot_dst_idxs = dsv4_build_input_1d (ctx ,GGML_TYPE_I32 ,plan .state_snapshot_dst_idxs .size (), std::string ("dsv4_" )+ name + "_state_snapshot_dst_idxs" ); 967inp .state_read_idxs = dsv4_build_input_1d (ctx ,GGML_TYPE_I32 ,plan .state_read_idxs .size (), std::string ("dsv4_" )+ name + "_state_read_idxs" ); 968inp .state_write_idxs = dsv4_build_input_1d (ctx ,GGML_TYPE_I64 ,plan .state_write_idxs .size (), std::string ("dsv4_" )+ name + "_state_write_idxs" ); 969inp .state_write_pos = dsv4_build_input_1d (ctx ,GGML_TYPE_I32 ,plan .state_write_pos .size (), std::string ("dsv4_" )+ name + "_state_write_pos" ); 970 971if (plan .n_kv > 0 ) { 972const int64_t n_tokens = (int64_t )plan .n_visible .size (); 973 974GGML_ASSERT (n_stream > 0 ); 975GGML_ASSERT (n_tokens %n_stream == 0 ); 976 977inp .kq_mask = ggml_new_tensor_4d (ctx , (strcmp (name ,"lid" )!= 0 && cparams .flash_attn )|| (strcmp (name ,"lid" )== 0 && cparams .fused_lid ) ?GGML_TYPE_F16 :GGML_TYPE_F32 ,plan .n_kv ,n_tokens /n_stream ,1 ,n_stream ); 978ggml_set_input (inp .kq_mask ); 979ggml_set_name (inp .kq_mask , (std::string ("dsv4_" )+ name + "_kq_mask" ).c_str ()); 980 } 981} 982 983void llm_graph_input_dsv4_raw::set_input (const llama_ubatch * ubatch ) { 984if (self_k_idxs && self_k_idxs -> buffer ) { 985mctx -> set_input_k_idxs (self_k_idxs ); 986 } 987 988if (self_kq_mask && self_kq_mask -> buffer ) { 989mctx -> set_input_kq_mask (self_kq_mask ,ubatch ,cparams .causal_attn ); 990 } 991 992if (self_k_rot ) { 993mctx -> set_input_k_rot (self_k_rot ); 994 } 995} 996 997void llm_graph_input_dsv4::set_input (const llama_ubatch * ubatch ) { 998const auto & plan_csa = mctx -> get_csa_plan (* ubatch ); 999const auto & plan_hca = mctx -> get_hca_plan (* ubatch ); 1000const auto & plan_lid = mctx -> get_lid_plan (* ubatch ); 1001const int64_t n_stream = plan_csa .n_stream ; 1002 1003inp_raw -> mctx = mctx -> get_raw (); 1004inp_raw -> set_input (ubatch ); 1005 1006dsv4_set_comp_inputs (inp_csa ,plan_csa ,"csa" ,debug > 0 ,ubatch -> n_tokens ,n_stream ); 1007dsv4_set_comp_inputs (inp_hca ,plan_hca ,"hca" ,debug > 0 ,ubatch -> n_tokens ,n_stream ); 1008dsv4_set_comp_inputs (inp_lid ,plan_lid ,"lid" ,debug > 0 ,ubatch -> n_tokens ,n_stream ); 1009 1010if (inp_csa .k_rot && inp_csa .k_rot -> buffer ) { 1011mctx -> get_csa ()-> set_input_k_rot (inp_csa .k_rot ); 1012 } 1013 1014if (inp_hca .k_rot && inp_hca .k_rot -> buffer ) { 1015mctx -> get_hca ()-> set_input_k_rot (inp_hca .k_rot ); 1016 } 1017 1018if (inp_lid .k_rot && inp_lid .k_rot -> buffer ) { 1019mctx -> get_lid ()-> set_input_k_rot (inp_lid .k_rot ); 1020 } 1021} 1022 1023bool llm_graph_input_dsv4::can_reuse (const llm_graph_params & params ) { 1024const auto * mctx = static_cast < const llama_kv_cache_dsv4_context *> (params .mctx ); 1025 1026this -> mctx = mctx ; 1027inp_raw -> mctx = mctx -> get_raw (); 1028 1029bool res = true; 1030 1031const auto & plan_csa = mctx -> get_csa_plan (params .ubatch ); 1032const auto & plan_hca = mctx -> get_hca_plan (params .ubatch ); 1033const auto & plan_lid = mctx -> get_lid_plan (params .ubatch ); 1034const int64_t n_stream = plan_csa .n_stream ; 1035 1036const auto * raw_ctx = mctx -> get_raw (); 1037inp_raw -> mctx = raw_ctx ; 1038 1039if (inp_raw -> self_k_idxs && inp_raw -> self_k_idxs -> buffer ) { 1040res &=inp_raw -> self_k_idxs -> ne [0 ]== raw_ctx -> get_n_write (); 1041 } 1042if (inp_raw -> self_kq_mask && inp_raw -> self_kq_mask -> buffer ) { 1043res &=dsv4_can_reuse_raw_kq_mask (inp_raw -> self_kq_mask ,raw_ctx ,params .ubatch ,n_stream ); 1044 } 1045 1046res &=dsv4_can_reuse_comp_input (inp_csa ,plan_csa ,params .ubatch .n_tokens ,n_stream ); 1047res &=dsv4_can_reuse_comp_input (inp_hca ,plan_hca ,params .ubatch .n_tokens ,n_stream ); 1048res &=dsv4_can_reuse_comp_input (inp_lid ,plan_lid ,params .ubatch .n_tokens ,n_stream ); 1049 1050return res ; 1051} 1052 1053void llm_graph_input_attn_cross::set_input (const llama_ubatch * ubatch ) { 1054GGML_ASSERT (cross_kq_mask ); 1055 1056const int64_t n_enc = cross_kq_mask -> ne [0 ]; 1057const int64_t n_tokens = ubatch -> n_tokens ; 1058 1059GGML_ASSERT (ggml_backend_buffer_is_host (cross_kq_mask -> buffer )); 1060GGML_ASSERT (!ubatch -> equal_seqs ());// TODO: use ubatch->n_seqs instead of failing 1061 1062const auto fill_mask = [& ](auto * data ) { 1063using T = std::remove_reference_t < decltype(* data )> ; 1064for (int i = 0 ;i < n_tokens ;++ i ) { 1065GGML_ASSERT (!cross -> seq_ids_enc .empty ()&& "llama_encode must be called first" ); 1066for (int j = 0 ;j < n_enc ;++ j ) { 1067float f = - INFINITY ; 1068 1069for (int s = 0 ;s < ubatch -> n_seq_id [i ];++ s ) { 1070const llama_seq_id seq_id = ubatch -> seq_id [i ][s ]; 1071 1072if (cross -> seq_ids_enc [j ].find (seq_id )!= cross -> seq_ids_enc [j ].end ()) { 1073f = 0.0f ; 1074 } 1075 } 1076 1077data [i * n_enc + j ]= llama_cast < T > (f ); 1078 } 1079 } 1080 }; 1081 1082if (cross_kq_mask -> type == GGML_TYPE_F16 ) { 1083fill_mask ((ggml_fp16_t * )cross_kq_mask -> data ); 1084 }else { 1085fill_mask ((float * )cross_kq_mask -> data ); 1086 } 1087} 1088 1089void llm_graph_input_mem_hybrid::set_input (const llama_ubatch * ubatch ) { 1090mctx -> get_attn ()-> set_input_k_idxs (inp_attn -> self_k_idxs ,ubatch ); 1091mctx -> get_attn ()-> set_input_v_idxs (inp_attn -> self_v_idxs ,ubatch ); 1092 1093mctx -> get_attn ()-> set_input_kq_mask (inp_attn -> self_kq_mask ,ubatch ,cparams .causal_attn ); 1094 1095if (inp_attn -> self_k_rot ) { 1096mctx -> get_attn ()-> set_input_k_rot (inp_attn -> self_k_rot ); 1097 } 1098 1099if (inp_attn -> self_v_rot ) { 1100mctx -> get_attn ()-> set_input_v_rot (inp_attn -> self_v_rot ); 1101 } 1102 1103const int64_t n_rs = mctx -> get_recr ()-> get_n_rs (); 1104 1105if (inp_rs -> s_copy ) { 1106GGML_ASSERT (ggml_backend_buffer_is_host (inp_rs -> s_copy -> buffer )); 1107int32_t * data = (int32_t * )inp_rs -> s_copy -> data ; 1108 1109// assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n 1110for (uint32_t i = 0 ;i < n_rs ;++ i ) { 1111data [i ]= mctx -> get_recr ()-> s_copy (i ); 1112 } 1113 } 1114} 1115 1116bool llm_graph_input_mem_hybrid::can_reuse (const llm_graph_params & params ) { 1117const auto * mctx = static_cast < const llama_memory_hybrid_context *> (params .mctx ); 1118 1119this -> mctx = mctx ; 1120 1121bool res = true; 1122 1123res &=inp_attn -> self_k_idxs -> ne [0 ]== params .ubatch .n_tokens ; 1124//res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there 1125 1126res &=can_reuse_kq_mask (inp_attn -> self_kq_mask ,mctx -> get_attn (),params .ubatch ,params .cparams ); 1127 1128res &=inp_rs -> s_copy -> ne [0 ]== mctx -> get_recr ()-> get_n_rs (); 1129 1130res &=inp_rs -> s_copy_main -> ne [0 ]== params .ubatch .n_seqs ; 1131res &=inp_rs -> s_copy_extra -> ne [0 ]== mctx -> get_recr ()-> get_n_rs ()- params .ubatch .n_seqs ; 1132 1133res &=inp_rs -> head == mctx -> get_recr ()-> get_head (); 1134res &=inp_rs -> rs_z == mctx -> get_recr ()-> get_rs_z (); 1135 1136return res ; 1137} 1138 1139// TODO: Hybrid input classes are a bit redundant. 1140// Instead of creating a hybrid input, the graph can simply create 2 separate inputs. 1141// Refactoring is required in the future. 1142void llm_graph_input_mem_hybrid_k::set_input (const llama_ubatch * ubatch ) { 1143mctx -> get_attn ()-> set_input_k_idxs (inp_attn -> self_k_idxs ,ubatch ); 1144 1145mctx -> get_attn ()-> set_input_kq_mask (inp_attn -> self_kq_mask ,ubatch ,cparams .causal_attn ); 1146 1147const int64_t n_rs = mctx -> get_recr ()-> get_n_rs (); 1148 1149if (inp_rs -> s_copy ) { 1150GGML_ASSERT (ggml_backend_buffer_is_host (inp_rs -> s_copy -> buffer )); 1151int32_t * data = (int32_t * )inp_rs -> s_copy -> data ; 1152 1153// assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n 1154for (uint32_t i = 0 ;i < n_rs ;++ i ) { 1155data [i ]= mctx -> get_recr ()-> s_copy (i ); 1156 } 1157 } 1158} 1159 1160bool llm_graph_input_mem_hybrid_k::can_reuse (const llm_graph_params & params ) { 1161const auto * mctx = static_cast < const llama_memory_hybrid_context *> (params .mctx ); 1162 1163this -> mctx = mctx ; 1164 1165bool res = true; 1166 1167res &=inp_attn -> self_k_idxs -> ne [0 ]== params .ubatch .n_tokens ; 1168 1169res &=can_reuse_kq_mask (inp_attn -> self_kq_mask ,mctx -> get_attn (),params .ubatch ,params .cparams ); 1170 1171res &=inp_rs -> s_copy -> ne [0 ]== mctx -> get_recr ()-> get_n_rs (); 1172 1173res &=inp_rs -> s_copy_main -> ne [0 ]== params .ubatch .n_seqs ; 1174res &=inp_rs -> s_copy_extra -> ne [0 ]== mctx -> get_recr ()-> get_n_rs ()- params .ubatch .n_seqs ; 1175 1176res &=inp_rs -> head == mctx -> get_recr ()-> get_head (); 1177res &=inp_rs -> rs_z == mctx -> get_recr ()-> get_rs_z (); 1178 1179return res ; 1180} 1181 1182void llm_graph_input_mem_hybrid_iswa::set_input (const llama_ubatch * ubatch ) { 1183const auto * attn_ctx = mctx -> get_attn (); 1184 1185// base tensors may not be allocated if there are no non-SWA attention layers 1186if (inp_attn -> self_k_idxs && inp_attn -> self_k_idxs -> buffer ) { 1187attn_ctx -> get_base ()-> set_input_k_idxs (inp_attn -> self_k_idxs ,ubatch ); 1188attn_ctx -> get_base ()-> set_input_v_idxs (inp_attn -> self_v_idxs ,ubatch ); 1189 } 1190 1191if (inp_attn -> self_kq_mask && inp_attn -> self_kq_mask -> buffer ) { 1192attn_ctx -> get_base ()-> set_input_kq_mask (inp_attn -> self_kq_mask ,ubatch ,cparams .causal_attn ); 1193 } 1194 1195// swa tensors may not be allocated if there are no SWA attention layers 1196if (inp_attn -> self_k_idxs_swa && inp_attn -> self_k_idxs_swa -> buffer ) { 1197attn_ctx -> get_swa ()-> set_input_k_idxs (inp_attn -> self_k_idxs_swa ,ubatch ); 1198attn_ctx -> get_swa ()-> set_input_v_idxs (inp_attn -> self_v_idxs_swa ,ubatch ); 1199 } 1200 1201if (inp_attn -> self_kq_mask_swa && inp_attn -> self_kq_mask_swa -> buffer ) { 1202attn_ctx -> get_swa ()-> set_input_kq_mask (inp_attn -> self_kq_mask_swa ,ubatch ,cparams .causal_attn ); 1203 } 1204 1205if (inp_attn -> self_k_rot ) { 1206attn_ctx -> get_base ()-> set_input_k_rot (inp_attn -> self_k_rot ); 1207 } 1208 1209if (inp_attn -> self_v_rot ) { 1210attn_ctx -> get_base ()-> set_input_v_rot (inp_attn -> self_v_rot ); 1211 } 1212 1213if (inp_attn -> self_k_rot_swa ) { 1214attn_ctx -> get_swa ()-> set_input_k_rot (inp_attn -> self_k_rot_swa ); 1215 } 1216 1217if (inp_attn -> self_v_rot_swa ) { 1218attn_ctx -> get_swa ()-> set_input_v_rot (inp_attn -> self_v_rot_swa ); 1219 } 1220 1221const int64_t n_rs = mctx -> get_recr ()-> get_n_rs (); 1222 1223if (inp_rs -> s_copy ) { 1224GGML_ASSERT (ggml_backend_buffer_is_host (inp_rs -> s_copy -> buffer )); 1225int32_t * data = (int32_t * )inp_rs -> s_copy -> data ; 1226 1227// assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n 1228for (uint32_t i = 0 ;i < n_rs ;++ i ) { 1229data [i ]= mctx -> get_recr ()-> s_copy (i ); 1230 } 1231 } 1232} 1233 1234bool llm_graph_input_mem_hybrid_iswa::can_reuse (const llm_graph_params & params ) { 1235const auto * mctx = static_cast < const llama_memory_hybrid_iswa_context *> (params .mctx ); 1236 1237this -> mctx = mctx ; 1238 1239bool res = true; 1240 1241const auto * attn_ctx = mctx -> get_attn (); 1242 1243// base tensors may not be allocated if there are no non-SWA attention layers 1244if (inp_attn -> self_k_idxs && inp_attn -> self_k_idxs -> buffer ) { 1245res &=inp_attn -> self_k_idxs -> ne [0 ]== params .ubatch .n_tokens ; 1246//res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there 1247 } 1248 1249res &=can_reuse_kq_mask (inp_attn -> self_kq_mask ,attn_ctx -> get_base (),params .ubatch ,params .cparams ); 1250 1251// swa tensors may not be allocated if there are no SWA attention layers 1252if (inp_attn -> self_k_idxs_swa && inp_attn -> self_k_idxs_swa -> buffer ) { 1253res &=inp_attn -> self_k_idxs_swa -> ne [0 ]== params .ubatch .n_tokens ; 1254//res &= inp_attn->self_v_idxs_swa->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there 1255 } 1256 1257res &=can_reuse_kq_mask (inp_attn -> self_kq_mask_swa ,attn_ctx -> get_swa (),params .ubatch ,params .cparams ); 1258 1259res &=inp_rs -> s_copy -> ne [0 ]== mctx -> get_recr ()-> get_n_rs (); 1260 1261res &=inp_rs -> s_copy_main -> ne [0 ]== params .ubatch .n_seqs ; 1262res &=inp_rs -> s_copy_extra -> ne [0 ]== mctx -> get_recr ()-> get_n_rs ()- params .ubatch .n_seqs ; 1263 1264res &=inp_rs -> head == mctx -> get_recr ()-> get_head (); 1265res &=inp_rs -> rs_z == mctx -> get_recr ()-> get_rs_z (); 1266 1267return res ; 1268} 1269 1270void llm_graph_input_sampling::set_input (const llama_ubatch * ubatch ) { 1271// set the inputs only for the active samplers in the current ubatch 1272 std::unordered_set < llama_seq_id > active_samplers ; 1273for (uint32_t i = 0 ;i < ubatch -> n_tokens ;i ++ ) { 1274if (ubatch -> output [i ]) { 1275llama_seq_id seq_id = ubatch -> seq_id [i ][0 ]; 1276active_samplers .insert (seq_id ); 1277 } 1278 } 1279 1280for (auto seq_id :active_samplers ) { 1281if (samplers .find (seq_id )== samplers .end ()) { 1282continue ; 1283 } 1284 1285auto & sampler = samplers [seq_id ]; 1286 1287if (sampler -> iface -> backend_set_input ) { 1288sampler -> iface -> backend_set_input (sampler ); 1289 } 1290 } 1291} 1292 1293bool llm_graph_input_sampling::can_reuse (const llm_graph_params & params ) { 1294if (samplers .size ()!= params .samplers .size ()) { 1295return false; 1296 } 1297 1298for (const auto & [seq_id ,sampler ] :params .samplers ) { 1299if (samplers [seq_id ]!= sampler ) { 1300return false; 1301 } 1302 } 1303 1304return true; 1305} 1306 1307// 1308// llm_graph_result 1309// 1310 1311llm_graph_result::llm_graph_result (int64_t max_nodes ) :max_nodes (max_nodes ) { 1312reset (); 1313 1314const char * LLAMA_GRAPH_RESULT_DEBUG = getenv ("LLAMA_GRAPH_RESULT_DEBUG" ); 1315debug = LLAMA_GRAPH_RESULT_DEBUG ?atoi (LLAMA_GRAPH_RESULT_DEBUG ) :0 ; 1316} 1317 1318int64_t llm_graph_result::get_max_nodes ()const { 1319return max_nodes ; 1320} 1321 1322void llm_graph_result::reset () { 1323t_inp_tokens = nullptr ; 1324t_inp_embd = nullptr ; 1325t_logits = nullptr ; 1326t_embd = nullptr ; 1327t_embd_pooled = nullptr ; 1328t_h_nextn = nullptr ; 1329 1330t_layer_inp .resize (LLAMA_MAX_LAYERS + 1 ); 1331 std::fill (t_layer_inp .begin (),t_layer_inp .end (),nullptr ); 1332 1333t_sampled .clear (); 1334t_sampled_probs .clear (); 1335t_sampled_logits .clear (); 1336t_candidates .clear (); 1337 1338params = {}; 1339 1340inputs .clear (); 1341fused_nodes .clear (); 1342 1343buf_compute_meta .resize (ggml_tensor_overhead ()* max_nodes + ggml_graph_overhead_custom (max_nodes , false)); 1344 1345ggml_init_params params = { 1346/*.mem_size =*/ buf_compute_meta .size (), 1347/*.mem_buffer =*/ buf_compute_meta .data (), 1348/*.no_alloc =*/ true, 1349 }; 1350 1351ctx_compute .reset (ggml_init (params )); 1352 1353gf = ggml_new_graph_custom (ctx_compute .get (),max_nodes , false); 1354} 1355 1356void llm_graph_result::set_inputs (const llama_ubatch * ubatch ) { 1357for (auto & input :inputs ) { 1358input -> set_input (ubatch ); 1359 } 1360} 1361 1362void llm_graph_result::set_outputs (const llm_graph_params & params ) { 1363if (t_logits != nullptr ) { 1364ggml_set_output (t_logits ); 1365 } 1366if (t_embd != nullptr ) { 1367ggml_set_output (t_embd ); 1368 } 1369if (t_embd_pooled != nullptr ) { 1370ggml_set_output (t_embd_pooled ); 1371 } 1372if (t_h_nextn != nullptr ) { 1373ggml_set_output (t_h_nextn ); 1374 } 1375 { 1376const auto & embeddings_layer_inp = params .cparams .embeddings_layer_inp ; 1377for (size_t il = 0 ;il < embeddings_layer_inp .size ();++ il ) { 1378if (embeddings_layer_inp [il ]) { 1379GGML_ASSERT (t_layer_inp [il ]!= nullptr && "layer input tensor is null" ); 1380ggml_set_output (t_layer_inp [il ]); 1381 } 1382 } 1383 } 1384for (auto * tensor :t_sampled ) { 1385if (tensor != nullptr ) { 1386ggml_set_output (tensor ); 1387 } 1388 } 1389for (auto * tensor :t_sampled_probs ) { 1390if (tensor != nullptr ) { 1391ggml_set_output (tensor ); 1392 } 1393 } 1394for (auto * tensor :t_sampled_logits ) { 1395if (tensor != nullptr ) { 1396ggml_set_output (tensor ); 1397 } 1398 } 1399for (auto * tensor :t_candidates ) { 1400if (tensor != nullptr ) { 1401ggml_set_output (tensor ); 1402 } 1403 } 1404} 1405 1406bool llm_graph_result::can_reuse (const llm_graph_params & params ) { 1407if (!this -> params .allow_reuse (params )) { 1408if (debug > 1 ) { 1409LLAMA_LOG_DEBUG ("%s: cannot reuse graph due to incompatible graph parameters\n" ,__func__ ); 1410 } 1411 1412return false; 1413 } 1414 1415if (debug > 1 ) { 1416LLAMA_LOG_DEBUG ("%s: checking compatibility of %d inputs:\n" ,__func__ , (int )inputs .size ()); 1417 } 1418 1419bool res = true; 1420 1421for (auto & input :inputs ) { 1422const bool cur = input -> can_reuse (params ); 1423 1424if (debug > 1 ) { 1425LLAMA_LOG_DEBUG ("%s: can_reuse = %d\n" ,"placeholder" ,cur ); 1426 } 1427 1428res = res && cur ; 1429 } 1430 1431if (debug > 0 ) { 1432LLAMA_LOG_DEBUG ("%s: can reuse graph = %d\n" ,__func__ ,res ); 1433 } 1434 1435return res ; 1436} 1437 1438llm_graph_input_i * llm_graph_result::add_input (llm_graph_input_ptr input ) { 1439inputs .emplace_back (std::move (input )); 1440return inputs .back ().get (); 1441} 1442 1443void llm_graph_result::add_fused_node (llm_graph_fused_node result ) { 1444fused_nodes .push_back (result ); 1445} 1446 1447void llm_graph_result::set_params (const llm_graph_params & params ) { 1448this -> params = params ; 1449} 1450 1451// 1452// llm_graph_context 1453// 1454 1455llm_graph_context::llm_graph_context (const llm_graph_params & params ) : 1456arch (params .arch ), 1457hparams (params .hparams ), 1458cparams (params .cparams ), 1459ubatch (params .ubatch ), 1460n_embd (hparams .n_embd ), 1461n_layer (hparams .n_layer ()), 1462n_layer_nextn (hparams .n_layer_nextn ), 1463n_rot (hparams .n_rot ()), 1464n_ctx (cparams .n_ctx ), 1465n_head (hparams .n_head ()), 1466n_head_kv (hparams .n_head_kv ()), 1467n_embd_head_k (hparams .n_embd_head_k ()), 1468n_embd_k_gqa (hparams .n_embd_k_gqa ()), 1469n_embd_head_v (hparams .n_embd_head_v ()), 1470n_embd_v_gqa (hparams .n_embd_v_gqa ()), 1471n_expert (hparams .n_expert ), 1472n_expert_used (cparams .warmup ?hparams .n_expert :hparams .n_expert_used ()), 1473freq_base (cparams .rope_freq_base ), 1474freq_scale (cparams .rope_freq_scale ), 1475ext_factor (cparams .yarn_ext_factor ), 1476attn_factor (cparams .yarn_attn_factor ), 1477beta_fast (cparams .yarn_beta_fast ), 1478beta_slow (cparams .yarn_beta_slow ), 1479norm_eps (hparams .f_norm_eps ), 1480norm_rms_eps (hparams .f_norm_rms_eps ), 1481n_tokens (ubatch .n_tokens ), 1482n_outputs (params .n_outputs ), 1483n_ctx_orig (cparams .n_ctx_orig_yarn ), 1484pooling_type (cparams .pooling_type ), 1485rope_type (hparams .rope_type ), 1486sched (params .sched ), 1487backend_cpu (params .backend_cpu ), 1488cvec (params .cvec ), 1489loras (params .loras ), 1490mctx (params .mctx ), 1491cross (params .cross ), 1492samplers (params .samplers ), 1493cb_func (params .cb ), 1494res (params .res ), 1495ctx0 (res -> get_ctx ()), 1496gf (res -> get_gf ()) { 1497res -> set_params (params ); 1498 } 1499 1500void llm_graph_context::cb (ggml_tensor * cur ,const char * name ,int il )const { 1501if (cb_func ) { 1502cb_func (ubatch ,cur ,name ,il ); 1503 } 1504} 1505 1506 1507 1508ggml_tensor * llm_graph_context::build_cvec ( 1509ggml_tensor * cur , 1510int il )const { 1511return cvec -> apply_to (ctx0 ,cur ,il ); 1512} 1513 1514ggml_tensor * llm_graph_context::build_lora_mm ( 1515ggml_tensor * w , 1516ggml_tensor * cur , 1517ggml_tensor * w_s )const { 1518ggml_tensor * res = ggml_mul_mat (ctx0 ,w ,cur ); 1519 1520if (w_s ) { 1521res = ggml_mul (ctx0 ,res ,w_s ); 1522 } 1523 1524for (const auto & lora :* loras ) { 1525llama_adapter_lora_weight * lw = lora .first -> get_weight (w ); 1526if (lw == nullptr ) { 1527continue ; 1528 } 1529 1530const float adapter_scale = lora .second ; 1531const float scale = lw -> get_scale (lora .first -> alpha ,adapter_scale ); 1532 1533ggml_tensor * ab_cur = ggml_mul_mat ( 1534ctx0 ,lw -> b , 1535ggml_mul_mat (ctx0 ,lw -> a ,cur ) 1536 ); 1537 1538ab_cur = ggml_scale (ctx0 ,ab_cur ,scale ); 1539res = ggml_add (ctx0 ,res ,ab_cur ); 1540 } 1541 1542return res ; 1543} 1544 1545ggml_tensor * llm_graph_context::build_lora_mm_id ( 1546ggml_tensor * w ,// ggml_tensor * as 1547ggml_tensor * cur ,// ggml_tensor * b 1548ggml_tensor * ids , 1549ggml_tensor * w_s )const { 1550ggml_tensor * res = ggml_mul_mat_id (ctx0 ,w ,cur ,ids ); 1551 1552if (w_s ) { 1553const int64_t n_expert = w_s -> ne [0 ]; 1554const int64_t n_tokens = cur -> ne [2 ]; 1555ggml_tensor * s = ggml_reshape_3d (ctx0 ,w_s ,1 ,n_expert ,1 ); 1556s = ggml_repeat_4d (ctx0 ,s ,1 ,n_expert ,n_tokens ,1 ); 1557s = ggml_get_rows (ctx0 ,s ,ids ); 1558res = ggml_mul (ctx0 ,res ,s ); 1559 } 1560for (const auto & lora :* loras ) { 1561llama_adapter_lora_weight * lw = lora .first -> get_weight (w ); 1562if (lw == nullptr ) { 1563continue ; 1564 } 1565 1566const float alpha = lora .first -> alpha ; 1567const float rank = (float )lw -> b -> ne [0 ]; 1568const float scale = alpha ?lora .second * alpha /rank :lora .second ; 1569 1570ggml_tensor * ab_cur = ggml_mul_mat_id ( 1571ctx0 ,lw -> b , 1572ggml_mul_mat_id (ctx0 ,lw -> a ,cur ,ids ), 1573ids 1574 ); 1575 1576ab_cur = ggml_scale (ctx0 ,ab_cur ,scale ); 1577res = ggml_add (ctx0 ,res ,ab_cur ); 1578 } 1579 1580return res ; 1581} 1582 1583ggml_tensor * llm_graph_context::build_norm ( 1584ggml_tensor * cur , 1585ggml_tensor * mw , 1586ggml_tensor * mb , 1587llm_norm_type type , 1588int il )const { 1589switch (type ) { 1590case LLM_NORM :cur = ggml_norm (ctx0 ,cur ,hparams .f_norm_eps );break ; 1591case LLM_NORM_RMS :cur = ggml_rms_norm (ctx0 ,cur ,hparams .f_norm_rms_eps );break ; 1592case LLM_NORM_GROUP : 1593 { 1594cur = ggml_reshape_3d (ctx0 ,cur ,cur -> ne [0 ],1 ,cur -> ne [1 ]); 1595cur = ggml_group_norm (ctx0 ,cur ,hparams .n_norm_groups ,hparams .f_norm_group_eps ); 1596cur = ggml_reshape_2d (ctx0 ,cur ,cur -> ne [0 ],cur -> ne [2 ]); 1597 }break ; 1598 } 1599 1600if (mw || mb ) { 1601cb (cur ,"norm" ,il ); 1602 } 1603 1604if (mw ) { 1605cur = ggml_mul (ctx0 ,cur ,mw ); 1606if (mb ) { 1607cb (cur ,"norm_w" ,il ); 1608 } 1609 } 1610 1611if (mb ) { 1612cur = ggml_add (ctx0 ,cur ,mb ); 1613 } 1614 1615return cur ; 1616} 1617 1618 1619llm_graph_qkv llm_graph_context::build_qkv ( 1620const llama_layer & layer , 1621ggml_tensor * cur , 1622int64_t n_embd_head , 1623int64_t n_head , 1624int64_t n_head_kv , 1625int il )const { 1626return build_qkv (layer ,cur , 1627n_embd_head ,n_head , 1628n_embd_head ,n_head_kv , 1629n_embd_head ,n_head_kv , 1630il ); 1631} 1632 1633llm_graph_qkv llm_graph_context::build_qkv ( 1634const llama_layer & layer , 1635ggml_tensor * cur , 1636int64_t n_embd_head_q , 1637int64_t n_head_q , 1638int64_t n_embd_head_k , 1639int64_t n_head_k , 1640int64_t n_embd_head_v , 1641int64_t n_head_v , 1642int il , 1643bool reshape )const { 1644const int64_t n_embd_q = n_embd_head_q * n_head_q ; 1645const int64_t n_embd_k = n_embd_head_k * n_head_k ; 1646 1647ggml_tensor * Qcur ,* Kcur ,* Vcur ; 1648 1649if (layer .wqkv ) { 1650// fused QKV path 1651ggml_tensor * qkv = build_lora_mm (layer .wqkv ,cur ,layer .wqkv_s ); 1652cb (qkv ,"wqkv" ,il ); 1653if (layer .wqkv_b ) { 1654qkv = ggml_add (ctx0 ,qkv ,layer .wqkv_b ); 1655cb (qkv ,"wqkv_b" ,il ); 1656 }else if (layer .wq_b && layer .wk_b && layer .wv_b ) { 1657// Fused weights may coexist with separate Q/K/V biases in legacy or custom GGUFs. 1658ggml_tensor * qkv_b = ggml_concat (ctx0 ,ggml_concat (ctx0 ,layer .wq_b ,layer .wk_b ,0 ),layer .wv_b ,0 ); 1659qkv = ggml_add (ctx0 ,qkv ,qkv_b ); 1660cb (qkv ,"wqkv_b" ,il ); 1661 } 1662if (reshape && hparams .f_clamp_kqv > 0.0f ) { 1663qkv = ggml_clamp (ctx0 ,qkv ,- hparams .f_clamp_kqv ,hparams .f_clamp_kqv ); 1664cb (qkv ,"wqkv_clamped" ,il ); 1665 } 1666if (reshape ) { 1667Qcur = ggml_view_3d (ctx0 ,qkv ,n_embd_head_q ,n_head_q ,n_tokens , 1668ggml_row_size (qkv -> type ,n_embd_head_q ),qkv -> nb [1 ],0 ); 1669Kcur = ggml_view_3d (ctx0 ,qkv ,n_embd_head_k ,n_head_k ,n_tokens , 1670ggml_row_size (qkv -> type ,n_embd_head_k ),qkv -> nb [1 ], 1671ggml_row_size (qkv -> type ,n_embd_q )); 1672Vcur = ggml_view_3d (ctx0 ,qkv ,n_embd_head_v ,n_head_v ,n_tokens , 1673ggml_row_size (qkv -> type ,n_embd_head_v ),qkv -> nb [1 ], 1674ggml_row_size (qkv -> type ,n_embd_q + n_embd_k )); 1675 }else { 1676Qcur = ggml_view_2d (ctx0 ,qkv ,n_embd_q ,n_tokens ,qkv -> nb [1 ],0 ); 1677Kcur = ggml_view_2d (ctx0 ,qkv ,n_embd_k ,n_tokens ,qkv -> nb [1 ], 1678ggml_row_size (qkv -> type ,n_embd_q )); 1679Vcur = ggml_view_2d (ctx0 ,qkv ,n_embd_head_v * n_head_v ,n_tokens ,qkv -> nb [1 ], 1680ggml_row_size (qkv -> type ,n_embd_q + n_embd_k )); 1681 } 1682if (!reshape ) { 1683Qcur = ggml_cont (ctx0 ,Qcur ); 1684Kcur = ggml_cont (ctx0 ,Kcur ); 1685Vcur = ggml_cont (ctx0 ,Vcur ); 1686 } 1687 }else { 1688// separate Q/K/V path 1689Qcur = build_lora_mm (layer .wq ,cur ,layer .wq_s ); 1690if (reshape ) { 1691cb (Qcur ,"Qcur" ,il ); 1692 } 1693if (layer .wq_b ) { 1694Qcur = ggml_add (ctx0 ,Qcur ,layer .wq_b ); 1695if (reshape ) { 1696cb (Qcur ,"Qcur" ,il ); 1697 } 1698 } 1699if (reshape && hparams .f_clamp_kqv > 0.0f ) { 1700Qcur = ggml_clamp (ctx0 ,Qcur ,- hparams .f_clamp_kqv ,hparams .f_clamp_kqv ); 1701cb (Qcur ,"Qcur_clamped" ,il ); 1702 } 1703Kcur = build_lora_mm (layer .wk ,cur ,layer .wk_s ); 1704if (reshape ) { 1705cb (Kcur ,"Kcur" ,il ); 1706 } 1707if (layer .wk_b ) { 1708Kcur = ggml_add (ctx0 ,Kcur ,layer .wk_b ); 1709if (reshape ) { 1710cb (Kcur ,"Kcur" ,il ); 1711 } 1712 } 1713if (reshape && hparams .f_clamp_kqv > 0.0f ) { 1714Kcur = ggml_clamp (ctx0 ,Kcur ,- hparams .f_clamp_kqv ,hparams .f_clamp_kqv ); 1715cb (Kcur ,"Kcur_clamped" ,il ); 1716 } 1717Vcur = build_lora_mm (layer .wv ,cur ,layer .wv_s ); 1718if (reshape ) { 1719cb (Vcur ,"Vcur" ,il ); 1720 } 1721if (layer .wv_b ) { 1722Vcur = ggml_add (ctx0 ,Vcur ,layer .wv_b ); 1723if (reshape ) { 1724cb (Vcur ,"Vcur" ,il ); 1725 } 1726 } 1727if (reshape && hparams .f_clamp_kqv > 0.0f ) { 1728Vcur = ggml_clamp (ctx0 ,Vcur ,- hparams .f_clamp_kqv ,hparams .f_clamp_kqv ); 1729cb (Vcur ,"Vcur_clamped" ,il ); 1730 } 1731if (reshape ) { 1732Qcur = ggml_reshape_3d (ctx0 ,Qcur ,n_embd_head_q ,n_head_q ,n_tokens ); 1733Kcur = ggml_reshape_3d (ctx0 ,Kcur ,n_embd_head_k ,n_head_k ,n_tokens ); 1734Vcur = ggml_reshape_3d (ctx0 ,Vcur ,n_embd_head_v ,n_head_v ,n_tokens ); 1735 } 1736 } 1737 1738if (reshape ) { 1739cb (Qcur ,"Qcur" ,il ); 1740cb (Kcur ,"Kcur" ,il ); 1741cb (Vcur ,"Vcur" ,il ); 1742 } 1743 1744return {Qcur ,Kcur ,Vcur }; 1745} 1746 1747 1748ggml_tensor * llm_graph_context::build_ffn ( 1749ggml_tensor * cur , 1750ggml_tensor * up , 1751ggml_tensor * up_b , 1752ggml_tensor * up_s , 1753ggml_tensor * gate , 1754ggml_tensor * gate_b , 1755ggml_tensor * gate_s , 1756ggml_tensor * down , 1757ggml_tensor * down_b , 1758ggml_tensor * down_s , 1759ggml_tensor * act_scales , 1760llm_ffn_op_type type_op , 1761llm_ffn_gate_type type_gate , 1762int il )const { 1763// NVFP4 support is currently restricted to 1764// 1) LORA absence (*_s would be applied after LORA residual, which is incorrect) 1765// 2) bias absense (*_s would be applied after bias addition, which is incorrect) 1766// TODO: disambiguate LLM-architectural scales (which use *_s) from NVFP4 scale_2 (which also uses *_s currently) 1767auto has_lora = [this ](ggml_tensor * w ) { 1768if (!w ) { 1769return false; 1770 } 1771for (const auto & lora :* loras ) { 1772if (lora .first -> get_weight (w )!= nullptr ) { 1773return true; 1774 } 1775 } 1776return false; 1777 }; 1778 1779GGML_ASSERT (!up_s || !up_b || !up || up -> type != GGML_TYPE_NVFP4 ); 1780GGML_ASSERT (!gate_s || !gate_b || !gate || gate -> type != GGML_TYPE_NVFP4 ); 1781GGML_ASSERT (!down_s || !down_b || !down || down -> type != GGML_TYPE_NVFP4 ); 1782GGML_ASSERT (!up_s || !up || up -> type != GGML_TYPE_NVFP4 || !has_lora (up )); 1783GGML_ASSERT (!gate_s || !gate || gate -> type != GGML_TYPE_NVFP4 || !has_lora (gate )); 1784GGML_ASSERT (!down_s || !down || down -> type != GGML_TYPE_NVFP4 || !has_lora (down )); 1785 1786ggml_tensor * tmp = up ?build_lora_mm (up ,cur ) :cur ; 1787cb (tmp ,"ffn_up" ,il ); 1788 1789if (up_b ) { 1790tmp = ggml_add (ctx0 ,tmp ,up_b ); 1791cb (tmp ,"ffn_up_b" ,il ); 1792 } 1793 1794if (up_s ) { 1795tmp = ggml_mul (ctx0 ,tmp ,up_s ); 1796cb (tmp ,"ffn_up_s" ,il ); 1797 } 1798 1799if (gate ) { 1800switch (type_gate ) { 1801case LLM_FFN_SEQ : 1802 { 1803cur = build_lora_mm (gate ,tmp ); 1804cb (cur ,"ffn_gate" ,il ); 1805 }break ; 1806case LLM_FFN_PAR : 1807 { 1808cur = build_lora_mm (gate ,cur ); 1809cb (cur ,"ffn_gate" ,il ); 1810 }break ; 1811 } 1812 1813if (gate_b ) { 1814cur = ggml_add (ctx0 ,cur ,gate_b ); 1815cb (cur ,"ffn_gate_b" ,il ); 1816 } 1817 1818if (gate_s ) { 1819cur = ggml_mul (ctx0 ,cur ,gate_s ); 1820cb (cur ,"ffn_gate_s" ,il ); 1821 } 1822 1823 }else { 1824cur = tmp ; 1825 } 1826 1827switch (type_op ) { 1828case LLM_FFN_SILU : 1829if (gate && type_gate == LLM_FFN_PAR ) { 1830if (il >=0 ) { 1831const float limit = hparams .swiglu_clamp_shexp [il ]; 1832constexpr float eps = 1e-6f ; 1833if (limit > eps ) { 1834if (arch == LLM_ARCH_DEEPSEEK4 || (arch == LLM_ARCH_DFLASH && hparams .dsv4_hc_mult > 0 )) { 1835cur = ggml_swiglu_clamp (ctx0 ,cur ,tmp ,limit ); 1836 }else { 1837tmp = ggml_clamp (ctx0 ,tmp ,- limit ,limit ); 1838cb (tmp ,"ffn_up_clamped" ,il ); 1839ggml_tensor * gate_act = ggml_silu (ctx0 ,cur ); 1840cb (gate_act ,"ffn_silu" ,il ); 1841gate_act = ggml_clamp (ctx0 ,gate_act ,- INFINITY ,limit ); 1842cb (gate_act ,"ffn_silu_clamped" ,il ); 1843cur = ggml_mul (ctx0 ,gate_act ,tmp ); 1844 } 1845cb (cur ,"ffn_swiglu_limited" ,il ); 1846type_gate = LLM_FFN_SEQ ; 1847break ; 1848 } 1849 } 1850 1851cur = ggml_swiglu_split (ctx0 ,cur ,tmp ); 1852cb (cur ,"ffn_swiglu" ,il ); 1853type_gate = LLM_FFN_SEQ ; 1854 }else { 1855cur = ggml_silu (ctx0 ,cur ); 1856cb (cur ,"ffn_silu" ,il ); 1857 }break ; 1858case LLM_FFN_GELU : 1859if (gate && type_gate == LLM_FFN_PAR ) { 1860cur = ggml_geglu_split (ctx0 ,cur ,tmp ); 1861cb (cur ,"ffn_geglu" ,il ); 1862type_gate = LLM_FFN_SEQ ; 1863 }else { 1864cur = ggml_gelu (ctx0 ,cur ); 1865cb (cur ,"ffn_gelu" ,il ); 1866if (act_scales != NULL ) { 1867cur = ggml_div (ctx0 ,cur ,act_scales ); 1868cb (cur ,"ffn_act" ,il ); 1869 } 1870 }break ; 1871case LLM_FFN_RELU : 1872if (gate && type_gate == LLM_FFN_PAR ) { 1873cur = ggml_reglu_split (ctx0 ,cur ,tmp ); 1874cb (cur ,"ffn_reglu" ,il ); 1875type_gate = LLM_FFN_SEQ ; 1876 }else { 1877cur = ggml_relu (ctx0 ,cur ); 1878cb (cur ,"ffn_relu" ,il ); 1879 }break ; 1880case LLM_FFN_RELU_SQR : 1881 { 1882cur = ggml_relu (ctx0 ,cur ); 1883cb (cur ,"ffn_relu" ,il ); 1884 1885cur = ggml_sqr (ctx0 ,cur ); 1886cb (cur ,"ffn_sqr(relu)" ,il ); 1887 }break ; 1888case LLM_FFN_SWIGLU : 1889 { 1890cur = ggml_swiglu (ctx0 ,cur ); 1891cb (cur ,"ffn_swiglu" ,il ); 1892 }break ; 1893case LLM_FFN_SWIGLU_OAI_MOE : 1894if (gate && type_gate == LLM_FFN_PAR ) { 1895// same alpha/limit constants as gpt-oss 1896const float alpha = 1.702f ; 1897const float limit = 7.0f ; 1898cur = ggml_swiglu_oai (ctx0 ,cur ,tmp ,alpha ,limit ); 1899cb (cur ,"ffn_swiglu_oai" ,il ); 1900type_gate = LLM_FFN_SEQ ; 1901 }else { 1902GGML_ABORT ("LLM_FFN_SWIGLU_OAI_MOE requires a parallel gate" ); 1903 }break ; 1904case LLM_FFN_GEGLU : 1905 { 1906cur = ggml_geglu (ctx0 ,cur ); 1907cb (cur ,"ffn_geglu" ,il ); 1908 }break ; 1909case LLM_FFN_REGLU : 1910 { 1911cur = ggml_reglu (ctx0 ,cur ); 1912cb (cur ,"ffn_reglu" ,il ); 1913 }break ; 1914case LLM_FFN_SITU : 1915GGML_ABORT ("not yet supported" ); 1916default : 1917GGML_ABORT ("fatal error" ); 1918 } 1919 1920if (gate && type_gate == LLM_FFN_PAR ) { 1921cur = ggml_mul (ctx0 ,cur ,tmp ); 1922cb (cur ,"ffn_gate_par" ,il ); 1923 } 1924 1925if (down ) { 1926cur = build_lora_mm (down ,cur ); 1927if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2 ) { 1928// GLM4, GLM4_MOE, and JAIS2 seem to have numerical issues with half-precision accumulators 1929ggml_prec_set_acc (cur ,GGML_PREC_F32 ); 1930 } 1931 } 1932 1933if (down_b ) { 1934cb (cur ,"ffn_down" ,il ); 1935 } 1936 1937if (down_b ) { 1938cur = ggml_add (ctx0 ,cur ,down_b ); 1939 } 1940 1941if (down_s ) { 1942cur = ggml_mul (ctx0 ,cur ,down_s ); 1943cb (cur ,"ffn_down_s" ,il ); 1944 } 1945 1946return cur ; 1947} 1948 1949ggml_tensor * llm_graph_context::build_moe_ffn ( 1950ggml_tensor * cur , 1951ggml_tensor * gate_inp , 1952ggml_tensor * up_exps , 1953ggml_tensor * gate_exps , 1954ggml_tensor * down_exps , 1955ggml_tensor * exp_probs_b , 1956int64_t n_expert , 1957int64_t n_expert_used , 1958llm_ffn_op_type type_op , 1959bool norm_w , 1960float w_scale , 1961llama_expert_gating_func_type gating_op , 1962int il , 1963ggml_tensor * probs_in , 1964ggml_tensor * gate_up_exps , 1965ggml_tensor * up_exps_s , 1966ggml_tensor * gate_exps_s , 1967ggml_tensor * down_exps_s , 1968ggml_tensor * selected_experts_in )const { 1969return build_moe_ffn ( 1970cur , 1971gate_inp ,/* gate_inp_b */ nullptr , 1972up_exps ,/* up_exps_b */ nullptr , 1973gate_exps ,/* gate_exps_b */ nullptr , 1974down_exps ,/* down_exps_b */ nullptr , 1975exp_probs_b , 1976n_expert , 1977n_expert_used , 1978type_op , 1979norm_w , 1980w_scale , 1981gating_op , 1982il , 1983probs_in , 1984gate_up_exps , 1985/* gate_up_exps_b */ nullptr , 1986up_exps_s , 1987gate_exps_s , 1988down_exps_s , 1989selected_experts_in 1990 ); 1991} 1992 1993ggml_tensor * llm_graph_context::build_moe_ffn ( 1994ggml_tensor * cur , 1995ggml_tensor * gate_inp , 1996ggml_tensor * gate_inp_b , 1997ggml_tensor * up_exps , 1998ggml_tensor * up_exps_b , 1999ggml_tensor * gate_exps , 2000ggml_tensor * gate_exps_b , 2001ggml_tensor * down_exps , 2002ggml_tensor * down_exps_b , 2003ggml_tensor * exp_probs_b , 2004int64_t n_expert , 2005int64_t n_expert_used , 2006llm_ffn_op_type type_op , 2007bool norm_w , 2008float w_scale , 2009llama_expert_gating_func_type gating_op , 2010int il , 2011ggml_tensor * probs_in , 2012ggml_tensor * gate_up_exps , 2013ggml_tensor * gate_up_exps_b , 2014ggml_tensor * up_exps_s , 2015ggml_tensor * gate_exps_s , 2016ggml_tensor * down_exps_s , 2017ggml_tensor * selected_experts_in )const { 2018const int64_t n_embd = cur -> ne [0 ]; 2019const int64_t n_tokens = cur -> ne [1 ]; 2020const bool weight_before_ffn = arch == LLM_ARCH_LLAMA4 ;// for llama4, we apply the sigmoid-ed weights before the FFN 2021 2022ggml_tensor * logits = nullptr ; 2023 2024if (probs_in == nullptr ) { 2025logits = build_lora_mm (gate_inp ,cur );// [n_expert, n_tokens] 2026if (gating_op == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS ) { 2027ggml_prec_set_acc (logits ,GGML_PREC_F32 ); 2028 } 2029cb (logits ,"ffn_moe_logits" ,il ); 2030 }else { 2031logits = probs_in ; 2032 } 2033 2034if (gate_inp_b ) { 2035logits = ggml_add (ctx0 ,logits ,gate_inp_b ); 2036cb (logits ,"ffn_moe_logits_biased" ,il ); 2037 } 2038 2039ggml_tensor * probs = nullptr ; 2040switch (gating_op ) { 2041case LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX : 2042 { 2043probs = ggml_soft_max (ctx0 ,logits );// [n_expert, n_tokens] 2044 }break ; 2045case LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID : 2046 { 2047probs = ggml_sigmoid (ctx0 ,logits );// [n_expert, n_tokens] 2048 }break ; 2049case LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX_WEIGHT : 2050 { 2051probs = logits ;// [n_expert, n_tokens] 2052 }break ; 2053case LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS : 2054 { 2055probs = ggml_sqrt (ctx0 ,ggml_softplus (ctx0 ,logits ));// [n_expert, n_tokens] 2056 }break ; 2057default : 2058GGML_ABORT ("fatal error" ); 2059 } 2060cb (probs ,"ffn_moe_probs" ,il ); 2061 2062// add experts selection bias - introduced in DeepSeek V3 2063// leave probs unbiased as it's later used to get expert weights 2064ggml_tensor * selection_probs = probs ; 2065if (exp_probs_b != nullptr ) { 2066selection_probs = ggml_add (ctx0 ,probs ,exp_probs_b ); 2067cb (selection_probs ,"ffn_moe_probs_biased" ,il ); 2068 } 2069 2070// llama4 doesn't have exp_probs_b, and sigmoid is only used after top_k 2071// see: https://github.com/meta-llama/llama-models/blob/699a02993512fb36936b1b0741e13c06790bcf98/models/llama4/moe.py#L183-L198 2072if (arch == LLM_ARCH_LLAMA4 ) { 2073selection_probs = logits ; 2074 } 2075 2076if (arch == LLM_ARCH_GROVEMOE ) { 2077selection_probs = ggml_sigmoid (ctx0 ,logits );// [n_expert, n_tokens] 2078cb (selection_probs ,"ffn_moe_probs_biased" ,il ); 2079 } 2080 2081// select top n_group_used expert groups 2082// https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/e815299b0bcbac849fa540c768ef21845365c9eb/modeling_deepseek.py#L440-L457 2083if (hparams .n_expert_groups > 1 && n_tokens > 0 ) { 2084const int64_t n_exp_per_group = n_expert /hparams .n_expert_groups ; 2085 2086// organize experts into n_expert_groups 2087ggml_tensor * selection_groups = ggml_reshape_3d (ctx0 ,selection_probs ,n_exp_per_group ,hparams .n_expert_groups ,n_tokens );// [n_exp_per_group, n_expert_groups, n_tokens] 2088 2089ggml_tensor * group_scores = ggml_argsort_top_k (ctx0 ,selection_groups ,2 );// [2, n_expert_groups, n_tokens] 2090group_scores = ggml_get_rows (ctx0 ,ggml_reshape_4d (ctx0 ,selection_groups ,1 ,selection_groups -> ne [0 ],selection_groups -> ne [1 ],selection_groups -> ne [2 ]),group_scores );// [1, 2, n_expert_groups, n_tokens] 2091 2092// get top n_group_used expert groups 2093group_scores = ggml_sum_rows (ctx0 ,ggml_reshape_3d (ctx0 ,group_scores ,group_scores -> ne [1 ],group_scores -> ne [2 ],group_scores -> ne [3 ]));// [1, n_expert_groups, n_tokens] 2094group_scores = ggml_reshape_2d (ctx0 ,group_scores ,group_scores -> ne [1 ],group_scores -> ne [2 ]);// [n_expert_groups, n_tokens] 2095 2096ggml_tensor * expert_groups = ggml_argsort_top_k (ctx0 ,group_scores ,hparams .n_group_used );// [n_group_used, n_tokens] 2097cb (expert_groups ,"ffn_moe_group_topk" ,il ); 2098 2099// mask out the other groups 2100selection_probs = ggml_get_rows (ctx0 ,selection_groups ,expert_groups );// [n_exp_per_group, n_group_used, n_tokens] 2101selection_probs = ggml_set_rows (ctx0 ,ggml_fill (ctx0 ,selection_groups ,- INFINITY ),selection_probs ,expert_groups );// [n_exp_per_group, n_expert_groups, n_tokens] 2102selection_probs = ggml_reshape_2d (ctx0 ,selection_probs ,n_expert ,n_tokens );// [n_expert, n_tokens] 2103cb (selection_probs ,"ffn_moe_probs_masked" ,il ); 2104 } 2105 2106// select experts 2107ggml_tensor * selected_experts = selected_experts_in ; 2108if (selected_experts == nullptr ) { 2109selected_experts = ggml_argsort_top_k (ctx0 ,selection_probs ,n_expert_used );// [n_expert_used, n_tokens] 2110cb (selected_experts -> src [0 ],"ffn_moe_argsort" ,il ); 2111 } 2112cb (selected_experts ,"ffn_moe_topk" ,il ); 2113 2114if (arch == LLM_ARCH_GROVEMOE && n_expert != hparams .n_expert ) { 2115// TODO: Use scalar div instead when/if implemented 2116ggml_tensor * f_sel = ggml_cast (ctx0 ,selected_experts ,GGML_TYPE_F32 ); 2117selected_experts = ggml_cast (ctx0 ,ggml_scale (ctx0 ,f_sel ,1.0f /float (hparams .n_group_experts )),GGML_TYPE_I32 ); 2118probs = ggml_reshape_3d (ctx0 ,probs ,1 ,hparams .n_expert ,n_tokens ); 2119 }else { 2120probs = ggml_reshape_3d (ctx0 ,probs ,1 ,n_expert ,n_tokens ); 2121 } 2122 2123ggml_tensor * weights = ggml_get_rows (ctx0 ,probs ,selected_experts );// [1, n_expert_used, n_tokens] 2124cb (weights ,"ffn_moe_weights" ,il ); 2125 2126 2127if (gating_op == LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX_WEIGHT ) { 2128weights = ggml_reshape_2d (ctx0 ,weights ,n_expert_used ,n_tokens ); 2129weights = ggml_soft_max (ctx0 ,weights );// [n_expert_used, n_tokens] 2130weights = ggml_reshape_3d (ctx0 ,weights ,1 ,n_expert_used ,n_tokens ); 2131cb (weights ,"ffn_moe_weights_softmax" ,il ); 2132 } 2133 2134if (norm_w ) { 2135weights = ggml_reshape_2d (ctx0 ,weights ,n_expert_used ,n_tokens ); 2136 2137ggml_tensor * weights_sum = ggml_sum_rows (ctx0 ,weights );// [1, n_tokens] 2138cb (weights_sum ,"ffn_moe_weights_sum" ,il ); 2139 2140// Avoid division by zero, clamp to smallest number representable by F16 2141weights_sum = ggml_clamp (ctx0 ,weights_sum ,6.103515625e-5 ,INFINITY ); 2142cb (weights_sum ,"ffn_moe_weights_sum_clamped" ,il ); 2143 2144weights = ggml_div (ctx0 ,weights ,weights_sum );// [n_expert_used, n_tokens] 2145cb (weights ,"ffn_moe_weights_norm" ,il ); 2146 2147weights = ggml_reshape_3d (ctx0 ,weights ,1 ,n_expert_used ,n_tokens ); 2148 } 2149if (w_scale != 0.0f && w_scale != 1.0f ) { 2150weights = ggml_scale (ctx0 ,weights ,w_scale ); 2151cb (weights ,"ffn_moe_weights_scaled" ,il ); 2152 } 2153 2154//call early so that topk-moe can be used 2155ggml_build_forward_expand (gf ,weights ); 2156 2157cur = ggml_reshape_3d (ctx0 ,cur ,n_embd ,1 ,n_tokens ); 2158 2159if (weight_before_ffn ) { 2160// repeat cur to [n_embd, n_expert_used, n_tokens] 2161ggml_tensor * repeated = ggml_repeat_4d (ctx0 ,cur ,n_embd ,n_expert_used ,n_tokens ,1 ); 2162cur = ggml_mul (ctx0 ,repeated ,weights ); 2163cb (cur ,"ffn_moe_weighted" ,il ); 2164 } 2165 2166ggml_tensor * up = nullptr ; 2167ggml_tensor * experts = nullptr ; 2168 2169if (gate_up_exps ) { 2170// merged gate_up path: one mul_mat_id, then split into gate and up views 2171ggml_tensor * gate_up = build_lora_mm_id (gate_up_exps ,cur ,selected_experts ,up_exps_s );// [n_ff*2, n_expert_used, n_tokens] 2172cb (gate_up ,"ffn_moe_gate_up" ,il ); 2173 2174if (up_exps_s ) { 2175cb (gate_up ,"ffn_moe_gate_up_scaled" ,il ); 2176 } 2177 2178if (gate_up_exps_b ) { 2179gate_up = ggml_add_id (ctx0 ,gate_up ,gate_up_exps_b ,selected_experts ); 2180cb (gate_up ,"ffn_moe_gate_up_biased" ,il ); 2181 } 2182 2183const int64_t n_ff = gate_up -> ne [0 ] /2 ; 2184cur = ggml_view_3d (ctx0 ,gate_up ,n_ff ,gate_up -> ne [1 ],gate_up -> ne [2 ],gate_up -> nb [1 ],gate_up -> nb [2 ],0 ); 2185cb (cur ,"ffn_moe_gate" ,il ); 2186up = ggml_view_3d (ctx0 ,gate_up ,n_ff ,gate_up -> ne [1 ],gate_up -> ne [2 ],gate_up -> nb [1 ],gate_up -> nb [2 ],n_ff * gate_up -> nb [0 ]); 2187cb (up ,"ffn_moe_up" ,il ); 2188 }else { 2189// separate gate and up path 2190up = build_lora_mm_id (up_exps ,cur ,selected_experts ,up_exps_s );// [n_ff, n_expert_used, n_tokens] 2191cb (up ,"ffn_moe_up" ,il ); 2192 2193if (up_exps_s ) { 2194cb (up ,"ffn_moe_up_scaled" ,il ); 2195 } 2196 2197if (up_exps_b ) { 2198up = ggml_add_id (ctx0 ,up ,up_exps_b ,selected_experts ); 2199cb (up ,"ffn_moe_up_biased" ,il ); 2200 } 2201 2202if (gate_exps ) { 2203cur = build_lora_mm_id (gate_exps ,cur ,selected_experts ,gate_exps_s );// [n_ff, n_expert_used, n_tokens] 2204cb (cur ,"ffn_moe_gate" ,il ); 2205 }else { 2206cur = up ; 2207 } 2208 2209if (gate_exps_s ) { 2210cb (cur ,"ffn_moe_gate_scaled" ,il ); 2211 } 2212 2213if (gate_exps_b ) { 2214cur = ggml_add_id (ctx0 ,cur ,gate_exps_b ,selected_experts ); 2215cb (cur ,"ffn_moe_gate_biased" ,il ); 2216 } 2217 } 2218 2219const bool has_gate = gate_exps || gate_up_exps ; 2220 2221switch (type_op ) { 2222case LLM_FFN_SILU : 2223if (gate_exps ) { 2224if (il >=0 ) { 2225const float limit = hparams .swiglu_clamp_exp [il ]; 2226constexpr float eps = 1e-6f ; 2227if (limit > eps ) { 2228if (arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_DEEPSEEK4 || (arch == LLM_ARCH_DFLASH && hparams .dsv4_hc_mult > 0 )|| arch == LLM_ARCH_HY_V4 ) { 2229cur = ggml_swiglu_clamp (ctx0 ,cur ,up ,limit ); 2230 }else { 2231up = ggml_clamp (ctx0 ,up ,- limit ,limit ); 2232cb (up ,"ffn_moe_up_clamped" ,il ); 2233ggml_tensor * gate_act = ggml_silu (ctx0 ,cur ); 2234cb (gate_act ,"ffn_moe_silu" ,il ); 2235gate_act = ggml_clamp (ctx0 ,gate_act ,- INFINITY ,limit ); 2236cb (gate_act ,"ffn_moe_silu_clamped" ,il ); 2237cur = ggml_mul (ctx0 ,gate_act ,up ); 2238 } 2239cb (cur ,"ffn_moe_swiglu_limited" ,il ); 2240break ; 2241 } 2242 } 2243 } 2244 2245if (has_gate ) { 2246cur = ggml_swiglu_split (ctx0 ,cur ,up ); 2247cb (cur ,"ffn_moe_swiglu" ,il ); 2248 }else { 2249cur = ggml_silu (ctx0 ,cur ); 2250cb (cur ,"ffn_moe_silu" ,il ); 2251 }break ; 2252case LLM_FFN_SITU : 2253 { 2254// situ(gate, up) = beta*tanh(gate/beta)*sigmoid(gate) * lb*tanh(up/lb) 2255GGML_ASSERT (has_gate ); 2256const float beta = hparams .situ_beta ; 2257const float lb = hparams .situ_linear_beta ; 2258 2259ggml_tensor * act = ggml_scale (ctx0 ,ggml_tanh (ctx0 ,ggml_scale (ctx0 ,cur ,1.0f /beta )),beta ); 2260act = ggml_mul (ctx0 ,act ,ggml_sigmoid (ctx0 ,cur )); 2261if (lb > 0.0f ) { 2262up = ggml_scale (ctx0 ,ggml_tanh (ctx0 ,ggml_scale (ctx0 ,up ,1.0f /lb )),lb ); 2263 } 2264cur = ggml_mul (ctx0 ,act ,up ); 2265cb (cur ,"ffn_moe_situ" ,il ); 2266 }break ; 2267case LLM_FFN_GELU : 2268if (has_gate ) { 2269cur = ggml_geglu_split (ctx0 ,cur ,up ); 2270cb (cur ,"ffn_moe_geglu" ,il ); 2271 }else { 2272cur = ggml_gelu (ctx0 ,cur ); 2273cb (cur ,"ffn_moe_gelu" ,il ); 2274 }break ; 2275case LLM_FFN_SWIGLU_OAI_MOE : 2276 { 2277// TODO: move to hparams? 2278constexpr float alpha = 1.702f ; 2279constexpr float limit = 7.0f ; 2280cur = ggml_swiglu_oai (ctx0 ,cur ,up ,alpha ,limit ); 2281cb (cur ,"ffn_moe_swiglu_oai" ,il ); 2282 }break ; 2283case LLM_FFN_RELU : 2284if (has_gate ) { 2285cur = ggml_reglu_split (ctx0 ,cur ,up ); 2286cb (cur ,"ffn_moe_reglu" ,il ); 2287 }else { 2288cur = ggml_relu (ctx0 ,cur ); 2289cb (cur ,"ffn_moe_relu" ,il ); 2290 }break ; 2291case LLM_FFN_RELU_SQR : 2292if (has_gate ) { 2293// TODO: add support for gated squared relu 2294GGML_ABORT ("fatal error: gated squared relu not implemented" ); 2295 }else { 2296cur = ggml_relu (ctx0 ,cur ); 2297cur = ggml_sqr (ctx0 ,cur ); 2298cb (cur ,"ffn_moe_relu_sqr" ,il ); 2299 }break ; 2300default : 2301GGML_ABORT ("fatal error" ); 2302 } 2303 2304experts = build_lora_mm_id (down_exps ,cur ,selected_experts ,down_exps_s );// [n_embd, n_expert_used, n_tokens] 2305cb (experts ,"ffn_moe_down" ,il ); 2306 2307if (down_exps_s ) { 2308cb (experts ,"ffn_moe_down_scaled" ,il ); 2309 } 2310 2311if (down_exps_b ) { 2312experts = ggml_add_id (ctx0 ,experts ,down_exps_b ,selected_experts ); 2313cb (experts ,"ffn_moe_down_biased" ,il ); 2314 } 2315 2316if (!weight_before_ffn ) { 2317experts = ggml_mul (ctx0 ,experts ,weights ); 2318cb (experts ,"ffn_moe_weighted" ,il ); 2319 } 2320 2321ggml_build_forward_expand (gf ,experts ); 2322 2323ggml_tensor * cur_experts [LLAMA_MAX_EXPERTS ]= {nullptr }; 2324 2325assert (n_expert_used > 0 ); 2326 2327// order the views before the adds 2328// Use per-layer n_expert_used to bound the graph even during warmup (avoids 2329// the large-add-nodes issue for uniform arches; for Puzzle the per-layer 2330// value is correct). ref: https://github.com/ggml-org/llama.cpp/pull/14753 2331const uint32_t n_expert_used_il = hparams .n_expert_used (il ); 2332for (uint32_t i = 0 ;i < n_expert_used_il ;++ i ) { 2333cur_experts [i ]= ggml_view_2d (ctx0 ,experts ,n_embd ,n_tokens ,experts -> nb [2 ],i * experts -> nb [1 ]); 2334 2335ggml_build_forward_expand (gf ,cur_experts [i ]); 2336 } 2337 2338// aggregate experts 2339ggml_tensor * moe_out = cur_experts [0 ]; 2340 2341for (uint32_t i = 1 ;i < n_expert_used_il ;++ i ) { 2342moe_out = ggml_add (ctx0 ,moe_out ,cur_experts [i ]); 2343 2344ggml_build_forward_expand (gf ,moe_out ); 2345 } 2346 2347if (n_expert_used_il == 1 ) { 2348// avoid returning a non-contiguous tensor 2349moe_out = ggml_cont (ctx0 ,moe_out ); 2350 } 2351 2352cb (moe_out ,"ffn_moe_out" ,il ); 2353 2354return moe_out ; 2355} 2356 2357// input embeddings with optional lora 2358ggml_tensor * llm_graph_context::build_inp_embd (ggml_tensor * tok_embd )const { 2359const int64_t n_embd_inp = hparams .n_embd_inp (); 2360const int64_t n_embd = hparams .n_embd ; 2361 2362assert (n_embd_inp >=n_embd ); 2363 2364auto inp = std::make_unique < llm_graph_input_embd > (n_embd_inp ); 2365 2366inp -> tokens = ggml_new_tensor_1d (ctx0 ,GGML_TYPE_I32 ,ubatch .n_tokens ); 2367cb (inp -> tokens ,"inp_tokens" ,-1 ); 2368ggml_set_input (inp -> tokens ); 2369res -> t_inp_tokens = inp -> tokens ; 2370 2371inp -> embd = ggml_new_tensor_2d (ctx0 ,GGML_TYPE_F32 ,n_embd_inp ,ubatch .n_tokens ); 2372cb (inp -> embd ,"inp_embd" ,-1 ); 2373ggml_set_input (inp -> embd ); 2374 2375// select one of the 2 inputs, based on the batch contents 2376// ref: https://github.com/ggml-org/llama.cpp/pull/18550 2377 std::array < ggml_tensor * ,2 > inps ; 2378 2379// token embeddings path (ubatch.token != nullptr) 2380 { 2381auto & cur = inps [0 ]; 2382 2383cur = ggml_get_rows (ctx0 ,tok_embd ,inp -> tokens ); 2384 2385// apply lora for embedding tokens if needed 2386for (const auto & lora :* loras ) { 2387llama_adapter_lora_weight * lw = lora .first -> get_weight (tok_embd ); 2388if (lw == nullptr ) { 2389continue ; 2390 } 2391 2392const float adapter_scale = lora .second ; 2393const float scale = lw -> get_scale (lora .first -> alpha ,adapter_scale ); 2394 2395ggml_tensor * inpL_delta = ggml_scale (ctx0 ,ggml_mul_mat ( 2396ctx0 ,lw -> b ,// non-transposed lora_b 2397ggml_get_rows (ctx0 ,lw -> a ,inp -> tokens ) 2398 ),scale ); 2399 2400cur = ggml_add (ctx0 ,cur ,inpL_delta ); 2401 } 2402 2403if (n_embd_inp != n_embd ) { 2404cur = ggml_pad (ctx0 ,cur ,hparams .n_embd_inp ()- n_embd ,0 ,0 ,0 ); 2405 } 2406 } 2407 2408// vector embeddings path (ubatch.embd != nullptr) 2409 { 2410auto & cur = inps [1 ]; 2411 2412cur = inp -> embd ; 2413 } 2414 2415assert (ggml_are_same_shape (inps [0 ],inps [1 ])); 2416assert (ggml_are_same_stride (inps [0 ],inps [1 ])); 2417 2418ggml_tensor * cur = ggml_build_forward_select (gf ,inps .data (),inps .size (),ubatch .token ?0 :1 ); 2419 2420if (n_embd_inp != n_embd ) { 2421cur = ggml_view_2d (ctx0 ,cur ,n_embd ,n_tokens ,cur -> nb [1 ],0 ); 2422 } 2423 2424res -> t_inp_embd = cur ; 2425 2426// For Granite architecture 2427// NOTE: For deepstack models, only apply scale to token inputs (ie text-only input). 2428// Raw embeddings are assumed to be multimodal inputs that should not be scaled. 2429if (hparams .f_embedding_scale != 0.0f && (ubatch .token || hparams .n_deepstack_layers == 0 )) { 2430if (!ggml_is_contiguous (cur )) { 2431cur = ggml_cont (ctx0 ,cur ); 2432 } 2433cur = ggml_scale (ctx0 ,cur ,hparams .f_embedding_scale ); 2434 } 2435 2436cb (cur ,"embd" ,-1 ); 2437 2438res -> add_input (std::move (inp )); 2439 2440// make sure the produced embeddings are immediately materialized in the ggml graph 2441// ref: https://github.com/ggml-org/llama.cpp/pull/18599 2442ggml_build_forward_expand (gf ,cur ); 2443 2444return cur ; 2445} 2446 2447ggml_tensor * llm_graph_context::build_inp_pos ()const { 2448auto inp = std::make_unique < llm_graph_input_pos > (hparams .n_pos_per_embd ()); 2449 2450auto & cur = inp -> pos ; 2451 2452cur = ggml_new_tensor_1d (ctx0 ,GGML_TYPE_I32 , (int64_t )n_tokens * hparams .n_pos_per_embd ()); 2453ggml_set_input (cur ); 2454 2455res -> add_input (std::move (inp )); 2456 2457return cur ; 2458} 2459 2460ggml_tensor * llm_graph_context::build_inp_attn_scale ()const { 2461auto inp = std::make_unique < llm_graph_input_attn_temp > (hparams .n_attn_temp_floor_scale ,hparams .f_attn_temp_scale ,hparams .f_attn_temp_offset ); 2462 2463auto & cur = inp -> attn_scale ; 2464 2465// this need to be 1x1xN for broadcasting 2466cur = ggml_new_tensor_3d (ctx0 ,GGML_TYPE_F32 ,1 ,1 ,n_tokens ); 2467ggml_set_input (cur ); 2468ggml_set_name (cur ,"attn_scale" ); 2469 2470res -> add_input (std::move (inp )); 2471 2472return cur ; 2473} 2474 2475ggml_tensor * llm_graph_context::build_inp_out_ids ()const { 2476// note: when all tokens are output, we could skip this optimization to spare the ggml_get_rows() calls, 2477// but this would make the graph topology depend on the number of output tokens, which can interfere with 2478// features that require constant topology such as pipeline parallelism 2479// ref: https://github.com/ggml-org/llama.cpp/pull/14275#issuecomment-2987424471 2480//if (n_outputs < n_tokens) { 2481// return nullptr; 2482//} 2483 2484auto inp = std::make_unique < llm_graph_input_out_ids > (hparams ,cparams ,n_outputs ); 2485 2486auto & cur = inp -> out_ids ; 2487 2488cur = ggml_new_tensor_1d (ctx0 ,GGML_TYPE_I32 ,n_outputs ); 2489ggml_set_input (cur ); 2490 2491res -> add_input (std::move (inp )); 2492 2493return cur ; 2494} 2495 2496ggml_tensor * llm_graph_context::build_inp_mean ()const { 2497auto inp = std::make_unique < llm_graph_input_mean > (cparams ); 2498 2499auto & cur = inp -> mean ; 2500 2501cur = ggml_new_tensor_2d (ctx0 ,GGML_TYPE_F32 ,n_tokens ,ubatch .n_seqs_unq ); 2502ggml_set_input (cur ); 2503 2504res -> add_input (std::move (inp )); 2505 2506return cur ; 2507} 2508 2509ggml_tensor * llm_graph_context::build_inp_cls ()const { 2510auto inp = std::make_unique < llm_graph_input_cls > (cparams ,arch ); 2511 2512auto & cur = inp -> cls ; 2513 2514cur = ggml_new_tensor_1d (ctx0 ,GGML_TYPE_I32 ,ubatch .n_seqs_unq ); 2515ggml_set_input (cur ); 2516 2517res -> add_input (std::move (inp )); 2518 2519return cur ; 2520} 2521 2522ggml_tensor * llm_graph_context::build_inp_cross_embd ()const { 2523auto inp = std::make_unique < llm_graph_input_cross_embd > (cross ); 2524 2525auto & cur = inp -> cross_embd ; 2526 2527// if we have the output embeddings from the encoder, use them directly 2528// TODO: needs more work to be correct, for now just use the tensor shape 2529//if (cross->t_embd) { 2530// cur = ggml_view_tensor(ctx0, cross->t_embd); 2531 2532// return cur; 2533//} 2534 2535const auto n_embd = !cross -> v_embd .empty () ?cross -> n_embd :hparams .n_embd_inp (); 2536const auto n_enc = !cross -> v_embd .empty () ?cross -> n_enc :hparams .n_ctx_train ; 2537 2538cur = ggml_new_tensor_2d (ctx0 ,GGML_TYPE_F32 ,n_embd ,n_enc ); 2539ggml_set_input (cur ); 2540 2541res -> add_input (std::move (inp )); 2542 2543return cur ; 2544} 2545 2546ggml_tensor * llm_graph_context::build_inp_pos_bucket_enc ()const { 2547auto inp = std::make_unique < llm_graph_input_pos_bucket > (hparams ); 2548 2549auto & cur = inp -> pos_bucket ; 2550 2551cur = ggml_new_tensor_2d (ctx0 ,GGML_TYPE_I32 ,n_tokens ,n_tokens ); 2552ggml_set_input (cur ); 2553 2554res -> add_input (std::move (inp )); 2555 2556return cur ; 2557} 2558 2559ggml_tensor * llm_graph_context::build_inp_pos_bucket_dec ()const { 2560const auto * mctx_cur = static_cast < const llama_kv_cache_context *> (mctx ); 2561 2562auto inp = std::make_unique < llm_graph_input_pos_bucket_kv > (hparams ,mctx_cur ); 2563 2564const auto n_kv = mctx_cur -> get_n_kv (); 2565 2566auto & cur = inp -> pos_bucket ; 2567 2568cur = ggml_new_tensor_2d (ctx0 ,GGML_TYPE_I32 ,n_kv ,n_tokens ); 2569ggml_set_input (cur ); 2570 2571res -> add_input (std::move (inp )); 2572 2573return cur ; 2574} 2575 2576ggml_tensor * llm_graph_context::build_pos_bias (ggml_tensor * pos_bucket ,ggml_tensor * attn_rel_b )const { 2577ggml_tensor * pos_bucket_1d = ggml_reshape_1d (ctx0 ,pos_bucket ,pos_bucket -> ne [0 ]* pos_bucket -> ne [1 ]); 2578cb (pos_bucket_1d ,"pos_bucket_1d" ,-1 ); 2579 2580ggml_tensor * pos_bias = ggml_get_rows (ctx0 ,attn_rel_b ,pos_bucket_1d ); 2581 2582pos_bias = ggml_reshape_3d (ctx0 ,pos_bias ,pos_bias -> ne [0 ],pos_bucket -> ne [0 ],pos_bucket -> ne [1 ]); 2583pos_bias = ggml_permute (ctx0 ,pos_bias ,2 ,0 ,1 ,3 ); 2584pos_bias = ggml_cont (ctx0 ,pos_bias ); 2585 2586cb (pos_bias ,"pos_bias" ,-1 ); 2587 2588return pos_bias ; 2589} 2590 2591ggml_tensor * llm_graph_context::build_attn_mha ( 2592ggml_tensor * q , 2593ggml_tensor * k , 2594ggml_tensor * v , 2595ggml_tensor * kq_b , 2596ggml_tensor * kq_mask , 2597ggml_tensor * sinks , 2598ggml_tensor * v_mla , 2599int64_t n_kv_max , 2600float kq_scale , 2601int il )const { 2602const bool v_trans = v -> nb [1 ]> v -> nb [2 ]; 2603 2604// split the batch into streams if needed 2605const auto n_stream = k -> ne [3 ]; 2606 2607q = ggml_view_4d (ctx0 ,q ,q -> ne [0 ],q -> ne [1 ],q -> ne [2 ]/n_stream ,n_stream ,q -> nb [1 ],q -> nb [2 ],q -> nb [3 ]/n_stream ,0 ); 2608 2609q = ggml_permute (ctx0 ,q ,0 ,2 ,1 ,3 ); 2610k = ggml_permute (ctx0 ,k ,0 ,2 ,1 ,3 ); 2611v = ggml_permute (ctx0 ,v ,0 ,2 ,1 ,3 ); 2612 2613ggml_tensor * cur ; 2614 2615const bool use_flash_attn = cparams .flash_attn && kq_b == nullptr ; 2616if (use_flash_attn ) { 2617GGML_ASSERT (kq_b == nullptr && "Flash attention does not support KQ bias yet" ); 2618 2619if (v_trans ) { 2620v = ggml_transpose (ctx0 ,v ); 2621 } 2622 2623// this can happen when KV cache is not used (e.g. an embedding model with non-causal attn) 2624if (k -> type == GGML_TYPE_F32 ) { 2625k = ggml_cast (ctx0 ,k ,GGML_TYPE_F16 ); 2626 } 2627 2628if (v -> type == GGML_TYPE_F32 ) { 2629v = ggml_cast (ctx0 ,v ,GGML_TYPE_F16 ); 2630 } 2631 2632cur = ggml_flash_attn_ext (ctx0 ,q ,k ,v ,kq_mask ,kq_scale ,hparams .f_max_alibi_bias , 2633hparams .attn_soft_cap ?hparams .f_attn_logit_softcapping :0.0f ); 2634res -> add_fused_node ({LLM_FUSED_OP_FLASH_ATTN ,cur ,il }); 2635 2636ggml_flash_attn_ext_add_sinks (cur ,sinks ); 2637GGML_ASSERT (n_kv_max >=0 && n_kv_max <=INT32_MAX ); 2638ggml_flash_attn_ext_set_n_kv_max (cur ,static_cast < int32_t > (n_kv_max )); 2639ggml_prec_set_acc (cur ,GGML_PREC_F32 ); 2640 2641if (v_mla ) { 2642#if 0 2643// v_mla can be applied as a matrix-vector multiplication with broadcasting across dimension 3 == n_tokens. 2644// However, the code is optimized for dimensions 0 and 1 being large, so this is inefficient. 2645cur = ggml_reshape_4d (ctx0 ,cur ,v_mla -> ne [0 ],1 ,n_head ,n_tokens ); 2646cur = ggml_mul_mat (ctx0 ,v_mla ,cur ); 2647#else 2648// It's preferable to do the calculation as a matrix-matrix multiplication with n_tokens in dimension 1. 2649// The permutations are noops and only change how the tensor data is interpreted. 2650cur = ggml_permute (ctx0 ,cur ,0 ,2 ,1 ,3 ); 2651cur = ggml_mul_mat (ctx0 ,v_mla ,cur ); 2652cb (cur ,"fattn_mla" ,il ); 2653cur = ggml_permute (ctx0 ,cur ,0 ,2 ,1 ,3 ); 2654cur = ggml_cont (ctx0 ,cur );// Needed because ggml_reshape_2d expects contiguous inputs. 2655#endif 2656 } 2657 2658cur = ggml_reshape_2d (ctx0 ,cur ,cur -> ne [0 ]* cur -> ne [1 ],cur -> ne [2 ]* cur -> ne [3 ]); 2659 }else { 2660ggml_tensor * kq = ggml_mul_mat (ctx0 ,k ,q ); 2661cb (kq ,"kq" ,il ); 2662 2663// note: this op tends to require high floating point range 2664// while for some models F16 is enough, for others it is not, so we default to F32 here 2665ggml_prec_set_acc (kq ,GGML_PREC_F32 ); 2666 2667if (arch == LLM_ARCH_GROK ) { 2668// need to do the following: 2669// multiply by attn_output_multiplier 2670// and then : 2671// kq = 30 * tanh(kq / 30) 2672// before the softmax below 2673 2674kq = ggml_tanh (ctx0 ,ggml_scale (ctx0 ,kq ,hparams .f_attn_out_scale /hparams .f_attn_logit_softcapping )); 2675cb (kq ,"kq_tanh" ,il ); 2676kq = ggml_scale (ctx0 ,kq ,hparams .f_attn_logit_softcapping ); 2677cb (kq ,"kq_scaled" ,il ); 2678 } 2679 2680if (hparams .attn_soft_cap ) { 2681kq = ggml_scale (ctx0 ,kq ,1.0f /hparams .f_attn_logit_softcapping ); 2682cb (kq ,"kq_scaled_1" ,il ); 2683kq = ggml_tanh (ctx0 ,kq ); 2684cb (kq ,"kq_tanh" ,il ); 2685kq = ggml_scale (ctx0 ,kq ,hparams .f_attn_logit_softcapping ); 2686cb (kq ,"kq_scaled_2" ,il ); 2687 } 2688 2689if (kq_b ) { 2690kq = ggml_add (ctx0 ,kq ,kq_b ); 2691cb (kq ,"kq_plus_kq_b" ,il ); 2692 } 2693 2694kq = ggml_soft_max_ext (ctx0 ,kq ,kq_mask ,kq_scale ,hparams .f_max_alibi_bias ); 2695ggml_soft_max_add_sinks (kq ,sinks ); 2696cb (kq ,"kq_soft_max" ,il ); 2697 2698if (!v_trans ) { 2699// note: avoid this branch 2700v = ggml_cont (ctx0 ,ggml_transpose (ctx0 ,v )); 2701cb (v ,"v_cont" ,il ); 2702 } 2703 2704ggml_tensor * kqv = ggml_mul_mat (ctx0 ,v ,kq ); 2705cb (kqv ,"kqv" ,il ); 2706 2707// for MLA with the absorption optimization, we need to "decompress" from MQA back to MHA 2708if (v_mla ) { 2709kqv = ggml_mul_mat (ctx0 ,v_mla ,kqv ); 2710cb (kqv ,"kqv_mla" ,il ); 2711 } 2712 2713cur = ggml_permute (ctx0 ,kqv ,0 ,2 ,1 ,3 ); 2714 2715// recombine streams 2716cur = ggml_cont_2d (ctx0 ,cur ,cur -> ne [0 ]* cur -> ne [1 ],cur -> ne [2 ]* cur -> ne [3 ]); 2717 2718if (!cparams .offload_kqv ) { 2719// all nodes between the KV store and the attention output are run on the CPU 2720ggml_backend_sched_set_tensor_backend (sched ,cur ,backend_cpu ); 2721 } 2722 } 2723 2724ggml_build_forward_expand (gf ,cur ); 2725 2726return cur ; 2727} 2728 2729llm_graph_input_attn_no_cache * llm_graph_context::build_attn_inp_no_cache ()const { 2730auto inp = std::make_unique < llm_graph_input_attn_no_cache > (hparams ,cparams ); 2731 2732// flash attention requires an f16 mask 2733const auto type_mask = cparams .flash_attn ?GGML_TYPE_F16 :GGML_TYPE_F32 ; 2734 2735// note: there is no KV cache, so the number of KV values is equal to the number of tokens in the batch 2736inp -> self_kq_mask = ggml_new_tensor_4d (ctx0 ,type_mask ,n_tokens ,n_tokens ,1 ,1 ); 2737ggml_set_input (inp -> self_kq_mask ); 2738 2739inp -> self_kq_mask_cnv = inp -> self_kq_mask ; 2740 2741if (hparams .swa_type != LLAMA_SWA_TYPE_NONE ) { 2742inp -> self_kq_mask_swa = ggml_new_tensor_4d (ctx0 ,type_mask ,n_tokens ,n_tokens ,1 ,1 ); 2743ggml_set_input (inp -> self_kq_mask_swa ); 2744 2745inp -> self_kq_mask_swa_cnv = inp -> self_kq_mask_swa ; 2746 }else { 2747inp -> self_kq_mask_swa = nullptr ; 2748inp -> self_kq_mask_swa_cnv = nullptr ; 2749 } 2750 2751return (llm_graph_input_attn_no_cache * )res -> add_input (std::move (inp )); 2752} 2753 2754ggml_tensor * llm_graph_context::build_attn ( 2755llm_graph_input_attn_no_cache * inp , 2756ggml_tensor * wo , 2757ggml_tensor * wo_b , 2758ggml_tensor * wo_s , 2759ggml_tensor * q_cur , 2760ggml_tensor * k_cur , 2761ggml_tensor * v_cur , 2762ggml_tensor * kq_b , 2763ggml_tensor * sinks , 2764ggml_tensor * v_mla , 2765float kq_scale , 2766int il )const { 2767GGML_UNUSED (n_tokens ); 2768 2769// these nodes are added to the graph together so that they are not reordered 2770// by doing so, the number of splits in the graph is reduced 2771ggml_build_forward_expand (gf ,q_cur ); 2772ggml_build_forward_expand (gf ,k_cur ); 2773ggml_build_forward_expand (gf ,v_cur ); 2774 2775const bool is_swa = hparams .is_swa (il ); 2776 2777const auto & kq_mask = is_swa ?inp -> get_kq_mask_swa () :inp -> get_kq_mask (); 2778 2779// [TAG_NO_CACHE_PAD] 2780// TODO: if ubatch.equal_seqs() == true, we can split the three tensors below into ubatch.n_seqs_unq streams 2781// but it might not be worth it: https://github.com/ggml-org/llama.cpp/pull/15636 2782//assert(!ubatch.equal_seqs() || (k_cur->ne[3] == 1 && k_cur->ne[3] == ubatch.n_seqs_unq)); 2783 2784ggml_tensor * q = q_cur ; 2785ggml_tensor * k = k_cur ; 2786ggml_tensor * v = v_cur ; 2787 2788ggml_tensor * cur = build_attn_mha (q ,k ,v ,kq_b ,kq_mask ,sinks ,v_mla ,0 ,kq_scale ,il ); 2789cb (cur ,"kqv_out" ,il ); 2790 2791if (wo ) { 2792cur = build_lora_mm (wo ,cur ,wo_s ); 2793 } 2794 2795if (wo_b ) { 2796//cb(cur, "kqv_wo", il); 2797 } 2798 2799if (wo_b ) { 2800cur = ggml_add (ctx0 ,cur ,wo_b ); 2801 } 2802 2803return cur ; 2804} 2805 2806static std::unique_ptr < llm_graph_input_attn_kv > build_attn_inp_kv_impl ( 2807ggml_context * ctx0 , 2808const llama_ubatch & ubatch , 2809const llama_hparams & hparams , 2810const llama_cparams & cparams , 2811const llama_kv_cache_context * mctx_cur ) { 2812 2813auto inp = std::make_unique < llm_graph_input_attn_kv > (hparams ,cparams ,mctx_cur ); 2814 2815 { 2816GGML_ASSERT (hparams .swa_type == LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache_iswa for SWA" ); 2817 2818inp -> self_k_idxs = mctx_cur -> build_input_k_idxs (ctx0 ,ubatch ); 2819inp -> self_v_idxs = mctx_cur -> build_input_v_idxs (ctx0 ,ubatch ); 2820 2821inp -> self_kq_mask = build_attn_inp_kq_mask (ctx0 ,mctx_cur ,ubatch ,cparams ); 2822inp -> self_kq_mask_cnv = inp -> self_kq_mask ; 2823 } 2824 2825inp -> self_k_rot = mctx_cur -> build_input_k_rot (ctx0 ); 2826inp -> self_v_rot = mctx_cur -> build_input_v_rot (ctx0 ); 2827 2828return inp ; 2829} 2830 2831llm_graph_input_attn_kv * llm_graph_context::build_attn_inp_kv ()const { 2832const auto * mctx_cur = static_cast < const llama_kv_cache_context *> (mctx ); 2833 2834auto inp = build_attn_inp_kv_impl (ctx0 ,ubatch ,hparams ,cparams ,mctx_cur ); 2835 2836return (llm_graph_input_attn_kv * )res -> add_input (std::move (inp )); 2837} 2838 2839ggml_tensor * llm_graph_context::build_attn ( 2840llm_graph_input_attn_kv * inp , 2841ggml_tensor * wo , 2842ggml_tensor * wo_b , 2843ggml_tensor * wo_s , 2844ggml_tensor * q_cur , 2845ggml_tensor * k_cur , 2846ggml_tensor * v_cur , 2847ggml_tensor * kq_b , 2848ggml_tensor * sinks , 2849ggml_tensor * v_mla ,// TODO: remove 2850float kq_scale , 2851int il )const { 2852GGML_ASSERT (v_mla == nullptr ); 2853 2854if (inp -> self_k_rot ) { 2855q_cur = llama_mul_mat_hadamard (ctx0 ,q_cur ,inp -> self_k_rot ); 2856k_cur = llama_mul_mat_hadamard (ctx0 ,k_cur ,inp -> self_k_rot ); 2857 } 2858 2859if (inp -> self_v_rot ) { 2860v_cur = llama_mul_mat_hadamard (ctx0 ,v_cur ,inp -> self_v_rot ); 2861 } 2862 2863// these nodes are added to the graph together so that they are not reordered 2864// by doing so, the number of splits in the graph is reduced 2865// expand k later to enable rope fusion which directly writes into k-v cache 2866ggml_build_forward_expand (gf ,q_cur ); 2867ggml_build_forward_expand (gf ,v_cur ); 2868ggml_build_forward_expand (gf ,k_cur ); 2869 2870const auto * mctx_cur = inp -> mctx ; 2871 2872// store to KV cache 2873 { 2874const auto & k_idxs = inp -> get_k_idxs (); 2875const auto & v_idxs = inp -> get_v_idxs (); 2876 2877ggml_build_forward_expand (gf ,mctx_cur -> cpy_k (ctx0 ,k_cur ,k_idxs ,il )); 2878ggml_build_forward_expand (gf ,mctx_cur -> cpy_v (ctx0 ,v_cur ,v_idxs ,il )); 2879 } 2880 2881ggml_tensor * kq_mask = inp -> get_kq_mask (); 2882 2883ggml_tensor * q = q_cur ; 2884ggml_tensor * k = mctx_cur -> get_k (ctx0 ,il ); 2885ggml_tensor * v = mctx_cur -> get_v (ctx0 ,il ); 2886 2887ggml_tensor * cur = build_attn_mha (q ,k ,v ,kq_b ,kq_mask ,sinks ,v_mla ,0 ,kq_scale ,il ); 2888cb (cur ,"kqv_out" ,il ); 2889 2890if (inp -> self_v_rot ) { 2891cur = llama_mul_mat_hadamard (ctx0 ,cur ,inp -> self_v_rot ); 2892 } 2893 2894if (wo ) { 2895if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2 ) { 2896// GLM4, GLM4_MOE, and JAIS2 seem to have numerical issues with half-precision accumulators 2897cur = build_lora_mm (wo ,cur ); 2898ggml_prec_set_acc (cur ,GGML_PREC_F32 ); 2899if (wo_s ) { 2900cur = ggml_mul (ctx0 ,cur ,wo_s ); 2901 } 2902 }else { 2903cur = build_lora_mm (wo ,cur ,wo_s ); 2904 } 2905 } 2906 2907if (wo_b ) { 2908cur = ggml_add (ctx0 ,cur ,wo_b ); 2909 } 2910 2911return cur ; 2912} 2913 2914static std::unique_ptr < llm_graph_input_attn_k > build_attn_inp_k_impl ( 2915ggml_context * ctx0 , 2916const llama_ubatch & ubatch , 2917const llama_hparams & hparams , 2918const llama_cparams & cparams , 2919const llama_kv_cache_context * mctx_cur ) { 2920 2921auto inp = std::make_unique < llm_graph_input_attn_k > (hparams ,cparams ,mctx_cur ); 2922 2923 { 2924GGML_ASSERT (hparams .swa_type == LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache_iswa for SWA" ); 2925 2926inp -> self_k_idxs = mctx_cur -> build_input_k_idxs (ctx0 ,ubatch ); 2927 2928inp -> self_kq_mask = build_attn_inp_kq_mask (ctx0 ,mctx_cur ,ubatch ,cparams ); 2929inp -> self_kq_mask_cnv = inp -> self_kq_mask ; 2930 } 2931 2932return inp ; 2933} 2934 2935llm_graph_input_attn_k * llm_graph_context::build_attn_inp_k ()const { 2936const auto * mctx_cur = static_cast < const llama_kv_cache_context *> (mctx ); 2937 2938auto inp = build_attn_inp_k_impl (ctx0 ,ubatch ,hparams ,cparams ,mctx_cur ); 2939 2940return (llm_graph_input_attn_k * )res -> add_input (std::move (inp )); 2941} 2942 2943ggml_tensor * llm_graph_context::build_attn ( 2944llm_graph_input_attn_k * inp , 2945ggml_tensor * wo , 2946ggml_tensor * wo_b , 2947ggml_tensor * wo_s , 2948ggml_tensor * q_cur , 2949ggml_tensor * k_cur , 2950ggml_tensor * v_cur , 2951ggml_tensor * kq_b , 2952ggml_tensor * sinks , 2953ggml_tensor * v_mla , 2954float kq_scale , 2955int il )const { 2956// these nodes are added to the graph together so that they are not reordered 2957// by doing so, the number of splits in the graph is reduced 2958// expand k later to enable rope fusion which directly writes into k-v cache 2959ggml_build_forward_expand (gf ,q_cur ); 2960ggml_build_forward_expand (gf ,v_cur ); 2961ggml_build_forward_expand (gf ,k_cur ); 2962 2963const auto * mctx_cur = inp -> mctx ; 2964 2965// store to KV cache 2966 { 2967const auto & k_idxs = inp -> get_k_idxs (); 2968 2969ggml_build_forward_expand (gf ,mctx_cur -> cpy_k (ctx0 ,k_cur ,k_idxs ,il )); 2970 } 2971 2972const auto & kq_mask = inp -> get_kq_mask (); 2973 2974ggml_tensor * q = q_cur ; 2975ggml_tensor * k = mctx_cur -> get_k (ctx0 ,il ); 2976ggml_tensor * v = ggml_view_4d (ctx0 ,k ,v_cur -> ne [0 ],k -> ne [1 ],k -> ne [2 ],k -> ne [3 ],k -> nb [1 ],k -> nb [2 ],k -> nb [3 ],0 ); 2977 2978ggml_tensor * cur = build_attn_mha (q ,k ,v ,kq_b ,kq_mask ,sinks ,v_mla ,0 ,kq_scale ,il ); 2979cb (cur ,"kqv_out" ,il ); 2980 2981if (wo ) { 2982if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE ) { 2983// GLM4 and GLM4_MOE seem to have numerical issues with half-precision accumulators 2984cur = build_lora_mm (wo ,cur ); 2985ggml_prec_set_acc (cur ,GGML_PREC_F32 ); 2986if (wo_s ) { 2987cur = ggml_mul (ctx0 ,cur ,wo_s ); 2988 } 2989 }else { 2990cur = build_lora_mm (wo ,cur ,wo_s ); 2991 } 2992 } 2993 2994if (wo_b ) { 2995cur = ggml_add (ctx0 ,cur ,wo_b ); 2996 } 2997 2998return cur ; 2999} 3000 3001ggml_tensor * llm_graph_context::build_attn ( 3002llm_graph_input_attn_k_dsa * inp , 3003ggml_tensor * wo , 3004ggml_tensor * wo_b , 3005ggml_tensor * wo_s , 3006ggml_tensor * q_cur , 3007ggml_tensor * k_cur , 3008ggml_tensor * v_cur , 3009ggml_tensor * kq_b , 3010ggml_tensor * sinks , 3011ggml_tensor * v_mla , 3012ggml_tensor * top_k , 3013float kq_scale , 3014int il )const { 3015// these nodes are added to the graph together so that they are not reordered 3016// by doing so, the number of splits in the graph is reduced 3017// expand k later to enable rope fusion which directly writes into k-v cache 3018ggml_build_forward_expand (gf ,q_cur ); 3019ggml_build_forward_expand (gf ,v_cur ); 3020ggml_build_forward_expand (gf ,k_cur ); 3021 3022const auto * mctx_cur = inp -> mctx -> get_mla (); 3023 3024// store to KV cache 3025 { 3026const auto & k_idxs = inp -> get_k_idxs_mla (); 3027 3028ggml_build_forward_expand (gf ,mctx_cur -> cpy_k (ctx0 ,k_cur ,k_idxs ,il )); 3029 } 3030 3031const auto & kq_mask = inp -> get_kq_mask_mla (); 3032 3033// prepare new kq mask - starts filled with -INFINITY 3034ggml_tensor * kq_mask_all = ggml_fill (ctx0 ,kq_mask ,- INFINITY ); 3035 3036// reshape KQ mask into tensor with rows of size 1: 3037// [n_kv, n_batch, 1, n_stream] -> [1, n_kv, n_batch, n_stream] 3038kq_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 ],kq_mask_all -> nb [0 ],kq_mask_all -> nb [1 ],kq_mask_all -> nb [2 ],0 ); 3039 3040// reshape top_k indices: [n_top_k, n_batch, 1, n_stream] -> [n_top_k, n_batch, n_stream, 1] 3041ggml_tensor * top_k_3d = ggml_view_4d (ctx0 ,top_k ,top_k -> ne [0 ],top_k -> ne [1 ],top_k -> ne [3 ],1 ,top_k -> nb [1 ],top_k -> nb [2 ],top_k -> ne [3 ]* top_k -> nb [3 ],0 ); 3042 3043// prepare zero-filled tensor with rows of size 1: [1, n_top_k, n_batch, n_stream] 3044// this will be our source of zero values for unmasking top k mask elements 3045ggml_tensor * zeros = ggml_new_tensor_4d (ctx0 ,GGML_TYPE_F32 ,1 ,top_k_3d -> ne [0 ],top_k_3d -> ne [1 ],top_k_3d -> ne [2 ]); 3046zeros = ggml_fill (ctx0 ,zeros ,0.0f ); 3047 3048// modify KQ mask by unmasking elements that are in top_k indices 3049// ggml_set_rows([1, n_kv, n_batch, n_stream], [1, n_top_k, n_batch, n_stream], [n_top_k, n_batch, n_stream, 1]) 3050ggml_tensor * kq_mask_top_k = ggml_set_rows (ctx0 ,kq_mask_all ,zeros ,top_k_3d ); 3051 3052// reshape to restore the original shape of KQ mask: 3053// [1, n_kv, n_batch, n_stream] -> [n_kv, n_batch, 1, n_stream] 3054kq_mask_top_k = ggml_view_4d (ctx0 ,kq_mask_top_k ,kq_mask_top_k -> ne [1 ],kq_mask_top_k -> ne [2 ],1 ,kq_mask_top_k -> ne [3 ],kq_mask_top_k -> nb [2 ],kq_mask_top_k -> nb [3 ],kq_mask_top_k -> nb [3 ],0 ); 3055 3056// combine with the original kq mask 3057kq_mask_top_k = ggml_add (ctx0 ,kq_mask_top_k ,kq_mask ); 3058 3059ggml_tensor * q = q_cur ; 3060ggml_tensor * k = mctx_cur -> get_k (ctx0 ,il ); 3061ggml_tensor * v = ggml_view_4d (ctx0 ,k ,v_cur -> ne [0 ],k -> ne [1 ],k -> ne [2 ],k -> ne [3 ],k -> nb [1 ],k -> nb [2 ],k -> nb [3 ],0 ); 3062 3063ggml_tensor * cur = build_attn_mha (q ,k ,v ,kq_b ,kq_mask_top_k ,sinks ,v_mla ,top_k -> ne [0 ],kq_scale ,il ); 3064cb (cur ,"kqv_out" ,il ); 3065 3066if (wo ) { 3067cur = build_lora_mm (wo ,cur ,wo_s ); 3068 } 3069 3070if (wo_b ) { 3071cur = ggml_add (ctx0 ,cur ,wo_b ); 3072 } 3073 3074return cur ; 3075} 3076 3077ggml_tensor * llm_graph_context::build_attn ( 3078llm_graph_input_attn_kv_iswa * inp , 3079ggml_tensor * wo , 3080ggml_tensor * wo_b , 3081ggml_tensor * wo_s , 3082ggml_tensor * q_cur , 3083ggml_tensor * k_cur , 3084ggml_tensor * v_cur , 3085ggml_tensor * kq_b , 3086ggml_tensor * sinks , 3087ggml_tensor * v_mla , 3088float kq_scale , 3089int il )const { 3090const bool is_swa = hparams .is_swa (il ); 3091 3092auto * k_rot = is_swa ?inp -> self_k_rot_swa :inp -> self_k_rot ; 3093auto * v_rot = is_swa ?inp -> self_v_rot_swa :inp -> self_v_rot ; 3094 3095if (k_rot ) { 3096q_cur = llama_mul_mat_hadamard (ctx0 ,q_cur ,k_rot ); 3097if (k_cur ) { 3098k_cur = llama_mul_mat_hadamard (ctx0 ,k_cur ,k_rot ); 3099 } 3100 } 3101if (v_rot ) { 3102if (v_cur ) { 3103v_cur = llama_mul_mat_hadamard (ctx0 ,v_cur ,v_rot ); 3104 } 3105 } 3106 3107// these nodes are added to the graph together so that they are not reordered 3108// by doing so, the number of splits in the graph is reduced 3109ggml_build_forward_expand (gf ,q_cur ); 3110 3111if (k_cur ) { 3112ggml_build_forward_expand (gf ,k_cur ); 3113 } 3114 3115if (v_cur ) { 3116ggml_build_forward_expand (gf ,v_cur ); 3117 } 3118 3119const auto * mctx_iswa = inp -> mctx ; 3120 3121const auto * mctx_cur = is_swa ?mctx_iswa -> get_swa () :mctx_iswa -> get_base (); 3122 3123// optionally store to KV cache 3124if (k_cur ) { 3125const auto & k_idxs = is_swa ?inp -> get_k_idxs_swa () :inp -> get_k_idxs (); 3126 3127ggml_build_forward_expand (gf ,mctx_cur -> cpy_k (ctx0 ,k_cur ,k_idxs ,il )); 3128 } 3129 3130if (v_cur ) { 3131const auto & v_idxs = is_swa ?inp -> get_v_idxs_swa () :inp -> get_v_idxs (); 3132 3133ggml_build_forward_expand (gf ,mctx_cur -> cpy_v (ctx0 ,v_cur ,v_idxs ,il )); 3134 } 3135 3136const auto & kq_mask = is_swa ?inp -> get_kq_mask_swa () :inp -> get_kq_mask (); 3137 3138ggml_tensor * q = q_cur ; 3139ggml_tensor * k = mctx_cur -> get_k (ctx0 ,il ); 3140ggml_tensor * v = mctx_cur -> get_v (ctx0 ,il ); 3141 3142ggml_tensor * cur = build_attn_mha (q ,k ,v ,kq_b ,kq_mask ,sinks ,v_mla ,0 ,kq_scale ,il ); 3143cb (cur ,"kqv_out" ,il ); 3144 3145if (v_rot ) { 3146cur = llama_mul_mat_hadamard (ctx0 ,cur ,v_rot ); 3147 } 3148 3149if (wo ) { 3150cur = build_lora_mm (wo ,cur ,wo_s ); 3151 } 3152 3153if (wo_b ) { 3154//cb(cur, "kqv_wo", il); 3155 } 3156 3157if (wo_b ) { 3158cur = ggml_add (ctx0 ,cur ,wo_b ); 3159 } 3160 3161return cur ; 3162} 3163 3164ggml_tensor * llm_graph_context::build_attn ( 3165llm_graph_input_attn_k_iswa * inp , 3166ggml_tensor * wo , 3167ggml_tensor * wo_b , 3168ggml_tensor * wo_s , 3169ggml_tensor * q_cur , 3170ggml_tensor * k_cur , 3171ggml_tensor * v_cur , 3172ggml_tensor * kq_b , 3173ggml_tensor * sinks , 3174ggml_tensor * v_mla , 3175float kq_scale , 3176int il )const { 3177const bool is_swa = hparams .is_swa (il ); 3178 3179auto * k_rot = is_swa ?inp -> self_k_rot_swa :inp -> self_k_rot ; 3180 3181if (k_rot ) { 3182q_cur = llama_mul_mat_hadamard (ctx0 ,q_cur ,k_rot ); 3183if (k_cur ) { 3184k_cur = llama_mul_mat_hadamard (ctx0 ,k_cur ,k_rot ); 3185 } 3186 } 3187 3188// these nodes are added to the graph together so that they are not reordered 3189// by doing so, the number of splits in the graph is reduced 3190ggml_build_forward_expand (gf ,q_cur ); 3191 3192if (k_cur ) { 3193ggml_build_forward_expand (gf ,k_cur ); 3194 } 3195 3196const auto * mctx_iswa = inp -> mctx ; 3197const auto * mctx_cur = is_swa ?mctx_iswa -> get_swa () :mctx_iswa -> get_base (); 3198 3199// optionally store to KV cache 3200if (k_cur ) { 3201const auto & k_idxs = is_swa ?inp -> get_k_idxs_swa () :inp -> get_k_idxs (); 3202 3203ggml_build_forward_expand (gf ,mctx_cur -> cpy_k (ctx0 ,k_cur ,k_idxs ,il )); 3204 } 3205 3206const auto & kq_mask = is_swa ?inp -> get_kq_mask_swa () :inp -> get_kq_mask (); 3207 3208// MLA-style attention: the cached K is used as V 3209ggml_tensor * q = q_cur ; 3210ggml_tensor * k = mctx_cur -> get_k (ctx0 ,il ); 3211ggml_tensor * v = ggml_view_4d (ctx0 ,k ,v_cur -> ne [0 ],k -> ne [1 ],k -> ne [2 ],k -> ne [3 ],k -> nb [1 ],k -> nb [2 ],k -> nb [3 ],0 ); 3212 3213ggml_tensor * cur = build_attn_mha (q ,k ,v ,kq_b ,kq_mask ,sinks ,v_mla ,0 ,kq_scale ,il ); 3214cb (cur ,"kqv_out" ,il ); 3215 3216if (k_rot ) { 3217cur = llama_mul_mat_hadamard (ctx0 ,cur ,k_rot ); 3218 } 3219 3220if (wo ) { 3221cur = build_lora_mm (wo ,cur ,wo_s ); 3222 } 3223 3224if (wo_b ) { 3225cur = ggml_add (ctx0 ,cur ,wo_b ); 3226 } 3227 3228return cur ; 3229} 3230 3231llm_graph_input_attn_cross * llm_graph_context::build_attn_inp_cross ()const { 3232auto inp = std::make_unique < llm_graph_input_attn_cross > (cross ); 3233 3234const int32_t n_enc = !cross -> v_embd .empty () ?cross -> n_enc :hparams .n_ctx_train ; 3235 3236// flash attention requires an f16 mask 3237const auto type_mask = cparams .flash_attn ?GGML_TYPE_F16 :GGML_TYPE_F32 ; 3238 3239inp -> cross_kq_mask = ggml_new_tensor_4d (ctx0 ,type_mask ,n_enc ,n_tokens ,1 ,1 ); 3240ggml_set_input (inp -> cross_kq_mask ); 3241 3242inp -> cross_kq_mask_cnv = inp -> cross_kq_mask ; 3243 3244return (llm_graph_input_attn_cross * )res -> add_input (std::move (inp )); 3245} 3246 3247ggml_tensor * llm_graph_context::build_attn ( 3248llm_graph_input_attn_cross * inp , 3249ggml_tensor * wo , 3250ggml_tensor * wo_b , 3251ggml_tensor * wo_s , 3252ggml_tensor * q_cur , 3253ggml_tensor * k_cur , 3254ggml_tensor * v_cur , 3255ggml_tensor * kq_b , 3256ggml_tensor * sinks , 3257ggml_tensor * v_mla , 3258float kq_scale , 3259int il )const { 3260// these nodes are added to the graph together so that they are not reordered 3261// by doing so, the number of splits in the graph is reduced 3262ggml_build_forward_expand (gf ,q_cur ); 3263ggml_build_forward_expand (gf ,k_cur ); 3264ggml_build_forward_expand (gf ,v_cur ); 3265 3266const auto & kq_mask = inp -> get_kq_mask_cross (); 3267 3268ggml_tensor * q = q_cur ; 3269ggml_tensor * k = k_cur ; 3270ggml_tensor * v = v_cur ; 3271 3272ggml_tensor * cur = build_attn_mha (q ,k ,v ,kq_b ,kq_mask ,sinks ,v_mla ,0 ,kq_scale ,il ); 3273cb (cur ,"kqv_out" ,il ); 3274 3275if (wo ) { 3276cur = build_lora_mm (wo ,cur ,wo_s ); 3277 } 3278 3279if (wo_b ) { 3280//cb(cur, "kqv_wo", il); 3281 } 3282 3283if (wo_b ) { 3284cur = ggml_add (ctx0 ,cur ,wo_b ); 3285 } 3286 3287return cur ; 3288} 3289 3290static std::unique_ptr < llm_graph_input_attn_k_dsa > build_attn_inp_k_dsa_impl ( 3291ggml_context * ctx0 , 3292const llama_ubatch & ubatch , 3293const llama_hparams & hparams , 3294const llama_cparams & cparams , 3295const llama_kv_cache_dsa_context * mctx_cur ) { 3296 3297auto inp = std::make_unique < llm_graph_input_attn_k_dsa > (hparams ,cparams ,mctx_cur ); 3298 3299 { 3300inp -> self_k_idxs_mla = mctx_cur -> get_mla ()-> build_input_k_idxs (ctx0 ,ubatch ); 3301 3302inp -> self_kq_mask_mla = build_attn_inp_kq_mask (ctx0 ,mctx_cur -> get_mla (),ubatch ,cparams ); 3303inp -> self_kq_mask_mla_cnv = inp -> self_kq_mask_mla ; 3304 } 3305 3306 { 3307inp -> self_k_idxs_lid = mctx_cur -> get_lid ()-> build_input_k_idxs (ctx0 ,ubatch ); 3308 3309// ensure that mask type matches fused lightning indexer use (requires f16 mask) 3310auto cparams_copy = cparams ; 3311cparams_copy .flash_attn = cparams .fused_lid ; 3312 3313inp -> self_kq_mask_lid = build_attn_inp_kq_mask (ctx0 ,mctx_cur -> get_lid (),ubatch ,cparams_copy ); 3314inp -> self_kq_mask_lid_cnv = inp -> self_kq_mask_lid ; 3315 3316inp -> self_k_rot_lid = mctx_cur -> get_lid ()-> build_input_k_rot (ctx0 ); 3317 } 3318 3319return inp ; 3320} 3321 3322llm_graph_input_attn_k_dsa * llm_graph_context::build_attn_inp_k_dsa ()const { 3323const auto * mctx_cur = static_cast < const llama_kv_cache_dsa_context *> (mctx ); 3324 3325auto inp = build_attn_inp_k_dsa_impl (ctx0 ,ubatch ,hparams ,cparams ,mctx_cur ); 3326 3327return (llm_graph_input_attn_k_dsa * )res -> add_input (std::move (inp )); 3328} 3329 3330llm_graph_input_attn_k_dsa_iswa * llm_graph_context::build_attn_inp_k_dsa_iswa ()const { 3331const auto * mctx_cur = static_cast < const llama_kv_cache_dsa_iswa_context *> (mctx ); 3332 3333auto inp_dsa = build_attn_inp_k_dsa_impl (ctx0 ,ubatch ,hparams ,cparams ,mctx_cur -> get_dsa ()); 3334 3335// build_attn_inp_k_impl rejects SWA caches, so construct the input directly 3336auto inp_swa = std::make_unique < llm_graph_input_attn_k > (hparams ,cparams ,mctx_cur -> get_swa ()); 3337 3338inp_swa -> self_k_idxs = mctx_cur -> get_swa ()-> build_input_k_idxs (ctx0 ,ubatch ); 3339 3340inp_swa -> self_kq_mask = build_attn_inp_kq_mask (ctx0 ,mctx_cur -> get_swa (),ubatch ,cparams ); 3341inp_swa -> self_kq_mask_cnv = inp_swa -> self_kq_mask ; 3342 3343auto inp = std::make_unique < llm_graph_input_attn_k_dsa_iswa > (std::move (inp_dsa ), std::move (inp_swa ),mctx_cur ); 3344 3345return (llm_graph_input_attn_k_dsa_iswa * )res -> add_input (std::move (inp )); 3346} 3347 3348llm_graph_input_attn_kv_msa * llm_graph_context::build_attn_inp_kv_msa (bool msa_enabled )const { 3349const auto * mctx_cur = static_cast < const llama_kv_cache_msa_context *> (mctx ); 3350 3351auto inp = std::make_unique < llm_graph_input_attn_kv_msa > (hparams ,cparams ,mctx_cur ); 3352 3353const auto * mctx_base = mctx_cur -> get_base (); 3354const auto * mctx_idx = mctx_cur -> get_idx (); 3355 3356 { 3357GGML_ASSERT (hparams .swa_type == LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache_iswa for SWA" ); 3358 3359inp -> self_k_idxs = mctx_base -> build_input_k_idxs (ctx0 ,ubatch ); 3360inp -> self_v_idxs = mctx_base -> build_input_v_idxs (ctx0 ,ubatch ); 3361 3362inp -> self_kq_mask = build_attn_inp_kq_mask (ctx0 ,mctx_base ,ubatch ,cparams ); 3363inp -> self_kq_mask_cnv = inp -> self_kq_mask ; 3364 } 3365 3366inp -> self_k_rot = mctx_base -> build_input_k_rot (ctx0 ); 3367inp -> self_v_rot = mctx_base -> build_input_v_rot (ctx0 ); 3368 3369if (msa_enabled ) { 3370inp -> self_k_idxs_idx = mctx_idx -> build_input_k_idxs (ctx0 ,ubatch ); 3371 } 3372 3373return (llm_graph_input_attn_kv_msa * )res -> add_input (std::move (inp )); 3374} 3375 3376// TODO: maybe separate the inner implementation into a separate function 3377// like with the non-sliding window equivalent 3378// once sliding-window hybrid caches are a thing. 3379llm_graph_input_attn_kv_iswa * llm_graph_context::build_attn_inp_kv_iswa ()const { 3380const auto * mctx_cur = static_cast < const llama_kv_cache_iswa_context *> (mctx ); 3381 3382auto inp = std::make_unique < llm_graph_input_attn_kv_iswa > (hparams ,cparams ,mctx_cur ); 3383 3384 { 3385inp -> self_k_idxs = mctx_cur -> get_base ()-> build_input_k_idxs (ctx0 ,ubatch ); 3386inp -> self_v_idxs = mctx_cur -> get_base ()-> build_input_v_idxs (ctx0 ,ubatch ); 3387 3388inp -> self_kq_mask = build_attn_inp_kq_mask (ctx0 ,mctx_cur -> get_base (),ubatch ,cparams ); 3389inp -> self_kq_mask_cnv = inp -> self_kq_mask ; 3390 } 3391 3392 { 3393GGML_ASSERT (hparams .swa_type != LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache for non-SWA" ); 3394 3395inp -> self_k_idxs_swa = mctx_cur -> get_swa ()-> build_input_k_idxs (ctx0 ,ubatch ); 3396inp -> self_v_idxs_swa = mctx_cur -> get_swa ()-> build_input_v_idxs (ctx0 ,ubatch ); 3397 3398inp -> self_kq_mask_swa = build_attn_inp_kq_mask (ctx0 ,mctx_cur -> get_swa (),ubatch ,cparams ); 3399inp -> self_kq_mask_swa_cnv = inp -> self_kq_mask_swa ; 3400 } 3401 3402inp -> self_k_rot = mctx_cur -> get_base ()-> build_input_k_rot (ctx0 ); 3403inp -> self_v_rot = mctx_cur -> get_base ()-> build_input_v_rot (ctx0 ); 3404 3405inp -> self_k_rot_swa = mctx_cur -> get_swa ()-> build_input_k_rot (ctx0 ); 3406inp -> self_v_rot_swa = mctx_cur -> get_swa ()-> build_input_v_rot (ctx0 ); 3407 3408return (llm_graph_input_attn_kv_iswa * )res -> add_input (std::move (inp )); 3409} 3410 3411llm_graph_input_attn_k_iswa * llm_graph_context::build_attn_inp_k_iswa ()const { 3412const auto * mctx_cur = static_cast < const llama_kv_cache_iswa_context *> (mctx ); 3413 3414auto inp = std::make_unique < llm_graph_input_attn_k_iswa > (hparams ,cparams ,mctx_cur ); 3415 3416 { 3417inp -> self_k_idxs = mctx_cur -> get_base ()-> build_input_k_idxs (ctx0 ,ubatch ); 3418 3419inp -> self_kq_mask = build_attn_inp_kq_mask (ctx0 ,mctx_cur -> get_base (),ubatch ,cparams ); 3420inp -> self_kq_mask_cnv = inp -> self_kq_mask ; 3421 } 3422 3423 { 3424GGML_ASSERT (hparams .swa_type != LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache for non-SWA" ); 3425 3426inp -> self_k_idxs_swa = mctx_cur -> get_swa ()-> build_input_k_idxs (ctx0 ,ubatch ); 3427 3428inp -> self_kq_mask_swa = build_attn_inp_kq_mask (ctx0 ,mctx_cur -> get_swa (),ubatch ,cparams ); 3429inp -> self_kq_mask_swa_cnv = inp -> self_kq_mask_swa ; 3430 } 3431 3432inp -> self_k_rot = mctx_cur -> get_base ()-> build_input_k_rot (ctx0 ); 3433 3434inp -> self_k_rot_swa = mctx_cur -> get_swa ()-> build_input_k_rot (ctx0 ); 3435 3436return (llm_graph_input_attn_k_iswa * )res -> add_input (std::move (inp )); 3437} 3438 3439llm_graph_input_dsv4 * llm_graph_context::build_inp_dsv4 ()const { 3440const auto * mctx_cur = static_cast < const llama_kv_cache_dsv4_context *> (mctx ); 3441const auto * raw_ctx = mctx_cur -> get_raw (); 3442 3443auto inp_raw = std::make_unique < llm_graph_input_dsv4_raw > (cparams ,raw_ctx ); 3444 3445const int64_t n_stream = mctx_cur -> get_csa_plan (ubatch ).n_stream ; 3446 3447GGML_ASSERT (hparams .swa_type != LLAMA_SWA_TYPE_NONE && "DSV4 expects SWA raw cache" ); 3448 3449inp_raw -> self_k_idxs = raw_ctx -> build_input_k_idxs (ctx0 ,ubatch ); 3450inp_raw -> self_kq_mask = dsv4_build_raw_kq_mask (ctx0 ,raw_ctx ,ubatch ,cparams ,n_stream ); 3451inp_raw -> self_kq_mask_cnv = inp_raw -> self_kq_mask ; 3452 3453inp_raw -> self_k_rot = raw_ctx -> build_input_k_rot (ctx0 ); 3454auto inp = std::make_unique < llm_graph_input_dsv4 > (cparams , std::move (inp_raw ),mctx_cur ); 3455 3456dsv4_build_comp_inputs (ctx0 ,inp -> inp_csa ,mctx_cur -> get_csa_plan (ubatch ),"csa" ,cparams ,n_stream ); 3457dsv4_build_comp_inputs (ctx0 ,inp -> inp_hca ,mctx_cur -> get_hca_plan (ubatch ),"hca" ,cparams ,n_stream ); 3458dsv4_build_comp_inputs (ctx0 ,inp -> inp_lid ,mctx_cur -> get_lid_plan (ubatch ),"lid" ,cparams ,n_stream ); 3459inp -> inp_csa .k_rot = mctx_cur -> get_csa ()-> build_input_k_rot (ctx0 ); 3460inp -> inp_hca .k_rot = mctx_cur -> get_hca ()-> build_input_k_rot (ctx0 ); 3461inp -> inp_lid .k_rot = mctx_cur -> get_lid ()-> build_input_k_rot (ctx0 ); 3462 3463return (llm_graph_input_dsv4 * )res -> add_input (std::move (inp )); 3464} 3465 3466ggml_tensor * llm_graph_context::build_rs ( 3467ggml_tensor * s , 3468ggml_tensor * state_copy_main , 3469ggml_tensor * state_copy_extra , 3470int32_t state_size , 3471int32_t n_seqs , 3472uint32_t n_rs , 3473uint32_t rs_head , 3474uint32_t rs_size , 3475int32_t rs_zero , 3476const llm_graph_get_rows_fn & get_state_rows )const { 3477 3478GGML_UNUSED (rs_size ); 3479ggml_tensor * states = ggml_reshape_2d (ctx0 ,s ,state_size ,s -> ne [1 ]); 3480 3481// Clear a single state which will then be copied to the other cleared states. 3482// Note that this is a no-op when the view is zero-sized. 3483ggml_tensor * state_zero = ggml_view_1d (ctx0 ,states ,state_size * (rs_zero >=0 ),rs_zero * states -> nb [1 ]* (rs_zero >=0 )); 3484ggml_build_forward_expand (gf ,ggml_scale_inplace (ctx0 ,state_zero ,0 )); 3485 3486// copy states 3487// NOTE: assuming the copy destinations are ALL contained between rs_head and rs_head + n_rs 3488// {state_size, rs_size} -> {state_size, n_seqs} 3489ggml_tensor * output_states = get_state_rows (ctx0 ,states ,state_copy_main ); 3490ggml_build_forward_expand (gf ,output_states ); 3491 3492// copy extra states which won't be changed further (between n_seqs and n_rs) 3493ggml_tensor * states_extra = ggml_get_rows (ctx0 ,states ,state_copy_extra ); 3494ggml_build_forward_expand (gf , 3495ggml_cpy (ctx0 , 3496states_extra , 3497ggml_view_2d (ctx0 ,s ,state_size , (n_rs - n_seqs ),s -> nb [1 ], (rs_head + n_seqs )* s -> nb [1 ]))); 3498 3499return output_states ; 3500} 3501 3502static std::unique_ptr < llm_graph_input_rs > build_rs_inp_impl ( 3503ggml_context * ctx0 , 3504const llama_ubatch & ubatch , 3505const llama_memory_recurrent_context * mctx_cur ) { 3506 3507auto inp = std::make_unique < llm_graph_input_rs > (mctx_cur ); 3508 3509const int64_t n_rs = mctx_cur -> get_n_rs (); 3510const int64_t n_seqs = ubatch .n_seqs ; 3511 3512inp -> s_copy = ggml_new_tensor_1d (ctx0 ,GGML_TYPE_I32 ,n_rs ); 3513ggml_set_input (inp -> s_copy ); 3514 3515inp -> s_copy_main = ggml_view_1d (ctx0 ,inp -> s_copy ,n_seqs ,0 ); 3516inp -> s_copy_extra = ggml_view_1d (ctx0 ,inp -> s_copy ,n_rs - n_seqs ,n_seqs * inp -> s_copy -> nb [0 ]); 3517 3518inp -> head = mctx_cur -> get_head (); 3519inp -> rs_z = mctx_cur -> get_rs_z (); 3520 3521return inp ; 3522} 3523 3524llm_graph_input_rs * llm_graph_context::build_rs_inp ()const { 3525const auto * mctx_cur = static_cast < const llama_memory_recurrent_context *> (mctx ); 3526 3527auto inp = build_rs_inp_impl (ctx0 ,ubatch ,mctx_cur ); 3528 3529return (llm_graph_input_rs * )res -> add_input (std::move (inp )); 3530} 3531 3532ggml_tensor * llm_graph_context::build_rs ( 3533llm_graph_input_rs * inp , 3534ggml_tensor * s , 3535int32_t state_size , 3536int32_t n_seqs , 3537const llm_graph_get_rows_fn & get_state_rows )const { 3538const auto * kv_state = inp -> mctx ; 3539 3540return build_rs (s ,inp -> s_copy_main ,inp -> s_copy_extra ,state_size ,n_seqs , 3541kv_state -> get_n_rs (),kv_state -> get_head (),kv_state -> get_size (),kv_state -> get_rs_z (), 3542get_state_rows ); 3543} 3544 3545ggml_tensor * llm_graph_context::build_rwkv_token_shift_load ( 3546llm_graph_input_rs * inp , 3547const llama_ubatch & ubatch , 3548int il )const { 3549const auto * mctx_cur = static_cast < const llama_memory_recurrent_context *> (mctx ); 3550 3551const auto token_shift_count = hparams .token_shift_count ; 3552 3553const int64_t n_seqs = ubatch .n_seqs ; 3554 3555ggml_tensor * token_shift_all = mctx_cur -> get_r_l (il ); 3556 3557ggml_tensor * token_shift = build_rs ( 3558inp ,token_shift_all , 3559hparams .n_embd_r (),n_seqs ); 3560 3561token_shift = ggml_reshape_3d (ctx0 ,token_shift ,hparams .n_embd ,token_shift_count ,n_seqs ); 3562 3563return token_shift ; 3564} 3565 3566ggml_tensor * llm_graph_context::build_rwkv_token_shift_store ( 3567ggml_tensor * token_shift , 3568const llama_ubatch & ubatch , 3569int il )const { 3570const auto * mctx_cur = static_cast < const llama_memory_recurrent_context *> (mctx ); 3571 3572const auto token_shift_count = hparams .token_shift_count ; 3573const auto n_embd = hparams .n_embd ; 3574 3575const int64_t n_seqs = ubatch .n_seqs ; 3576 3577const auto kv_head = mctx_cur -> get_head (); 3578 3579return ggml_cpy ( 3580ctx0 , 3581ggml_view_1d (ctx0 ,token_shift ,n_embd * n_seqs * token_shift_count ,0 ), 3582ggml_view_1d (ctx0 ,mctx_cur -> get_r_l (il ),hparams .n_embd_r ()* n_seqs ,hparams .n_embd_r ()* kv_head * ggml_element_size (mctx_cur -> get_r_l (il ))) 3583 ); 3584} 3585 3586llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid ()const { 3587const auto * mctx_cur = static_cast < const llama_memory_hybrid_context *> (mctx ); 3588 3589auto inp_rs = build_rs_inp_impl (ctx0 ,ubatch ,mctx_cur -> get_recr ()); 3590auto inp_attn = build_attn_inp_kv_impl (ctx0 ,ubatch ,hparams ,cparams ,mctx_cur -> get_attn ()); 3591 3592auto inp = std::make_unique < llm_graph_input_mem_hybrid > (cparams , std::move (inp_attn ), std::move (inp_rs ),mctx_cur ); 3593 3594return (llm_graph_input_mem_hybrid * )res -> add_input (std::move (inp )); 3595} 3596 3597llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k ()const { 3598const auto * mctx_cur = static_cast < const llama_memory_hybrid_context *> (mctx ); 3599 3600auto inp_rs = build_rs_inp_impl (ctx0 ,ubatch ,mctx_cur -> get_recr ()); 3601auto inp_attn = build_attn_inp_k_impl (ctx0 ,ubatch ,hparams ,cparams ,mctx_cur -> get_attn ()); 3602 3603auto inp = std::make_unique < llm_graph_input_mem_hybrid_k > (cparams , std::move (inp_attn ), std::move (inp_rs ),mctx_cur ); 3604 3605return (llm_graph_input_mem_hybrid_k * )res -> add_input (std::move (inp )); 3606} 3607 3608llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa ()const { 3609const auto * mctx_cur = static_cast < const llama_memory_hybrid_iswa_context *> (mctx ); 3610 3611auto inp_rs = build_rs_inp_impl (ctx0 ,ubatch ,mctx_cur -> get_recr ()); 3612 3613// build iswa attention input 3614const auto * attn_ctx = mctx_cur -> get_attn (); 3615 3616auto inp_attn = std::make_unique < llm_graph_input_attn_kv_iswa > (hparams ,cparams ,attn_ctx ); 3617 3618 { 3619inp_attn -> self_k_idxs = attn_ctx -> get_base ()-> build_input_k_idxs (ctx0 ,ubatch ); 3620inp_attn -> self_v_idxs = attn_ctx -> get_base ()-> build_input_v_idxs (ctx0 ,ubatch ); 3621 3622inp_attn -> self_kq_mask = build_attn_inp_kq_mask (ctx0 ,attn_ctx -> get_base (),ubatch ,cparams ); 3623inp_attn -> self_kq_mask_cnv = inp_attn -> self_kq_mask ; 3624 } 3625 3626 { 3627inp_attn -> self_k_idxs_swa = attn_ctx -> get_swa ()-> build_input_k_idxs (ctx0 ,ubatch ); 3628inp_attn -> self_v_idxs_swa = attn_ctx -> get_swa ()-> build_input_v_idxs (ctx0 ,ubatch ); 3629 3630inp_attn -> self_kq_mask_swa = build_attn_inp_kq_mask (ctx0 ,attn_ctx -> get_swa (),ubatch ,cparams ); 3631inp_attn -> self_kq_mask_swa_cnv = inp_attn -> self_kq_mask_swa ; 3632 } 3633 3634auto inp = std::make_unique < llm_graph_input_mem_hybrid_iswa > (cparams , std::move (inp_attn ), std::move (inp_rs ),mctx_cur ); 3635 3636return (llm_graph_input_mem_hybrid_iswa * )res -> add_input (std::move (inp )); 3637} 3638 3639void llm_graph_context::build_dense_out ( 3640ggml_tensor * dense_2 , 3641ggml_tensor * dense_2_b , 3642ggml_tensor * dense_3 )const { 3643if (!cparams .embeddings || !(dense_2 || dense_2_b || dense_3 )) { 3644return ; 3645 } 3646ggml_tensor * cur = res -> t_embd_pooled != nullptr ?res -> t_embd_pooled :res -> t_embd ; 3647GGML_ASSERT (cur != nullptr && "missing t_embd_pooled/t_embd" ); 3648 3649if (dense_2 ) { 3650cur = ggml_mul_mat (ctx0 ,dense_2 ,cur ); 3651 } 3652if (dense_2_b ) { 3653cur = ggml_add (ctx0 ,cur ,dense_2_b ); 3654 } 3655if (dense_3 ) { 3656cur = ggml_mul_mat (ctx0 ,dense_3 ,cur ); 3657 } 3658cb (cur ,"result_embd_pooled" ,-1 ); 3659res -> t_embd_pooled = cur ; 3660ggml_build_forward_expand (gf ,cur ); 3661} 3662 3663 3664void llm_graph_context::build_pooling ( 3665ggml_tensor * cls , 3666ggml_tensor * cls_b , 3667ggml_tensor * cls_out , 3668ggml_tensor * cls_out_b , 3669ggml_tensor * cls_norm )const { 3670if (!cparams .embeddings ) { 3671return ; 3672 } 3673 3674ggml_tensor * inp = res -> t_embd ; 3675 3676//// find result_norm tensor for input 3677//for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) { 3678// inp = ggml_graph_node(gf, i); 3679// if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) { 3680// break; 3681// } 3682 3683// inp = nullptr; 3684//} 3685 3686GGML_ASSERT (inp != nullptr && "missing result_norm/result_embd tensor" ); 3687 3688ggml_tensor * cur ; 3689 3690switch (pooling_type ) { 3691case LLAMA_POOLING_TYPE_NONE : 3692 { 3693cur = inp ; 3694 }break ; 3695case LLAMA_POOLING_TYPE_MEAN : 3696 { 3697ggml_tensor * inp_mean = build_inp_mean (); 3698cur = ggml_mul_mat (ctx0 ,ggml_cont (ctx0 ,ggml_transpose (ctx0 ,inp )),inp_mean ); 3699 }break ; 3700case LLAMA_POOLING_TYPE_CLS : 3701case LLAMA_POOLING_TYPE_LAST : 3702 { 3703ggml_tensor * inp_cls = build_inp_cls (); 3704cur = ggml_get_rows (ctx0 ,inp ,inp_cls ); 3705 }break ; 3706case LLAMA_POOLING_TYPE_RANK : 3707 { 3708if (arch == LLM_ARCH_MODERN_BERT ) { 3709// modern bert gte reranker builds mean first then applies prediction head and classifier 3710// https://github.com/huggingface/transformers/blob/main/src/transformers/models/modernbert/modular_modernbert.py#L1404-1411 3711ggml_tensor * inp_mean = build_inp_mean (); 3712cur = ggml_mul_mat (ctx0 ,ggml_cont (ctx0 ,ggml_transpose (ctx0 ,inp )),inp_mean ); 3713 }else { 3714ggml_tensor * inp_cls = build_inp_cls (); 3715cur = ggml_get_rows (ctx0 ,inp ,inp_cls ); 3716 } 3717 3718// classification head 3719// https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566 3720if (cls ) { 3721cur = ggml_mul_mat (ctx0 ,cls ,cur ); 3722if (cls_b ) { 3723cur = ggml_add (ctx0 ,cur ,cls_b ); 3724 } 3725if (arch == LLM_ARCH_MODERN_BERT ) { 3726cur = ggml_gelu (ctx0 ,cur ); 3727 }else { 3728cur = ggml_tanh (ctx0 ,cur ); 3729 } 3730if (cls_norm ) { 3731// head norm 3732cur = build_norm (cur ,cls_norm ,NULL ,LLM_NORM ,-1 ); 3733 } 3734 } 3735 3736// some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en 3737// https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896 3738// Single layer classification head (direct projection) 3739// https://github.com/huggingface/transformers/blob/f4fc42216cd56ab6b68270bf80d811614d8d59e4/src/transformers/models/bert/modeling_bert.py#L1476 3740if (cls_out ) { 3741cur = ggml_mul_mat (ctx0 ,cls_out ,cur ); 3742if (cls_out_b ) { 3743cur = ggml_add (ctx0 ,cur ,cls_out_b ); 3744 } 3745 } 3746 3747// softmax for qwen3 reranker 3748if (arch == LLM_ARCH_QWEN3 || arch == LLM_ARCH_QWEN3VL ) { 3749cur = ggml_soft_max (ctx0 ,cur ); 3750 } 3751 }break ; 3752default : 3753 { 3754GGML_ABORT ("unknown pooling type" ); 3755 } 3756 } 3757 3758cb (cur ,"result_embd_pooled" ,-1 ); 3759res -> t_embd_pooled = cur ; 3760 3761ggml_build_forward_expand (gf ,cur ); 3762} 3763 3764void llm_graph_context::build_sampling ()const { 3765if (samplers .empty ()|| !res -> t_logits ) { 3766return ; 3767 } 3768 3769 std::array < ggml_tensor * ,2 > outs ; 3770outs [0 ]= res -> t_logits ; 3771 3772auto inp_sampling = std::make_unique < llm_graph_input_sampling > (samplers ); 3773res -> add_input (std::move (inp_sampling )); 3774 3775 std::map < llama_seq_id , std::vector < uint32_t >> sampling_rows ; 3776uint32_t n_rows = 0 ; 3777for (uint32_t i = 0 ;i < ubatch .n_tokens ;++ i ) { 3778if (ubatch .output [i ]) { 3779sampling_rows [ubatch .seq_id [i ][0 ]].push_back (n_rows ++ ); 3780 } 3781 } 3782 3783res -> t_sampled .resize (n_rows ,nullptr ); 3784res -> t_sampled_probs .resize (n_rows ,nullptr ); 3785res -> t_sampled_logits .resize (n_rows ,nullptr ); 3786res -> t_candidates .resize (n_rows ,nullptr ); 3787 3788// res->t_logits will contain logits for all tokens that want the logits calculated (logits=1 or output=1) 3789GGML_ASSERT (res -> t_logits != nullptr && "missing t_logits tensor" ); 3790 3791// add a dummy row to keep the single-output graph static regardless of active samplers 3792// multi-output graphs can still vary with the number of output rows 3793ggml_tensor * logits_t = ggml_pad (ctx0 ,res -> t_logits ,0 ,1 ,0 ,0 ); 3794 3795for (const auto & entry :samplers ) { 3796if (entry .second -> iface -> backend_reset ) { 3797entry .second -> iface -> backend_reset (entry .second ); 3798 } 3799 } 3800 3801static const std::vector < uint32_t > dummy_row = {0 }; 3802 3803for (const auto & [seq_id ,sampler ] :samplers ) { 3804const auto it = sampling_rows .find (seq_id ); 3805 3806// inactive samplers always work on the first row 3807const bool active = it != sampling_rows .end (); 3808const auto & rows = active ?it -> second :dummy_row ; 3809const int i_out = active ?1 :0 ; 3810 3811for (uint32_t i = 0 ;i < rows .size ();++ i ) { 3812ggml_tensor * logits_seq = ggml_view_1d (ctx0 ,logits_t ,logits_t -> ne [0 ],rows [i ]* logits_t -> nb [1 ]); 3813ggml_format_name (logits_seq ,"logits_seq_%d_%u" ,seq_id ,i ); 3814 3815struct llama_sampler_data data = { 3816/*.logits =*/ logits_seq , 3817/*.probs =*/ nullptr , 3818/*.sampled =*/ nullptr , 3819/*.candidates =*/ nullptr , 3820 }; 3821 3822assert (sampler -> iface -> backend_apply ); 3823sampler -> iface -> backend_apply (sampler ,ctx0 ,gf ,& data ); 3824 3825if (data .sampled != nullptr ) { 3826if (active ) { 3827res -> t_sampled [rows [i ]]= data .sampled ; 3828 } 3829outs [1 ]= data .sampled ; 3830ggml_build_forward_select (gf ,outs .data (),outs .size (),i_out ); 3831 } 3832 3833if (data .probs != nullptr ) { 3834if (active ) { 3835res -> t_sampled_probs [rows [i ]]= data .probs ; 3836 } 3837outs [1 ]= data .probs ; 3838ggml_build_forward_select (gf ,outs .data (),outs .size (),i_out ); 3839 } 3840 3841if (data .logits != nullptr ) { 3842if (active ) { 3843res -> t_sampled_logits [rows [i ]]= data .logits ; 3844 } 3845outs [1 ]= data .logits ; 3846ggml_build_forward_select (gf ,outs .data (),outs .size (),i_out ); 3847 } 3848 3849if (data .candidates != nullptr ) { 3850if (active ) { 3851res -> t_candidates [rows [i ]]= data .candidates ; 3852 } 3853outs [1 ]= data .candidates ; 3854ggml_build_forward_select (gf ,outs .data (),outs .size (),i_out ); 3855 } 3856 } 3857 } 3858 3859// TODO: Call backend_accept after all samplers have been applied. 3860/* 3861for (const auto & [seq_id, sampler] : samplers) { 3862const auto it = sampling_rows.find(seq_id); 3863if (it == sampling_rows.end()) { 3864continue; 3865} 3866 3867for (uint32_t row : it->second) { 3868ggml_tensor * selected_token = res->t_sampled[row]; 3869if (selected_token != nullptr && sampler->iface->backend_accept) { 3870sampler->iface->backend_accept(sampler, ctx0, gf, selected_token); 3871} 3872} 3873} 3874*/ 3875} 3876 3877int32_t llama_relative_position_bucket (llama_pos x ,llama_pos y ,uint64_t n_buckets ,bool bidirectional ) { 3878// TODO move to hparams if a T5 variant appears that uses a different value 3879const int64_t max_distance = 128 ; 3880 3881if (bidirectional ) { 3882n_buckets >>=1 ; 3883 } 3884 3885const int64_t max_exact = n_buckets >>1 ; 3886 3887int32_t relative_position = x - y ; 3888int32_t relative_bucket = 0 ; 3889 3890if (bidirectional ) { 3891relative_bucket += (relative_position > 0 )* n_buckets ; 3892relative_position = std::abs (relative_position ); 3893 }else { 3894relative_position = - std::min < int32_t > (relative_position ,0 ); 3895 } 3896 3897int32_t relative_position_if_large = floorf (max_exact + logf (1.0 * relative_position /max_exact )* (n_buckets - max_exact ) /log (1.0 * max_distance /max_exact )); 3898relative_position_if_large = std::min < int32_t > (relative_position_if_large ,n_buckets - 1 ); 3899relative_bucket += (relative_position < max_exact ?relative_position :relative_position_if_large ); 3900 3901return relative_bucket ; 3902}