char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
163a40796
char/aliceai-t5-moe
1#include "llama-kv-cache.h" 2 3#include "llama-impl.h" 4#include "llama-io.h" 5#include "llama-model.h" 6#include "llama-context.h" 7 8#include <algorithm> 9#include <cassert> 10#include <cmath> 11#include <cstring> 12#include <limits> 13#include <map> 14#include <stdexcept> 15#include <unordered_map> 16 17static bool ggml_is_power_of_2 (int n ) { 18return (n & (n - 1 ))== 0 ; 19} 20 21// orthonormal Walsh-Hadamard rotation matrix 22// note: res^2 == I 23static void ggml_gen_hadamard (ggml_tensor * tensor ) { 24assert (tensor -> type == GGML_TYPE_F32 ); 25 26const int n = tensor -> ne [0 ]; 27 28assert (ggml_is_power_of_2 (n )); 29assert (tensor -> ne [1 ]== n ); 30assert (tensor -> ne [2 ]== 1 ); 31assert (tensor -> ne [3 ]== 1 ); 32 33 std::vector < float > data_f32 ; 34 35float * data = (float * )tensor -> data ; 36 37if (tensor -> type != GGML_TYPE_F32 ) { 38data_f32 .resize (n * n ); 39data = data_f32 .data (); 40 } 41 42data [0 * n + 0 ]= 1.0 /sqrtf (n ); 43 44for (int s = 1 ;s < n ;s *=2 ) { 45for (int i = 0 ;i < s ;i ++ ) { 46for (int j = 0 ;j < s ;j ++ ) { 47const float val = data [i * n + j ]; 48 49data [(i + s )* n + (j )]= val ; 50data [(i )* n + (j + s )]= val ; 51data [(i + s )* n + (j + s )]= - val ; 52 } 53 } 54 } 55 56if (tensor -> type != GGML_TYPE_F32 ) { 57ggml_quantize_chunk (tensor -> type ,data ,tensor -> data ,0 ,1 ,n * n ,nullptr ); 58 } 59} 60 61// 62// llama_kv_cache 63// 64 65llama_kv_cache::llama_kv_cache ( 66const llama_model & model , 67const llama_hparams & hparams , 68ggml_type type_k , 69ggml_type type_v , 70bool v_trans , 71bool offload , 72bool unified , 73uint32_t kv_size , 74uint32_t n_seq_max , 75uint32_t n_pad , 76uint32_t n_swa , 77llama_swa_type swa_type , 78llama_memory_t mem_other , 79const layer_filter_cb & filter , 80const layer_reuse_cb & reuse , 81const layer_share_cb & share , 82const char * name_tag ) : 83model (model ),hparams (hparams ),v_trans (v_trans ), 84n_seq_max (n_seq_max ),n_stream (unified ?1 :n_seq_max ),n_pad (n_pad ),n_swa (n_swa ),swa_type (swa_type ), 85other (static_cast < llama_kv_cache *> (mem_other )), 86v_cells_impl (other ?other -> v_cells_impl : std::make_shared < llama_kv_cells_vec > ()), 87v_cells (* v_cells_impl ) { 88 89// shared cells view the source cache's K/V tensors, so the cell count 90// follows the source allocation: a fitted target can be smaller than the 91// draft default and oversized views would overflow the source tensors 92if (other ) { 93const uint32_t size_other = other -> get_size (); 94if (kv_size != size_other ) { 95LLAMA_LOG_WARN ("%s: kv_size = %u overridden to %u to match the shared source cache\n" ,__func__ ,kv_size ,size_other ); 96kv_size = size_other ; 97 } 98 } 99 100GGML_ASSERT (kv_size %n_pad == 0 ); 101 102const uint32_t n_layer = hparams .n_layer_all ; 103 104// define a comparator for the buft -> ctx map to ensure that the order is well-defined: 105struct ggml_backend_buft_comparator { 106bool operator()(const ggml_backend_buffer_type_t & lhs ,const ggml_backend_buffer_type_t & rhs )const { 107return strcmp (ggml_backend_buft_name (lhs ),ggml_backend_buft_name (rhs ))< 0 ; 108 } 109 }; 110 std::map < ggml_backend_buffer_type_t ,ggml_context_ptr ,ggml_backend_buft_comparator > ctx_map ; 111 112// create a context for each buffer type 113auto ctx_for_buft = [& ](ggml_backend_buffer_type_t buft )-> ggml_context * { 114auto it = ctx_map .find (buft ); 115if (it == ctx_map .end ()) { 116ggml_init_params params = { 117/*.mem_size =*/ size_t (2u * (1 + n_stream )* n_layer * ggml_tensor_overhead ()), 118/*.mem_buffer =*/ NULL , 119/*.no_alloc =*/ true, 120 }; 121 122ggml_context * ctx = ggml_init (params ); 123if (!ctx ) { 124return nullptr ; 125 } 126 127ctx_map .emplace (buft ,ctx ); 128 129return ctx ; 130 } 131 132return it -> second .get (); 133 }; 134 135GGML_ASSERT (n_stream == 1 || n_stream == n_seq_max ); 136 137v_heads .resize (n_stream ); 138for (uint32_t s = 0 ;s < n_stream ;++ s ) { 139v_heads [s ]= 0 ; 140 } 141 142v_cells .resize (n_stream ); 143for (uint32_t s = 0 ;s < n_stream ;++ s ) { 144v_cells [s ].resize (kv_size ); 145 } 146 147// by default, all sequence ids are mapped to the 0th stream 148seq_to_stream .resize (LLAMA_MAX_SEQ ,0 ); 149 150if (n_stream > 1 ) { 151seq_to_stream .resize (n_stream ,0 ); 152for (uint32_t s = 0 ;s < n_stream ;++ s ) { 153seq_to_stream [s ]= s ; 154 } 155 } 156 157// [TAG_V_CACHE_VARIABLE] 158if (v_trans && hparams .is_n_embd_v_gqa_variable ()) { 159LLAMA_LOG_WARN ("%s: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to %d\n" , 160__func__ ,hparams .n_embd_v_gqa_max ()); 161 } 162 163const bool is_mla = hparams .is_mla (); 164 165for (uint32_t il = 0 ;il < n_layer ;il ++ ) { 166if (!hparams .has_kv (il )) { 167LLAMA_LOG_DEBUG ("%s: layer %3d: does not have KV cache\n" ,__func__ ,il ); 168continue ; 169 } 170 171if (filter && !filter (il )) { 172LLAMA_LOG_DEBUG ("%s: layer %3d: filtered\n" ,__func__ ,il ); 173continue ; 174 } 175 176if (share && other ) { 177const int32_t il_share = share (il ); 178 179if (il_share >=0 ) { 180const auto & layer_share = other -> layers [other -> map_layer_ids [il_share ]]; 181 182LLAMA_LOG_WARN ("%s: layer %3d: sharing with layer %d. k = %p, v = %p\n" ,__func__ ,il ,il_share , 183layer_share .k -> data ,layer_share .v -> data ); 184 185map_layer_ids [il ]= layers .size (); 186 187layers .push_back (layer_share ); 188layers .back ().il = il ; 189 190continue ; 191 } 192 } 193 194if (n_embd_head_k_all == 0 ) { 195n_embd_head_k_all = (int32_t )hparams .n_embd_head_k (il ); 196 }else if (n_embd_head_k_all > 0 && n_embd_head_k_all != (int32_t )hparams .n_embd_head_k (il )) { 197n_embd_head_k_all = -1 ; 198 } 199 200if (!is_mla ) { 201if (n_embd_head_v_all == 0 ) { 202n_embd_head_v_all = (int32_t )hparams .n_embd_head_v (il ); 203 }else if (n_embd_head_v_all > 0 && n_embd_head_v_all != (int32_t )hparams .n_embd_head_v (il )) { 204n_embd_head_v_all = -1 ; 205 } 206 } 207 208// [TAG_V_CACHE_VARIABLE] 209const uint32_t n_embd_k_gqa = hparams .n_embd_k_gqa (il ); 210const uint32_t n_embd_v_gqa = !v_trans ?hparams .n_embd_v_gqa (il ) :hparams .n_embd_v_gqa_max (); 211 212const char * dev_name = "CPU" ; 213 214ggml_backend_buffer_type_t buft = ggml_backend_cpu_buffer_type (); 215 216if (offload ) { 217auto * dev = model .dev_layer (il ); 218buft = ggml_backend_dev_buffer_type (dev ); 219 220dev_name = ggml_backend_dev_name (dev ); 221 } 222 223LLAMA_LOG_DEBUG ("%s: layer %3d: dev = %s\n" ,__func__ ,il ,dev_name ); 224 225ggml_context * ctx = ctx_for_buft (buft ); 226if (!ctx ) { 227throw std::runtime_error ("failed to create ggml context for kv cache" ); 228 } 229 230const bool has_k = true; 231const bool has_v = !is_mla ; 232 233ggml_tensor * k = has_k ?ggml_new_tensor_3d (ctx ,type_k ,n_embd_k_gqa ,kv_size ,n_stream ) :nullptr ; 234ggml_tensor * v = has_v ?ggml_new_tensor_3d (ctx ,type_v ,n_embd_v_gqa ,kv_size ,n_stream ) :nullptr ; 235 236has_k && ggml_format_name (k ,"cache_%sk_l%d" ,name_tag ,il ); 237has_v && ggml_format_name (v ,"cache_%sv_l%d" ,name_tag ,il ); 238 239 std::vector < ggml_tensor *> k_stream ; 240 std::vector < ggml_tensor *> v_stream ; 241 242for (uint32_t s = 0 ;s < n_stream ;++ s ) { 243k_stream .push_back (has_k ?ggml_view_2d (ctx ,k ,n_embd_k_gqa ,kv_size ,k -> nb [1 ],s * k -> nb [2 ]) :nullptr ); 244v_stream .push_back (has_v ?ggml_view_2d (ctx ,v ,n_embd_v_gqa ,kv_size ,v -> nb [1 ],s * v -> nb [2 ]) :nullptr ); 245 } 246 247map_layer_ids [il ]= layers .size (); 248 249layers .push_back ({il ,k ,v ,k_stream ,v_stream , }); 250 } 251 252if (reuse ) { 253LLAMA_LOG_DEBUG ("%s: reusing layers:\n" ,__func__ ); 254 255for (uint32_t il = 0 ;il < n_layer ;il ++ ) { 256const int32_t il_reuse = reuse (il ); 257 258if (il_reuse < 0 ) { 259LLAMA_LOG_DEBUG ("%s: - layer %3d: no reuse\n" ,__func__ ,il ); 260continue ; 261 } 262 263if (filter && !filter (il )) { 264LLAMA_LOG_DEBUG ("%s: - layer %3d: filtered\n" ,__func__ ,il ); 265continue ; 266 } 267 268GGML_ASSERT (map_layer_ids .find (il_reuse )!= map_layer_ids .end ()); 269 270map_layer_ids [il ]= map_layer_ids [il_reuse ]; 271 272LLAMA_LOG_DEBUG ("%s: - layer %3d: reuse layer %d, is_swa = %d\n" ,__func__ ,il ,il_reuse ,hparams .is_swa (il )); 273 } 274 } 275 276// allocate tensors and initialize the buffers to avoid NaNs in the padding 277for (auto & [buft ,ctx ] :ctx_map ) { 278ggml_backend_buffer_t buf ; 279if (hparams .no_alloc ) { 280buf = ggml_backend_buft_alloc_buffer (buft ,/*size =*/ 0 );// dummy buffer 281for (ggml_tensor * t = ggml_get_first_tensor (ctx .get ());t != nullptr ;t = ggml_get_next_tensor (ctx .get (),t )) { 282t -> buffer = buf ;// set dummy buffer for KV cache so that the backend scheduler won't try to allocate it 283 } 284 }else { 285buf = ggml_backend_alloc_ctx_tensors_from_buft (ctx .get (),buft );// real buffer 286 } 287if (!buf ) { 288throw std::runtime_error ("failed to allocate buffer for kv cache" ); 289 } 290 291LLAMA_LOG_INFO ("%s: %10s KV buffer size = %8.2f MiB\n" ,__func__ ,ggml_backend_buffer_name (buf ),ggml_backend_buffer_get_size (buf )/1024.0 /1024.0 ); 292 293ggml_backend_buffer_clear (buf ,0 ); 294ctxs_bufs .emplace_back (std::move (ctx ),buf ); 295 } 296 297 { 298const size_t memory_size_k = size_k_bytes (); 299const size_t memory_size_v = size_v_bytes (); 300 301LLAMA_LOG_INFO ("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u/%u seqs), K (%s): %7.2f MiB, V (%s): %7.2f MiB\n" ,__func__ , 302 (float )(memory_size_k + memory_size_v ) / (1024.0f * 1024.0f ),kv_size , (int )layers .size (),n_seq_max ,n_stream , 303ggml_type_name (type_k ), (float )memory_size_k / (1024.0f * 1024.0f ), 304ggml_type_name (type_v ), (float )memory_size_v / (1024.0f * 1024.0f )); 305 } 306 307// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 308if (other ) { 309n_embd_head_k_all = other -> n_embd_head_k_all ; 310n_embd_head_v_all = other -> n_embd_head_v_all ; 311 312attn_rot_k = other -> attn_rot_k ; 313attn_rot_v = other -> attn_rot_v ; 314 }else { 315const char * LLAMA_ATTN_ROT_DISABLE = getenv ("LLAMA_ATTN_ROT_DISABLE" ); 316const bool attn_rot_disable = LLAMA_ATTN_ROT_DISABLE ?atoi (LLAMA_ATTN_ROT_DISABLE ) : false; 317if (attn_rot_disable ) { 318LLAMA_LOG_WARN ("%s: attention rotation force disabled (LLAMA_ATTN_ROT_DISABLE)\n" ,__func__ ); 319 } 320 321attn_rot_k = 322 !attn_rot_disable && 323n_embd_head_k_all > 0 && 324ggml_is_quantized (type_k )&& 325hparams .n_embd_head_k () %64 == 0 ; 326 327// always create Hadamard rotation tensors for DeepSeek lightning indexers 328if ((model .arch == LLM_ARCH_DEEPSEEK32 || model .arch == LLM_ARCH_DEEPSEEK4 || 329model .arch == LLM_ARCH_GLM_DSA || model .arch == LLM_ARCH_DOTS3NOTE )&& 330hparams .n_embd_head_k_full == hparams .indexer_head_size ) { 331attn_rot_k = true; 332 } 333 334attn_rot_v = 335 !attn_rot_disable && 336n_embd_head_v_all > 0 && 337ggml_is_quantized (type_v )&& 338hparams .n_embd_head_v () %64 == 0 ; 339 } 340 341LLAMA_LOG_INFO ("%s: attn_rot_k = %d, n_embd_head_k_all = %d\n" ,__func__ ,attn_rot_k ,n_embd_head_k_all ); 342LLAMA_LOG_INFO ("%s: attn_rot_v = %d, n_embd_head_k_all = %d\n" ,__func__ ,attn_rot_v ,n_embd_head_v_all ); 343 344// pre-compute the haramard matrices and keep them in host memory 345// TODO: in the future, we can make copies in the backend buffers to avoid host -> device transfers 346if (attn_rot_k || attn_rot_v ) { 347for (int64_t n = 64 ;n <= std::max (n_embd_head_k_all ,n_embd_head_v_all );n *=2 ) { 348attn_rot_hadamard [n ]= std::vector < float > (n * n ); 349 350ggml_init_params params = { 351/* .mem_size = */ 1 * ggml_tensor_overhead (), 352/* .mem_buffer = */ nullptr , 353/* .no_alloc = */ true, 354 }; 355 356ggml_context_ptr ctx {ggml_init (params ) }; 357 358ggml_tensor * tmp = ggml_new_tensor_2d (ctx .get (),GGML_TYPE_F32 ,n ,n ); 359tmp -> data = attn_rot_hadamard [n ].data (); 360 361ggml_gen_hadamard (tmp ); 362 } 363 } 364 365const char * LLAMA_KV_CACHE_DEBUG = getenv ("LLAMA_KV_CACHE_DEBUG" ); 366debug = LLAMA_KV_CACHE_DEBUG ?atoi (LLAMA_KV_CACHE_DEBUG ) :0 ; 367} 368 369void llama_kv_cache::clear (bool data ) { 370for (uint32_t s = 0 ;s < n_stream ;++ s ) { 371v_cells [s ].reset (); 372v_heads [s ]= 0 ; 373 } 374 375if (data ) { 376for (auto & [_ ,buf ] :ctxs_bufs ) { 377ggml_backend_buffer_clear (buf .get (),0 ); 378 } 379 } 380} 381 382bool llama_kv_cache::seq_rm (llama_seq_id seq_id ,llama_pos p0 ,llama_pos p1 ) { 383// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 384if (other ) { 385return true; 386 } 387 388// TODO: fix incosistent handling of `seq_id < 0` and `seq_id == -1` in the codebase [TAG_LLAMA_SEQ_ID_NEG] 389GGML_ASSERT (seq_id == -1 || (seq_id >=0 && (size_t )seq_id < seq_to_stream .size ())); 390 391if (p0 < 0 ) { 392p0 = 0 ; 393 } 394 395if (p1 < 0 ) { 396p1 = std::numeric_limits < llama_pos > ::max (); 397 } 398 399if (seq_id >=0 ) { 400auto & cells = v_cells [seq_to_stream [seq_id ]]; 401auto & head = v_heads [seq_to_stream [seq_id ]]; 402 403uint32_t new_head = cells .size (); 404 405for (uint32_t i = 0 ;i < cells .size ();++ i ) { 406if (!cells .pos_in (i ,p0 ,p1 )) { 407continue ; 408 } 409 410if (cells .seq_has (i ,seq_id )&& cells .seq_rm (i ,seq_id )) { 411if (new_head == cells .size ()) { 412new_head = i ; 413 } 414 } 415 } 416 417// If we freed up a slot, set head to it so searching can start there. 418if (new_head != cells .size ()&& new_head < head ) { 419head = new_head ; 420 } 421 }else { 422// match any sequence 423for (uint32_t s = 0 ;s < n_stream ;++ s ) { 424auto & cells = v_cells [s ]; 425auto & head = v_heads [s ]; 426 427uint32_t new_head = cells .size (); 428 429for (uint32_t i = 0 ;i < cells .size ();++ i ) { 430if (!cells .pos_in (i ,p0 ,p1 )) { 431continue ; 432 } 433 434cells .rm (i ); 435 436if (new_head == cells .size ()) { 437new_head = i ; 438 } 439 } 440 441// If we freed up a slot, set head to it so searching can start there. 442if (new_head != cells .size ()&& new_head < head ) { 443head = new_head ; 444 } 445 } 446 } 447 448return true; 449} 450 451void llama_kv_cache::seq_cp (llama_seq_id seq_id_src ,llama_seq_id seq_id_dst ,llama_pos p0 ,llama_pos p1 ) { 452// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 453if (other ) { 454return ; 455 } 456 457GGML_ASSERT (seq_id_src >=0 && (size_t )seq_id_src < seq_to_stream .size ()); 458GGML_ASSERT (seq_id_dst >=0 && (size_t )seq_id_dst < seq_to_stream .size ()); 459 460const auto s0 = seq_to_stream [seq_id_src ]; 461const auto s1 = seq_to_stream [seq_id_dst ]; 462 463if (s0 == s1 ) { 464// since both sequences are in the same stream, no data copy is necessary 465// we just have to update the cells meta data 466 467auto & cells = v_cells [s0 ]; 468 469if (seq_id_src == seq_id_dst ) { 470return ; 471 } 472 473if (p0 < 0 ) { 474p0 = 0 ; 475 } 476 477if (p1 < 0 ) { 478p1 = std::numeric_limits < llama_pos > ::max (); 479 } 480 481for (uint32_t i = 0 ;i < cells .size ();++ i ) { 482if (!cells .pos_in (i ,p0 ,p1 )) { 483continue ; 484 } 485 486if (cells .seq_has (i ,seq_id_src )) { 487cells .seq_add (i ,seq_id_dst ); 488 } 489 } 490 491return ; 492 } 493 494// cross-stream sequence copies require to copy the actual buffer data 495 496bool is_full = true; 497 498if (p0 > 0 && p0 + 1 < (int )get_size ()) { 499is_full = false; 500 } 501 502if (p1 > 0 && p1 + 1 < (int )get_size ()) { 503is_full = false; 504 } 505 506GGML_ASSERT (is_full && "seq_cp() is only supported for full KV buffers" ); 507 508// enqueue the copy operation - the buffer copy will be performed during the next update 509sc_info .ssrc .push_back (s0 ); 510sc_info .sdst .push_back (s1 ); 511 512v_cells [s1 ].reset (); 513for (uint32_t i = 0 ;i < v_cells [s0 ].size ();++ i ) { 514if (v_cells [s0 ].seq_has (i ,seq_id_src )) { 515llama_pos pos = v_cells [s0 ].pos_get (i ); 516llama_pos shift = v_cells [s0 ].get_shift (i ); 517 518llama_kv_cell_ext ext = v_cells [s0 ].ext_get (i ); 519 520if (shift != 0 ) { 521pos -= shift ; 522assert (pos >=0 ); 523 } 524 525v_cells [s1 ].pos_set (i ,pos ); 526v_cells [s1 ].seq_add (i ,seq_id_dst ); 527 528if (shift != 0 ) { 529v_cells [s1 ].pos_add (i ,shift ); 530 } 531 532v_cells [s1 ].ext_set (i ,ext ); 533 } 534 } 535 536v_heads [s1 ]= v_heads [s0 ]; 537 538//for (uint32_t s = 0; s < n_stream; ++s) { 539// LLAMA_LOG_WARN("%s: seq %d: min = %d, max = %d\n", __func__, s, v_cells[s].seq_pos_min(s), v_cells[s].seq_pos_max(s)); 540//} 541} 542 543void llama_kv_cache::seq_keep (llama_seq_id seq_id ) { 544// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 545if (other ) { 546return ; 547 } 548 549GGML_ASSERT (seq_id >=0 && (size_t )seq_id < seq_to_stream .size ()); 550 551auto & cells = v_cells [seq_to_stream [seq_id ]]; 552auto & head = v_heads [seq_to_stream [seq_id ]]; 553 554uint32_t new_head = cells .size (); 555 556for (uint32_t i = 0 ;i < cells .size ();++ i ) { 557if (cells .seq_keep (i ,seq_id )) { 558if (new_head == cells .size ()) { 559new_head = i ; 560 } 561 } 562 } 563 564// If we freed up a slot, set head to it so searching can start there. 565if (new_head != cells .size ()&& new_head < head ) { 566head = new_head ; 567 } 568} 569 570void llama_kv_cache::seq_add (llama_seq_id seq_id ,llama_pos p0 ,llama_pos p1 ,llama_pos shift ) { 571// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 572if (other ) { 573return ; 574 } 575 576GGML_ASSERT (seq_id >=0 && (size_t )seq_id < seq_to_stream .size ()); 577GGML_ASSERT (hparams .n_pos_per_embd ()== 1 && "seq_add() is only supported for n_pos_per_embd() == 1" ); 578 579auto & cells = v_cells [seq_to_stream [seq_id ]]; 580auto & head = v_heads [seq_to_stream [seq_id ]]; 581 582if (shift == 0 ) { 583return ; 584 } 585 586uint32_t new_head = cells .size (); 587 588if (p0 < 0 ) { 589p0 = 0 ; 590 } 591 592if (p1 < 0 ) { 593p1 = std::numeric_limits < llama_pos > ::max (); 594 } 595 596// If there is no range then return early to avoid looping over all cells. 597if (p0 == p1 ) { 598return ; 599 } 600 601for (uint32_t i = 0 ;i < cells .size ();++ i ) { 602if (!cells .pos_in (i ,p0 ,p1 )) { 603continue ; 604 } 605 606if (cells .seq_has (i ,seq_id )) { 607if (cells .pos_add (i ,shift )) { 608if (new_head == cells .size ()) { 609new_head = i ; 610 } 611 } 612 } 613 } 614 615// If we freed up a slot, set head to it so searching can start there. 616// Otherwise we just start the next search from the beginning. 617head = new_head != cells .size () ?new_head :0 ; 618} 619 620void llama_kv_cache::seq_div (llama_seq_id seq_id ,llama_pos p0 ,llama_pos p1 ,int d ) { 621// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 622if (other ) { 623return ; 624 } 625 626GGML_ASSERT (seq_id >=0 && (size_t )seq_id < seq_to_stream .size ()); 627GGML_ASSERT (hparams .n_pos_per_embd ()== 1 && "seq_div() is only supported for n_pos_per_embd() == 1" ); 628 629auto & cells = v_cells [seq_to_stream [seq_id ]]; 630 631if (d == 1 ) { 632return ; 633 } 634 635if (p0 < 0 ) { 636p0 = 0 ; 637 } 638 639if (p1 < 0 ) { 640p1 = std::numeric_limits < llama_pos > ::max (); 641 } 642 643// If there is no range then return early to avoid looping over the cache. 644if (p0 == p1 ) { 645return ; 646 } 647 648for (uint32_t i = 0 ;i < cells .size ();++ i ) { 649if (!cells .pos_in (i ,p0 ,p1 )) { 650continue ; 651 } 652 653if (cells .seq_has (i ,seq_id )) { 654cells .pos_div (i ,d ); 655 } 656 } 657} 658 659llama_pos llama_kv_cache::seq_pos_min (llama_seq_id seq_id )const { 660// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 661if (other ) { 662return other -> seq_pos_min (seq_id ); 663 } 664 665GGML_ASSERT (seq_id >=0 && (size_t )seq_id < seq_to_stream .size ()); 666 667const auto & cells = v_cells [seq_to_stream [seq_id ]]; 668 669return cells .seq_pos_min (seq_id ); 670} 671 672llama_pos llama_kv_cache::seq_pos_max (llama_seq_id seq_id )const { 673// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 674if (other ) { 675return other -> seq_pos_max (seq_id ); 676 } 677 678GGML_ASSERT (seq_id >=0 && (size_t )seq_id < seq_to_stream .size ()); 679 680const auto & cells = v_cells [seq_to_stream [seq_id ]]; 681 682return cells .seq_pos_max (seq_id ); 683} 684 685std::map < ggml_backend_buffer_type_t ,size_t > llama_kv_cache::memory_breakdown ()const { 686 std::map < ggml_backend_buffer_type_t ,size_t > ret ; 687for (const auto & [ctx ,buf ] :ctxs_bufs ) { 688ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type (buf .get ()); 689 690if (hparams .no_alloc ) { 691GGML_ASSERT (ggml_backend_buffer_get_base (buf .get ())== nullptr ); 692ret [buft ]+= ggml_backend_alloc_ctx_tensors_from_buft_size (ctx .get (),buft ); 693 }else { 694// GGML_ASSERT(ggml_backend_buffer_get_base(buf.get()) != nullptr); // multi_buffer does not have a defined base 695ret [buft ]+= ggml_backend_buffer_get_size (buf .get ()); 696 } 697 } 698 699return ret ; 700} 701 702llama_memory_context_ptr llama_kv_cache::init_batch ( 703llama_batch_allocr & balloc , 704uint32_t n_ubatch , 705bool embd_all ) { 706GGML_UNUSED (embd_all ); 707 708do { 709balloc .split_reset (); 710 711 std::vector < llama_ubatch > ubatches ; 712while (true) { 713auto ubatch = n_stream == 1 ?balloc .split_simple (n_ubatch ) :balloc .split_equal (n_ubatch , true,0 ); 714 715if (ubatch .n_tokens == 0 ) { 716break ; 717 } 718 719ubatches .push_back (std::move (ubatch ));// NOLINT 720 } 721 722if (balloc .get_n_used ()< balloc .get_n_tokens ()) { 723// failed to find a suitable split 724break ; 725 } 726 727auto sinfos = prepare (ubatches ); 728if (sinfos .empty ()) { 729break ; 730 } 731 732return std::make_unique < llama_kv_cache_context > ( 733this , std::move (sinfos ), std::move (ubatches )); 734 }while (false); 735 736return std::make_unique < llama_kv_cache_context > (LLAMA_MEMORY_STATUS_FAILED_PREPARE ); 737} 738 739llama_memory_context_ptr llama_kv_cache::init_full () { 740return std::make_unique < llama_kv_cache_context > (this ); 741} 742 743llama_memory_context_ptr llama_kv_cache::init_update (llama_context * lctx ,bool optimize ) { 744GGML_UNUSED (optimize ); 745 746bool do_shift = get_has_shift (); 747 748return std::make_unique < llama_kv_cache_context > (this ,lctx ,do_shift , std::move (sc_info )); 749} 750 751llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare (const std::vector < llama_ubatch > & ubatches ) { 752 llama_kv_cache::slot_info_vec_t res ; 753 754struct state_t { 755slot_info sinfo ;// slot info for the ubatch 756 757 std::vector < uint32_t > v_heads_old ;// old positions of the heads, before placing the ubatch 758 759 std::vector < llama_kv_cells > v_cells ;// copy of the old cells, before placing the ubatch 760 }; 761 762// remember the old state of the cells so we can restore it in the end 763 std::vector < state_t > states ; 764 765bool success = true; 766 767for (const auto & ubatch :ubatches ) { 768// only find a suitable slot for the ubatch. don't modify the cells yet 769const auto sinfo_new = find_slot (ubatch , false); 770if (sinfo_new .empty ()) { 771success = false; 772break ; 773 } 774 775// remember the position that we found 776res .push_back (sinfo_new ); 777 778// store the old state of the cells in the recovery stack 779 { 780state_t state = {sinfo_new ,v_heads , {} }; 781 782for (uint32_t s = 0 ;s < sinfo_new .n_stream ();++ s ) { 783auto & cells = v_cells [sinfo_new .strm [s ]]; 784 785state .v_cells .push_back (cells .cp (sinfo_new .idxs [s ])); 786 } 787 788states .push_back (std::move (state )); 789 } 790 791// now emplace the ubatch 792apply_ubatch (sinfo_new ,ubatch ); 793 } 794 795GGML_ASSERT (!states .empty ()|| !success ); 796 797// iterate backwards and restore the cells to their original state 798for (auto it = states .rbegin ();it != states .rend ();++ it ) { 799const auto & sinfo = it -> sinfo ; 800 801for (uint32_t s = 0 ;s < sinfo .n_stream ();++ s ) { 802auto & cells = v_cells [sinfo .strm [s ]]; 803auto & head = v_heads [sinfo .strm [s ]]; 804 805cells .set (sinfo .idxs [s ],it -> v_cells [s ]); 806head = it -> v_heads_old [s ]; 807 } 808 } 809 810if (!success ) { 811return {}; 812 } 813 814return res ; 815} 816 817bool llama_kv_cache::update (llama_context * lctx ,bool do_shift ,const stream_copy_info & sc_info ) { 818// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 819if (other ) { 820return true; 821 } 822 823bool updated = false; 824 825auto * sched = lctx -> get_sched (); 826 827if (!sc_info .empty ()) { 828assert (n_stream > 1 && "stream copy should never happen with a single stream" ); 829 830llama_synchronize (lctx ); 831 832const size_t n_copy = sc_info .ssrc .size (); 833 834for (size_t i = 0 ;i < n_copy ;++ i ) { 835const auto ssrc = sc_info .ssrc [i ]; 836const auto sdst = sc_info .sdst [i ]; 837 838assert (ssrc < n_stream ); 839assert (sdst < n_stream ); 840 841LLAMA_LOG_DEBUG ("%s: copying KV buffer: stream %d to stream %d\n" ,__func__ ,ssrc ,sdst ); 842 843assert (ssrc != sdst ); 844 845for (uint32_t il = 0 ;il < layers .size ();++ il ) { 846const auto & layer = layers [il ]; 847 848ggml_backend_tensor_copy (layer .k_stream [ssrc ],layer .k_stream [sdst ]); 849 850if (layer .v_stream [ssrc ]) { 851ggml_backend_tensor_copy (layer .v_stream [ssrc ],layer .v_stream [sdst ]); 852 } 853 } 854 } 855 } 856 857if (do_shift ) { 858if (!get_can_shift ()) { 859GGML_ABORT ("The current KV cache / model configuration does not support K-shift" ); 860 } 861 862LLAMA_LOG_DEBUG ("%s: applying K-shift\n" ,__func__ ); 863 864// apply K-shift if needed 865if (hparams .rope_type != LLAMA_ROPE_TYPE_NONE ) { 866ggml_backend_sched_reset (sched ); 867 868auto * res = lctx -> get_gf_res_reserve (); 869 870res -> reset (); 871 872auto * gf = build_graph_shift (res ,lctx ); 873if (!ggml_backend_sched_alloc_graph (sched ,gf )) { 874LLAMA_LOG_ERROR ("%s: failed to allocate compute graph for K-shift\n" ,__func__ ); 875return updated ; 876 } 877 878res -> set_inputs (nullptr ); 879 880if (lctx -> graph_compute (gf , false)!= GGML_STATUS_SUCCESS ) { 881LLAMA_LOG_ERROR ("%s: failed to compute K-shift\n" ,__func__ ); 882return updated ; 883 } 884 885updated = true; 886 } 887 888for (uint32_t s = 0 ;s < n_stream ;++ s ) { 889auto & cells = v_cells [s ]; 890 891cells .reset_shift (); 892 } 893 } 894 895return updated ; 896} 897 898llama_kv_cache::slot_info llama_kv_cache::find_slot (const llama_ubatch & ubatch ,bool cont )const { 899 900if (debug > 0 ) { 901for (uint32_t s = 0 ;s < ubatch .n_seqs_unq ;++ s ) { 902const auto seq_id = ubatch .seq_id_unq [s ]; 903const auto stream_id = seq_to_stream [seq_id ]; 904const auto & cells = v_cells [stream_id ]; 905const uint32_t head_cur = v_heads [stream_id ]; 906 907LLAMA_LOG_DEBUG ("%s: stream[%d], n = %5d, used = %5d, head = %5d, size = %5d, n_swa = %5d\n" , 908__func__ ,stream_id ,cells .used_max_p1 (),cells .get_used (),head_cur ,get_size (),n_swa ); 909 910if ((debug == 2 && n_swa > 0 )|| debug > 2 ) { 911 std::string ss ; 912for (uint32_t i = 0 ;i < cells .size ();++ i ) { 913if (cells .is_empty (i )) { 914ss += '.' ; 915 }else { 916assert (cells .seq_count (i ) >=1 ); 917 918if (cells .seq_count (i )== 1 ) { 919ss += std::to_string (cells .seq_get (i )); 920 }else { 921ss += 'M' ; 922 } 923 } 924if (i %256 == 255 ) { 925ss += " *" ; 926ss += '\n' ; 927 } 928 } 929LLAMA_LOG_DEBUG ("\n%s\n" ,ss .c_str ()); 930 } 931 932if ((debug == 2 && n_swa > 0 )|| debug > 2 ) { 933 std::string ss ; 934for (uint32_t i = 0 ;i < cells .size ();++ i ) { 935 std::string cur ; 936if (cells .is_empty (i )) { 937cur = '.' ; 938 }else { 939cur = std::to_string (cells .pos_get (i )); 940 } 941const int n = cur .size (); 942for (int j = 0 ;j < 5 - n ;++ j ) { 943cur += ' ' ; 944 } 945ss += cur ; 946if (i %256 == 255 ) { 947ss += " *" ; 948 } 949if (i %64 == 63 ) { 950ss += '\n' ; 951 } 952 } 953LLAMA_LOG_DEBUG ("\n%s\n" ,ss .c_str ()); 954 } 955 956for (int s = 0 ;s < LLAMA_MAX_SEQ ;++ s ) { 957if (cells .seq_pos_min (s )< 0 ) { 958continue ; 959 } 960 961LLAMA_LOG_DEBUG ("%s: stream[%d] min[%d] = %5d, max[%d] = %5d\n" ,__func__ ,stream_id ,s ,cells .seq_pos_min (s ),s ,cells .seq_pos_max (s )); 962 } 963 } 964 } 965 966uint32_t n_tokens = ubatch .n_tokens ; 967uint32_t n_seqs = 1 ; 968 969if (n_stream > 1 ) { 970GGML_ASSERT (n_tokens %ubatch .n_seqs_unq == 0 ); 971 972n_seqs = ubatch .n_seqs_unq ; 973n_tokens = n_tokens /n_seqs ; 974 } 975 976slot_info res = { 977/*.s0 =*/ LLAMA_MAX_SEQ , 978/*.s1 =*/ 0 , 979/*.strm =*/ { }, 980/*.idxs =*/ { }, 981 }; 982 983res .resize (n_seqs ); 984 985for (uint32_t s = 0 ;s < n_seqs ;++ s ) { 986const auto seq_id = ubatch .seq_id_unq [s ]; 987 988if (n_stream > 1 ) { 989GGML_ASSERT (ubatch .n_seq_id [s * n_tokens ]== 1 ); 990GGML_ASSERT (ubatch .seq_id [s * n_tokens ][0 ]== seq_id ); 991 } 992 993res .s0 = std::min < uint32_t > (res .s0 ,seq_to_stream [seq_id ]); 994res .s1 = std::max < uint32_t > (res .s1 ,seq_to_stream [seq_id ]); 995 996res .strm [s ]= seq_to_stream [seq_id ]; 997res .idxs [s ].reserve (n_tokens ); 998 999const auto & cells = v_cells [seq_to_stream [seq_id ]]; 1000 1001uint32_t head_cur = v_heads [seq_to_stream [seq_id ]]; 1002 1003// if we have enough unused cells before the current head -> 1004// better to start searching from the beginning of the cache, hoping to fill it 1005if (head_cur > cells .get_used ()+ 2 * n_tokens ) { 1006head_cur = 0 ; 1007 } 1008 1009if (n_tokens > cells .size ()) { 1010LLAMA_LOG_ERROR ("%s: n_tokens = %d > size = %u\n" ,__func__ ,n_tokens ,cells .size ()); 1011return { }; 1012 } 1013 1014uint32_t n_tested = 0 ; 1015 1016// for continuous slots, we test that all tokens in the ubatch fit, starting from the current head 1017// for non-continuous slots, we test the tokens one by one 1018const uint32_t n_test = cont ?n_tokens :1 ; 1019 1020while (true) { 1021if (head_cur + n_test > cells .size ()) { 1022n_tested += cells .size ()- head_cur ; 1023head_cur = 0 ; 1024continue ; 1025 } 1026 1027for (uint32_t i = 0 ;i < n_test ;i ++ ) { 1028const auto idx = head_cur ; 1029 1030head_cur ++ ; 1031n_tested ++ ; 1032 1033//const llama_pos pos = ubatch.pos[i]; 1034//const llama_seq_id seq_id = ubatch.seq_id[i][0]; 1035 1036// can we use this cell? either: 1037// - the cell is empty 1038// - the cell is occupied only by one sequence: 1039// - (disabled) mask causally, if the sequence is the same as the one we are inserting 1040// - mask SWA, using current max pos for that sequence in the cache 1041// always insert in the cell with minimum pos 1042bool can_use = cells .is_empty (idx ); 1043 1044if (!can_use && cells .seq_count (idx )== 1 ) { 1045const llama_pos pos_cell = cells .pos_get (idx ); 1046 1047// (disabled) causal mask 1048// note: it's better to purge any "future" tokens beforehand 1049//if (cells.seq_has(idx, seq_id)) { 1050// can_use = pos_cell >= pos; 1051//} 1052 1053if (!can_use ) { 1054const llama_seq_id seq_id_cell = cells .seq_get (idx ); 1055 1056// SWA mask 1057if (llama_hparams::is_masked_swa (n_swa ,swa_type ,pos_cell ,cells .seq_pos_max (seq_id_cell )+ 1 )) { 1058can_use = true; 1059 } 1060 } 1061 } 1062 1063if (can_use ) { 1064res .idxs [s ].push_back (idx ); 1065 }else { 1066if (cont ) { 1067break ; 1068 } 1069 } 1070 } 1071 1072if (res .idxs [s ].size ()== n_tokens ) { 1073break ; 1074 } 1075 1076if (cont ) { 1077res .idxs [s ].clear (); 1078 } 1079 1080if (n_tested >=cells .size ()) { 1081//LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens); 1082return { }; 1083 } 1084 } 1085 1086// we didn't find a suitable slot - return empty result 1087if (res .idxs [s ].size ()< n_tokens ) { 1088return { }; 1089 } 1090 } 1091 1092assert (res .s1 >=res .s0 ); 1093 1094return res ; 1095} 1096 1097void llama_kv_cache::apply_ubatch (const slot_info & sinfo ,const llama_ubatch & ubatch ) { 1098// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 1099if (other ) { 1100return ; 1101 } 1102 1103// keep track of the max sequence position that we would overwrite with this ubatch 1104// for non-SWA cache, this would be always empty 1105llama_seq_id seq_pos_max_rm [LLAMA_MAX_SEQ ]; 1106for (uint32_t s = 0 ;s < LLAMA_MAX_SEQ ;++ s ) { 1107seq_pos_max_rm [s ]= -1 ; 1108 } 1109 1110assert (ubatch .n_tokens == sinfo .n_stream ()* sinfo .size ()); 1111 1112for (uint32_t s = 0 ;s < sinfo .n_stream ();++ s ) { 1113for (uint32_t ii = 0 ;ii < sinfo .size ();++ ii ) { 1114const uint32_t i = s * sinfo .size ()+ ii ; 1115 1116auto & cells = v_cells [sinfo .strm [s ]]; 1117 1118const auto idx = sinfo .idxs [s ][ii ]; 1119 1120if (!cells .is_empty (idx )) { 1121assert (cells .seq_count (idx )== 1 ); 1122 1123const llama_seq_id seq_id = cells .seq_get (idx ); 1124const llama_pos pos = cells .pos_get (idx ); 1125 1126seq_pos_max_rm [seq_id ]= std::max (seq_pos_max_rm [seq_id ],pos ); 1127 1128cells .rm (idx ); 1129 } 1130 1131cells .pos_set (idx ,ubatch .pos [i ]); 1132 1133if (ubatch .is_pos_2d ()|| ubatch .token || hparams .ple_n_heads > 0 ) { 1134llama_kv_cell_ext ext ; 1135 1136if (ubatch .is_pos_2d ()) { 1137ext .x = ubatch .pos [i + ubatch .n_tokens * 2 ]; 1138ext .y = ubatch .pos [i + ubatch .n_tokens ]; 1139 } 1140 1141if (ubatch .token ) { 1142ext .tok = ubatch .token [i ]; 1143 }else if (hparams .ple_n_heads > 0 ) { 1144// embd batch (multimodal input) has no token ids, need to pad it with the correct ID for PLE layers 1145// TODO @ngxson : check if we can do the same as gemma 3n / gemma 4 1146ext .tok = hparams .ple_image_token_id != 0 1147 ? (llama_token )hparams .ple_image_token_id 1148 : (llama_token )hparams .ple_eos_token_id ; 1149 } 1150 1151cells .ext_set (idx ,ext ); 1152 } 1153 1154for (int32_t s = 0 ;s < ubatch .n_seq_id [i ];s ++ ) { 1155cells .seq_add (idx ,ubatch .seq_id [i ][s ]); 1156 } 1157 } 1158 } 1159 1160// note: we want to preserve the invariant that all positions between [pos_min, pos_max] for each sequence 1161// will be present in the cache. so we have to purge any position which is less than those we would overwrite 1162// ref: https://github.com/ggml-org/llama.cpp/pull/13746#issuecomment-2916057092 1163for (uint32_t s = 0 ;s < LLAMA_MAX_SEQ ;++ s ) { 1164if (seq_pos_max_rm [s ]== -1 ) { 1165continue ; 1166 } 1167 1168GGML_ASSERT (s < seq_to_stream .size ()); 1169 1170auto & cells = v_cells [seq_to_stream [s ]]; 1171 1172if (cells .seq_pos_min (s ) <=seq_pos_max_rm [s ]) { 1173LLAMA_LOG_DEBUG ("%s: purging positions [%d, %d] of sequence %d from KV cache\n" , 1174__func__ ,cells .seq_pos_min (s ),seq_pos_max_rm [s ],s ); 1175 1176seq_rm (s ,cells .seq_pos_min (s ),seq_pos_max_rm [s ]+ 1 ); 1177 } 1178 } 1179 1180// move the head at the end of the slot 1181for (uint32_t s = 0 ;s < sinfo .n_stream ();++ s ) { 1182auto & head = v_heads [sinfo .strm [s ]]; 1183 1184head = sinfo .idxs [s ].back ()+ 1 ; 1185 } 1186} 1187 1188bool llama_kv_cache::get_can_shift ()const { 1189// Step35 uses per-layer RoPE dims; K-shift assumes a single global n_rot. 1190if (model .arch == LLM_ARCH_STEP35 ) { 1191return false; 1192 } 1193if (hparams .n_pos_per_embd ()> 1 ) { 1194return false; 1195 } 1196return true; 1197} 1198 1199uint32_t llama_kv_cache::get_size ()const { 1200const auto & cells = v_cells [seq_to_stream [0 ]]; 1201 1202return cells .size (); 1203} 1204 1205uint32_t llama_kv_cache::get_n_stream ()const { 1206return n_stream ; 1207} 1208 1209bool llama_kv_cache::get_has_shift ()const { 1210bool result = false; 1211 1212for (uint32_t s = 0 ;s < n_stream ;++ s ) { 1213result |=v_cells [s ].get_has_shift (); 1214 } 1215 1216return result ; 1217} 1218 1219ggml_type llama_kv_cache::type_k ()const { 1220return layers [0 ].k -> type ; 1221} 1222 1223ggml_type llama_kv_cache::type_v ()const { 1224return layers [0 ].v -> type ; 1225} 1226 1227std::vector < uint32_t > llama_kv_cache::get_layer_ids ()const { 1228 std::vector < uint32_t > res ; 1229res .reserve (layers .size ()); 1230 1231for (const auto & layer :layers ) { 1232res .push_back (layer .il ); 1233 } 1234 1235return res ; 1236} 1237 1238ggml_tensor * llama_kv_cache::get_k_storage (int32_t il )const { 1239const int32_t ikv = map_layer_ids .at (il ); 1240 1241return layers [ikv ].k ; 1242} 1243 1244const llama_kv_cells & llama_kv_cache::get_cells (llama_seq_id seq_id )const { 1245GGML_ASSERT (seq_id >=0 && (size_t )seq_id < seq_to_stream .size ()); 1246 1247return v_cells [seq_to_stream [seq_id ]]; 1248} 1249 1250uint32_t llama_kv_cache::get_n_kv (const slot_info & sinfo )const { 1251uint32_t result = 0 ; 1252 1253// pad the n_kv value so that the graph remains constant across batches and can be reused 1254// note: this also helps some backends with performance (f.ex https://github.com/ggml-org/llama.cpp/pull/16812#issuecomment-3455112220) 1255const uint32_t n_pad_cur = std::max (n_pad ,256u ); 1256 1257for (uint32_t s = 0 ;s < sinfo .n_stream ();++ s ) { 1258const auto & cells = v_cells [sinfo .strm [s ]]; 1259 1260result = std::max (std::min (cells .size (), std::max (n_pad_cur ,GGML_PAD (cells .used_max_p1 (),n_pad_cur ))),result ); 1261 } 1262 1263return result ; 1264} 1265 1266ggml_tensor * llama_kv_cache::get_k (ggml_context * ctx ,int32_t il ,uint32_t n_kv ,const slot_info & sinfo )const { 1267const int32_t ikv = map_layer_ids .at (il ); 1268 1269auto * k = layers [ikv ].k ; 1270 1271const uint64_t kv_size = get_size (); 1272const uint64_t n_embd_k_gqa = k -> ne [0 ]; 1273 1274assert (n_embd_k_gqa == hparams .n_embd_k_gqa (il )); 1275 1276const uint32_t ns = sinfo .s1 - sinfo .s0 + 1 ; 1277 1278return ggml_view_4d (ctx ,k , 1279hparams .n_embd_head_k (il ),hparams .n_head_kv (il ),n_kv ,ns , 1280ggml_row_size (k -> type ,hparams .n_embd_head_k (il )), 1281ggml_row_size (k -> type ,n_embd_k_gqa ), 1282ggml_row_size (k -> type ,n_embd_k_gqa * kv_size ), 1283ggml_row_size (k -> type ,n_embd_k_gqa * kv_size )* sinfo .s0 ); 1284} 1285 1286ggml_tensor * llama_kv_cache::get_v (ggml_context * ctx ,int32_t il ,uint32_t n_kv ,const slot_info & sinfo )const { 1287const int32_t ikv = map_layer_ids .at (il ); 1288 1289auto * v = layers [ikv ].v ; 1290 1291const uint64_t kv_size = get_size (); 1292const uint64_t n_embd_v_gqa = v -> ne [0 ]; 1293 1294// [TAG_V_CACHE_VARIABLE] 1295assert (n_embd_v_gqa >=hparams .n_embd_v_gqa (il )); 1296 1297const uint32_t ns = sinfo .s1 - sinfo .s0 + 1 ; 1298 1299if (!v_trans ) { 1300// note: v->nb[1] <= v->nb[2] 1301return ggml_view_4d (ctx ,v , 1302hparams .n_embd_head_v (il ),hparams .n_head_kv (il ),n_kv ,ns , 1303ggml_row_size (v -> type ,hparams .n_embd_head_v (il )),// v->nb[1] 1304ggml_row_size (v -> type ,n_embd_v_gqa ),// v->nb[2] 1305ggml_row_size (v -> type ,n_embd_v_gqa * kv_size ),// v->nb[3] 1306ggml_row_size (v -> type ,n_embd_v_gqa * kv_size )* sinfo .s0 ); 1307 } 1308 1309// note: v->nb[1] > v->nb[2] 1310return ggml_view_4d (ctx ,v , 1311n_kv ,hparams .n_head_kv (il ),hparams .n_embd_head_v (il ),ns , 1312ggml_row_size (v -> type ,kv_size * hparams .n_embd_head_v (il )),// v->nb[1] 1313ggml_row_size (v -> type ,kv_size ),// v->nb[2] 1314ggml_row_size (v -> type ,kv_size * n_embd_v_gqa ),// v->nb[3] 1315ggml_row_size (v -> type ,kv_size * n_embd_v_gqa )* sinfo .s0 ); 1316} 1317 1318ggml_tensor * llama_kv_cache::cpy_k (ggml_context * ctx ,ggml_tensor * k_cur ,ggml_tensor * k_idxs ,int32_t il ,const slot_info & sinfo )const { 1319GGML_UNUSED (sinfo ); 1320 1321const int32_t ikv = map_layer_ids .at (il ); 1322 1323ggml_tensor * k = layers [ikv ].k ; 1324 1325const int64_t n_embd_head = k_cur -> ne [0 ]; 1326const int64_t n_head = k_cur -> ne [1 ]; 1327const int64_t n_tokens = k_cur -> ne [2 ]; 1328 1329const int64_t n_embd_gqa = n_embd_head * n_head ; 1330 1331// we can merge dims 0 and 1 1332// TODO: add ggml helper function for this? 1333GGML_ASSERT (ggml_row_size (k_cur -> type ,n_embd_head )== k_cur -> nb [1 ]); 1334 1335k_cur = ggml_view_2d (ctx ,k_cur ,n_embd_gqa ,n_tokens ,k_cur -> nb [2 ],0 ); 1336 1337const int64_t n_stream = k -> ne [2 ]; 1338 1339if (n_stream > 1 ) { 1340const int64_t kv_size = get_size (); 1341 1342assert (n_embd_gqa == k -> ne [0 ]); 1343assert (kv_size == k -> ne [1 ]); 1344 1345// merge the buffer across all streams because the idxs are global 1346k = ggml_reshape_2d (ctx ,k ,n_embd_gqa ,kv_size * n_stream ); 1347 } 1348 1349// store the current K values into the cache 1350return ggml_set_rows (ctx ,k ,k_cur ,k_idxs ); 1351} 1352 1353ggml_tensor * llama_kv_cache::cpy_v (ggml_context * ctx ,ggml_tensor * v_cur ,ggml_tensor * v_idxs ,int32_t il ,const slot_info & sinfo )const { 1354GGML_UNUSED (sinfo ); 1355 1356const int32_t ikv = map_layer_ids .at (il ); 1357 1358auto * v = layers [ikv ].v ; 1359 1360const int64_t n_embd_head = v_cur -> ne [0 ]; 1361const int64_t n_head = v_cur -> ne [1 ]; 1362const int64_t n_tokens = v_cur -> ne [2 ]; 1363 1364const int64_t n_embd_gqa = n_embd_head * n_head ; 1365 1366// we can merge dims 0 and 1 1367GGML_ASSERT (ggml_row_size (v_cur -> type ,n_embd_head )== v_cur -> nb [1 ]); 1368 1369const int64_t n_stream = v -> ne [2 ]; 1370 1371// take this branch when FA is enabled (the V cache is not transposed) 1372if (!v_trans ) { 1373v_cur = ggml_view_2d (ctx ,v_cur ,n_embd_gqa ,n_tokens ,v_cur -> nb [2 ],0 ); 1374 1375if (n_stream > 1 ) { 1376const int64_t kv_size = get_size (); 1377 1378assert (n_embd_gqa == v -> ne [0 ]); 1379assert (kv_size == v -> ne [1 ]); 1380 1381// merge the buffer across all streams because the idxs are global 1382v = ggml_reshape_2d (ctx ,v ,n_embd_gqa ,kv_size * n_stream ); 1383 } 1384 1385return ggml_set_rows (ctx ,v ,v_cur ,v_idxs ); 1386 } 1387 1388if (ggml_row_size (v_cur -> type ,n_embd_gqa )== v_cur -> nb [2 ]) { 1389// we can merge dims 0, 1 and 2 1390v_cur = ggml_reshape_2d (ctx ,v_cur ,n_embd_gqa ,n_tokens ); 1391 }else { 1392// otherwise -> make a copy to get contiguous data 1393v_cur = ggml_cont_2d (ctx ,v_cur ,n_embd_gqa ,n_tokens ); 1394 } 1395 1396// [TAG_V_CACHE_VARIABLE] 1397if (n_embd_gqa < v -> ne [0 ]) { 1398v_cur = ggml_pad (ctx ,v_cur ,v -> ne [0 ]- n_embd_gqa ,0 ,0 ,0 ); 1399 } 1400 1401// in this branch the v_idxs are constructed in such a way that each row is a single head element 1402ggml_tensor * v_view = ggml_reshape_2d (ctx ,v ,1 ,ggml_nelements (v )); 1403 1404v_cur = ggml_reshape_2d (ctx ,v_cur ,1 ,ggml_nelements (v_cur )); 1405 1406return ggml_set_rows (ctx ,v_view ,v_cur ,v_idxs ); 1407} 1408 1409ggml_tensor * llama_kv_cache::build_input_k_idxs (ggml_context * ctx ,const llama_ubatch & ubatch )const { 1410const uint32_t n_tokens = ubatch .n_tokens ; 1411 1412ggml_tensor * k_idxs = ggml_new_tensor_1d (ctx ,GGML_TYPE_I64 ,n_tokens ); 1413 1414ggml_set_input (k_idxs ); 1415 1416return k_idxs ; 1417} 1418 1419ggml_tensor * llama_kv_cache::build_input_v_idxs (ggml_context * ctx ,const llama_ubatch & ubatch )const { 1420const uint32_t n_tokens = ubatch .n_tokens ; 1421 1422ggml_tensor * v_idxs ; 1423 1424if (!v_trans ) { 1425v_idxs = ggml_new_tensor_1d (ctx ,GGML_TYPE_I64 ,n_tokens ); 1426 }else { 1427v_idxs = ggml_new_tensor_1d (ctx ,GGML_TYPE_I64 ,n_tokens * hparams .n_embd_v_gqa_max ()); 1428 } 1429 1430ggml_set_input (v_idxs ); 1431 1432return v_idxs ; 1433} 1434 1435ggml_tensor * llama_kv_cache::build_input_k_rot (ggml_context * ctx )const { 1436ggml_tensor * res = nullptr ; 1437 1438if (attn_rot_k ) { 1439int nrot = 64 ; 1440 1441// TODO: investigate if using the smallest rotation matrix is beneficial also for K (similar as for V) 1442// ref: https://github.com/ggml-org/llama.cpp/pull/21038#issuecomment-4141323088 1443do { 1444nrot *=2 ; 1445 }while (n_embd_head_k_all %nrot == 0 ); 1446nrot /=2 ; 1447 1448res = ggml_new_tensor_2d (ctx ,GGML_TYPE_F32 ,nrot ,nrot ); 1449ggml_set_input (res ); 1450ggml_set_name (res ,"attn_inp_k_rot" ); 1451 } 1452 1453return res ; 1454} 1455 1456ggml_tensor * llama_kv_cache::build_input_v_rot (ggml_context * ctx )const { 1457ggml_tensor * res = nullptr ; 1458 1459if (attn_rot_v ) { 1460int nrot = 64 ; 1461// using smaller rotation matrices for V seems beneficial 1462// ref: https://github.com/ggml-org/llama.cpp/pull/21038#issuecomment-4146397570 1463//do { 1464// nrot *= 2; 1465//} while (hparams.n_embd_head_v() % nrot == 0); 1466//nrot /= 2; 1467 1468res = ggml_new_tensor_2d (ctx ,GGML_TYPE_F32 ,nrot ,nrot ); 1469ggml_set_input (res ); 1470ggml_set_name (res ,"attn_inp_v_rot" ); 1471 } 1472 1473return res ; 1474} 1475 1476void llama_kv_cache::set_input_k_idxs (ggml_tensor * dst ,const llama_ubatch * ubatch ,const slot_info & sinfo )const { 1477const uint32_t n_tokens = ubatch -> n_tokens ; 1478GGML_ASSERT (n_tokens == (int64_t )sinfo .size ()* sinfo .n_stream ()); 1479 1480GGML_ASSERT (ggml_backend_buffer_is_host (dst -> buffer )); 1481int64_t * data = (int64_t * )dst -> data ; 1482 1483for (uint32_t s = 0 ;s < sinfo .n_stream ();++ s ) { 1484const int64_t offs = sinfo .strm [s ]* get_size (); 1485 1486for (uint32_t i = 0 ;i < sinfo .size ();++ i ) { 1487data [s * sinfo .size ()+ i ]= offs + sinfo .idxs [s ][i ]; 1488 } 1489 } 1490} 1491 1492void llama_kv_cache::set_input_v_idxs (ggml_tensor * dst ,const llama_ubatch * ubatch ,const slot_info & sinfo )const { 1493const uint32_t n_tokens = ubatch -> n_tokens ; 1494GGML_ASSERT (n_tokens == (int64_t )sinfo .size ()* sinfo .n_stream ()); 1495 1496GGML_ASSERT (ggml_backend_buffer_is_host (dst -> buffer )); 1497int64_t * data = (int64_t * )dst -> data ; 1498 1499if (!v_trans ) { 1500for (uint32_t s = 0 ;s < sinfo .n_stream ();++ s ) { 1501const int64_t offs = sinfo .strm [s ]* get_size (); 1502 1503for (uint32_t i = 0 ;i < sinfo .size ();++ i ) { 1504data [s * sinfo .size ()+ i ]= offs + sinfo .idxs [s ][i ]; 1505 } 1506 } 1507 }else { 1508// note: the V cache is transposed when not using flash attention 1509const int64_t kv_size = get_size (); 1510 1511const int64_t n_embd_v_gqa = hparams .n_embd_v_gqa_max (); 1512 1513for (uint32_t s = 0 ;s < sinfo .n_stream ();++ s ) { 1514const int64_t offs = sinfo .strm [s ]* kv_size * n_embd_v_gqa ; 1515 1516for (uint32_t i = 0 ;i < sinfo .size ();++ i ) { 1517for (uint32_t j = 0 ;j < n_embd_v_gqa ;++ j ) { 1518data [s * sinfo .size ()* n_embd_v_gqa + i * n_embd_v_gqa + j ]= offs + j * kv_size + sinfo .idxs [s ][i ]; 1519 } 1520 } 1521 } 1522 } 1523} 1524 1525void llama_kv_cache::set_input_k_shift (ggml_tensor * dst )const { 1526GGML_ASSERT (ggml_backend_buffer_is_host (dst -> buffer )); 1527 1528int32_t * data = (int32_t * )dst -> data ; 1529 1530for (uint32_t s = 0 ;s < n_stream ;++ s ) { 1531const auto & cells = v_cells [s ]; 1532 1533for (uint32_t i = 0 ;i < cells .size ();++ i ) { 1534data [s * cells .size ()+ i ]= cells .is_empty (i ) ?0 :cells .get_shift (i ); 1535 } 1536 } 1537} 1538 1539struct args_set_input_kq_mask { 1540const llama_hparams & hparams ; 1541const llama_ubatch * ubatch ; 1542 1543const std::vector < llama_kv_cells > & v_cells ; 1544const std::vector < uint32_t > & seq_to_stream ; 1545 1546uint32_t n_swa ; 1547llama_swa_type swa_type ; 1548 1549int64_t n_kv ; 1550int64_t n_stream ; 1551int64_t n_tps ; 1552}; 1553 1554template < typename T ,bool causal ,bool swa ,bool is_2d ,bool alibi > 1555static void set_input_kq_mask_impl (const args_set_input_kq_mask & args ,T * data ) { 1556//const auto & hparams = args.hparams; 1557const auto & ubatch = args .ubatch ; 1558 1559const auto & v_cells = args .v_cells ; 1560const auto & seq_to_stream = args .seq_to_stream ; 1561 1562const uint32_t n_swa = args .n_swa ; 1563const llama_swa_type swa_type = args .swa_type ; 1564 1565const int64_t n_kv = args .n_kv ; 1566const int64_t n_stream = args .n_stream ; 1567const int64_t n_tps = args .n_tps ; 1568 1569const T mask_keep = llama_cast < T > (0.0f ); 1570const T mask_drop = llama_cast < T > (- INFINITY ); 1571 1572// the min position in the batch for each sequence 1573llama_pos seq_pos_min [LLAMA_MAX_SEQ ]; 1574 std::fill (seq_pos_min ,seq_pos_min + LLAMA_MAX_SEQ ,INT32_MAX ); 1575 1576for (uint32_t i = 0 ;i < ubatch -> n_tokens ;++ i ) { 1577const llama_seq_id seq_id = ubatch -> seq_id [i ][0 ]; 1578 1579seq_pos_min [seq_id ]= std::min (seq_pos_min [seq_id ],ubatch -> pos [i ]); 1580 } 1581 1582for (uint32_t s = 0 ;s < n_stream ;++ s ) { 1583// bookkeeping of the KQ mask cells that could change for other tokens of the same sequence 1584 std::unordered_map < llama_seq_id ,uint32_t > seq_srct ; 1585 std::unordered_map < llama_seq_id , std::vector < uint32_t >> seq_idxs ; 1586 1587for (uint32_t ii = 0 ;ii < n_tps ;++ ii ) { 1588const uint32_t i = s * n_tps + ii ; 1589 1590const llama_seq_id seq_id = ubatch -> seq_id [i ][0 ]; 1591 1592const auto & cells = v_cells .at (seq_to_stream [seq_id ]); 1593 1594llama_pos p0 = -1 ; 1595const llama_pos p1 = ubatch -> pos [i ]; 1596 1597// for M-RoPE 1598const llama_pos p1_x = is_2d ?ubatch -> pos [i + ubatch -> n_tokens * 2 ] :0 ; 1599const llama_pos p1_y = is_2d ?ubatch -> pos [i + ubatch -> n_tokens ] :0 ; 1600 1601const uint64_t idst = n_kv * i ; 1602 1603// for tokens of the same sequence, the mask is mostly the same, so we can reuse it 1604// the only cells that could change are the ones that are with similar positions as the 1605// ones in the batch (i.e. due to causal masking, SWA, etc.) 1606// keep track of those cells and shortcut the loop to save time 1607// note: this optimization is not compatible with Alibi position encoding 1608// ref: https://github.com/ggml-org/llama.cpp/pull/18842 1609bool prev = false; 1610 1611auto & idxs = seq_idxs [seq_id ]; 1612 1613if (!alibi ) { 1614if (seq_srct .find (seq_id )!= seq_srct .end ()) { 1615const uint32_t srct = seq_srct [seq_id ]; 1616 1617const uint64_t idst_prev = n_kv * srct ; 1618 1619 std::copy (data + idst_prev ,data + idst_prev + n_kv ,data + idst ); 1620 1621prev = true; 1622 }else { 1623idxs .clear (); 1624idxs .reserve (ubatch -> n_tokens + n_swa + 32 ); 1625 1626seq_srct [seq_id ]= i ; 1627 } 1628 } 1629 1630for (uint32_t jj = 0 ;jj < n_kv ;++ jj ) { 1631uint32_t j = jj ; 1632 1633// we have an exiting mask for this sequence -> update just seq_idxs 1634if (!alibi ) { 1635if (prev ) { 1636if (jj >=idxs .size ()) { 1637break ; 1638 } 1639 1640j = idxs [jj ]; 1641 } 1642 } 1643 1644if (cells .is_empty (j )) { 1645 gotoskip ; 1646 } 1647 1648// mask the token if not the same sequence 1649if (!cells .seq_has (j ,seq_id )) { 1650 gotoskip ; 1651 } 1652 1653p0 = cells .pos_get (j ); 1654 1655if (!alibi ) { 1656if (!prev ) { 1657// record all cells for which: p0 >= seq_pos_min[seq_id] - n_swa - 32 1658if (p0 + (int32_t ) (n_swa + 32 ) >=seq_pos_min [seq_id ]) { 1659idxs .push_back (j ); 1660 } 1661 } 1662 } 1663 1664if (causal ) { 1665// mask future tokens 1666if (p0 > p1 ) { 1667 gotoskip ; 1668 } 1669 1670// M-RoPE causal mask 1671if (is_2d ) { 1672if (p0 == p1 ) { 1673const auto & p0_ext = cells .ext_get (j ); 1674 1675if (p0_ext .is_2d_gt (p1_x ,p1_y )) { 1676 gotoskip ; 1677 } 1678 } 1679 } 1680 } 1681 1682// apply SWA if any 1683if (swa ) { 1684// see llama_non_causal_type 1685const bool in_span = !causal && args .hparams .non_causal_type == LLAMA_NON_CAUSAL_TYPE_SWA_FULL && p0 >=seq_pos_min [seq_id ]; 1686if (!in_span && llama_hparams::is_masked_swa (n_swa ,swa_type ,p0 ,p1 )) { 1687 gotoskip ; 1688 } 1689 } 1690 1691if (alibi ) { 1692data [idst + j ]= llama_cast < T > (static_cast < float > (- std::abs (p0 - p1 ))); 1693 }else { 1694data [idst + j ]= mask_keep ; 1695 } 1696 1697continue ; 1698skip : 1699data [idst + j ]= mask_drop ; 1700 } 1701 } 1702 } 1703} 1704 1705template < typename T ,bool causal ,bool swa ,bool is_2d > 1706static void set_input_kq_mask_impl (const args_set_input_kq_mask & args ,T * data ) { 1707const bool alibi = args .hparams .use_alibi ; 1708if (alibi ) { 1709set_input_kq_mask_impl < T ,causal ,swa ,is_2d , true> (args ,data ); 1710 }else { 1711set_input_kq_mask_impl < T ,causal ,swa ,is_2d , false> (args ,data ); 1712 } 1713} 1714 1715template < typename T ,bool causal ,bool swa > 1716static void set_input_kq_mask_impl (const args_set_input_kq_mask & args ,T * data ) { 1717const bool is_2d = args .ubatch -> is_pos_2d (); 1718if (is_2d ) { 1719set_input_kq_mask_impl < T ,causal ,swa , true> (args ,data ); 1720 }else { 1721set_input_kq_mask_impl < T ,causal ,swa , false> (args ,data ); 1722 } 1723} 1724 1725template < typename T ,bool causal > 1726static void set_input_kq_mask_impl (const args_set_input_kq_mask & args ,T * data ) { 1727const bool swa = args .swa_type != LLAMA_SWA_TYPE_NONE ; 1728if (swa ) { 1729set_input_kq_mask_impl < T ,causal , true> (args ,data ); 1730 }else { 1731set_input_kq_mask_impl < T ,causal , false> (args ,data ); 1732 } 1733} 1734 1735template < typename T > 1736static void set_input_kq_mask_impl (const args_set_input_kq_mask & args ,T * data ,bool causal_attn ) { 1737if (causal_attn ) { 1738set_input_kq_mask_impl < T , true> (args ,data ); 1739 }else { 1740set_input_kq_mask_impl < T , false> (args ,data ); 1741 } 1742} 1743 1744void llama_kv_cache::set_input_kq_mask (ggml_tensor * dst ,const llama_ubatch * ubatch ,bool causal_attn )const { 1745const uint32_t n_tokens = ubatch -> n_tokens ; 1746 1747GGML_ASSERT (ggml_backend_buffer_is_host (dst -> buffer )); 1748 1749const int64_t n_kv = dst -> ne [0 ]; 1750const int64_t n_stream = dst -> ne [3 ];// num streams in the current ubatch 1751 1752GGML_ASSERT (n_tokens %n_stream == 0 ); 1753 1754// n_tps == n_tokens_per_stream 1755const int64_t n_tps = n_tokens /n_stream ; 1756 1757// see llama_non_causal_type 1758// only the SWA cache (or the SWA layers of a single cache) become non-causal 1759if (!causal_attn && hparams .non_causal_type == LLAMA_NON_CAUSAL_TYPE_SWA_ONLY ) { 1760causal_attn = swa_type == LLAMA_SWA_TYPE_NONE ; 1761 } 1762 1763//const int64_t t_start = ggml_time_us(); 1764 1765const args_set_input_kq_mask args = { 1766/*.hparams =*/ hparams , 1767/*.ubatch =*/ ubatch , 1768/*.v_cells =*/ v_cells , 1769/*.seq_to_stream =*/ seq_to_stream , 1770/*.n_swa =*/ n_swa , 1771/*.swa_type =*/ swa_type , 1772/*.n_kv =*/ n_kv , 1773/*.n_stream =*/ n_stream , 1774/*.n_tps =*/ n_tps , 1775 }; 1776 1777if (dst -> type == GGML_TYPE_F16 ) { 1778set_input_kq_mask_impl < ggml_fp16_t > (args , (ggml_fp16_t * )dst -> data ,causal_attn ); 1779 }else { 1780set_input_kq_mask_impl < float > (args , (float * )dst -> data ,causal_attn ); 1781 } 1782 1783//const int64_t t_end = ggml_time_us(); 1784 1785//LLAMA_LOG_ERROR("%s: kq mask time: %0.3f ms\n", __func__, (t_end - t_start)/1000.0); 1786} 1787 1788void llama_kv_cache::set_input_pos_bucket (ggml_tensor * dst ,const llama_ubatch * ubatch )const { 1789const int64_t n_tokens = ubatch -> n_tokens ; 1790 1791GGML_ASSERT (n_stream == 1 && "TODO: support multiple streams" ); 1792const auto & cells = v_cells [0 ]; 1793 1794GGML_ASSERT (ggml_backend_buffer_is_host (dst -> buffer )); 1795GGML_ASSERT (!ubatch -> equal_seqs ());// TODO: use ubatch->n_seqs instead of failing 1796 1797int32_t * data = (int32_t * )dst -> data ; 1798 1799const int32_t n_kv = dst -> ne [0 ]; 1800 1801for (int h = 0 ;h < 1 ;++ h ) { 1802for (int i = 0 ;i < n_tokens ;++ i ) { 1803for (int j = 0 ;j < n_kv ;++ j ) { 1804// the position when the cells is empty is irrelevant - it will be masked out later in the attention 1805const llama_pos p0 = cells .is_empty (j ) ?-1 :cells .pos_get (j ); 1806 1807data [h * (n_kv * n_tokens )+ i * n_kv + j ]= llama_relative_position_bucket (p0 ,ubatch -> pos [i ],hparams .n_rel_attn_bkts , false); 1808 } 1809 } 1810 } 1811} 1812 1813void llama_kv_cache::set_input_k_rot (ggml_tensor * dst )const { 1814GGML_ASSERT (ggml_backend_buffer_is_host (dst -> buffer )); 1815 1816const auto n_rot = dst -> ne [0 ]; 1817GGML_ASSERT (attn_rot_hadamard .count (dst -> ne [0 ])); 1818 1819memcpy (dst -> data ,attn_rot_hadamard .at (n_rot ).data (),ggml_nbytes (dst )); 1820} 1821 1822void llama_kv_cache::set_input_v_rot (ggml_tensor * dst )const { 1823GGML_ASSERT (ggml_backend_buffer_is_host (dst -> buffer )); 1824 1825const auto n_rot = dst -> ne [0 ]; 1826GGML_ASSERT (attn_rot_hadamard .count (dst -> ne [0 ])); 1827 1828memcpy (dst -> data ,attn_rot_hadamard .at (n_rot ).data (),ggml_nbytes (dst )); 1829} 1830 1831bool llama_kv_cache::has_cell_ext ()const { 1832// M-RoPE needs the 2D position, the PLE n-gram hash needs the token id 1833return hparams .n_pos_per_embd ()> 1 || hparams .ple_n_heads > 0 ; 1834} 1835 1836void llama_kv_cache::get_prev_tokens (const llama_ubatch & ubatch ,uint32_t n , std::vector < llama_token > & res )const { 1837const uint32_t n_tokens = ubatch .n_tokens ; 1838 1839res .clear (); 1840res .resize (n_tokens * n ,LLAMA_TOKEN_NULL ); 1841 1842if (n == 0 ) { 1843return ; 1844 } 1845 1846// note: apply_ubatch() has already stored the current ubatch, so the cells cover the tokens 1847// of this very ubatch as well, which is what we want 1848// the nearest cell at or before a position also resolves M-RoPE gaps, where multiple tokens 1849// share the same temporal pos 1850 1851// an embd (multimodal) ubatch can repeat one position for a whole image, so positions 1852// do not encode the token order; resolve its predecessors by ubatch order instead 1853 std::vector < uint32_t > ord ;// index among the ubatch tokens of the same seq 1854 std::unordered_map < llama_seq_id , std::vector < uint32_t >> seq_idx ; 1855 1856if (!ubatch .token ) { 1857ord .resize (n_tokens ); 1858for (uint32_t i = 0 ;i < n_tokens ;++ i ) { 1859auto & v = seq_idx [ubatch .seq_id [i ][0 ]]; 1860ord [i ]= v .size (); 1861v .push_back (i ); 1862 } 1863 } 1864 1865for (uint32_t i = 0 ;i < n_tokens ;++ i ) { 1866// TODO: a token that belongs to more than one sequence has an ambiguous history. 1867// the n-gram architectures have to reject such batches 1868const llama_seq_id seq_id = ubatch .seq_id [i ][0 ]; 1869 1870for (uint32_t j = 0 ;j < n ;++ j ) { 1871const llama_pos d = (llama_pos ) (n - j ); 1872 1873llama_pos p ; 1874if (!ubatch .token ) { 1875const auto & v = seq_idx [seq_id ]; 1876const int64_t k = (int64_t )ord [i ]- d ; 1877// k >= 0: an earlier token of this very ubatch; k < 0: before the chunk 1878p = k >=0 ?ubatch .pos [v [k ]] :ubatch .pos [v [0 ]]+ (llama_pos )k ; 1879 }else { 1880p = ubatch .pos [i ]- d ; 1881 } 1882 1883if (p < 0 ) { 1884continue ; 1885 } 1886 1887res [i * n + j ]= v_cells [seq_to_stream [seq_id ]].seq_pos_tok_le (seq_id ,p ); 1888 } 1889 } 1890} 1891 1892size_t llama_kv_cache::total_size ()const { 1893size_t size = 0 ; 1894 1895for (const auto & [_ ,buf ] :ctxs_bufs ) { 1896size += ggml_backend_buffer_get_size (buf .get ()); 1897 } 1898 1899return size ; 1900} 1901 1902size_t llama_kv_cache::size_k_bytes ()const { 1903size_t size_k_bytes = 0 ; 1904 1905for (const auto & layer :layers ) { 1906size_k_bytes += ggml_nbytes (layer .k ); 1907 } 1908 1909return size_k_bytes ; 1910} 1911 1912size_t llama_kv_cache::size_v_bytes ()const { 1913size_t size_v_bytes = 0 ; 1914 1915for (const auto & layer :layers ) { 1916size_v_bytes += layer .v ?ggml_nbytes (layer .v ) :0 ; 1917 } 1918 1919return size_v_bytes ; 1920} 1921 1922ggml_tensor * llama_kv_cache::build_rope_shift ( 1923const llama_cparams & cparams , 1924ggml_context * ctx , 1925ggml_tensor * cur , 1926ggml_tensor * shift , 1927ggml_tensor * rot , 1928ggml_tensor * factors , 1929float freq_base , 1930float freq_scale , 1931uint32_t il )const { 1932const auto & n_ctx_orig = cparams .n_ctx_orig_yarn ; 1933 1934const auto & yarn_ext_factor = cparams .yarn_ext_factor ; 1935const auto & yarn_beta_fast = cparams .yarn_beta_fast ; 1936const auto & yarn_beta_slow = cparams .yarn_beta_slow ; 1937const auto & yarn_attn_factor = cparams .yarn_attn_factor ; 1938 1939const auto & n_rot = hparams .n_rot (il ); 1940const auto & rope_type = hparams .rope_type == LLAMA_ROPE_TYPE_MROPE || hparams .rope_type == LLAMA_ROPE_TYPE_IMROPE 1941// @ngxson : this is a workaround 1942// for M-RoPE, we want to rotate the whole vector when doing KV shift 1943// a normal RoPE should work, we just need to use the correct ordering 1944// ref: https://github.com/ggml-org/llama.cpp/pull/13870 1945 ?LLAMA_ROPE_TYPE_NEOX 1946 :hparams .rope_type ; 1947ggml_tensor * tmp ; 1948 1949if (ggml_is_quantized (cur -> type )) { 1950// dequantize to f32 -> RoPE -> quantize back 1951tmp = ggml_cast (ctx ,cur ,GGML_TYPE_F32 ); 1952 1953// rotate back 1954tmp = llama_mul_mat_hadamard (ctx ,tmp ,rot ); 1955 1956tmp = ggml_rope_ext (ctx ,tmp , 1957shift ,factors ,n_rot ,rope_type ,n_ctx_orig ,freq_base ,freq_scale , 1958yarn_ext_factor ,yarn_attn_factor ,yarn_beta_fast ,yarn_beta_slow ); 1959 1960// rotate fwd 1961tmp = llama_mul_mat_hadamard (ctx ,tmp ,rot ); 1962 1963tmp = ggml_cpy (ctx ,tmp ,cur ); 1964 }else { 1965// we rotate only the first n_rot dimensions 1966tmp = ggml_rope_ext_inplace (ctx ,cur , 1967shift ,factors ,n_rot ,rope_type ,n_ctx_orig ,freq_base ,freq_scale , 1968yarn_ext_factor ,yarn_attn_factor ,yarn_beta_fast ,yarn_beta_slow ); 1969 } 1970 1971return tmp ; 1972} 1973 1974class llm_graph_input_k_shift :public llm_graph_input_i { 1975public : 1976llm_graph_input_k_shift (const llama_kv_cache * kv_self ) :kv_self (kv_self ) {} 1977virtual ~llm_graph_input_k_shift ()= default ; 1978 1979void set_input (const llama_ubatch * ubatch )override ; 1980 1981ggml_tensor * k_shift ;// I32 [kv_size*n_stream] 1982 1983// note: assumes k_rot^2 == I 1984ggml_tensor * k_rot = nullptr ; 1985 1986const llama_kv_cache * kv_self ; 1987}; 1988 1989void llm_graph_input_k_shift::set_input (const llama_ubatch * ubatch ) { 1990GGML_UNUSED (ubatch ); 1991 1992if (k_shift ) { 1993kv_self -> set_input_k_shift (k_shift ); 1994 } 1995 1996if (k_rot && k_rot -> buffer ) { 1997kv_self -> set_input_k_rot (k_rot ); 1998 } 1999} 2000 2001ggml_cgraph * llama_kv_cache::build_graph_shift (llm_graph_result * res ,llama_context * lctx )const { 2002// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 2003GGML_ASSERT (!other ); 2004 2005auto * ctx = res -> get_ctx (); 2006auto * gf = res -> get_gf (); 2007 2008auto inp = std::make_unique < llm_graph_input_k_shift > (this ); 2009 2010inp -> k_shift = ggml_new_tensor_1d (ctx ,GGML_TYPE_I32 , (int64_t )get_size ()* n_stream ); 2011ggml_set_input (inp -> k_shift ); 2012 2013inp -> k_rot = build_input_k_rot (ctx ); 2014 2015const auto & cparams = lctx -> get_cparams (); 2016 2017for (const auto & layer :layers ) { 2018const uint32_t il = layer .il ; 2019 2020if (!hparams .has_rope (il )) { 2021continue ; 2022 } 2023 2024const int64_t n_head_kv = hparams .n_head_kv (il ); 2025const int64_t n_embd_k_gqa = hparams .n_embd_k_gqa (il ); 2026 2027const auto n_rot = hparams .n_rot (il ); 2028const auto n_embd_head_k = hparams .n_embd_head_k (il ); 2029const auto n_embd_nope = hparams .n_lora_kv > 0 ?n_embd_head_k - n_rot :0 ; 2030 2031const float freq_base_l = model .get_rope_freq_base (cparams ,il ); 2032const float freq_scale_l = model .get_rope_freq_scale (cparams ,il ); 2033 2034ggml_tensor * rope_factors = model .get_rope_factors (cparams ,il ); 2035 2036ggml_tensor * k = 2037ggml_view_3d (ctx ,layer .k , 2038n_rot ,n_head_kv ,get_size ()* n_stream , 2039ggml_row_size (layer .k -> type ,n_embd_head_k ), 2040ggml_row_size (layer .k -> type ,n_embd_k_gqa ), 2041ggml_row_size (layer .k -> type ,n_embd_nope )); 2042 2043ggml_tensor * cur = build_rope_shift (cparams ,ctx ,k ,inp -> k_shift ,inp -> k_rot ,rope_factors ,freq_base_l ,freq_scale_l ,il ); 2044 2045ggml_build_forward_expand (gf ,cur ); 2046 } 2047 2048res -> add_input (std::move (inp )); 2049 2050return gf ; 2051} 2052 2053void llama_kv_cache::state_write (llama_io_write_i & io ,llama_seq_id seq_id ,llama_state_seq_flags flags )const { 2054// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 2055if (other ) { 2056return ; 2057 } 2058 2059GGML_UNUSED (flags ); 2060 2061io .write (& n_stream ,sizeof (n_stream )); 2062 2063for (uint32_t s = 0 ;s < n_stream ;++ s ) { 2064cell_ranges_t cr {s , {} }; 2065 2066uint32_t cell_count = 0 ; 2067 2068const auto & cells = v_cells [s ]; 2069 2070// Count the number of cells with the specified seq_id 2071// Find all the ranges of cells with this seq id (or all, when -1) 2072uint32_t cell_range_begin = cells .size (); 2073 2074for (uint32_t i = 0 ;i < cells .size ();++ i ) { 2075bool add_cell = true; 2076 2077add_cell = add_cell && !cells .is_empty (i ); 2078add_cell = add_cell && (seq_id == -1 || cells .seq_has (i ,seq_id )); 2079 2080// check the cell is not SWA-masked 2081if (add_cell && seq_id != -1 ) { 2082const bool is_masked = llama_hparams::is_masked_swa (n_swa ,swa_type ,cells .pos_get (i ),cells .seq_pos_max (seq_id )); 2083 2084add_cell = !is_masked ; 2085 } 2086 2087if (add_cell ) { 2088++ cell_count ; 2089if (cell_range_begin == cells .size ()) { 2090cell_range_begin = i ; 2091 } 2092 }else { 2093if (cell_range_begin != cells .size ()) { 2094cr .data .emplace_back (cell_range_begin ,i ); 2095cell_range_begin = cells .size (); 2096 } 2097 } 2098 } 2099 2100if (cell_range_begin != cells .size ()) { 2101cr .data .emplace_back (cell_range_begin ,cells .size ()); 2102 } 2103 2104// DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count 2105uint32_t cell_count_check = 0 ; 2106for (const auto & range :cr .data ) { 2107cell_count_check += range .second - range .first ; 2108 } 2109GGML_ASSERT (cell_count == cell_count_check ); 2110 2111io .write (& cell_count ,sizeof (cell_count )); 2112 2113// skip empty streams 2114if (cell_count == 0 ) { 2115continue ; 2116 } 2117 2118state_write_meta (io ,cr ,seq_id ); 2119state_write_data (io ,cr ); 2120 } 2121} 2122 2123void llama_kv_cache::state_read (llama_io_read_i & io ,llama_seq_id seq_id ,llama_state_seq_flags flags ) { 2124state_read_sinfo (io ,seq_id ,flags ,nullptr ,nullptr ); 2125} 2126 2127void llama_kv_cache::state_read_sinfo ( 2128llama_io_read_i & io , 2129llama_seq_id seq_id , 2130llama_state_seq_flags flags , 2131slot_info_vec_t * sinfos_out , 2132const slot_info_vec_t * sinfos_in ) { 2133// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] 2134if (other ) { 2135return ; 2136 } 2137 2138GGML_UNUSED (flags ); 2139 2140// TODO: fix incosistent handling of `seq_id < 0` and `seq_id == -1` in the codebase [TAG_LLAMA_SEQ_ID_NEG] 2141GGML_ASSERT (seq_id == -1 || (seq_id >=0 && (size_t )seq_id < seq_to_stream .size ())); 2142 2143if (sinfos_out ) { 2144sinfos_out -> assign (n_stream ,slot_info {}); 2145 } 2146 2147if (sinfos_in && sinfos_in -> size ()!= n_stream ) { 2148throw std::runtime_error ("failed to restore kv cache: mirrored slot layout has the wrong stream count" ); 2149 } 2150 2151uint32_t n_stream_cur ; 2152io .read (& n_stream_cur ,sizeof (n_stream_cur )); 2153if (n_stream_cur != n_stream ) { 2154throw std::runtime_error ("n_stream mismatch" ); 2155 } 2156 2157// a whole-context restore replaces every stream, so the cache is emptied once here 2158// clear() resets all streams at once, so doing it per stream below would keep only the last one 2159if (seq_id == -1 ) { 2160clear (true); 2161 } 2162 2163for (uint32_t s = 0 ;s < n_stream ;++ s ) { 2164uint32_t cell_count ; 2165io .read (& cell_count ,sizeof (cell_count )); 2166 2167if (cell_count == 0 ) { 2168// a mirrored cache must be empty here as well, or the two no longer agree cell for cell 2169if (sinfos_in && !(* sinfos_in )[s ].empty ()) { 2170throw std::runtime_error ("failed to restore kv cache: mirrored cache holds cells this one does not" ); 2171 } 2172continue ; 2173 } 2174 2175const uint32_t strm = seq_id == -1 ?s :seq_to_stream [seq_id ]; 2176 2177slot_info sinfo ; 2178 2179bool res = true; 2180res = res && state_read_meta (io ,strm ,cell_count ,sinfo ,seq_id ,sinfos_in ?& (* sinfos_in )[s ] :nullptr ); 2181 2182try { 2183res = res && state_read_data (io ,strm ,cell_count ,sinfo ); 2184 }catch (...) { 2185res = false; 2186 } 2187 2188if (!res ) { 2189if (seq_id == -1 ) { 2190clear (true); 2191 }else { 2192seq_rm (seq_id ,-1 ,-1 ); 2193 } 2194throw std::runtime_error ("failed to restore kv cache" ); 2195 } 2196 2197if (sinfos_out ) { 2198 (* sinfos_out )[s ]= sinfo ; 2199 } 2200 } 2201} 2202 2203void llama_kv_cache::state_write_meta (llama_io_write_i & io ,const cell_ranges_t & cr ,llama_seq_id seq_id )const { 2204const auto & cells = v_cells [cr .strm ]; 2205 2206for (const auto & range :cr .data ) { 2207for (uint32_t i = range .first ;i < range .second ;++ i ) { 2208 std::vector < llama_seq_id > seq_ids ; 2209 2210for (llama_seq_id cur = 0 ;cur < (int )n_seq_max ;++ cur ) { 2211if (cur == seq_id || seq_id == -1 ) { 2212if (cells .seq_has (i ,cur )) { 2213seq_ids .push_back (cur ); 2214 } 2215 } 2216 } 2217 2218const llama_pos pos = cells .pos_get (i ); 2219const uint32_t n_seq_id = seq_ids .size (); 2220 2221io .write (& pos ,sizeof (pos )); 2222io .write (& n_seq_id ,sizeof (n_seq_id )); 2223 2224if (has_cell_ext ()) { 2225const llama_kv_cell_ext ext = cells .ext_get (i ); 2226io .write (& ext ,sizeof (ext )); 2227 } 2228 2229for (const auto & seq_id :seq_ids ) { 2230io .write (& seq_id ,sizeof (seq_id )); 2231 } 2232 } 2233 } 2234} 2235 2236void llama_kv_cache::state_write_data (llama_io_write_i & io ,const cell_ranges_t & cr )const { 2237const auto & cells = v_cells [cr .strm ]; 2238 2239const uint32_t v_trans = this -> v_trans ?1 :0 ; 2240const uint32_t n_layer = layers .size (); 2241 2242io .write (& v_trans ,sizeof (v_trans )); 2243io .write (& n_layer ,sizeof (n_layer )); 2244 2245// Iterate and write all the keys first, each row is a cell 2246// Get whole range at a time 2247for (const auto & layer :layers ) { 2248const uint32_t il = layer .il ; 2249 2250const uint32_t n_embd_k_gqa = hparams .n_embd_k_gqa (il ); 2251 2252auto * k = layer .k_stream [cr .strm ]; 2253 2254// Write key type 2255const int32_t k_type_i = (int32_t )k -> type ; 2256io .write (& k_type_i ,sizeof (k_type_i )); 2257 2258// Write row size of key 2259const uint64_t k_size_row = ggml_row_size (k -> type ,n_embd_k_gqa ); 2260io .write (& k_size_row ,sizeof (k_size_row )); 2261 2262// Read each range of cells of k_size length and write out 2263for (const auto & range :cr .data ) { 2264const size_t range_size = range .second - range .first ; 2265const size_t buf_size = range_size * k_size_row ; 2266io .write_tensor (k ,range .first * k_size_row ,buf_size ); 2267 } 2268 } 2269 2270if (!v_trans ) { 2271for (const auto & layer :layers ) { 2272const uint32_t il = layer .il ; 2273 2274const uint32_t n_embd_v_gqa = hparams .n_embd_v_gqa (il ); 2275 2276auto * v = layer .v_stream [cr .strm ]; 2277if (!v ) { 2278continue ; 2279 } 2280 2281// Write value type 2282const int32_t v_type_i = (int32_t )v -> type ; 2283io .write (& v_type_i ,sizeof (v_type_i )); 2284 2285// Write row size of value 2286const uint64_t v_size_row = ggml_row_size (v -> type ,n_embd_v_gqa ); 2287io .write (& v_size_row ,sizeof (v_size_row )); 2288 2289// Read each range of cells of v_size length and write out 2290for (const auto & range :cr .data ) { 2291const size_t range_size = range .second - range .first ; 2292const size_t buf_size = range_size * v_size_row ; 2293io .write_tensor (v ,range .first * v_size_row ,buf_size ); 2294 } 2295 } 2296 }else { 2297// When v is transposed, we also need the element size and get the element ranges from each row 2298const uint32_t kv_size = cells .size (); 2299 2300for (const auto & layer :layers ) { 2301const uint32_t il = layer .il ; 2302 2303const uint32_t n_embd_v_gqa = hparams .n_embd_v_gqa (il ); 2304 2305auto * v = layer .v_stream [cr .strm ]; 2306if (!v ) { 2307continue ; 2308 } 2309 2310// Write value type 2311const int32_t v_type_i = (int32_t )v -> type ; 2312io .write (& v_type_i ,sizeof (v_type_i )); 2313 2314// Write element size 2315const uint32_t v_size_el = ggml_type_size (v -> type ); 2316io .write (& v_size_el ,sizeof (v_size_el )); 2317 2318// Write GQA embedding size 2319io .write (& n_embd_v_gqa ,sizeof (n_embd_v_gqa )); 2320 2321// For each row, we get the element values of each cell 2322for (uint32_t j = 0 ;j < n_embd_v_gqa ;++ j ) { 2323// Read each range of cells of v_size_el length and write out 2324for (const auto & range :cr .data ) { 2325const size_t range_size = range .second - range .first ; 2326const size_t src_offset = (range .first + j * kv_size )* v_size_el ; 2327const size_t buf_size = range_size * v_size_el ; 2328io .write_tensor (v ,src_offset ,buf_size ); 2329 } 2330 } 2331 } 2332 } 2333} 2334 2335bool llama_kv_cache::state_read_meta (llama_io_read_i & io ,uint32_t strm ,uint32_t cell_count ,slot_info & sinfo ,llama_seq_id dest_seq_id ,const slot_info * sinfo_in ) { 2336auto & cells = v_cells [strm ]; 2337auto & head = v_heads [strm ]; 2338 2339if (dest_seq_id != -1 ) { 2340// single sequence 2341seq_rm (dest_seq_id ,-1 ,-1 ); 2342 2343llama_batch_allocr balloc (hparams .n_pos_per_embd ()); 2344 2345llama_ubatch ubatch = balloc .ubatch_reserve (cell_count ,1 ); 2346 2347ubatch .seq_id_unq [0 ]= dest_seq_id ; 2348 2349// the ext as it was saved, to put back after apply_ubatch() 2350 std::vector < llama_kv_cell_ext > exts ; 2351if (has_cell_ext ()) { 2352exts .resize (cell_count ); 2353 } 2354 2355for (uint32_t i = 0 ;i < cell_count ;++ i ) { 2356llama_pos pos ; 2357uint32_t n_seq_id ; 2358 2359io .read (& pos ,sizeof (pos )); 2360io .read (& n_seq_id ,sizeof (n_seq_id )); 2361 2362if (n_seq_id != 1 ) { 2363LLAMA_LOG_ERROR ("%s: invalid seq_id-agnostic kv cell\n" ,__func__ ); 2364return false; 2365 } 2366 2367if (has_cell_ext ()) { 2368llama_kv_cell_ext ext ; 2369io .read (& ext ,sizeof (ext )); 2370 2371if (hparams .n_pos_per_embd ()> 1 ) { 2372ubatch .pos [i + ubatch .n_tokens ]= ext .y ; 2373ubatch .pos [i + ubatch .n_tokens * 2 ]= ext .x ; 2374 } 2375 2376// apply_ubatch() below restores ext.tok from the ubatch tokens 2377ubatch .token [i ]= ext .tok ; 2378 2379exts [i ]= ext ; 2380 } 2381 2382// read the sequence id, but directly discard it - we will use dest_seq_id instead 2383 { 2384llama_seq_id seq_id ; 2385io .read (& seq_id ,sizeof (seq_id )); 2386 } 2387 2388ubatch .pos [i ]= pos ; 2389ubatch .n_seq_id [i ]= n_seq_id ; 2390ubatch .seq_id [i ]= & dest_seq_id ; 2391 } 2392 2393if (sinfo_in ) { 2394// this cache mirrors another one, so it takes that cache's layout instead of searching for its own cells 2395if (sinfo_in -> empty ()|| sinfo_in -> n_stream ()!= 1 || sinfo_in -> idxs [0 ].size ()!= cell_count ) { 2396LLAMA_LOG_ERROR ("%s: mirrored slot layout holds %d cells, this cache restores %d\n" ,__func__ , 2397sinfo_in -> empty () ?0 : (int )sinfo_in -> idxs [0 ].size (),cell_count ); 2398return false; 2399 } 2400 2401sinfo = * sinfo_in ; 2402 2403// the layout is cell indices, so it means the same in both caches only while their streams line up 2404sinfo .s0 = strm ; 2405sinfo .s1 = strm ; 2406sinfo .strm [0 ]= strm ; 2407 2408// seq_rm above freed exactly the cells this sequence held 2409// anything else in the way is a cache that had already drifted, which this restore must not hide 2410for (uint32_t i = 0 ;i < cell_count ;++ i ) { 2411const uint32_t idx = sinfo .idxs [0 ][i ]; 2412 2413if (idx >=cells .size ()|| !cells .is_empty (idx )) { 2414LLAMA_LOG_ERROR ("%s: cell %u of the mirrored slot layout is not free\n" ,__func__ ,idx ); 2415return false; 2416 } 2417 } 2418 }else { 2419sinfo = find_slot (ubatch , false); 2420if (sinfo .empty ()) { 2421LLAMA_LOG_ERROR ("%s: failed to find %d available cells in kv cache\n" ,__func__ ,cell_count ); 2422return false; 2423 } 2424 } 2425 2426// note: apply_ubatch() rebuilds llama_kv_cell_ext from the ubatch 2427// only ext.tok and the M-RoPE 2D position round-trip through it 2428// see: https://github.com/ggml-org/llama.cpp/pull/16825#issuecomment-3460868350 2429apply_ubatch (sinfo ,ubatch ); 2430 2431// apply_ubatch() takes the 2D position from the ubatch, and that ubatch is built with this 2432// cache's own n_pos_per_embd. a cache that does not use M-RoPE itself but mirrors one that 2433// does (the qwen4exp QSA indexer) would drop x and y. put the saved ext back instead, which 2434// is what the whole-context path below already does. 2435for (uint32_t i = 0 ;i < (uint32_t )exts .size ();++ i ) { 2436cells .ext_set (sinfo .idxs [0 ][i ],exts [i ]); 2437 } 2438 2439LLAMA_LOG_DEBUG ("%s: cell_count = %d, dest_seq_id = %d\n" ,__func__ ,cell_count ,dest_seq_id ); 2440 2441// DEBUG CHECK: verify that all cells were allocated and have correct seq_id and pos values 2442GGML_ASSERT (sinfo .n_stream ()== 1 ); 2443GGML_ASSERT (sinfo .idxs [0 ].size ()== cell_count ); 2444for (uint32_t i = 0 ;i < cell_count ;++ i ) { 2445const uint32_t idx = sinfo .idxs [0 ][i ]; 2446GGML_ASSERT (cells .pos_get (idx )== ubatch .pos [i ]); 2447GGML_ASSERT (cells .seq_has (idx ,dest_seq_id )); 2448 } 2449 }else { 2450// whole KV cache restore 2451 2452if (cell_count > cells .size ()) { 2453LLAMA_LOG_ERROR ("%s: not enough cells in kv cache\n" ,__func__ ); 2454return false; 2455 } 2456 2457// the cells go in from 0, so a mirrored cache lands on the same ones as long as it restores the same count. the layout itself carries no more information here 2458if (sinfo_in && (sinfo_in -> empty ()|| sinfo_in -> n_stream ()!= 1 || sinfo_in -> idxs [0 ].size ()!= cell_count )) { 2459LLAMA_LOG_ERROR ("%s: mirrored slot layout holds %d cells, this cache restores %d\n" ,__func__ , 2460sinfo_in -> empty () ?0 : (int )sinfo_in -> idxs [0 ].size (),cell_count ); 2461return false; 2462 } 2463 2464for (uint32_t i = 0 ;i < cell_count ;++ i ) { 2465llama_pos pos ; 2466uint32_t n_seq_id ; 2467 2468io .read (& pos ,sizeof (pos )); 2469io .read (& n_seq_id ,sizeof (n_seq_id )); 2470 2471cells .pos_set (i ,pos ); 2472 2473if (has_cell_ext ()) { 2474llama_kv_cell_ext ext ; 2475io .read (& ext ,sizeof (ext )); 2476cells .ext_set (i ,ext ); 2477 } 2478 2479for (uint32_t j = 0 ;j < n_seq_id ;++ j ) { 2480llama_seq_id seq_id ; 2481io .read (& seq_id ,sizeof (seq_id )); 2482 2483if (seq_id < 0 || (uint32_t )seq_id >=n_seq_max ) { 2484LLAMA_LOG_ERROR ("%s: invalid seq_id, %d is out of range [0, %u)\n" ,__func__ ,seq_id ,n_seq_max ); 2485return false; 2486 } 2487 2488cells .seq_add (i ,seq_id ); 2489 } 2490 } 2491 2492// Create contiguous slot_info for whole cache restore 2493sinfo .s0 = strm ; 2494sinfo .s1 = strm ; 2495sinfo .resize (1 ); 2496sinfo .strm [0 ]= strm ; 2497sinfo .idxs [0 ].resize (cell_count ); 2498for (uint32_t i = 0 ;i < cell_count ;++ i ) { 2499sinfo .idxs [0 ][i ]= i ; 2500 } 2501 2502head = 0 ; 2503 } 2504 2505return true; 2506} 2507 2508bool llama_kv_cache::state_read_data (llama_io_read_i & io ,uint32_t strm ,uint32_t cell_count ,const slot_info & sinfo ) { 2509auto & cells = v_cells [strm ]; 2510 2511// batch the scatter reads per contiguous run of destination indices 2512// from inclusive, to exclusive - same convention as cell_ranges_t 2513// contiguous cells yield a single run covering the whole block 2514struct cell_run {uint32_t from ;uint32_t to ; }; 2515 std::vector < cell_run > runs ; 2516if (cell_count > 0 ) { 2517const auto & idxs = sinfo .idxs [0 ]; 2518uint32_t i0 = 0 ; 2519while (i0 < cell_count ) { 2520uint32_t i1 = i0 + 1 ; 2521while (i1 < cell_count && idxs [i1 ]== idxs [i1 - 1 ]+ 1 ) { 2522++ i1 ; 2523 } 2524runs .push_back ({idxs [i0 ],idxs [i1 - 1 ]+ 1 }); 2525i0 = i1 ; 2526 } 2527 } 2528 2529uint32_t v_trans ; 2530uint32_t n_layer ; 2531 2532io .read (& v_trans ,sizeof (v_trans )); 2533io .read (& n_layer ,sizeof (n_layer )); 2534 2535if (n_layer != layers .size ()) { 2536LLAMA_LOG_ERROR ("%s: mismatched layer count (%u instead of %u)\n" ,__func__ ,n_layer , (uint32_t )layers .size ()); 2537return false; 2538 } 2539 2540if (cell_count > cells .size ()) { 2541LLAMA_LOG_ERROR ("%s: not enough cells in kv cache to restore state (%u > %u)\n" ,__func__ ,cell_count ,cells .size ()); 2542return false; 2543 } 2544 2545if (this -> v_trans != (bool )v_trans ) { 2546LLAMA_LOG_ERROR ("%s: incompatible V transposition\n" ,__func__ ); 2547return false; 2548 } 2549 2550// For each layer, read the keys for each cell, one row is one cell, read as one contiguous block 2551for (const auto & layer :layers ) { 2552const uint32_t il = layer .il ; 2553 2554const uint32_t n_embd_k_gqa = hparams .n_embd_k_gqa (il ); 2555 2556auto * k = layer .k_stream [strm ]; 2557 2558// Read type of key 2559int32_t k_type_i_ref ; 2560io .read (& k_type_i_ref ,sizeof (k_type_i_ref )); 2561const int32_t k_type_i = (int32_t )k -> type ; 2562if (k_type_i != k_type_i_ref ) { 2563LLAMA_LOG_ERROR ("%s: mismatched key type (%d != %d, layer %d)\n" ,__func__ ,k_type_i ,k_type_i_ref ,il ); 2564return false; 2565 } 2566 2567// Read row size of key 2568uint64_t k_size_row_ref ; 2569io .read (& k_size_row_ref ,sizeof (k_size_row_ref )); 2570const size_t k_size_row = ggml_row_size (k -> type ,n_embd_k_gqa ); 2571if (k_size_row != k_size_row_ref ) { 2572LLAMA_LOG_ERROR ("%s: mismatched key row size (%zu != %zu, layer %d)\n" ,__func__ ,k_size_row , (size_t )k_size_row_ref ,il ); 2573return false; 2574 } 2575 2576for (const auto & r :runs ) { 2577io .read_tensor (k , (size_t )r .from * k_size_row , (size_t ) (r .to - r .from )* k_size_row ); 2578 } 2579 } 2580 2581if (!this -> v_trans ) { 2582for (const auto & layer :layers ) { 2583const uint32_t il = layer .il ; 2584 2585const uint32_t n_embd_v_gqa = hparams .n_embd_v_gqa (il ); 2586 2587auto * v = layer .v_stream [strm ]; 2588if (!v ) { 2589continue ; 2590 } 2591 2592// Read type of value 2593int32_t v_type_i_ref ; 2594io .read (& v_type_i_ref ,sizeof (v_type_i_ref )); 2595const int32_t v_type_i = (int32_t )v -> type ; 2596if (v_type_i != v_type_i_ref ) { 2597LLAMA_LOG_ERROR ("%s: mismatched value type (%d != %d, layer %d)\n" ,__func__ ,v_type_i ,v_type_i_ref ,il ); 2598return false; 2599 } 2600 2601// Read row size of value 2602uint64_t v_size_row_ref ; 2603io .read (& v_size_row_ref ,sizeof (v_size_row_ref )); 2604const size_t v_size_row = ggml_row_size (v -> type ,n_embd_v_gqa ); 2605if (v_size_row != v_size_row_ref ) { 2606LLAMA_LOG_ERROR ("%s: mismatched value row size (%zu != %zu, layer %d)\n" ,__func__ ,v_size_row , (size_t )v_size_row_ref ,il ); 2607return false; 2608 } 2609 2610for (const auto & r :runs ) { 2611io .read_tensor (v , (size_t )r .from * v_size_row , (size_t ) (r .to - r .from )* v_size_row ); 2612 } 2613 } 2614 }else { 2615// For each layer, read the values for each cell (transposed) 2616for (const auto & layer :layers ) { 2617const uint32_t il = layer .il ; 2618 2619const uint32_t n_embd_v_gqa = hparams .n_embd_v_gqa (il ); 2620 2621auto * v = layer .v_stream [strm ]; 2622if (!v ) { 2623continue ; 2624 } 2625 2626// Read type of value 2627int32_t v_type_i_ref ; 2628io .read (& v_type_i_ref ,sizeof (v_type_i_ref )); 2629const int32_t v_type_i = (int32_t )v -> type ; 2630if (v_type_i != v_type_i_ref ) { 2631LLAMA_LOG_ERROR ("%s: mismatched value type (%d != %d, layer %d)\n" ,__func__ ,v_type_i ,v_type_i_ref ,il ); 2632return false; 2633 } 2634 2635// Read element size of value 2636uint32_t v_size_el_ref ; 2637io .read (& v_size_el_ref ,sizeof (v_size_el_ref )); 2638const size_t v_size_el = ggml_type_size (v -> type ); 2639if (v_size_el != v_size_el_ref ) { 2640LLAMA_LOG_ERROR ("%s: mismatched value element size (%zu != %zu, layer %d)\n" ,__func__ ,v_size_el , (size_t )v_size_el_ref ,il ); 2641return false; 2642 } 2643 2644// Read GQA embedding size 2645uint32_t n_embd_v_gqa_ref ; 2646io .read (& n_embd_v_gqa_ref ,sizeof (n_embd_v_gqa_ref )); 2647if (n_embd_v_gqa != n_embd_v_gqa_ref ) { 2648LLAMA_LOG_ERROR ("%s: mismatched GQA embedding size (%u != %u, layer %d)\n" ,__func__ ,n_embd_v_gqa ,n_embd_v_gqa_ref ,il ); 2649return false; 2650 } 2651 2652for (uint32_t j = 0 ;j < n_embd_v_gqa ;++ j ) { 2653for (const auto & r :runs ) { 2654const size_t dst_offset = ((size_t )r .from + j * cells .size ())* v_size_el ; 2655io .read_tensor (v ,dst_offset , (size_t ) (r .to - r .from )* v_size_el ); 2656 } 2657 } 2658 } 2659 } 2660 2661return true; 2662} 2663 2664// 2665// llama_kv_cache_context 2666// 2667 2668llama_kv_cache_context::llama_kv_cache_context (llama_memory_status status ) :status (status ) {} 2669 2670llama_kv_cache_context::llama_kv_cache_context ( 2671llama_kv_cache * kv ) :status (LLAMA_MEMORY_STATUS_SUCCESS ),kv (kv ) { 2672n_kv = kv -> get_size (); 2673 2674const uint32_t n_stream = kv -> get_n_stream (); 2675 2676// create a dummy slot info - the actual data is irrelevant. we just need to build the graph 2677sinfos .resize (1 ); 2678sinfos [0 ].s0 = 0 ; 2679sinfos [0 ].s1 = n_stream - 1 ; 2680sinfos [0 ].idxs .resize (n_stream ); 2681for (uint32_t s = 0 ;s < n_stream ;++ s ) { 2682sinfos [0 ].strm .push_back (s ); 2683sinfos [0 ].idxs [s ].resize (1 ,0 ); 2684 } 2685} 2686 2687llama_kv_cache_context::llama_kv_cache_context ( 2688llama_kv_cache * kv , 2689llama_context * lctx , 2690bool do_shift , 2691stream_copy_info sc_info ) :status (LLAMA_MEMORY_STATUS_SUCCESS ),kv (kv ),lctx (lctx ),do_shift (do_shift ),sc_info (std::move (sc_info )) { 2692if (!do_shift && this -> sc_info .empty ()) { 2693status = LLAMA_MEMORY_STATUS_NO_UPDATE ; 2694 } 2695} 2696 2697llama_kv_cache_context::llama_kv_cache_context ( 2698llama_kv_cache * kv , 2699 llama_kv_cache::slot_info_vec_t sinfos , 2700 std::vector < llama_ubatch > ubatches ) :status (LLAMA_MEMORY_STATUS_SUCCESS ),kv (kv ),sinfos (std::move (sinfos )),ubatches (std::move (ubatches )) { 2701} 2702 2703llama_kv_cache_context::~llama_kv_cache_context ()= default ; 2704 2705bool llama_kv_cache_context::next () { 2706assert (status == LLAMA_MEMORY_STATUS_SUCCESS ); 2707 2708if (++ i_cur >=ubatches .size ()) { 2709return false; 2710 } 2711 2712return true; 2713} 2714 2715bool llama_kv_cache_context::apply () { 2716assert (!llama_memory_status_is_fail (status )); 2717 2718// no ubatches -> this is a KV cache update 2719if (ubatches .empty ()) { 2720kv -> update (lctx ,do_shift ,sc_info ); 2721 2722return true; 2723 } 2724 2725kv -> apply_ubatch (sinfos [i_cur ],ubatches [i_cur ]); 2726n_kv = kv -> get_n_kv (sinfos [i_cur ]); 2727 2728return true; 2729} 2730 2731llama_memory_status llama_kv_cache_context::get_status ()const { 2732return status ; 2733} 2734 2735const llama_ubatch & llama_kv_cache_context::get_ubatch ()const { 2736assert (status == LLAMA_MEMORY_STATUS_SUCCESS ); 2737 2738return ubatches [i_cur ]; 2739} 2740 2741uint32_t llama_kv_cache_context::get_n_kv ()const { 2742return n_kv ; 2743} 2744 2745ggml_type llama_kv_cache_context::type_k ()const { 2746return kv -> type_k (); 2747} 2748 2749ggml_type llama_kv_cache_context::type_v ()const { 2750return kv -> type_v (); 2751} 2752 2753ggml_tensor * llama_kv_cache_context::get_k (ggml_context * ctx ,int32_t il )const { 2754return kv -> get_k (ctx ,il ,n_kv ,sinfos [i_cur ]); 2755} 2756 2757ggml_tensor * llama_kv_cache_context::get_v (ggml_context * ctx ,int32_t il )const { 2758return kv -> get_v (ctx ,il ,n_kv ,sinfos [i_cur ]); 2759} 2760 2761ggml_tensor * llama_kv_cache_context::cpy_k (ggml_context * ctx ,ggml_tensor * k_cur ,ggml_tensor * k_idxs ,int32_t il )const { 2762return kv -> cpy_k (ctx ,k_cur ,k_idxs ,il ,sinfos [i_cur ]); 2763} 2764 2765ggml_tensor * llama_kv_cache_context::cpy_v (ggml_context * ctx ,ggml_tensor * v_cur ,ggml_tensor * v_idxs ,int32_t il )const { 2766return kv -> cpy_v (ctx ,v_cur ,v_idxs ,il ,sinfos [i_cur ]); 2767} 2768 2769ggml_tensor * llama_kv_cache_context::build_input_k_idxs (ggml_context * ctx ,const llama_ubatch & ubatch )const { 2770return kv -> build_input_k_idxs (ctx ,ubatch ); 2771} 2772 2773ggml_tensor * llama_kv_cache_context::build_input_v_idxs (ggml_context * ctx ,const llama_ubatch & ubatch )const { 2774return kv -> build_input_v_idxs (ctx ,ubatch ); 2775} 2776 2777ggml_tensor * llama_kv_cache_context::build_input_k_rot (ggml_context * ctx )const { 2778return kv -> build_input_k_rot (ctx ); 2779} 2780 2781ggml_tensor * llama_kv_cache_context::build_input_v_rot (ggml_context * ctx )const { 2782return kv -> build_input_v_rot (ctx ); 2783} 2784 2785void llama_kv_cache_context::set_input_k_shift (ggml_tensor * dst )const { 2786kv -> set_input_k_shift (dst ); 2787} 2788 2789void llama_kv_cache_context::set_input_k_idxs (ggml_tensor * dst ,const llama_ubatch * ubatch )const { 2790kv -> set_input_k_idxs (dst ,ubatch ,sinfos [i_cur ]); 2791} 2792 2793void llama_kv_cache_context::set_input_v_idxs (ggml_tensor * dst ,const llama_ubatch * ubatch )const { 2794kv -> set_input_v_idxs (dst ,ubatch ,sinfos [i_cur ]); 2795} 2796 2797void llama_kv_cache_context::set_input_kq_mask (ggml_tensor * dst ,const llama_ubatch * ubatch ,bool causal_attn )const { 2798kv -> set_input_kq_mask (dst ,ubatch ,causal_attn ); 2799} 2800 2801void llama_kv_cache_context::set_input_pos_bucket (ggml_tensor * dst ,const llama_ubatch * ubatch )const { 2802kv -> set_input_pos_bucket (dst ,ubatch ); 2803} 2804 2805void llama_kv_cache_context::set_input_k_rot (ggml_tensor * dst )const { 2806kv -> set_input_k_rot (dst ); 2807} 2808 2809void llama_kv_cache_context::set_input_v_rot (ggml_tensor * dst )const { 2810kv -> set_input_v_rot (dst ); 2811} 2812 2813void llama_kv_cache_context::get_prev_tokens (const llama_ubatch & ubatch ,uint32_t n , std::vector < llama_token > & res )const { 2814kv -> get_prev_tokens (ubatch ,n ,res ); 2815}