llama-kv-cache-unified.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410
  1. #include "llama-kv-cache-unified.h"
  2. #include "llama-impl.h"
  3. #include "llama-io.h"
  4. #include "llama-model.h"
  5. #include "llama-context.h"
  6. #include <algorithm>
  7. #include <cassert>
  8. #include <cmath>
  9. #include <limits>
  10. #include <map>
  11. #include <stdexcept>
  12. //
  13. // llama_kv_cache_unified
  14. //
  15. llama_kv_cache_unified::llama_kv_cache_unified(
  16. const llama_model & model,
  17. layer_filter_cb && filter,
  18. ggml_type type_k,
  19. ggml_type type_v,
  20. bool v_trans,
  21. bool offload,
  22. bool unified,
  23. uint32_t kv_size,
  24. uint32_t n_seq_max,
  25. uint32_t n_pad,
  26. uint32_t n_swa,
  27. llama_swa_type swa_type) :
  28. model(model), hparams(model.hparams), v_trans(v_trans),
  29. n_seq_max(n_seq_max), n_stream(unified ? 1 : n_seq_max), n_pad(n_pad), n_swa(n_swa), swa_type(swa_type) {
  30. GGML_ASSERT(kv_size % n_pad == 0);
  31. // TODO: this is temporary until we support passing reuse layer filters [KV_REUSE]
  32. auto n_layer_cache = hparams.n_layer;
  33. if (model.arch == LLM_ARCH_GEMMA3N) {
  34. n_layer_cache = 20;
  35. }
  36. if (model.arch == LLM_ARCH_GLM4_MOE) {
  37. // GLM-4.5: Only process up to last layer, skip final NextN layer
  38. n_layer_cache = hparams.n_layer - hparams.nextn_predict_layers;
  39. }
  40. // create a context for each buffer type
  41. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  42. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  43. auto it = ctx_map.find(buft);
  44. if (it == ctx_map.end()) {
  45. ggml_init_params params = {
  46. /*.mem_size =*/ size_t(2u*(1 + n_stream)*n_layer_cache*ggml_tensor_overhead()),
  47. /*.mem_buffer =*/ NULL,
  48. /*.no_alloc =*/ true,
  49. };
  50. ggml_context * ctx = ggml_init(params);
  51. if (!ctx) {
  52. return nullptr;
  53. }
  54. ctx_map[buft] = ctx;
  55. ctxs.emplace_back(ctx);
  56. return ctx;
  57. }
  58. return it->second;
  59. };
  60. GGML_ASSERT(n_stream == 1 || n_stream == n_seq_max);
  61. v_heads.resize(n_stream);
  62. for (uint32_t s = 0; s < n_stream; ++s) {
  63. v_heads[s] = 0;
  64. }
  65. v_cells.resize(n_stream);
  66. for (uint32_t s = 0; s < n_stream; ++s) {
  67. v_cells[s].resize(kv_size);
  68. }
  69. // by default, all sequence ids are mapped to the 0th stream
  70. seq_to_stream.resize(LLAMA_MAX_SEQ, 0);
  71. if (n_stream > 1) {
  72. seq_to_stream.resize(n_stream, 0);
  73. for (uint32_t s = 0; s < n_stream; ++s) {
  74. seq_to_stream[s] = s;
  75. }
  76. }
  77. // [TAG_V_CACHE_VARIABLE]
  78. if (v_trans && hparams.is_n_embd_v_gqa_variable()) {
  79. LLAMA_LOG_WARN("%s: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to %d\n",
  80. __func__, hparams.n_embd_v_gqa_max());
  81. }
  82. for (uint32_t il = 0; il < n_layer_cache; il++) {
  83. if (filter && !filter(il)) {
  84. LLAMA_LOG_DEBUG("%s: layer %3d: skipped\n", __func__, il);
  85. continue;
  86. }
  87. // [TAG_V_CACHE_VARIABLE]
  88. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  89. const uint32_t n_embd_v_gqa = !v_trans ? hparams.n_embd_v_gqa(il) : hparams.n_embd_v_gqa_max();
  90. const char * dev_name = "CPU";
  91. ggml_backend_buffer_type_t buft = ggml_backend_cpu_buffer_type();
  92. if (offload) {
  93. auto * dev = model.dev_layer(il);
  94. buft = ggml_backend_dev_buffer_type(dev);
  95. dev_name = ggml_backend_dev_name(dev);
  96. }
  97. LLAMA_LOG_DEBUG("%s: layer %3d: dev = %s\n", __func__, il, dev_name);
  98. ggml_context * ctx = ctx_for_buft(buft);
  99. if (!ctx) {
  100. throw std::runtime_error("failed to create ggml context for kv cache");
  101. }
  102. ggml_tensor * k;
  103. ggml_tensor * v;
  104. k = ggml_new_tensor_3d(ctx, type_k, n_embd_k_gqa, kv_size, n_stream);
  105. v = ggml_new_tensor_3d(ctx, type_v, n_embd_v_gqa, kv_size, n_stream);
  106. ggml_format_name(k, "cache_k_l%d", il);
  107. ggml_format_name(v, "cache_v_l%d", il);
  108. std::vector<ggml_tensor *> k_stream;
  109. std::vector<ggml_tensor *> v_stream;
  110. for (uint32_t s = 0; s < n_stream; ++s) {
  111. k_stream.push_back(ggml_view_2d(ctx, k, n_embd_k_gqa, kv_size, k->nb[1], s*k->nb[2]));
  112. v_stream.push_back(ggml_view_2d(ctx, v, n_embd_v_gqa, kv_size, v->nb[1], s*v->nb[2]));
  113. }
  114. map_layer_ids[il] = layers.size();
  115. layers.push_back({ il, k, v, k_stream, v_stream, });
  116. }
  117. // TODO: this is temporary until we support passing reuse layer filters [KV_REUSE]
  118. if (model.arch == LLM_ARCH_GEMMA3N) {
  119. LLAMA_LOG_DEBUG("%s: GEMMA3N: reuse layers [%d, %d]\n", __func__, n_layer_cache, hparams.n_layer - 1);
  120. for (uint32_t il = n_layer_cache; il < hparams.n_layer; il++) {
  121. if (filter && !filter(il)) {
  122. LLAMA_LOG_DEBUG("%s: layer %3d: skipped\n", __func__, il);
  123. continue;
  124. }
  125. const bool is_swa = hparams.is_swa(il);
  126. const uint32_t il_reuse = n_layer_cache - (is_swa ? 2 : 1);
  127. GGML_ASSERT(map_layer_ids.find(il_reuse) != map_layer_ids.end());
  128. map_layer_ids[il] = map_layer_ids[il_reuse];
  129. LLAMA_LOG_DEBUG("%s: layer %3d: reuse layer %d, isw = %d\n", __func__, il, il_reuse, is_swa);
  130. }
  131. }
  132. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  133. for (auto it : ctx_map) {
  134. auto * buft = it.first;
  135. auto * ctx = it.second;
  136. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  137. if (!buf) {
  138. throw std::runtime_error("failed to allocate buffer for kv cache");
  139. }
  140. LLAMA_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);
  141. ggml_backend_buffer_clear(buf, 0);
  142. bufs.emplace_back(buf);
  143. }
  144. {
  145. const size_t memory_size_k = size_k_bytes();
  146. const size_t memory_size_v = size_v_bytes();
  147. LLAMA_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__,
  148. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f), kv_size, (int) layers.size(), n_seq_max, n_stream,
  149. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  150. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  151. }
  152. const char * LLAMA_KV_CACHE_DEBUG = getenv("LLAMA_KV_CACHE_DEBUG");
  153. debug = LLAMA_KV_CACHE_DEBUG ? atoi(LLAMA_KV_CACHE_DEBUG) : 0;
  154. const char * LLAMA_SET_ROWS = getenv("LLAMA_SET_ROWS");
  155. supports_set_rows = LLAMA_SET_ROWS ? atoi(LLAMA_SET_ROWS) != 0 : supports_set_rows;
  156. if (!supports_set_rows) {
  157. // ref: https://github.com/ggml-org/llama.cpp/pull/14363
  158. GGML_ASSERT(unified && "cannot use non-unified KV cache without ggml_set_rows() support");
  159. }
  160. if (!supports_set_rows) {
  161. LLAMA_LOG_WARN("%s: LLAMA_SET_ROWS=0, using old ggml_cpy() method for backwards compatibility\n", __func__);
  162. }
  163. }
  164. void llama_kv_cache_unified::clear(bool data) {
  165. for (uint32_t s = 0; s < n_stream; ++s) {
  166. v_cells[s].reset();
  167. v_heads[s] = 0;
  168. }
  169. if (data) {
  170. for (auto & buf : bufs) {
  171. ggml_backend_buffer_clear(buf.get(), 0);
  172. }
  173. }
  174. }
  175. bool llama_kv_cache_unified::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  176. GGML_ASSERT(seq_id == -1 || (seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()));
  177. if (p0 < 0) {
  178. p0 = 0;
  179. }
  180. if (p1 < 0) {
  181. p1 = std::numeric_limits<llama_pos>::max();
  182. }
  183. if (seq_id >= 0) {
  184. auto & cells = v_cells[seq_to_stream[seq_id]];
  185. auto & head = v_heads[seq_to_stream[seq_id]];
  186. uint32_t new_head = cells.size();
  187. for (uint32_t i = 0; i < cells.size(); ++i) {
  188. if (!cells.pos_in(i, p0, p1)) {
  189. continue;
  190. }
  191. if (cells.seq_has(i, seq_id) && cells.seq_rm(i, seq_id)) {
  192. if (new_head == cells.size()) {
  193. new_head = i;
  194. }
  195. }
  196. }
  197. // If we freed up a slot, set head to it so searching can start there.
  198. if (new_head != cells.size() && new_head < head) {
  199. head = new_head;
  200. }
  201. } else {
  202. // match any sequence
  203. for (uint32_t s = 0; s < n_stream; ++s) {
  204. auto & cells = v_cells[s];
  205. auto & head = v_heads[s];
  206. uint32_t new_head = cells.size();
  207. for (uint32_t i = 0; i < cells.size(); ++i) {
  208. if (!cells.pos_in(i, p0, p1)) {
  209. continue;
  210. }
  211. cells.rm(i);
  212. if (new_head == cells.size()) {
  213. new_head = i;
  214. }
  215. }
  216. // If we freed up a slot, set head to it so searching can start there.
  217. if (new_head != cells.size() && new_head < head) {
  218. head = new_head;
  219. }
  220. }
  221. }
  222. return true;
  223. }
  224. void llama_kv_cache_unified::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
  225. GGML_ASSERT(seq_id_src >= 0 && (size_t) seq_id_src < seq_to_stream.size());
  226. GGML_ASSERT(seq_id_dst >= 0 && (size_t) seq_id_dst < seq_to_stream.size());
  227. const auto s0 = seq_to_stream[seq_id_src];
  228. const auto s1 = seq_to_stream[seq_id_dst];
  229. if (s0 == s1) {
  230. // since both sequences are in the same stream, no data copy is necessary
  231. // we just have to update the cells meta data
  232. auto & cells = v_cells[s0];
  233. if (seq_id_src == seq_id_dst) {
  234. return;
  235. }
  236. if (p0 < 0) {
  237. p0 = 0;
  238. }
  239. if (p1 < 0) {
  240. p1 = std::numeric_limits<llama_pos>::max();
  241. }
  242. for (uint32_t i = 0; i < cells.size(); ++i) {
  243. if (!cells.pos_in(i, p0, p1)) {
  244. continue;
  245. }
  246. if (cells.seq_has(i, seq_id_src)) {
  247. cells.seq_add(i, seq_id_dst);
  248. }
  249. }
  250. return;
  251. }
  252. // cross-stream sequence copies require to copy the actual buffer data
  253. bool is_full = true;
  254. if (p0 > 0 && p0 + 1 < (int) get_size()) {
  255. is_full = false;
  256. }
  257. if (p1 > 0 && p1 + 1 < (int) get_size()) {
  258. is_full = false;
  259. }
  260. GGML_ASSERT(is_full && "seq_cp() is only supported for full KV buffers");
  261. // enqueue the copy operation - the buffer copy will be performed during the next update
  262. sc_info.ssrc.push_back(s0);
  263. sc_info.sdst.push_back(s1);
  264. v_cells[s1].reset();
  265. for (uint32_t i = 0; i < v_cells[s0].size(); ++i) {
  266. if (v_cells[s0].seq_has(i, seq_id_src)) {
  267. llama_pos pos = v_cells[s0].pos_get(i);
  268. llama_pos shift = v_cells[s0].get_shift(i);
  269. if (shift != 0) {
  270. pos -= shift;
  271. assert(pos >= 0);
  272. }
  273. v_cells[s1].pos_set(i, pos);
  274. v_cells[s1].seq_add(i, seq_id_dst);
  275. if (shift != 0) {
  276. v_cells[s1].pos_add(i, shift);
  277. }
  278. }
  279. }
  280. v_heads[s1] = v_heads[s0];
  281. //for (uint32_t s = 0; s < n_stream; ++s) {
  282. // 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));
  283. //}
  284. }
  285. void llama_kv_cache_unified::seq_keep(llama_seq_id seq_id) {
  286. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  287. auto & cells = v_cells[seq_to_stream[seq_id]];
  288. auto & head = v_heads[seq_to_stream[seq_id]];
  289. uint32_t new_head = cells.size();
  290. for (uint32_t i = 0; i < cells.size(); ++i) {
  291. if (cells.seq_keep(i, seq_id)) {
  292. if (new_head == cells.size()) {
  293. new_head = i;
  294. }
  295. }
  296. }
  297. // If we freed up a slot, set head to it so searching can start there.
  298. if (new_head != cells.size() && new_head < head) {
  299. head = new_head;
  300. }
  301. }
  302. void llama_kv_cache_unified::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) {
  303. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  304. auto & cells = v_cells[seq_to_stream[seq_id]];
  305. auto & head = v_heads[seq_to_stream[seq_id]];
  306. if (shift == 0) {
  307. return;
  308. }
  309. uint32_t new_head = cells.size();
  310. if (p0 < 0) {
  311. p0 = 0;
  312. }
  313. if (p1 < 0) {
  314. p1 = std::numeric_limits<llama_pos>::max();
  315. }
  316. // If there is no range then return early to avoid looping over all cells.
  317. if (p0 == p1) {
  318. return;
  319. }
  320. for (uint32_t i = 0; i < cells.size(); ++i) {
  321. if (!cells.pos_in(i, p0, p1)) {
  322. continue;
  323. }
  324. if (cells.seq_has(i, seq_id)) {
  325. if (cells.pos_add(i, shift)) {
  326. if (new_head == cells.size()) {
  327. new_head = i;
  328. }
  329. }
  330. }
  331. }
  332. // If we freed up a slot, set head to it so searching can start there.
  333. // Otherwise we just start the next search from the beginning.
  334. head = new_head != cells.size() ? new_head : 0;
  335. }
  336. void llama_kv_cache_unified::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  337. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  338. auto & cells = v_cells[seq_to_stream[seq_id]];
  339. if (d == 1) {
  340. return;
  341. }
  342. if (p0 < 0) {
  343. p0 = 0;
  344. }
  345. if (p1 < 0) {
  346. p1 = std::numeric_limits<llama_pos>::max();
  347. }
  348. // If there is no range then return early to avoid looping over the cache.
  349. if (p0 == p1) {
  350. return;
  351. }
  352. for (uint32_t i = 0; i < cells.size(); ++i) {
  353. if (!cells.pos_in(i, p0, p1)) {
  354. continue;
  355. }
  356. if (cells.seq_has(i, seq_id)) {
  357. cells.pos_div(i, d);
  358. }
  359. }
  360. }
  361. llama_pos llama_kv_cache_unified::seq_pos_min(llama_seq_id seq_id) const {
  362. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  363. const auto & cells = v_cells[seq_to_stream[seq_id]];
  364. return cells.seq_pos_min(seq_id);
  365. }
  366. llama_pos llama_kv_cache_unified::seq_pos_max(llama_seq_id seq_id) const {
  367. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  368. const auto & cells = v_cells[seq_to_stream[seq_id]];
  369. return cells.seq_pos_max(seq_id);
  370. }
  371. llama_memory_context_ptr llama_kv_cache_unified::init_batch(
  372. llama_batch_allocr & balloc,
  373. uint32_t n_ubatch,
  374. bool embd_all) {
  375. GGML_UNUSED(embd_all);
  376. do {
  377. balloc.split_reset();
  378. std::vector<llama_ubatch> ubatches;
  379. while (true) {
  380. auto ubatch = n_stream == 1 ? balloc.split_simple(n_ubatch) : balloc.split_equal(n_ubatch, true);
  381. if (ubatch.n_tokens == 0) {
  382. break;
  383. }
  384. ubatches.push_back(std::move(ubatch)); // NOLINT
  385. }
  386. if (balloc.get_n_used() < balloc.get_n_tokens()) {
  387. // failed to find a suitable split
  388. break;
  389. }
  390. auto sinfos = prepare(ubatches);
  391. if (sinfos.empty()) {
  392. break;
  393. }
  394. return std::make_unique<llama_kv_cache_unified_context>(
  395. this, std::move(sinfos), std::move(ubatches));
  396. } while (false);
  397. return std::make_unique<llama_kv_cache_unified_context>(LLAMA_MEMORY_STATUS_FAILED_PREPARE);
  398. }
  399. llama_memory_context_ptr llama_kv_cache_unified::init_full() {
  400. return std::make_unique<llama_kv_cache_unified_context>(this);
  401. }
  402. llama_memory_context_ptr llama_kv_cache_unified::init_update(llama_context * lctx, bool optimize) {
  403. bool do_shift = get_has_shift();
  404. defrag_info dinfo;
  405. // see if we need to defrag
  406. if (n_stream == 1) {
  407. // note : for now do not consider defrag for n_stream > 1
  408. const auto & cells = v_cells[seq_to_stream[0]];
  409. bool do_defrag = optimize;
  410. const auto thold = lctx->get_cparams().defrag_thold;
  411. if (!do_defrag && thold > 0.0f) {
  412. const auto n_kv = cells.used_max_p1();
  413. // - do not defrag small contexts (i.e. < 2048 tokens)
  414. // - count the padding towards the number of used tokens
  415. const float fragmentation = n_kv >= 2048 ? std::max(0.0f, 1.0f - (float(cells.get_used() + n_pad)/n_kv)) : 0.0f;
  416. if (fragmentation > thold) {
  417. LLAMA_LOG_DEBUG("%s: fragmentation: %.2f - requesting defrag\n", __func__, fragmentation);
  418. do_defrag = true;
  419. }
  420. }
  421. if (do_defrag) {
  422. dinfo = defrag_prepare(lctx->graph_max_nodes());
  423. }
  424. }
  425. return std::make_unique<llama_kv_cache_unified_context>(this, lctx, do_shift, std::move(dinfo), std::move(sc_info));
  426. }
  427. llama_kv_cache_unified::slot_info_vec_t llama_kv_cache_unified::prepare(const std::vector<llama_ubatch> & ubatches) {
  428. llama_kv_cache_unified::slot_info_vec_t res;
  429. struct state_t {
  430. slot_info sinfo; // slot info for the ubatch
  431. std::vector<uint32_t> v_heads_old; // old positions of the heads, before placing the ubatch
  432. std::vector<llama_kv_cells_unified> v_cells; // copy of the old cells, before placing the ubatch
  433. };
  434. // remember the old state of the cells so we can restore it in the end
  435. std::vector<state_t> states;
  436. bool success = true;
  437. for (const auto & ubatch : ubatches) {
  438. // non-continuous slots require support for ggml_set_rows()
  439. const bool cont = supports_set_rows ? false : true;
  440. // only find a suitable slot for the ubatch. don't modify the cells yet
  441. const auto sinfo_new = find_slot(ubatch, cont);
  442. if (sinfo_new.empty()) {
  443. success = false;
  444. break;
  445. }
  446. // remeber the position that we found
  447. res.push_back(sinfo_new);
  448. // store the old state of the cells in the recovery stack
  449. {
  450. state_t state = { sinfo_new, v_heads, {} };
  451. for (uint32_t s = 0; s < sinfo_new.n_stream(); ++s) {
  452. auto & cells = v_cells[sinfo_new.strm[s]];
  453. state.v_cells.push_back(cells.cp(sinfo_new.idxs[s]));
  454. }
  455. states.push_back(std::move(state));
  456. }
  457. // now emplace the ubatch
  458. apply_ubatch(sinfo_new, ubatch);
  459. }
  460. GGML_ASSERT(!states.empty() || !success);
  461. // iterate backwards and restore the cells to their original state
  462. for (auto it = states.rbegin(); it != states.rend(); ++it) {
  463. const auto & sinfo = it->sinfo;
  464. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  465. auto & cells = v_cells[sinfo.strm[s]];
  466. auto & head = v_heads[sinfo.strm[s]];
  467. cells.set(sinfo.idxs[s], it->v_cells[s]);
  468. head = it->v_heads_old[s];
  469. }
  470. }
  471. if (!success) {
  472. return {};
  473. }
  474. return res;
  475. }
  476. bool llama_kv_cache_unified::update(llama_context * lctx, bool do_shift, const defrag_info & dinfo, const stream_copy_info & sc_info) {
  477. bool updated = false;
  478. auto * sched = lctx->get_sched();
  479. if (!sc_info.empty()) {
  480. assert(n_stream > 1 && "stream copy should never happen with a single stream");
  481. llama_synchronize(lctx);
  482. const size_t n_copy = sc_info.ssrc.size();
  483. for (size_t i = 0; i < n_copy; ++i) {
  484. const auto ssrc = sc_info.ssrc[i];
  485. const auto sdst = sc_info.sdst[i];
  486. assert(ssrc < n_stream);
  487. assert(sdst < n_stream);
  488. LLAMA_LOG_DEBUG("%s: copying KV buffer: stream %d to stream %d\n", __func__, ssrc, sdst);
  489. assert(ssrc != sdst);
  490. for (uint32_t il = 0; il < layers.size(); ++il) {
  491. const auto & layer = layers[il];
  492. ggml_backend_tensor_copy(layer.k_stream[ssrc], layer.k_stream[sdst]);
  493. ggml_backend_tensor_copy(layer.v_stream[ssrc], layer.v_stream[sdst]);
  494. }
  495. }
  496. }
  497. if (do_shift) {
  498. if (!get_can_shift()) {
  499. GGML_ABORT("The current KV cache / model configuration does not support K-shift");
  500. }
  501. LLAMA_LOG_DEBUG("%s: applying K-shift\n", __func__);
  502. // apply K-shift if needed
  503. if (hparams.rope_type != LLAMA_ROPE_TYPE_NONE) {
  504. ggml_backend_sched_reset(sched);
  505. auto * res = lctx->get_gf_res_reserve();
  506. res->reset();
  507. auto * gf = build_graph_shift(res, lctx);
  508. if (!ggml_backend_sched_alloc_graph(sched, gf)) {
  509. LLAMA_LOG_ERROR("%s: failed to allocate compute graph for K-shift\n", __func__);
  510. return updated;
  511. }
  512. res->set_inputs(nullptr);
  513. if (lctx->graph_compute(gf, false) != GGML_STATUS_SUCCESS) {
  514. LLAMA_LOG_ERROR("%s: failed to compute K-shift\n", __func__);
  515. return updated;
  516. }
  517. updated = true;
  518. }
  519. for (uint32_t s = 0; s < n_stream; ++s) {
  520. auto & cells = v_cells[s];
  521. cells.reset_shift();
  522. }
  523. }
  524. if (!dinfo.empty()) {
  525. LLAMA_LOG_DEBUG("%s: defragmenting KV cache\n", __func__);
  526. // note: for now do not consider defrag for n_stream > 1
  527. auto & cells = v_cells[seq_to_stream[0]];
  528. auto & head = v_heads[seq_to_stream[0]];
  529. // apply moves:
  530. {
  531. const auto n_kv = dinfo.ids.size();
  532. for (uint32_t i = 0; i < n_kv; ++i) {
  533. assert(dinfo.ids[i] <= n_kv);
  534. if (dinfo.ids[i] == n_kv || dinfo.ids[i] == i) {
  535. continue;
  536. }
  537. cells.mv(i, dinfo.ids[i]);
  538. }
  539. // reset the head so we can find the first free slot during the next ubatch
  540. head = 0;
  541. }
  542. ggml_backend_sched_reset(sched);
  543. auto * res = lctx->get_gf_res_reserve();
  544. res->reset();
  545. auto * gf = build_graph_defrag(res, lctx, dinfo);
  546. if (!ggml_backend_sched_alloc_graph(sched, gf)) {
  547. LLAMA_LOG_ERROR("%s: failed to allocate compute graph for defrag\n", __func__);
  548. return updated;
  549. }
  550. res->set_inputs(nullptr);
  551. if (lctx->graph_compute(gf, false) != GGML_STATUS_SUCCESS) {
  552. LLAMA_LOG_ERROR("%s: failed to compute defrag\n", __func__);
  553. return updated;
  554. }
  555. updated = true;
  556. }
  557. return updated;
  558. }
  559. llama_kv_cache_unified::slot_info llama_kv_cache_unified::find_slot(const llama_ubatch & ubatch, bool cont) const {
  560. if (debug > 0) {
  561. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  562. const auto seq_id = ubatch.seq_id_unq[s];
  563. const auto stream_id = seq_to_stream[seq_id];
  564. const auto & cells = v_cells[stream_id];
  565. const uint32_t head_cur = v_heads[stream_id];
  566. LLAMA_LOG_DEBUG("%s: stream[%d], n = %5d, used = %5d, head = %5d, size = %5d, n_swa = %5d\n",
  567. __func__, stream_id, cells.used_max_p1(), cells.get_used(), head_cur, get_size(), n_swa);
  568. if ((debug == 2 && n_swa > 0) || debug > 2) {
  569. std::string ss;
  570. for (uint32_t i = 0; i < cells.size(); ++i) {
  571. if (cells.is_empty(i)) {
  572. ss += '.';
  573. } else {
  574. assert(cells.seq_count(i) >= 1);
  575. if (cells.seq_count(i) == 1) {
  576. ss += std::to_string(cells.seq_get(i));
  577. } else {
  578. ss += 'M';
  579. }
  580. }
  581. if (i%256 == 255) {
  582. ss += " *";
  583. ss += '\n';
  584. }
  585. }
  586. LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
  587. }
  588. if ((debug == 2 && n_swa > 0) || debug > 2) {
  589. std::string ss;
  590. for (uint32_t i = 0; i < cells.size(); ++i) {
  591. std::string cur;
  592. if (cells.is_empty(i)) {
  593. cur = '.';
  594. } else {
  595. cur = std::to_string(cells.pos_get(i));
  596. }
  597. const int n = cur.size();
  598. for (int j = 0; j < 5 - n; ++j) {
  599. cur += ' ';
  600. }
  601. ss += cur;
  602. if (i%256 == 255) {
  603. ss += " *";
  604. }
  605. if (i%64 == 63) {
  606. ss += '\n';
  607. }
  608. }
  609. LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
  610. }
  611. for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
  612. if (cells.seq_pos_min(s) < 0) {
  613. continue;
  614. }
  615. LLAMA_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));
  616. }
  617. }
  618. }
  619. uint32_t n_tokens = ubatch.n_tokens;
  620. uint32_t n_seqs = 1;
  621. if (n_stream > 1) {
  622. GGML_ASSERT(n_tokens % ubatch.n_seqs_unq == 0);
  623. n_seqs = ubatch.n_seqs_unq;
  624. n_tokens = n_tokens / n_seqs;
  625. }
  626. slot_info res = {
  627. /*.s0 =*/ LLAMA_MAX_SEQ,
  628. /*.s1 =*/ 0,
  629. /*.strm =*/ { },
  630. /*.idxs =*/ { },
  631. };
  632. res.resize(n_seqs);
  633. for (uint32_t s = 0; s < n_seqs; ++s) {
  634. const auto seq_id = ubatch.seq_id_unq[s];
  635. if (n_stream > 1) {
  636. GGML_ASSERT(ubatch.n_seq_id[s*n_tokens] == 1);
  637. GGML_ASSERT(ubatch.seq_id [s*n_tokens][0] == seq_id);
  638. }
  639. res.s0 = std::min<llama_seq_id>(res.s0, seq_to_stream[seq_id]);
  640. res.s1 = std::max<llama_seq_id>(res.s1, seq_to_stream[seq_id]);
  641. res.strm[s] = seq_to_stream[seq_id];
  642. res.idxs[s].reserve(n_tokens);
  643. const auto & cells = v_cells[seq_to_stream[seq_id]];
  644. uint32_t head_cur = v_heads[seq_to_stream[seq_id]];
  645. // if we have enough unused cells before the current head ->
  646. // better to start searching from the beginning of the cache, hoping to fill it
  647. if (head_cur > cells.get_used() + 2*n_tokens) {
  648. head_cur = 0;
  649. }
  650. if (n_tokens > cells.size()) {
  651. LLAMA_LOG_ERROR("%s: n_tokens = %d > size = %u\n", __func__, n_tokens, cells.size());
  652. return { };
  653. }
  654. uint32_t n_tested = 0;
  655. // for continuous slots, we test that all tokens in the ubatch fit, starting from the current head
  656. // for non-continuous slots, we test the tokens one by one
  657. const uint32_t n_test = cont ? n_tokens : 1;
  658. while (true) {
  659. if (head_cur + n_test > cells.size()) {
  660. n_tested += cells.size() - head_cur;
  661. head_cur = 0;
  662. continue;
  663. }
  664. for (uint32_t i = 0; i < n_test; i++) {
  665. const auto idx = head_cur;
  666. head_cur++;
  667. n_tested++;
  668. //const llama_pos pos = ubatch.pos[i];
  669. //const llama_seq_id seq_id = ubatch.seq_id[i][0];
  670. // can we use this cell? either:
  671. // - the cell is empty
  672. // - the cell is occupied only by one sequence:
  673. // - (disabled) mask causally, if the sequence is the same as the one we are inserting
  674. // - mask SWA, using current max pos for that sequence in the cache
  675. // always insert in the cell with minimum pos
  676. bool can_use = cells.is_empty(idx);
  677. if (!can_use && cells.seq_count(idx) == 1) {
  678. const llama_pos pos_cell = cells.pos_get(idx);
  679. // (disabled) causal mask
  680. // note: it's better to purge any "future" tokens beforehand
  681. //if (cells.seq_has(idx, seq_id)) {
  682. // can_use = pos_cell >= pos;
  683. //}
  684. if (!can_use) {
  685. const llama_seq_id seq_id_cell = cells.seq_get(idx);
  686. // SWA mask
  687. if (is_masked_swa(pos_cell, cells.seq_pos_max(seq_id_cell) + 1)) {
  688. can_use = true;
  689. }
  690. }
  691. }
  692. if (can_use) {
  693. res.idxs[s].push_back(idx);
  694. } else {
  695. if (cont) {
  696. break;
  697. }
  698. }
  699. }
  700. if (res.idxs[s].size() == n_tokens) {
  701. break;
  702. }
  703. if (cont) {
  704. res.idxs[s].clear();
  705. }
  706. if (n_tested >= cells.size()) {
  707. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  708. return { };
  709. }
  710. }
  711. // we didn't find a suitable slot - return empty result
  712. if (res.idxs[s].size() < n_tokens) {
  713. return { };
  714. }
  715. }
  716. assert(res.s1 >= res.s0);
  717. return res;
  718. }
  719. void llama_kv_cache_unified::apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch) {
  720. // keep track of the max sequence position that we would overwrite with this ubatch
  721. // for non-SWA cache, this would be always empty
  722. llama_seq_id seq_pos_max_rm[LLAMA_MAX_SEQ];
  723. for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) {
  724. seq_pos_max_rm[s] = -1;
  725. }
  726. assert(ubatch.n_tokens == sinfo.n_stream()*sinfo.size());
  727. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  728. for (uint32_t ii = 0; ii < sinfo.size(); ++ii) {
  729. const uint32_t i = s*sinfo.size() + ii;
  730. auto & cells = v_cells[sinfo.strm[s]];
  731. const auto idx = sinfo.idxs[s][ii];
  732. if (!cells.is_empty(idx)) {
  733. assert(cells.seq_count(idx) == 1);
  734. const llama_seq_id seq_id = cells.seq_get(idx);
  735. const llama_pos pos = cells.pos_get(idx);
  736. seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos);
  737. cells.rm(idx);
  738. }
  739. cells.pos_set(idx, ubatch.pos[i]);
  740. for (int32_t s = 0; s < ubatch.n_seq_id[i]; s++) {
  741. cells.seq_add(idx, ubatch.seq_id[i][s]);
  742. }
  743. }
  744. }
  745. // note: we want to preserve the invariant that all positions between [pos_min, pos_max] for each sequence
  746. // will be present in the cache. so we have to purge any position which is less than those we would overwrite
  747. // ref: https://github.com/ggml-org/llama.cpp/pull/13746#issuecomment-2916057092
  748. for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) {
  749. if (seq_pos_max_rm[s] == -1) {
  750. continue;
  751. }
  752. GGML_ASSERT(s < seq_to_stream.size());
  753. auto & cells = v_cells[seq_to_stream[s]];
  754. if (cells.seq_pos_min(s) <= seq_pos_max_rm[s]) {
  755. LLAMA_LOG_DEBUG("%s: purging positions [%d, %d] of sequence %d from KV cache\n",
  756. __func__, cells.seq_pos_min(s), seq_pos_max_rm[s], s);
  757. seq_rm(s, cells.seq_pos_min(s), seq_pos_max_rm[s] + 1);
  758. }
  759. }
  760. // move the head at the end of the slot
  761. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  762. auto & head = v_heads[sinfo.strm[s]];
  763. head = sinfo.idxs[s].back() + 1;
  764. }
  765. }
  766. bool llama_kv_cache_unified::get_can_shift() const {
  767. return true;
  768. }
  769. uint32_t llama_kv_cache_unified::get_size() const {
  770. const auto & cells = v_cells[seq_to_stream[0]];
  771. return cells.size();
  772. }
  773. uint32_t llama_kv_cache_unified::get_n_stream() const {
  774. return n_stream;
  775. }
  776. bool llama_kv_cache_unified::get_has_shift() const {
  777. bool result = false;
  778. for (uint32_t s = 0; s < n_stream; ++s) {
  779. result |= v_cells[s].get_has_shift();
  780. }
  781. return result;
  782. }
  783. uint32_t llama_kv_cache_unified::get_n_kv() const {
  784. uint32_t result = 0;
  785. for (uint32_t s = 0; s < n_stream; ++s) {
  786. const auto & cells = v_cells[s];
  787. result = std::max(std::min(cells.size(), std::max(n_pad, GGML_PAD(cells.used_max_p1(), n_pad))), result);
  788. }
  789. return result;
  790. }
  791. bool llama_kv_cache_unified::get_supports_set_rows() const {
  792. return supports_set_rows;
  793. }
  794. ggml_tensor * llama_kv_cache_unified::get_k(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const {
  795. const int32_t ikv = map_layer_ids.at(il);
  796. auto * k = layers[ikv].k;
  797. const uint64_t kv_size = get_size();
  798. const uint64_t n_embd_k_gqa = k->ne[0];
  799. assert(n_embd_k_gqa == hparams.n_embd_k_gqa(il));
  800. const uint32_t ns = sinfo.s1 - sinfo.s0 + 1;
  801. return ggml_view_4d(ctx, k,
  802. hparams.n_embd_head_k, hparams.n_head_kv(il), n_kv, ns,
  803. ggml_row_size(k->type, hparams.n_embd_head_k),
  804. ggml_row_size(k->type, n_embd_k_gqa),
  805. ggml_row_size(k->type, n_embd_k_gqa*kv_size),
  806. ggml_row_size(k->type, n_embd_k_gqa*kv_size)*sinfo.s0);
  807. }
  808. ggml_tensor * llama_kv_cache_unified::get_v(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const {
  809. const int32_t ikv = map_layer_ids.at(il);
  810. auto * v = layers[ikv].v;
  811. const uint64_t kv_size = get_size();
  812. const uint64_t n_embd_v_gqa = v->ne[0];
  813. // [TAG_V_CACHE_VARIABLE]
  814. assert(n_embd_v_gqa >= hparams.n_embd_v_gqa(il));
  815. const uint32_t ns = sinfo.s1 - sinfo.s0 + 1;
  816. if (!v_trans) {
  817. // note: v->nb[1] <= v->nb[2]
  818. return ggml_view_4d(ctx, v,
  819. hparams.n_embd_head_v, hparams.n_head_kv(il), n_kv, ns,
  820. ggml_row_size(v->type, hparams.n_embd_head_v), // v->nb[1]
  821. ggml_row_size(v->type, n_embd_v_gqa), // v->nb[2]
  822. ggml_row_size(v->type, n_embd_v_gqa*kv_size), // v->nb[3]
  823. ggml_row_size(v->type, n_embd_v_gqa*kv_size)*sinfo.s0);
  824. }
  825. // note: v->nb[1] > v->nb[2]
  826. return ggml_view_4d(ctx, v,
  827. n_kv, hparams.n_head_kv(il), hparams.n_embd_head_v, ns,
  828. ggml_row_size(v->type, kv_size*hparams.n_embd_head_v), // v->nb[1]
  829. ggml_row_size(v->type, kv_size), // v->nb[2]
  830. ggml_row_size(v->type, kv_size*n_embd_v_gqa), // v->nb[3]
  831. ggml_row_size(v->type, kv_size*n_embd_v_gqa)*sinfo.s0);
  832. }
  833. ggml_tensor * llama_kv_cache_unified::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il, const slot_info & sinfo) const {
  834. const int32_t ikv = map_layer_ids.at(il);
  835. auto * k = layers[ikv].k;
  836. const int64_t n_embd_k_gqa = k->ne[0];
  837. const int64_t n_tokens = k_cur->ne[2];
  838. k_cur = ggml_reshape_2d(ctx, k_cur, k->ne[0], n_tokens);
  839. if (k_idxs && supports_set_rows) {
  840. if (k->ne[2] > 1) {
  841. k = ggml_reshape_2d(ctx, k, k->ne[0], k->ne[1]*k->ne[2]);
  842. }
  843. return ggml_set_rows(ctx, k, k_cur, k_idxs);
  844. }
  845. // TODO: fallback to old ggml_cpy() method for backwards compatibility
  846. // will be removed when ggml_set_rows() is adopted by all backends
  847. GGML_ASSERT(n_stream == 1 && "n_stream > 1 not supported without LLAMA_SET_ROWS");
  848. ggml_tensor * k_view = ggml_view_1d(ctx, k,
  849. n_tokens*n_embd_k_gqa,
  850. ggml_row_size(k->type, n_embd_k_gqa)*sinfo.head());
  851. return ggml_cpy(ctx, k_cur, k_view);
  852. }
  853. ggml_tensor * llama_kv_cache_unified::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il, const slot_info & sinfo) const {
  854. const int32_t ikv = map_layer_ids.at(il);
  855. auto * v = layers[ikv].v;
  856. const int64_t n_embd_v_gqa = v_cur->ne[0]*v_cur->ne[1];
  857. const int64_t n_tokens = v_cur->ne[2];
  858. v_cur = ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens);
  859. if (v_idxs && supports_set_rows) {
  860. if (!v_trans) {
  861. if (v->ne[2] > 1) {
  862. v = ggml_reshape_2d(ctx, v, v->ne[0], v->ne[1]*v->ne[2]);
  863. }
  864. return ggml_set_rows(ctx, v, v_cur, v_idxs);
  865. }
  866. // [TAG_V_CACHE_VARIABLE]
  867. if (n_embd_v_gqa < v->ne[0]) {
  868. v_cur = ggml_pad(ctx, v_cur, v->ne[0] - n_embd_v_gqa, 0, 0, 0);
  869. }
  870. // the row becomes a single element
  871. ggml_tensor * v_view = ggml_reshape_2d(ctx, v, 1, v->ne[0]*v->ne[1]*v->ne[2]);
  872. v_cur = ggml_reshape_2d(ctx, v_cur, 1, v_cur->ne[0]*v_cur->ne[1]);
  873. return ggml_set_rows(ctx, v_view, v_cur, v_idxs);
  874. }
  875. // TODO: fallback to old ggml_cpy() method for backwards compatibility
  876. // will be removed when ggml_set_rows() is adopted by all backends
  877. GGML_ASSERT(n_stream == 1 && "n_stream > 1 not supported without LLAMA_SET_ROWS");
  878. ggml_tensor * v_view = nullptr;
  879. if (!v_trans) {
  880. v_view = ggml_view_1d(ctx, v,
  881. n_tokens*n_embd_v_gqa,
  882. ggml_row_size(v->type, n_embd_v_gqa)*sinfo.head());
  883. } else {
  884. v_cur = ggml_transpose(ctx, v_cur);
  885. v_view = ggml_view_2d(ctx, v, n_tokens, n_embd_v_gqa,
  886. (v->ne[1] )*ggml_element_size(v),
  887. (sinfo.head())*ggml_element_size(v));
  888. }
  889. return ggml_cpy(ctx, v_cur, v_view);
  890. }
  891. ggml_tensor * llama_kv_cache_unified::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  892. const uint32_t n_tokens = ubatch.n_tokens;
  893. ggml_tensor * k_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens);
  894. ggml_set_input(k_idxs);
  895. return k_idxs;
  896. }
  897. ggml_tensor * llama_kv_cache_unified::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  898. const uint32_t n_tokens = ubatch.n_tokens;
  899. ggml_tensor * v_idxs;
  900. if (!v_trans) {
  901. v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens);
  902. } else {
  903. v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens*hparams.n_embd_v_gqa_max());
  904. }
  905. ggml_set_input(v_idxs);
  906. return v_idxs;
  907. }
  908. void llama_kv_cache_unified::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const {
  909. if (!supports_set_rows) {
  910. return;
  911. }
  912. const uint32_t n_tokens = ubatch->n_tokens;
  913. GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream());
  914. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  915. int64_t * data = (int64_t *) dst->data;
  916. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  917. const int64_t offs = sinfo.strm[s]*get_size();
  918. for (uint32_t i = 0; i < sinfo.size(); ++i) {
  919. data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i];
  920. }
  921. }
  922. }
  923. void llama_kv_cache_unified::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const {
  924. if (!supports_set_rows) {
  925. return;
  926. }
  927. const uint32_t n_tokens = ubatch->n_tokens;
  928. GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream());
  929. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  930. int64_t * data = (int64_t *) dst->data;
  931. if (!v_trans) {
  932. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  933. const int64_t offs = sinfo.strm[s]*get_size();
  934. for (uint32_t i = 0; i < sinfo.size(); ++i) {
  935. data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i];
  936. }
  937. }
  938. } else {
  939. // note: the V cache is transposed when not using flash attention
  940. const int64_t kv_size = get_size();
  941. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa_max();
  942. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  943. const int64_t offs = sinfo.strm[s]*kv_size*n_embd_v_gqa;
  944. for (uint32_t i = 0; i < sinfo.size(); ++i) {
  945. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  946. data[s*sinfo.size()*n_embd_v_gqa + i*n_embd_v_gqa + j] = offs + j*kv_size + sinfo.idxs[s][i];
  947. }
  948. }
  949. }
  950. }
  951. }
  952. void llama_kv_cache_unified::set_input_k_shift(ggml_tensor * dst) const {
  953. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  954. int32_t * data = (int32_t *) dst->data;
  955. for (uint32_t s = 0; s < n_stream; ++s) {
  956. const auto & cells = v_cells[s];
  957. for (uint32_t i = 0; i < cells.size(); ++i) {
  958. data[s*cells.size() + i] = cells.is_empty(i) ? 0 : cells.get_shift(i);
  959. }
  960. }
  961. }
  962. void llama_kv_cache_unified::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
  963. const uint32_t n_tokens = ubatch->n_tokens;
  964. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  965. float * data = (float *) dst->data;
  966. const int64_t n_kv = dst->ne[0];
  967. const int64_t n_stream = dst->ne[3]; // num streams in the current ubatch
  968. GGML_ASSERT(n_tokens%n_stream == 0);
  969. // n_tps == n_tokens_per_stream
  970. const int64_t n_tps = n_tokens/n_stream;
  971. const int64_t n_tps_pad = GGML_PAD(n_tps, GGML_KQ_MASK_PAD);
  972. std::fill(data, data + ggml_nelements(dst), -INFINITY);
  973. // Use only the previous KV cells of the correct sequence for each token of the ubatch.
  974. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  975. // Example with a cache of 10 tokens, 2 tokens populated in cache and 3 tokens in batch:
  976. // Causal mask:
  977. // xxx-------
  978. // xxxx------
  979. // xxxxx-----
  980. // Non-causal mask:
  981. // xxxxx-----
  982. // xxxxx-----
  983. // xxxxx-----
  984. // To visualize the mask, see https://github.com/ggml-org/llama.cpp/pull/12615
  985. // TODO: optimize this section
  986. for (uint32_t h = 0; h < 1; ++h) {
  987. for (uint32_t s = 0; s < n_stream; ++s) {
  988. for (uint32_t ii = 0; ii < n_tps; ++ii) {
  989. const uint32_t i = s*n_tps + ii;
  990. const llama_seq_id seq_id = ubatch->seq_id[i][0];
  991. const auto & cells = v_cells[seq_to_stream[seq_id]];
  992. const llama_pos p1 = ubatch->pos[i];
  993. const uint64_t idst = n_kv*(h*n_stream*n_tps_pad + s*n_tps_pad + ii);
  994. for (uint32_t j = 0; j < n_kv; ++j) {
  995. if (cells.is_empty(j)) {
  996. continue;
  997. }
  998. // mask the token if not the same sequence
  999. if (!cells.seq_has(j, seq_id)) {
  1000. continue;
  1001. }
  1002. const llama_pos p0 = cells.pos_get(j);
  1003. // mask future tokens
  1004. if (causal_attn && p0 > p1) {
  1005. continue;
  1006. }
  1007. // apply SWA if any
  1008. if (is_masked_swa(p0, p1)) {
  1009. continue;
  1010. }
  1011. data[idst + j] = hparams.use_alibi ? -std::abs(p0 - p1) : 0.0f;
  1012. }
  1013. }
  1014. }
  1015. }
  1016. }
  1017. void llama_kv_cache_unified::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1018. const int64_t n_tokens = ubatch->n_tokens;
  1019. GGML_ASSERT(n_stream == 1 && "TODO: support multiple streams");
  1020. const auto & cells = v_cells[0];
  1021. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  1022. GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing
  1023. int32_t * data = (int32_t *) dst->data;
  1024. const int32_t n_kv = dst->ne[0];
  1025. for (int h = 0; h < 1; ++h) {
  1026. for (int i = 0; i < n_tokens; ++i) {
  1027. for (int j = 0; j < n_kv; ++j) {
  1028. // the position when the cells is empty is irrelevant - it will be masked out later in the attention
  1029. const llama_pos p0 = cells.is_empty(j) ? -1 : cells.pos_get(j);
  1030. data[h*(n_kv*n_tokens) + i*n_kv + j] = llama_relative_position_bucket(p0, ubatch->pos[i], hparams.n_rel_attn_bkts, false);
  1031. }
  1032. }
  1033. }
  1034. }
  1035. size_t llama_kv_cache_unified::total_size() const {
  1036. size_t size = 0;
  1037. for (const auto & buf : bufs) {
  1038. size += ggml_backend_buffer_get_size(buf.get());
  1039. }
  1040. return size;
  1041. }
  1042. size_t llama_kv_cache_unified::size_k_bytes() const {
  1043. size_t size_k_bytes = 0;
  1044. for (const auto & layer : layers) {
  1045. size_k_bytes += ggml_nbytes(layer.k);
  1046. }
  1047. return size_k_bytes;
  1048. }
  1049. size_t llama_kv_cache_unified::size_v_bytes() const {
  1050. size_t size_v_bytes = 0;
  1051. for (const auto & layer : layers) {
  1052. size_v_bytes += ggml_nbytes(layer.v);
  1053. }
  1054. return size_v_bytes;
  1055. }
  1056. ggml_tensor * llama_kv_cache_unified::build_rope_shift(
  1057. const llama_cparams & cparams,
  1058. ggml_context * ctx,
  1059. ggml_tensor * cur,
  1060. ggml_tensor * shift,
  1061. ggml_tensor * factors,
  1062. float freq_base,
  1063. float freq_scale) const {
  1064. const auto & n_ctx_orig = cparams.n_ctx_orig_yarn;
  1065. const auto & yarn_ext_factor = cparams.yarn_ext_factor;
  1066. const auto & yarn_beta_fast = cparams.yarn_beta_fast;
  1067. const auto & yarn_beta_slow = cparams.yarn_beta_slow;
  1068. const auto & n_rot = hparams.n_rot;
  1069. const auto & rope_type = hparams.rope_type == LLAMA_ROPE_TYPE_MROPE
  1070. // @ngxson : this is a workaround
  1071. // for M-RoPE, we want to rotate the whole vector when doing KV shift
  1072. // a normal RoPE should work, we just need to use the correct ordering
  1073. // ref: https://github.com/ggml-org/llama.cpp/pull/13870
  1074. ? LLAMA_ROPE_TYPE_NEOX
  1075. : hparams.rope_type;
  1076. // See llm_build_deepseek2() for why attn_factor has to be scaled for YaRN RoPE to work correctly.
  1077. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  1078. const float yarn_attn_factor = model.arch == LLM_ARCH_DEEPSEEK2
  1079. ? 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale))
  1080. : cparams.yarn_attn_factor;
  1081. ggml_tensor * tmp;
  1082. if (ggml_is_quantized(cur->type)) {
  1083. // dequantize to f32 -> RoPE -> quantize back
  1084. tmp = ggml_cast(ctx, cur, GGML_TYPE_F32);
  1085. tmp = ggml_rope_ext(ctx, tmp,
  1086. shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1087. yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
  1088. tmp = ggml_cpy(ctx, tmp, cur);
  1089. } else {
  1090. // we rotate only the first n_rot dimensions
  1091. tmp = ggml_rope_ext_inplace(ctx, cur,
  1092. shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1093. yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
  1094. }
  1095. return tmp;
  1096. }
  1097. class llm_graph_input_k_shift : public llm_graph_input_i {
  1098. public:
  1099. llm_graph_input_k_shift(const llama_kv_cache_unified * kv_self) : kv_self(kv_self) {}
  1100. virtual ~llm_graph_input_k_shift() = default;
  1101. void set_input(const llama_ubatch * ubatch) override;
  1102. ggml_tensor * k_shift; // I32 [kv_size*n_stream]
  1103. const llama_kv_cache_unified * kv_self;
  1104. };
  1105. void llm_graph_input_k_shift::set_input(const llama_ubatch * ubatch) {
  1106. GGML_UNUSED(ubatch);
  1107. if (k_shift) {
  1108. kv_self->set_input_k_shift(k_shift);
  1109. }
  1110. }
  1111. ggml_cgraph * llama_kv_cache_unified::build_graph_shift(llm_graph_result * res, llama_context * lctx) const {
  1112. auto * ctx = res->get_ctx();
  1113. auto * gf = res->get_gf();
  1114. const auto & n_embd_head_k = hparams.n_embd_head_k;
  1115. //const auto & n_embd_head_v = hparams.n_embd_head_v;
  1116. auto inp = std::make_unique<llm_graph_input_k_shift>(this);
  1117. inp->k_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, (int64_t) get_size()*n_stream);
  1118. ggml_set_input(inp->k_shift);
  1119. const auto & cparams = lctx->get_cparams();
  1120. for (const auto & layer : layers) {
  1121. const uint32_t il = layer.il;
  1122. const int64_t n_head_kv = hparams.n_head_kv(il);
  1123. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1124. const float freq_base_l = model.get_rope_freq_base (cparams, il);
  1125. const float freq_scale_l = model.get_rope_freq_scale(cparams, il);
  1126. ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);
  1127. ggml_tensor * k =
  1128. ggml_view_3d(ctx, layer.k,
  1129. n_embd_head_k, n_head_kv, get_size()*n_stream,
  1130. ggml_row_size(layer.k->type, n_embd_head_k),
  1131. ggml_row_size(layer.k->type, n_embd_k_gqa),
  1132. 0);
  1133. ggml_tensor * cur = build_rope_shift(cparams, ctx, k, inp->k_shift, rope_factors, freq_base_l, freq_scale_l);
  1134. ggml_build_forward_expand(gf, cur);
  1135. }
  1136. res->add_input(std::move(inp));
  1137. return gf;
  1138. }
  1139. ggml_cgraph * llama_kv_cache_unified::build_graph_defrag(
  1140. llm_graph_result * res,
  1141. llama_context * lctx,
  1142. const defrag_info & dinfo) const {
  1143. auto * ctx = res->get_ctx();
  1144. auto * gf = res->get_gf();
  1145. GGML_ASSERT(n_stream == 1 && "n_stream > 1 does not support defrag");
  1146. const auto & cells = v_cells[0];
  1147. const auto & ids = dinfo.ids;
  1148. const auto & cparams = lctx->get_cparams();
  1149. #if 0
  1150. // CPU defrag
  1151. //
  1152. // TODO: optimizations are possible:
  1153. // - multiple threads
  1154. // - avoid copying to the host memory when already there
  1155. //
  1156. // likely not worth the effort, as we have ggml_graph based defrag
  1157. //
  1158. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1159. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1160. const uint32_t kv_size = size;
  1161. std::vector<uint8_t> buf_k;
  1162. std::vector<uint8_t> buf_v;
  1163. for (uint32_t il = 0; il < n_layer; ++il) {
  1164. const size_t k_size_row = ggml_row_size(k_l[il]->type, n_embd_k_gqa);
  1165. const size_t k_size = ggml_row_size(k_l[il]->type, n_embd_k_gqa*kv_size);
  1166. const size_t v_size_el = ggml_type_size(v_l[il]->type);
  1167. const size_t v_size = ggml_row_size (v_l[il]->type, n_embd_v_gqa*kv_size);
  1168. buf_k.resize(k_size);
  1169. buf_v.resize(v_size);
  1170. ggml_backend_tensor_get(k_l[il], buf_k.data(), 0, buf_k.size());
  1171. ggml_backend_tensor_get(v_l[il], buf_v.data(), 0, buf_v.size());
  1172. // batch move [i, i+nm) to [id, id+nm)
  1173. // note: cells can move only to a lower index
  1174. for (uint32_t i = 0; i < n_kv; ++i) {
  1175. const uint32_t id = ids[i];
  1176. if (i == id || id == n_kv) {
  1177. continue;
  1178. }
  1179. uint32_t nm = 1;
  1180. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  1181. nm++;
  1182. }
  1183. // move keys
  1184. {
  1185. const int64_t os = i*k_size_row;
  1186. const int64_t od = id*k_size_row;
  1187. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  1188. }
  1189. // move values (note: they are transposed)
  1190. {
  1191. const int64_t os = i;
  1192. const int64_t od = id;
  1193. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1194. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  1195. }
  1196. }
  1197. i += nm - 1;
  1198. }
  1199. ggml_backend_tensor_set(k_l[il], buf_k.data(), 0, buf_k.size());
  1200. ggml_backend_tensor_set(v_l[il], buf_v.data(), 0, buf_v.size());
  1201. }
  1202. #else
  1203. for (uint32_t i = 0; i < ids.size(); ++i) {
  1204. const uint32_t id = ids[i];
  1205. if (i == id || id == ids.size()) {
  1206. continue;
  1207. }
  1208. uint32_t nm = 1;
  1209. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  1210. nm++;
  1211. }
  1212. for (const auto & layer : layers) {
  1213. const uint32_t il = layer.il;
  1214. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1215. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1216. ggml_tensor * view_k_src = ggml_view_2d(ctx, layer.k,
  1217. n_embd_k_gqa, nm,
  1218. ggml_row_size(layer.k->type, n_embd_k_gqa),
  1219. ggml_row_size(layer.k->type, n_embd_k_gqa*i));
  1220. ggml_tensor * view_k_dst = ggml_view_2d(ctx, layer.k,
  1221. n_embd_k_gqa, nm,
  1222. ggml_row_size(layer.k->type, n_embd_k_gqa),
  1223. ggml_row_size(layer.k->type, n_embd_k_gqa*id));
  1224. ggml_tensor * view_v_src;
  1225. ggml_tensor * view_v_dst;
  1226. if (cparams.flash_attn) {
  1227. // NOTE: the V cache is not transposed when using flash attention
  1228. view_v_src = ggml_view_2d(ctx, layer.v,
  1229. n_embd_v_gqa, nm,
  1230. ggml_row_size(layer.v->type, n_embd_v_gqa),
  1231. ggml_row_size(layer.v->type, n_embd_v_gqa*i));
  1232. view_v_dst = ggml_view_2d(ctx, layer.v,
  1233. n_embd_v_gqa, nm,
  1234. ggml_row_size(layer.v->type, n_embd_v_gqa),
  1235. ggml_row_size(layer.v->type, n_embd_v_gqa*id));
  1236. } else {
  1237. view_v_src = ggml_view_2d(ctx, layer.v,
  1238. nm, n_embd_v_gqa,
  1239. ggml_row_size(layer.v->type, cells.size()),
  1240. ggml_row_size(layer.v->type, i));
  1241. view_v_dst = ggml_view_2d(ctx, layer.v,
  1242. nm, n_embd_v_gqa,
  1243. ggml_row_size(layer.v->type, cells.size()),
  1244. ggml_row_size(layer.v->type, id));
  1245. }
  1246. ggml_build_forward_expand(gf, ggml_cpy(ctx, view_k_src, view_k_dst));
  1247. ggml_build_forward_expand(gf, ggml_cpy(ctx, view_v_src, view_v_dst));
  1248. }
  1249. i += nm - 1;
  1250. }
  1251. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  1252. #endif
  1253. return gf;
  1254. }
  1255. llama_kv_cache_unified::defrag_info llama_kv_cache_unified::defrag_prepare(int32_t n_max_nodes) const {
  1256. GGML_ASSERT(n_stream == 1 && "n_stream > 1 does not support defrag");
  1257. const auto & cells = v_cells[0];
  1258. const uint32_t n_layer = layers.size();
  1259. const uint32_t n_kv = cells.used_max_p1();
  1260. const uint32_t n_used = cells.get_used();
  1261. assert(n_used <= n_kv);
  1262. //const int64_t t_start = ggml_time_us();
  1263. // number of cells moved
  1264. uint32_t n_moves = 0;
  1265. // each move requires 6*n_layer tensors (see graph_build_kv_self_defrag)
  1266. // - source view, destination view, copy operation
  1267. // - x2 for keys and values
  1268. //const uint32_t max_moves = max_nodes()/(6*n_layer);
  1269. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  1270. const uint32_t max_moves = (n_max_nodes - 2*n_layer)/(6*n_layer);
  1271. // determine which KV cells to move where
  1272. defrag_info res;
  1273. auto & ids = res.ids;
  1274. ids.resize(n_kv, n_kv);
  1275. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  1276. if (!cells.is_empty(i0)) {
  1277. ids[i0] = i0;
  1278. continue;
  1279. }
  1280. // found a hole - fill it with data from the end of the cache
  1281. uint32_t nh = 1;
  1282. // determine the size of the hole
  1283. while (i0 + nh < n_used && cells.is_empty(i0 + nh)) {
  1284. nh++;
  1285. }
  1286. uint32_t nf = 0;
  1287. uint32_t is = n_kv - 1;
  1288. // starting from the end, find nh non-empty cells
  1289. for (; is > i0; --is) {
  1290. if (cells.is_empty(is) || ids[is] != n_kv) {
  1291. continue;
  1292. }
  1293. // non-empty cell which is not yet moved
  1294. nf++;
  1295. if (nf == nh) {
  1296. break;
  1297. }
  1298. }
  1299. // this can only happen if `n_used` is not accurate, which would be a bug
  1300. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  1301. nf = 0;
  1302. uint32_t i1 = is;
  1303. // are we moving a continuous block of memory?
  1304. bool cont = false;
  1305. // should we stop searching for the next move?
  1306. bool stop = false;
  1307. // go back and move the nf cells to the hole
  1308. for (; i1 < n_kv; ++i1) {
  1309. if (cells.is_empty(i1) || ids[i1] != n_kv) {
  1310. if (n_moves == max_moves) {
  1311. stop = true;
  1312. break;
  1313. }
  1314. cont = false;
  1315. continue;
  1316. }
  1317. // this cell goes to (i0 + nf)
  1318. ids[i1] = i0 + nf;
  1319. if (!cont) {
  1320. n_moves++;
  1321. cont = true;
  1322. }
  1323. nf++;
  1324. if (nf == nh) {
  1325. break;
  1326. }
  1327. }
  1328. if (stop || n_moves == max_moves) {
  1329. break;
  1330. }
  1331. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  1332. i0 += nh - 1;
  1333. }
  1334. if (n_moves == 0) {
  1335. return {};
  1336. }
  1337. LLAMA_LOG_DEBUG("%s: (tmp log) KV defrag cell moves: %u\n", __func__, n_moves);
  1338. LLAMA_LOG_DEBUG("%s: expected gf nodes: %u\n", __func__, 6*n_moves*n_layer);
  1339. return res;
  1340. }
  1341. bool llama_kv_cache_unified::is_masked_swa(llama_pos p0, llama_pos p1) const {
  1342. assert(p0 >= 0 && p1 >= 0);
  1343. switch (swa_type) {
  1344. case LLAMA_SWA_TYPE_NONE:
  1345. {
  1346. } break;
  1347. case LLAMA_SWA_TYPE_STANDARD:
  1348. {
  1349. if (p1 - p0 >= (int32_t) n_swa) {
  1350. return true;
  1351. }
  1352. } break;
  1353. case LLAMA_SWA_TYPE_CHUNKED:
  1354. {
  1355. const llama_pos pos_chunk_start = (p1 / n_swa) * n_swa;
  1356. if (p0 < pos_chunk_start) {
  1357. return true;
  1358. }
  1359. } break;
  1360. }
  1361. return false;
  1362. }
  1363. void llama_kv_cache_unified::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const {
  1364. GGML_UNUSED(flags);
  1365. io.write(&n_stream, sizeof(n_stream));
  1366. for (uint32_t s = 0; s < n_stream; ++s) {
  1367. cell_ranges_t cr { s, {} };
  1368. uint32_t cell_count = 0;
  1369. const auto & cells = v_cells[s];
  1370. // Count the number of cells with the specified seq_id
  1371. // Find all the ranges of cells with this seq id (or all, when -1)
  1372. uint32_t cell_range_begin = cells.size();
  1373. for (uint32_t i = 0; i < cells.size(); ++i) {
  1374. if (!cells.is_empty(i) && (seq_id == -1 || cells.seq_has(i, seq_id))) {
  1375. ++cell_count;
  1376. if (cell_range_begin == cells.size()) {
  1377. cell_range_begin = i;
  1378. }
  1379. } else {
  1380. if (cell_range_begin != cells.size()) {
  1381. cr.data.emplace_back(cell_range_begin, i);
  1382. cell_range_begin = cells.size();
  1383. }
  1384. }
  1385. }
  1386. if (cell_range_begin != cells.size()) {
  1387. cr.data.emplace_back(cell_range_begin, cells.size());
  1388. }
  1389. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  1390. uint32_t cell_count_check = 0;
  1391. for (const auto & range : cr.data) {
  1392. cell_count_check += range.second - range.first;
  1393. }
  1394. GGML_ASSERT(cell_count == cell_count_check);
  1395. io.write(&cell_count, sizeof(cell_count));
  1396. // skip empty streams
  1397. if (cell_count == 0) {
  1398. continue;
  1399. }
  1400. state_write_meta(io, cr, seq_id);
  1401. state_write_data(io, cr);
  1402. }
  1403. }
  1404. void llama_kv_cache_unified::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
  1405. GGML_UNUSED(flags);
  1406. GGML_ASSERT(seq_id == -1 || (seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()));
  1407. uint32_t n_stream_cur;
  1408. io.read_to(&n_stream_cur, sizeof(n_stream_cur));
  1409. if (n_stream_cur != n_stream) {
  1410. throw std::runtime_error("n_stream mismatch");
  1411. }
  1412. for (uint32_t s = 0; s < n_stream; ++s) {
  1413. uint32_t cell_count;
  1414. io.read_to(&cell_count, sizeof(cell_count));
  1415. if (cell_count == 0) {
  1416. continue;
  1417. }
  1418. const uint32_t strm = seq_id == -1 ? s : seq_to_stream[seq_id];
  1419. bool res = true;
  1420. res = res && state_read_meta(io, strm, cell_count, seq_id);
  1421. res = res && state_read_data(io, strm, cell_count);
  1422. if (!res) {
  1423. if (seq_id == -1) {
  1424. clear(true);
  1425. } else {
  1426. seq_rm(seq_id, -1, -1);
  1427. }
  1428. throw std::runtime_error("failed to restore kv cache");
  1429. }
  1430. }
  1431. }
  1432. void llama_kv_cache_unified::state_write_meta(llama_io_write_i & io, const cell_ranges_t & cr, llama_seq_id seq_id) const {
  1433. const auto & cells = v_cells[cr.strm];
  1434. for (const auto & range : cr.data) {
  1435. for (uint32_t i = range.first; i < range.second; ++i) {
  1436. std::vector<llama_seq_id> seq_ids;
  1437. for (llama_seq_id cur = 0; cur < (int) n_seq_max; ++cur) {
  1438. if (cur == seq_id || seq_id == -1) {
  1439. if (cells.seq_has(i, cur)) {
  1440. seq_ids.push_back(cur);
  1441. }
  1442. }
  1443. }
  1444. const llama_pos pos = cells.pos_get(i);
  1445. const uint32_t n_seq_id = seq_ids.size();
  1446. io.write(&pos, sizeof(pos));
  1447. io.write(&n_seq_id, sizeof(n_seq_id));
  1448. for (const auto & seq_id : seq_ids) {
  1449. io.write(&seq_id, sizeof(seq_id));
  1450. }
  1451. }
  1452. }
  1453. }
  1454. void llama_kv_cache_unified::state_write_data(llama_io_write_i & io, const cell_ranges_t & cr) const {
  1455. const auto & cells = v_cells[cr.strm];
  1456. const uint32_t v_trans = this->v_trans ? 1 : 0;
  1457. const uint32_t n_layer = layers.size();
  1458. io.write(&v_trans, sizeof(v_trans));
  1459. io.write(&n_layer, sizeof(n_layer));
  1460. std::vector<uint8_t> tmp_buf;
  1461. // Iterate and write all the keys first, each row is a cell
  1462. // Get whole range at a time
  1463. for (const auto & layer : layers) {
  1464. const uint32_t il = layer.il;
  1465. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1466. auto * k = layer.k_stream[cr.strm];
  1467. // Write key type
  1468. const int32_t k_type_i = (int32_t) k->type;
  1469. io.write(&k_type_i, sizeof(k_type_i));
  1470. // Write row size of key
  1471. const uint64_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
  1472. io.write(&k_size_row, sizeof(k_size_row));
  1473. // Read each range of cells of k_size length each into tmp_buf and write out
  1474. for (const auto & range : cr.data) {
  1475. const size_t range_size = range.second - range.first;
  1476. const size_t buf_size = range_size * k_size_row;
  1477. io.write_tensor(k, range.first * k_size_row, buf_size);
  1478. }
  1479. }
  1480. if (!v_trans) {
  1481. for (const auto & layer : layers) {
  1482. const uint32_t il = layer.il;
  1483. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1484. auto * v = layer.v_stream[cr.strm];
  1485. // Write value type
  1486. const int32_t v_type_i = (int32_t) v->type;
  1487. io.write(&v_type_i, sizeof(v_type_i));
  1488. // Write row size of value
  1489. const uint64_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
  1490. io.write(&v_size_row, sizeof(v_size_row));
  1491. // Read each range of cells of v_size length each into tmp_buf and write out
  1492. for (const auto & range : cr.data) {
  1493. const size_t range_size = range.second - range.first;
  1494. const size_t buf_size = range_size * v_size_row;
  1495. io.write_tensor(v, range.first * v_size_row, buf_size);
  1496. }
  1497. }
  1498. } else {
  1499. // When v is transposed, we also need the element size and get the element ranges from each row
  1500. const uint32_t kv_size = cells.size();
  1501. for (const auto & layer : layers) {
  1502. const uint32_t il = layer.il;
  1503. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1504. auto * v = layer.v_stream[cr.strm];
  1505. // Write value type
  1506. const int32_t v_type_i = (int32_t) v->type;
  1507. io.write(&v_type_i, sizeof(v_type_i));
  1508. // Write element size
  1509. const uint32_t v_size_el = ggml_type_size(v->type);
  1510. io.write(&v_size_el, sizeof(v_size_el));
  1511. // Write GQA embedding size
  1512. io.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  1513. // For each row, we get the element values of each cell
  1514. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1515. // Read each range of cells of v_size_el length each into tmp_buf and write out
  1516. for (const auto & range : cr.data) {
  1517. const size_t range_size = range.second - range.first;
  1518. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  1519. const size_t buf_size = range_size * v_size_el;
  1520. io.write_tensor(v, src_offset, buf_size);
  1521. }
  1522. }
  1523. }
  1524. }
  1525. }
  1526. bool llama_kv_cache_unified::state_read_meta(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, llama_seq_id dest_seq_id) {
  1527. auto & cells = v_cells[strm];
  1528. auto & head = v_heads[strm];
  1529. if (dest_seq_id != -1) {
  1530. // single sequence
  1531. seq_rm(dest_seq_id, -1, -1);
  1532. llama_batch_allocr balloc(hparams.n_pos_per_embd());
  1533. llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
  1534. ubatch.seq_id_unq[0] = dest_seq_id;
  1535. for (uint32_t i = 0; i < cell_count; ++i) {
  1536. llama_pos pos;
  1537. uint32_t n_seq_id;
  1538. io.read_to(&pos, sizeof(pos));
  1539. io.read_to(&n_seq_id, sizeof(n_seq_id));
  1540. if (n_seq_id != 1) {
  1541. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  1542. return false;
  1543. }
  1544. // read the sequence id, but directly discard it - we will use dest_seq_id instead
  1545. {
  1546. llama_seq_id seq_id;
  1547. io.read_to(&seq_id, sizeof(seq_id));
  1548. }
  1549. ubatch.pos[i] = pos;
  1550. ubatch.n_seq_id[i] = n_seq_id;
  1551. ubatch.seq_id[i] = &dest_seq_id;
  1552. }
  1553. const auto sinfo = find_slot(ubatch, true);
  1554. if (sinfo.empty()) {
  1555. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  1556. return false;
  1557. }
  1558. apply_ubatch(sinfo, ubatch);
  1559. const auto head_cur = sinfo.head();
  1560. // keep the head at the old position because we will read the KV data into it in state_read_data()
  1561. head = head_cur;
  1562. LLAMA_LOG_DEBUG("%s: head_cur = %d, head = %d, cell_count = %d, dest_seq_id = %d\n", __func__, head_cur, head, cell_count, dest_seq_id);
  1563. // DEBUG CHECK: head_cur should be our first cell, head_cur + cell_count - 1 should be our last cell (verify seq_id and pos values)
  1564. // Assume that this is one contiguous block of cells
  1565. GGML_ASSERT(head_cur + cell_count <= cells.size());
  1566. GGML_ASSERT(cells.pos_get(head_cur) == ubatch.pos[0]);
  1567. GGML_ASSERT(cells.pos_get(head_cur + cell_count - 1) == ubatch.pos[cell_count - 1]);
  1568. GGML_ASSERT(cells.seq_has(head_cur, dest_seq_id));
  1569. GGML_ASSERT(cells.seq_has(head_cur + cell_count - 1, dest_seq_id));
  1570. } else {
  1571. // whole KV cache restore
  1572. if (cell_count > cells.size()) {
  1573. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  1574. return false;
  1575. }
  1576. clear(true);
  1577. for (uint32_t i = 0; i < cell_count; ++i) {
  1578. llama_pos pos;
  1579. uint32_t n_seq_id;
  1580. io.read_to(&pos, sizeof(pos));
  1581. io.read_to(&n_seq_id, sizeof(n_seq_id));
  1582. cells.pos_set(i, pos);
  1583. for (uint32_t j = 0; j < n_seq_id; ++j) {
  1584. llama_seq_id seq_id;
  1585. io.read_to(&seq_id, sizeof(seq_id));
  1586. if (seq_id < 0 || (uint32_t) seq_id >= n_seq_max) {
  1587. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, n_seq_max);
  1588. return false;
  1589. }
  1590. cells.seq_add(i, seq_id);
  1591. }
  1592. }
  1593. head = 0;
  1594. }
  1595. return true;
  1596. }
  1597. bool llama_kv_cache_unified::state_read_data(llama_io_read_i & io, uint32_t strm, uint32_t cell_count) {
  1598. auto & cells = v_cells[strm];
  1599. auto & head = v_heads[strm];
  1600. uint32_t v_trans;
  1601. uint32_t n_layer;
  1602. io.read_to(&v_trans, sizeof(v_trans));
  1603. io.read_to(&n_layer, sizeof(n_layer));
  1604. if (n_layer != layers.size()) {
  1605. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, (uint32_t) layers.size());
  1606. return false;
  1607. }
  1608. if (cell_count > cells.size()) {
  1609. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, cells.size());
  1610. return false;
  1611. }
  1612. if (this->v_trans != (bool) v_trans) {
  1613. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  1614. return false;
  1615. }
  1616. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  1617. for (const auto & layer : layers) {
  1618. const uint32_t il = layer.il;
  1619. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1620. auto * k = layer.k_stream[strm];
  1621. // Read type of key
  1622. int32_t k_type_i_ref;
  1623. io.read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  1624. const int32_t k_type_i = (int32_t) k->type;
  1625. if (k_type_i != k_type_i_ref) {
  1626. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  1627. return false;
  1628. }
  1629. // Read row size of key
  1630. uint64_t k_size_row_ref;
  1631. io.read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  1632. const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
  1633. if (k_size_row != k_size_row_ref) {
  1634. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  1635. return false;
  1636. }
  1637. if (cell_count) {
  1638. // Read and set the keys for the whole cell range
  1639. ggml_backend_tensor_set(k, io.read(cell_count * k_size_row), head * k_size_row, cell_count * k_size_row);
  1640. }
  1641. }
  1642. if (!this->v_trans) {
  1643. for (const auto & layer : layers) {
  1644. const uint32_t il = layer.il;
  1645. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1646. auto * v = layer.v_stream[strm];
  1647. // Read type of value
  1648. int32_t v_type_i_ref;
  1649. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1650. const int32_t v_type_i = (int32_t) v->type;
  1651. if (v_type_i != v_type_i_ref) {
  1652. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1653. return false;
  1654. }
  1655. // Read row size of value
  1656. uint64_t v_size_row_ref;
  1657. io.read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  1658. const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
  1659. if (v_size_row != v_size_row_ref) {
  1660. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  1661. return false;
  1662. }
  1663. if (cell_count) {
  1664. // Read and set the values for the whole cell range
  1665. ggml_backend_tensor_set(v, io.read(cell_count * v_size_row), head * v_size_row, cell_count * v_size_row);
  1666. }
  1667. }
  1668. } else {
  1669. // For each layer, read the values for each cell (transposed)
  1670. for (const auto & layer : layers) {
  1671. const uint32_t il = layer.il;
  1672. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1673. auto * v = layer.v_stream[strm];
  1674. // Read type of value
  1675. int32_t v_type_i_ref;
  1676. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1677. const int32_t v_type_i = (int32_t) v->type;
  1678. if (v_type_i != v_type_i_ref) {
  1679. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1680. return false;
  1681. }
  1682. // Read element size of value
  1683. uint32_t v_size_el_ref;
  1684. io.read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  1685. const size_t v_size_el = ggml_type_size(v->type);
  1686. if (v_size_el != v_size_el_ref) {
  1687. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  1688. return false;
  1689. }
  1690. // Read GQA embedding size
  1691. uint32_t n_embd_v_gqa_ref;
  1692. io.read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  1693. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  1694. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  1695. return false;
  1696. }
  1697. if (cell_count) {
  1698. // For each row in the transposed matrix, read the values for the whole cell range
  1699. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1700. const size_t dst_offset = (head + j * cells.size()) * v_size_el;
  1701. ggml_backend_tensor_set(v, io.read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  1702. }
  1703. }
  1704. }
  1705. }
  1706. return true;
  1707. }
  1708. //
  1709. // llama_kv_cache_unified_context
  1710. //
  1711. llama_kv_cache_unified_context::llama_kv_cache_unified_context(llama_memory_status status) : status(status) {}
  1712. llama_kv_cache_unified_context::llama_kv_cache_unified_context(
  1713. llama_kv_cache_unified * kv) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv) {
  1714. n_kv = kv->get_size();
  1715. const uint32_t n_stream = kv->get_n_stream();
  1716. // create a dummy slot info - the actual data is irrelevant. we just need to build the graph
  1717. sinfos.resize(1);
  1718. sinfos[0].s0 = 0;
  1719. sinfos[0].s1 = n_stream - 1;
  1720. sinfos[0].idxs.resize(n_stream);
  1721. for (uint32_t s = 0; s < n_stream; ++s) {
  1722. sinfos[0].strm.push_back(s);
  1723. sinfos[0].idxs[s].resize(1, 0);
  1724. }
  1725. }
  1726. llama_kv_cache_unified_context::llama_kv_cache_unified_context(
  1727. llama_kv_cache_unified * kv,
  1728. llama_context * lctx,
  1729. bool do_shift,
  1730. defrag_info dinfo,
  1731. stream_copy_info sc_info) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), lctx(lctx), do_shift(do_shift), dinfo(std::move(dinfo)), sc_info(std::move(sc_info)) {
  1732. if (!do_shift && this->dinfo.empty() && this->sc_info.empty()) {
  1733. status = LLAMA_MEMORY_STATUS_NO_UPDATE;
  1734. }
  1735. }
  1736. llama_kv_cache_unified_context::llama_kv_cache_unified_context(
  1737. llama_kv_cache_unified * kv,
  1738. llama_kv_cache_unified::slot_info_vec_t sinfos,
  1739. std::vector<llama_ubatch> ubatches) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), sinfos(std::move(sinfos)), ubatches(std::move(ubatches)) {
  1740. }
  1741. llama_kv_cache_unified_context::~llama_kv_cache_unified_context() = default;
  1742. bool llama_kv_cache_unified_context::next() {
  1743. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1744. if (++i_cur >= ubatches.size()) {
  1745. return false;
  1746. }
  1747. return true;
  1748. }
  1749. bool llama_kv_cache_unified_context::apply() {
  1750. assert(!llama_memory_status_is_fail(status));
  1751. // no ubatches -> this is a KV cache update
  1752. if (ubatches.empty()) {
  1753. kv->update(lctx, do_shift, dinfo, sc_info);
  1754. return true;
  1755. }
  1756. kv->apply_ubatch(sinfos[i_cur], ubatches[i_cur]);
  1757. n_kv = kv->get_n_kv();
  1758. return true;
  1759. }
  1760. llama_memory_status llama_kv_cache_unified_context::get_status() const {
  1761. return status;
  1762. }
  1763. const llama_ubatch & llama_kv_cache_unified_context::get_ubatch() const {
  1764. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1765. return ubatches[i_cur];
  1766. }
  1767. uint32_t llama_kv_cache_unified_context::get_n_kv() const {
  1768. return n_kv;
  1769. }
  1770. bool llama_kv_cache_unified_context::get_supports_set_rows() const {
  1771. return kv->get_supports_set_rows();
  1772. }
  1773. ggml_tensor * llama_kv_cache_unified_context::get_k(ggml_context * ctx, int32_t il) const {
  1774. return kv->get_k(ctx, il, n_kv, sinfos[i_cur]);
  1775. }
  1776. ggml_tensor * llama_kv_cache_unified_context::get_v(ggml_context * ctx, int32_t il) const {
  1777. return kv->get_v(ctx, il, n_kv, sinfos[i_cur]);
  1778. }
  1779. ggml_tensor * llama_kv_cache_unified_context::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il) const {
  1780. return kv->cpy_k(ctx, k_cur, k_idxs, il, sinfos[i_cur]);
  1781. }
  1782. ggml_tensor * llama_kv_cache_unified_context::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il) const {
  1783. return kv->cpy_v(ctx, v_cur, v_idxs, il, sinfos[i_cur]);
  1784. }
  1785. ggml_tensor * llama_kv_cache_unified_context::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  1786. return kv->build_input_k_idxs(ctx, ubatch);
  1787. }
  1788. ggml_tensor * llama_kv_cache_unified_context::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  1789. return kv->build_input_v_idxs(ctx, ubatch);
  1790. }
  1791. void llama_kv_cache_unified_context::set_input_k_shift(ggml_tensor * dst) const {
  1792. kv->set_input_k_shift(dst);
  1793. }
  1794. void llama_kv_cache_unified_context::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1795. kv->set_input_k_idxs(dst, ubatch, sinfos[i_cur]);
  1796. }
  1797. void llama_kv_cache_unified_context::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1798. kv->set_input_v_idxs(dst, ubatch, sinfos[i_cur]);
  1799. }
  1800. void llama_kv_cache_unified_context::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
  1801. kv->set_input_kq_mask(dst, ubatch, causal_attn);
  1802. }
  1803. void llama_kv_cache_unified_context::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1804. kv->set_input_pos_bucket(dst, ubatch);
  1805. }
  1806. uint32_t llama_kv_cache_unified::get_padding(const llama_cparams & cparams) {
  1807. // the FA kernels require padding to avoid extra runtime boundary checks
  1808. return cparams.flash_attn ? 256u : 32u;
  1809. }