llama-kv-cache-unified.cpp 76 KB

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