llama-kv-cache-unified.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  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. uint32_t kv_size,
  23. uint32_t n_seq_max,
  24. uint32_t n_pad,
  25. uint32_t n_swa,
  26. llama_swa_type swa_type) :
  27. model(model), hparams(model.hparams), v_trans(v_trans),
  28. n_seq_max(n_seq_max), n_pad(n_pad), n_swa(n_swa), swa_type(swa_type) {
  29. GGML_ASSERT(kv_size % n_pad == 0);
  30. // create a context for each buffer type
  31. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  32. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  33. auto it = ctx_map.find(buft);
  34. if (it == ctx_map.end()) {
  35. ggml_init_params params = {
  36. /*.mem_size =*/ size_t(2u*hparams.n_layer*ggml_tensor_overhead()),
  37. /*.mem_buffer =*/ NULL,
  38. /*.no_alloc =*/ true,
  39. };
  40. ggml_context * ctx = ggml_init(params);
  41. if (!ctx) {
  42. return nullptr;
  43. }
  44. ctx_map[buft] = ctx;
  45. ctxs.emplace_back(ctx);
  46. return ctx;
  47. }
  48. return it->second;
  49. };
  50. head = 0;
  51. cells.resize(kv_size);
  52. for (uint32_t il = 0; il < hparams.n_layer; il++) {
  53. if (filter && !filter(il)) {
  54. LLAMA_LOG_DEBUG("%s: layer %3d: skipped\n", __func__, il);
  55. continue;
  56. }
  57. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  58. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  59. const char * dev_name = "CPU";
  60. ggml_backend_buffer_type_t buft = ggml_backend_cpu_buffer_type();
  61. if (offload) {
  62. auto * dev = model.dev_layer(il);
  63. buft = ggml_backend_dev_buffer_type(dev);
  64. dev_name = ggml_backend_dev_name(dev);
  65. }
  66. LLAMA_LOG_DEBUG("%s: layer %3d: dev = %s\n", __func__, il, dev_name);
  67. ggml_context * ctx = ctx_for_buft(buft);
  68. if (!ctx) {
  69. throw std::runtime_error("failed to create ggml context for kv cache");
  70. }
  71. ggml_tensor * k;
  72. ggml_tensor * v;
  73. k = ggml_new_tensor_2d(ctx, type_k, n_embd_k_gqa, kv_size);
  74. v = ggml_new_tensor_2d(ctx, type_v, n_embd_v_gqa, kv_size);
  75. ggml_format_name(k, "cache_k_l%d", il);
  76. ggml_format_name(v, "cache_v_l%d", il);
  77. map_layer_ids[il] = layers.size();
  78. layers.push_back({ il, k, v });
  79. }
  80. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  81. for (auto it : ctx_map) {
  82. auto * buft = it.first;
  83. auto * ctx = it.second;
  84. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  85. if (!buf) {
  86. throw std::runtime_error("failed to allocate buffer for kv cache");
  87. }
  88. 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);
  89. ggml_backend_buffer_clear(buf, 0);
  90. bufs.emplace_back(buf);
  91. }
  92. {
  93. const size_t memory_size_k = size_k_bytes();
  94. const size_t memory_size_v = size_v_bytes();
  95. LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs), K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  96. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f), kv_size, (int) layers.size(), n_seq_max,
  97. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  98. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  99. }
  100. const char * LLAMA_KV_CACHE_DEBUG = getenv("LLAMA_KV_CACHE_DEBUG");
  101. debug = LLAMA_KV_CACHE_DEBUG ? atoi(LLAMA_KV_CACHE_DEBUG) : 0;
  102. }
  103. void llama_kv_cache_unified::clear(bool data) {
  104. cells.reset();
  105. head = 0;
  106. if (data) {
  107. for (auto & buf : bufs) {
  108. ggml_backend_buffer_clear(buf.get(), 0);
  109. }
  110. }
  111. }
  112. bool llama_kv_cache_unified::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  113. uint32_t new_head = cells.size();
  114. if (p0 < 0) {
  115. p0 = 0;
  116. }
  117. if (p1 < 0) {
  118. p1 = std::numeric_limits<llama_pos>::max();
  119. }
  120. if (seq_id >= 0) {
  121. for (uint32_t i = 0; i < cells.size(); ++i) {
  122. if (!cells.pos_in(i, p0, p1)) {
  123. continue;
  124. }
  125. if (cells.seq_has(i, seq_id) && cells.seq_rm(i, seq_id)) {
  126. if (new_head == cells.size()) {
  127. new_head = i;
  128. }
  129. }
  130. }
  131. } else {
  132. // match any sequence
  133. for (uint32_t i = 0; i < cells.size(); ++i) {
  134. if (!cells.pos_in(i, p0, p1)) {
  135. continue;
  136. }
  137. cells.rm(i);
  138. if (new_head == cells.size()) {
  139. new_head = i;
  140. }
  141. }
  142. }
  143. // If we freed up a slot, set head to it so searching can start there.
  144. if (new_head != cells.size() && new_head < head) {
  145. head = new_head;
  146. }
  147. return true;
  148. }
  149. 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) {
  150. if (seq_id_src == seq_id_dst) {
  151. return;
  152. }
  153. if (p0 < 0) {
  154. p0 = 0;
  155. }
  156. if (p1 < 0) {
  157. p1 = std::numeric_limits<llama_pos>::max();
  158. }
  159. for (uint32_t i = 0; i < cells.size(); ++i) {
  160. if (!cells.pos_in(i, p0, p1)) {
  161. continue;
  162. }
  163. if (cells.seq_has(i, seq_id_src)) {
  164. cells.seq_add(i, seq_id_dst);
  165. }
  166. }
  167. }
  168. void llama_kv_cache_unified::seq_keep(llama_seq_id seq_id) {
  169. uint32_t new_head = cells.size();
  170. for (uint32_t i = 0; i < cells.size(); ++i) {
  171. if (cells.seq_keep(i, seq_id)) {
  172. if (new_head == cells.size()) {
  173. new_head = i;
  174. }
  175. }
  176. }
  177. // If we freed up a slot, set head to it so searching can start there.
  178. if (new_head != cells.size() && new_head < head) {
  179. head = new_head;
  180. }
  181. }
  182. void llama_kv_cache_unified::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) {
  183. if (shift == 0) {
  184. return;
  185. }
  186. uint32_t new_head = cells.size();
  187. if (p0 < 0) {
  188. p0 = 0;
  189. }
  190. if (p1 < 0) {
  191. p1 = std::numeric_limits<llama_pos>::max();
  192. }
  193. // If there is no range then return early to avoid looping over all cells.
  194. if (p0 == p1) {
  195. return;
  196. }
  197. for (uint32_t i = 0; i < cells.size(); ++i) {
  198. if (!cells.pos_in(i, p0, p1)) {
  199. continue;
  200. }
  201. if (cells.seq_has(i, seq_id)) {
  202. if (cells.pos_add(i, shift)) {
  203. if (new_head == cells.size()) {
  204. new_head = i;
  205. }
  206. }
  207. }
  208. }
  209. // If we freed up a slot, set head to it so searching can start there.
  210. // Otherwise we just start the next search from the beginning.
  211. head = new_head != cells.size() ? new_head : 0;
  212. }
  213. void llama_kv_cache_unified::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  214. if (d == 1) {
  215. return;
  216. }
  217. if (p0 < 0) {
  218. p0 = 0;
  219. }
  220. if (p1 < 0) {
  221. p1 = std::numeric_limits<llama_pos>::max();
  222. }
  223. // If there is no range then return early to avoid looping over the cache.
  224. if (p0 == p1) {
  225. return;
  226. }
  227. for (uint32_t i = 0; i < cells.size(); ++i) {
  228. if (!cells.pos_in(i, p0, p1)) {
  229. continue;
  230. }
  231. if (cells.seq_has(i, seq_id)) {
  232. cells.pos_div(i, d);
  233. }
  234. }
  235. }
  236. llama_pos llama_kv_cache_unified::seq_pos_min(llama_seq_id seq_id) const {
  237. return cells.seq_pos_min(seq_id);
  238. }
  239. llama_pos llama_kv_cache_unified::seq_pos_max(llama_seq_id seq_id) const {
  240. return cells.seq_pos_max(seq_id);
  241. }
  242. llama_memory_state_ptr llama_kv_cache_unified::init_batch(
  243. const llama_batch & batch,
  244. uint32_t n_ubatch,
  245. bool embd_pooled,
  246. bool logits_all) {
  247. GGML_UNUSED(embd_pooled);
  248. auto sbatch = llama_sbatch(batch, hparams.n_embd, true, logits_all);
  249. std::vector<llama_ubatch> ubatches;
  250. while (sbatch.n_tokens > 0) {
  251. ubatches.push_back(sbatch.split_simple(n_ubatch));
  252. }
  253. auto heads = prepare(ubatches);
  254. if (heads.empty()) {
  255. return std::make_unique<llama_kv_cache_unified_state>(LLAMA_MEMORY_STATUS_FAILED_PREPARE);
  256. }
  257. return std::make_unique<llama_kv_cache_unified_state>(
  258. this, std::move(sbatch), std::move(heads), std::move(ubatches));
  259. }
  260. llama_memory_state_ptr llama_kv_cache_unified::init_full() {
  261. return std::make_unique<llama_kv_cache_unified_state>(this);
  262. }
  263. llama_memory_state_ptr llama_kv_cache_unified::init_update(llama_context * lctx, bool optimize) {
  264. bool do_shift = get_has_shift();
  265. defrag_info dinfo;
  266. // see if we need to defrag
  267. {
  268. bool do_defrag = optimize;
  269. const auto thold = lctx->get_cparams().defrag_thold;
  270. if (!do_defrag && thold > 0.0f) {
  271. const auto n_kv = cells.used_max_p1();
  272. // - do not defrag small contexts (i.e. < 2048 tokens)
  273. // - count the padding towards the number of used tokens
  274. const float fragmentation = n_kv >= 2048 ? std::max(0.0f, 1.0f - (float(cells.get_used() + n_pad)/n_kv)) : 0.0f;
  275. if (fragmentation > thold) {
  276. LLAMA_LOG_DEBUG("%s: fragmentation: %.2f - requesting defrag\n", __func__, fragmentation);
  277. do_defrag = true;
  278. }
  279. }
  280. if (do_defrag) {
  281. dinfo = defrag_prepare(lctx->graph_max_nodes());
  282. }
  283. }
  284. return std::make_unique<llama_kv_cache_unified_state>(this, lctx, do_shift, std::move(dinfo));
  285. }
  286. llama_kv_cache_unified::ubatch_heads llama_kv_cache_unified::prepare(const std::vector<llama_ubatch> & ubatches) {
  287. llama_kv_cache_unified::ubatch_heads res;
  288. struct state {
  289. uint32_t head_old; // old position of the head, before placing the ubatch
  290. uint32_t head_new; // new position of the head, after placing the ubatch
  291. llama_kv_cells_unified cells; // copy of the old cells, before placing the ubatch
  292. };
  293. // remember the old state of the cells so we can restore it in the end
  294. std::vector<state> states;
  295. bool success = true;
  296. for (const auto & ubatch : ubatches) {
  297. // only find a suitable slot for the ubatch. don't modify the cells yet
  298. const int32_t head_new = find_slot(ubatch);
  299. if (head_new < 0) {
  300. success = false;
  301. break;
  302. }
  303. // remeber the position that we found
  304. res.push_back(head_new);
  305. // store the old state of the cells in the recovery stack
  306. states.push_back({head, (uint32_t) head_new, cells.cp(head_new, ubatch.n_tokens)});
  307. // now emplace the ubatch
  308. apply_ubatch(head_new, ubatch);
  309. }
  310. // iterate backwards and restore the cells to their original state
  311. for (auto it = states.rbegin(); it != states.rend(); ++it) {
  312. cells.set(it->head_new, it->cells);
  313. head = it->head_old;
  314. }
  315. if (!success) {
  316. return {};
  317. }
  318. return res;
  319. }
  320. bool llama_kv_cache_unified::update(llama_context * lctx, bool do_shift, const defrag_info & dinfo) {
  321. bool updated = false;
  322. auto * sched = lctx->get_sched();
  323. if (do_shift) {
  324. if (!get_can_shift()) {
  325. GGML_ABORT("The current KV cache / model configuration does not support K-shift");
  326. }
  327. LLAMA_LOG_DEBUG("%s: applying K-shift\n", __func__);
  328. // apply K-shift if needed
  329. if (hparams.rope_type != LLAMA_ROPE_TYPE_NONE) {
  330. ggml_backend_sched_reset(sched);
  331. auto * gf = lctx->graph_init();
  332. auto res = build_graph_shift(lctx->get_cparams(), lctx->get_ctx_compute(), gf);
  333. if (!res) {
  334. LLAMA_LOG_ERROR("%s: failed to build graph for K-shift\n", __func__);
  335. return updated;
  336. }
  337. if (!ggml_backend_sched_alloc_graph(sched, gf)) {
  338. LLAMA_LOG_ERROR("%s: failed to allocate compute graph for K-shift\n", __func__);
  339. return updated;
  340. }
  341. res->set_inputs(nullptr);
  342. if (lctx->graph_compute(gf, false) != GGML_STATUS_SUCCESS) {
  343. LLAMA_LOG_ERROR("%s: failed to compute K-shift\n", __func__);
  344. return updated;
  345. }
  346. updated = true;
  347. }
  348. cells.reset_shift();
  349. }
  350. if (!dinfo.empty()) {
  351. LLAMA_LOG_DEBUG("%s: defragmenting KV cache\n", __func__);
  352. // apply moves:
  353. {
  354. const auto n_kv = dinfo.ids.size();
  355. for (uint32_t i = 0; i < n_kv; ++i) {
  356. assert(dinfo.ids[i] <= n_kv);
  357. if (dinfo.ids[i] == n_kv || dinfo.ids[i] == i) {
  358. continue;
  359. }
  360. cells.mv(i, dinfo.ids[i]);
  361. }
  362. // reset the head so we can find the first free slot during the next ubatch
  363. head = 0;
  364. }
  365. ggml_backend_sched_reset(sched);
  366. auto * gf = lctx->graph_init();
  367. auto res = build_graph_defrag(lctx->get_cparams(), lctx->get_ctx_compute(), gf, dinfo);
  368. if (!res) {
  369. LLAMA_LOG_ERROR("%s: failed to build graph for defrag\n", __func__);
  370. return updated;
  371. }
  372. if (!ggml_backend_sched_alloc_graph(sched, gf)) {
  373. LLAMA_LOG_ERROR("%s: failed to allocate compute graph for defrag\n", __func__);
  374. return updated;
  375. }
  376. res->set_inputs(nullptr);
  377. if (lctx->graph_compute(gf, false) != GGML_STATUS_SUCCESS) {
  378. LLAMA_LOG_ERROR("%s: failed to compute defrag\n", __func__);
  379. return updated;
  380. }
  381. updated = true;
  382. }
  383. return updated;
  384. }
  385. int32_t llama_kv_cache_unified::find_slot(const llama_ubatch & ubatch) const {
  386. const uint32_t n_tokens = ubatch.n_tokens;
  387. uint32_t head_cur = this->head;
  388. // if we have enough unused cells before the current head ->
  389. // better to start searching from the beginning of the cache, hoping to fill it
  390. if (head_cur > cells.get_used() + 2*ubatch.n_tokens) {
  391. head_cur = 0;
  392. }
  393. if (n_tokens > cells.size()) {
  394. LLAMA_LOG_ERROR("%s: n_tokens = %d > size = %u\n", __func__, n_tokens, cells.size());
  395. return -1;
  396. }
  397. if (debug > 0) {
  398. LLAMA_LOG_CONT("\n");
  399. LLAMA_LOG_DEBUG("%s: n = %5d, used = %5d, head = %5d, size = %5d, n_swa = %5d\n", __func__, cells.used_max_p1(), cells.get_used(), head, get_size(), n_swa);
  400. if ((debug == 2 && n_swa > 0) || debug > 2) {
  401. std::string ss;
  402. for (uint32_t i = 0; i < cells.size(); ++i) {
  403. if (cells.is_empty(i)) {
  404. ss += '.';
  405. } else {
  406. ss += std::to_string(cells.seq_get(i));
  407. }
  408. if (i%256 == 255) {
  409. ss += " *";
  410. ss += '\n';
  411. }
  412. }
  413. LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
  414. }
  415. if ((debug == 2 && n_swa > 0) || debug > 2) {
  416. std::string ss;
  417. for (uint32_t i = 0; i < cells.size(); ++i) {
  418. std::string cur;
  419. if (cells.is_empty(i)) {
  420. cur = '.';
  421. } else {
  422. cur = std::to_string(cells.pos_get(i));
  423. }
  424. const int n = cur.size();
  425. for (int j = 0; j < 5 - n; ++j) {
  426. cur += ' ';
  427. }
  428. ss += cur;
  429. if (i%256 == 255) {
  430. ss += " *";
  431. }
  432. if (i%64 == 63) {
  433. ss += '\n';
  434. }
  435. }
  436. LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
  437. }
  438. for (int s = 0; s < LLAMA_MAX_PARALLEL_SEQUENCES; ++s) {
  439. if (cells.seq_pos_min(s) < 0) {
  440. continue;
  441. }
  442. LLAMA_LOG_DEBUG("%s: min[%d] = %5d, max[%d] = %5d\n", __func__, s, cells.seq_pos_min(s), s, cells.seq_pos_max(s));
  443. }
  444. }
  445. uint32_t n_tested = 0;
  446. while (true) {
  447. if (head_cur + n_tokens > cells.size()) {
  448. n_tested += cells.size() - head_cur;
  449. head_cur = 0;
  450. continue;
  451. }
  452. bool found = true;
  453. for (uint32_t i = 0; i < n_tokens; i++) {
  454. //const llama_pos pos = ubatch.pos[i];
  455. //const llama_seq_id seq_id = ubatch.seq_id[i][0];
  456. // can we use this cell? either:
  457. // - the cell is empty
  458. // - the cell is occupied only by one sequence:
  459. // - (disabled) mask causally, if the sequence is the same as the one we are inserting
  460. // - mask SWA, using current max pos for that sequence in the cache
  461. // always insert in the cell with minimum pos
  462. bool can_use = cells.is_empty(head_cur + i);
  463. if (!can_use && cells.seq_count(head_cur + i) == 1) {
  464. const llama_pos pos_cell = cells.pos_get(head_cur + i);
  465. // (disabled) causal mask
  466. // note: it's better to purge any "future" tokens beforehand
  467. //if (cells.seq_has(head_cur + i, seq_id)) {
  468. // can_use = pos_cell >= pos;
  469. //}
  470. if (!can_use) {
  471. const llama_seq_id seq_id_cell = cells.seq_get(head_cur + i);
  472. // SWA mask
  473. if (is_masked_swa(pos_cell, cells.seq_pos_max(seq_id_cell) + 1)) {
  474. can_use = true;
  475. }
  476. }
  477. }
  478. if (!can_use) {
  479. found = false;
  480. head_cur += i + 1;
  481. n_tested += i + 1;
  482. break;
  483. }
  484. }
  485. if (found) {
  486. break;
  487. }
  488. if (n_tested >= cells.size()) {
  489. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  490. return -1;
  491. }
  492. }
  493. return head_cur;
  494. }
  495. void llama_kv_cache_unified::apply_ubatch(uint32_t head_cur, const llama_ubatch & ubatch) {
  496. // keep track of the max sequence position that we would overwrite with this ubatch
  497. // for non-SWA cache, this would be always empty
  498. llama_seq_id seq_pos_max_rm[LLAMA_MAX_PARALLEL_SEQUENCES];
  499. for (int s = 0; s < LLAMA_MAX_PARALLEL_SEQUENCES; ++s) {
  500. seq_pos_max_rm[s] = -1;
  501. }
  502. for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
  503. if (!cells.is_empty(head_cur + i)) {
  504. assert(cells.seq_count(head_cur + i) == 1);
  505. const llama_seq_id seq_id = cells.seq_get(head_cur + i);
  506. const llama_pos pos = cells.pos_get(head_cur + i);
  507. seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos);
  508. cells.rm(head_cur + i);
  509. }
  510. cells.pos_set(head_cur + i, ubatch.pos[i]);
  511. for (int32_t j = 0; j < ubatch.n_seq_id[i]; j++) {
  512. cells.seq_add(head_cur + i, ubatch.seq_id[i][j]);
  513. }
  514. }
  515. // note: we want to preserve the invariant that all positions between [pos_min, pos_max] for each sequence
  516. // will be present in the cache. so we have to purge any position which is less than those we would overwrite
  517. // ref: https://github.com/ggml-org/llama.cpp/pull/13746#issuecomment-2916057092
  518. for (int s = 0; s < LLAMA_MAX_PARALLEL_SEQUENCES; ++s) {
  519. if (seq_pos_max_rm[s] == -1) {
  520. continue;
  521. }
  522. if (cells.seq_pos_min(s) <= seq_pos_max_rm[s]) {
  523. LLAMA_LOG_DEBUG("%s: purging positions [%d, %d] of sequence %d from KV cache\n",
  524. __func__, cells.seq_pos_min(s), seq_pos_max_rm[s], s);
  525. seq_rm(s, cells.seq_pos_min(s), seq_pos_max_rm[s] + 1);
  526. }
  527. }
  528. // move the head at the end of the slot
  529. head = head_cur + ubatch.n_tokens;
  530. }
  531. bool llama_kv_cache_unified::get_can_shift() const {
  532. return true;
  533. }
  534. uint32_t llama_kv_cache_unified::get_size() const {
  535. return cells.size();
  536. }
  537. bool llama_kv_cache_unified::get_has_shift() const {
  538. return cells.get_has_shift();
  539. }
  540. uint32_t llama_kv_cache_unified::get_n_kv() const {
  541. return std::min(cells.size(), std::max(n_pad, GGML_PAD(cells.used_max_p1(), n_pad)));
  542. }
  543. ggml_tensor * llama_kv_cache_unified::get_k(ggml_context * ctx, int32_t il, uint32_t n_kv) const {
  544. const int32_t ikv = map_layer_ids.at(il);
  545. auto * k = layers[ikv].k;
  546. return ggml_view_3d(ctx, k,
  547. hparams.n_embd_head_k, hparams.n_head_kv(il), n_kv,
  548. ggml_row_size(k->type, hparams.n_embd_head_k),
  549. ggml_row_size(k->type, hparams.n_embd_k_gqa(il)),
  550. 0);
  551. }
  552. ggml_tensor * llama_kv_cache_unified::get_v(ggml_context * ctx, int32_t il, uint32_t n_kv) const {
  553. const int32_t ikv = map_layer_ids.at(il);
  554. auto * v = layers[ikv].v;
  555. if (!v_trans) {
  556. // note: v->nb[1] <= v->nb[2]
  557. return ggml_view_3d(ctx, v,
  558. hparams.n_embd_head_v, hparams.n_head_kv(il), n_kv,
  559. ggml_row_size(v->type, hparams.n_embd_head_v), // v->nb[1]
  560. ggml_row_size(v->type, hparams.n_embd_v_gqa(il)), // v->nb[2]
  561. 0);
  562. }
  563. // note: v->nb[1] > v->nb[2]
  564. return ggml_view_3d(ctx, v,
  565. n_kv, hparams.n_head_kv(il), hparams.n_embd_head_v,
  566. ggml_row_size(v->type, v->ne[1]*hparams.n_embd_head_v), // v->nb[1]
  567. ggml_row_size(v->type, v->ne[1]), // v->nb[2]
  568. 0);
  569. }
  570. ggml_tensor * llama_kv_cache_unified::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, int32_t il, uint32_t head_cur) const {
  571. const int32_t ikv = map_layer_ids.at(il);
  572. auto * k = layers[ikv].k;
  573. const int64_t n_tokens = k_cur->ne[2];
  574. ggml_tensor * k_view = ggml_view_1d(ctx, k,
  575. n_tokens*hparams.n_embd_k_gqa(il),
  576. ggml_row_size(k->type, hparams.n_embd_k_gqa(il))*head_cur);
  577. return ggml_cpy(ctx, k_cur, k_view);
  578. }
  579. ggml_tensor * llama_kv_cache_unified::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, int32_t il, uint32_t head_cur) const {
  580. const int32_t ikv = map_layer_ids.at(il);
  581. auto * v = layers[ikv].v;
  582. const int64_t n_tokens = v_cur->ne[2];
  583. v_cur = ggml_reshape_2d(ctx, v_cur, hparams.n_embd_v_gqa(il), n_tokens);
  584. ggml_tensor * v_view = nullptr;
  585. if (!v_trans) {
  586. v_view = ggml_view_1d(ctx, v,
  587. n_tokens*hparams.n_embd_v_gqa(il),
  588. ggml_row_size(v->type, hparams.n_embd_v_gqa(il))*head_cur);
  589. } else {
  590. // note: the V cache is transposed when not using flash attention
  591. v_view = ggml_view_2d(ctx, v, n_tokens, hparams.n_embd_v_gqa(il),
  592. (v->ne[1])*ggml_element_size(v),
  593. (head_cur)*ggml_element_size(v));
  594. v_cur = ggml_transpose(ctx, v_cur);
  595. }
  596. return ggml_cpy(ctx, v_cur, v_view);
  597. }
  598. void llama_kv_cache_unified::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
  599. const int64_t n_tokens = ubatch->n_tokens;
  600. const int64_t n_seq_tokens = ubatch->n_seq_tokens;
  601. const int64_t n_seqs = ubatch->n_seqs;
  602. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  603. float * data = (float *) dst->data;
  604. const auto n_kv = dst->ne[0];
  605. // Use only the previous KV cells of the correct sequence for each token of the ubatch.
  606. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  607. // Example with a cache of 10 tokens, 2 tokens populated in cache and 3 tokens in batch:
  608. // Causal mask:
  609. // xxx-------
  610. // xxxx------
  611. // xxxxx-----
  612. // Non-causal mask:
  613. // xxxxx-----
  614. // xxxxx-----
  615. // xxxxx-----
  616. // To visualize the mask, see https://github.com/ggml-org/llama.cpp/pull/12615
  617. for (int h = 0; h < 1; ++h) {
  618. for (int s = 0; s < n_seqs; ++s) {
  619. const llama_seq_id seq_id = ubatch->seq_id[s][0];
  620. for (int j = 0; j < n_seq_tokens; ++j) {
  621. const llama_pos p1 = ubatch->pos[s*n_seq_tokens + j];
  622. for (uint32_t i = 0; i < n_kv; ++i) {
  623. float f = 0.0f;
  624. bool masked = false;
  625. if (cells.is_empty(i)) {
  626. masked = true;
  627. } else {
  628. const llama_pos p0 = cells.pos_get(i);
  629. // mask the token if not the same sequence
  630. masked = masked || (!cells.seq_has(i, seq_id));
  631. // mask future tokens
  632. masked = masked || (causal_attn && p0 > p1);
  633. // apply SWA if any
  634. masked = masked || (is_masked_swa(p0, p1));
  635. if (!masked && hparams.use_alibi) {
  636. f = -std::abs(p0 - p1);
  637. }
  638. }
  639. if (masked) {
  640. f = -INFINITY;
  641. }
  642. data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  643. }
  644. }
  645. }
  646. // mask padded tokens
  647. if (data) {
  648. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  649. for (uint32_t j = 0; j < n_kv; ++j) {
  650. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  651. }
  652. }
  653. }
  654. }
  655. }
  656. void llama_kv_cache_unified::set_input_k_shift(ggml_tensor * dst) const {
  657. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  658. int32_t * data = (int32_t *) dst->data;
  659. for (uint32_t i = 0; i < cells.size(); ++i) {
  660. data[i] = cells.is_empty(i) ? 0 : cells.get_shift(i);
  661. }
  662. }
  663. void llama_kv_cache_unified::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  664. const int64_t n_tokens = ubatch->n_tokens;
  665. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  666. GGML_ASSERT(!ubatch->equal_seqs); // TODO: use ubatch->n_seqs instead of failing
  667. int32_t * data = (int32_t *) dst->data;
  668. const int32_t n_kv = dst->ne[0];
  669. for (int h = 0; h < 1; ++h) {
  670. for (int j = 0; j < n_tokens; ++j) {
  671. for (int i = 0; i < n_kv; ++i) {
  672. // the position when the cells is empty is irrelevant - it will be masked out later in the attention
  673. const llama_pos p0 = cells.is_empty(i) ? -1 : cells.pos_get(i);
  674. data[h*(n_kv*n_tokens) + j*n_kv + i] = llama_relative_position_bucket(p0, ubatch->pos[j], hparams.n_rel_attn_bkts, false);
  675. }
  676. }
  677. }
  678. }
  679. size_t llama_kv_cache_unified::total_size() const {
  680. size_t size = 0;
  681. for (const auto & buf : bufs) {
  682. size += ggml_backend_buffer_get_size(buf.get());
  683. }
  684. return size;
  685. }
  686. size_t llama_kv_cache_unified::size_k_bytes() const {
  687. size_t size_k_bytes = 0;
  688. for (const auto & layer : layers) {
  689. size_k_bytes += ggml_nbytes(layer.k);
  690. }
  691. return size_k_bytes;
  692. }
  693. size_t llama_kv_cache_unified::size_v_bytes() const {
  694. size_t size_v_bytes = 0;
  695. for (const auto & layer : layers) {
  696. size_v_bytes += ggml_nbytes(layer.v);
  697. }
  698. return size_v_bytes;
  699. }
  700. ggml_tensor * llama_kv_cache_unified::build_rope_shift(
  701. const llama_cparams & cparams,
  702. ggml_context * ctx,
  703. ggml_tensor * cur,
  704. ggml_tensor * shift,
  705. ggml_tensor * factors,
  706. float freq_base,
  707. float freq_scale) const {
  708. const auto & n_ctx_orig = cparams.n_ctx_orig_yarn;
  709. const auto & yarn_ext_factor = cparams.yarn_ext_factor;
  710. const auto & yarn_beta_fast = cparams.yarn_beta_fast;
  711. const auto & yarn_beta_slow = cparams.yarn_beta_slow;
  712. const auto & n_rot = hparams.n_rot;
  713. const auto & rope_type = hparams.rope_type == LLAMA_ROPE_TYPE_MROPE
  714. // @ngxson : this is a workaround
  715. // for M-RoPE, we want to rotate the whole vector when doing KV shift
  716. // a normal RoPE should work, we just need to use the correct ordering
  717. // ref: https://github.com/ggml-org/llama.cpp/pull/13870
  718. ? LLAMA_ROPE_TYPE_NEOX
  719. : hparams.rope_type;
  720. // See llm_build_deepseek2() for why attn_factor has to be scaled for YaRN RoPE to work correctly.
  721. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  722. const float yarn_attn_factor = model.arch == LLM_ARCH_DEEPSEEK2
  723. ? 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale))
  724. : cparams.yarn_attn_factor;
  725. ggml_tensor * tmp;
  726. if (ggml_is_quantized(cur->type)) {
  727. // dequantize to f32 -> RoPE -> quantize back
  728. tmp = ggml_cast(ctx, cur, GGML_TYPE_F32);
  729. tmp = ggml_rope_ext(ctx, tmp,
  730. shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  731. yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
  732. tmp = ggml_cpy(ctx, tmp, cur);
  733. } else {
  734. // we rotate only the first n_rot dimensions
  735. tmp = ggml_rope_ext_inplace(ctx, cur,
  736. shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  737. yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
  738. }
  739. return tmp;
  740. }
  741. class llm_graph_input_k_shift : public llm_graph_input_i {
  742. public:
  743. llm_graph_input_k_shift(const llama_kv_cache_unified * kv_self) : kv_self(kv_self) {}
  744. virtual ~llm_graph_input_k_shift() = default;
  745. void set_input(const llama_ubatch * ubatch) override;
  746. ggml_tensor * k_shift; // I32 [kv_size]
  747. const llama_kv_cache_unified * kv_self;
  748. };
  749. void llm_graph_input_k_shift::set_input(const llama_ubatch * ubatch) {
  750. GGML_UNUSED(ubatch);
  751. if (k_shift) {
  752. kv_self->set_input_k_shift(k_shift);
  753. }
  754. }
  755. llm_graph_result_ptr llama_kv_cache_unified::build_graph_shift(
  756. const llama_cparams & cparams,
  757. ggml_context * ctx,
  758. ggml_cgraph * gf) const {
  759. auto res = std::make_unique<llm_graph_result>();
  760. const auto & n_embd_head_k = hparams.n_embd_head_k;
  761. //const auto & n_embd_head_v = hparams.n_embd_head_v;
  762. auto inp = std::make_unique<llm_graph_input_k_shift>(this);
  763. inp->k_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, cells.size());
  764. ggml_set_input(inp->k_shift);
  765. for (const auto & layer : layers) {
  766. const uint32_t il = layer.il;
  767. const int64_t n_head_kv = hparams.n_head_kv(il);
  768. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  769. const float freq_base_l = model.get_rope_freq_base (cparams, il);
  770. const float freq_scale_l = model.get_rope_freq_scale(cparams, il);
  771. ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);
  772. ggml_tensor * k =
  773. ggml_view_3d(ctx, layer.k,
  774. n_embd_head_k, n_head_kv, cells.size(),
  775. ggml_row_size(layer.k->type, n_embd_head_k),
  776. ggml_row_size(layer.k->type, n_embd_k_gqa),
  777. 0);
  778. ggml_tensor * cur = build_rope_shift(cparams, ctx, k, inp->k_shift, rope_factors, freq_base_l, freq_scale_l);
  779. ggml_build_forward_expand(gf, cur);
  780. }
  781. res->add_input(std::move(inp));
  782. return res;
  783. }
  784. llm_graph_result_ptr llama_kv_cache_unified::build_graph_defrag(
  785. const llama_cparams & cparams,
  786. ggml_context * ctx,
  787. ggml_cgraph * gf,
  788. const defrag_info & dinfo) const {
  789. auto res = std::make_unique<llm_graph_result>();
  790. const auto & ids = dinfo.ids;
  791. #if 0
  792. // CPU defrag
  793. //
  794. // TODO: optimizations are possible:
  795. // - multiple threads
  796. // - avoid copying to the host memory when already there
  797. //
  798. // likely not worth the effort, as we have ggml_graph based defrag
  799. //
  800. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  801. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  802. const uint32_t kv_size = size;
  803. std::vector<uint8_t> buf_k;
  804. std::vector<uint8_t> buf_v;
  805. for (uint32_t il = 0; il < n_layer; ++il) {
  806. const size_t k_size_row = ggml_row_size(k_l[il]->type, n_embd_k_gqa);
  807. const size_t k_size = ggml_row_size(k_l[il]->type, n_embd_k_gqa*kv_size);
  808. const size_t v_size_el = ggml_type_size(v_l[il]->type);
  809. const size_t v_size = ggml_row_size (v_l[il]->type, n_embd_v_gqa*kv_size);
  810. buf_k.resize(k_size);
  811. buf_v.resize(v_size);
  812. ggml_backend_tensor_get(k_l[il], buf_k.data(), 0, buf_k.size());
  813. ggml_backend_tensor_get(v_l[il], buf_v.data(), 0, buf_v.size());
  814. // batch move [i, i+nm) to [id, id+nm)
  815. // note: cells can move only to a lower index
  816. for (uint32_t i = 0; i < n_kv; ++i) {
  817. const uint32_t id = ids[i];
  818. if (i == id || id == n_kv) {
  819. continue;
  820. }
  821. uint32_t nm = 1;
  822. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  823. nm++;
  824. }
  825. // move keys
  826. {
  827. const int64_t os = i*k_size_row;
  828. const int64_t od = id*k_size_row;
  829. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  830. }
  831. // move values (note: they are transposed)
  832. {
  833. const int64_t os = i;
  834. const int64_t od = id;
  835. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  836. 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);
  837. }
  838. }
  839. i += nm - 1;
  840. }
  841. ggml_backend_tensor_set(k_l[il], buf_k.data(), 0, buf_k.size());
  842. ggml_backend_tensor_set(v_l[il], buf_v.data(), 0, buf_v.size());
  843. }
  844. #else
  845. for (uint32_t i = 0; i < ids.size(); ++i) {
  846. const uint32_t id = ids[i];
  847. if (i == id || id == ids.size()) {
  848. continue;
  849. }
  850. uint32_t nm = 1;
  851. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  852. nm++;
  853. }
  854. for (const auto & layer : layers) {
  855. const uint32_t il = layer.il;
  856. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  857. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  858. ggml_tensor * view_k_src = ggml_view_2d(ctx, layer.k,
  859. n_embd_k_gqa, nm,
  860. ggml_row_size(layer.k->type, n_embd_k_gqa),
  861. ggml_row_size(layer.k->type, n_embd_k_gqa*i));
  862. ggml_tensor * view_k_dst = ggml_view_2d(ctx, layer.k,
  863. n_embd_k_gqa, nm,
  864. ggml_row_size(layer.k->type, n_embd_k_gqa),
  865. ggml_row_size(layer.k->type, n_embd_k_gqa*id));
  866. ggml_tensor * view_v_src;
  867. ggml_tensor * view_v_dst;
  868. if (cparams.flash_attn) {
  869. // NOTE: the V cache is not transposed when using flash attention
  870. view_v_src = ggml_view_2d(ctx, layer.v,
  871. n_embd_v_gqa, nm,
  872. ggml_row_size(layer.v->type, n_embd_v_gqa),
  873. ggml_row_size(layer.v->type, n_embd_v_gqa*i));
  874. view_v_dst = ggml_view_2d(ctx, layer.v,
  875. n_embd_v_gqa, nm,
  876. ggml_row_size(layer.v->type, n_embd_v_gqa),
  877. ggml_row_size(layer.v->type, n_embd_v_gqa*id));
  878. } else {
  879. view_v_src = ggml_view_2d(ctx, layer.v,
  880. nm, n_embd_v_gqa,
  881. ggml_row_size(layer.v->type, cells.size()),
  882. ggml_row_size(layer.v->type, i));
  883. view_v_dst = ggml_view_2d(ctx, layer.v,
  884. nm, n_embd_v_gqa,
  885. ggml_row_size(layer.v->type, cells.size()),
  886. ggml_row_size(layer.v->type, id));
  887. }
  888. ggml_build_forward_expand(gf, ggml_cpy(ctx, view_k_src, view_k_dst));
  889. ggml_build_forward_expand(gf, ggml_cpy(ctx, view_v_src, view_v_dst));
  890. }
  891. i += nm - 1;
  892. }
  893. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  894. #endif
  895. return res;
  896. }
  897. llama_kv_cache_unified::defrag_info llama_kv_cache_unified::defrag_prepare(int32_t n_max_nodes) const {
  898. const uint32_t n_layer = layers.size();
  899. const uint32_t n_kv = cells.used_max_p1();
  900. const uint32_t n_used = cells.get_used();
  901. assert(n_used <= n_kv);
  902. //const int64_t t_start = ggml_time_us();
  903. // number of cells moved
  904. uint32_t n_moves = 0;
  905. // each move requires 6*n_layer tensors (see graph_build_kv_self_defrag)
  906. // - source view, destination view, copy operation
  907. // - x2 for keys and values
  908. //const uint32_t max_moves = max_nodes()/(6*n_layer);
  909. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  910. const uint32_t max_moves = (n_max_nodes - 2*n_layer)/(6*n_layer);
  911. // determine which KV cells to move where
  912. defrag_info res;
  913. auto & ids = res.ids;
  914. ids.resize(n_kv, n_kv);
  915. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  916. if (!cells.is_empty(i0)) {
  917. ids[i0] = i0;
  918. continue;
  919. }
  920. // found a hole - fill it with data from the end of the cache
  921. uint32_t nh = 1;
  922. // determine the size of the hole
  923. while (i0 + nh < n_used && cells.is_empty(i0 + nh)) {
  924. nh++;
  925. }
  926. uint32_t nf = 0;
  927. uint32_t is = n_kv - 1;
  928. // starting from the end, find nh non-empty cells
  929. for (; is > i0; --is) {
  930. if (cells.is_empty(is) || ids[is] != n_kv) {
  931. continue;
  932. }
  933. // non-empty cell which is not yet moved
  934. nf++;
  935. if (nf == nh) {
  936. break;
  937. }
  938. }
  939. // this can only happen if `n_used` is not accurate, which would be a bug
  940. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  941. nf = 0;
  942. uint32_t i1 = is;
  943. // are we moving a continuous block of memory?
  944. bool cont = false;
  945. // should we stop searching for the next move?
  946. bool stop = false;
  947. // go back and move the nf cells to the hole
  948. for (; i1 < n_kv; ++i1) {
  949. if (cells.is_empty(i1) || ids[i1] != n_kv) {
  950. if (n_moves == max_moves) {
  951. stop = true;
  952. break;
  953. }
  954. cont = false;
  955. continue;
  956. }
  957. // this cell goes to (i0 + nf)
  958. ids[i1] = i0 + nf;
  959. if (!cont) {
  960. n_moves++;
  961. cont = true;
  962. }
  963. nf++;
  964. if (nf == nh) {
  965. break;
  966. }
  967. }
  968. if (stop || n_moves == max_moves) {
  969. break;
  970. }
  971. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  972. i0 += nh - 1;
  973. }
  974. if (n_moves == 0) {
  975. return {};
  976. }
  977. LLAMA_LOG_DEBUG("%s: (tmp log) KV defrag cell moves: %u\n", __func__, n_moves);
  978. LLAMA_LOG_DEBUG("%s: expected gf nodes: %u\n", __func__, 6*n_moves*n_layer);
  979. return res;
  980. }
  981. bool llama_kv_cache_unified::is_masked_swa(llama_pos p0, llama_pos p1) const {
  982. assert(p0 >= 0 && p1 >= 0);
  983. switch (swa_type) {
  984. case LLAMA_SWA_TYPE_NONE:
  985. {
  986. } break;
  987. case LLAMA_SWA_TYPE_STANDARD:
  988. {
  989. if (p1 - p0 >= (int32_t) n_swa) {
  990. return true;
  991. }
  992. } break;
  993. case LLAMA_SWA_TYPE_CHUNKED:
  994. {
  995. const llama_pos pos_chunk_start = (p1 / n_swa) * n_swa;
  996. if (p0 < pos_chunk_start) {
  997. return true;
  998. }
  999. } break;
  1000. }
  1001. return false;
  1002. }
  1003. void llama_kv_cache_unified::state_write(llama_io_write_i & io, llama_seq_id seq_id) const {
  1004. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  1005. uint32_t cell_count = 0;
  1006. // Count the number of cells with the specified seq_id
  1007. // Find all the ranges of cells with this seq id (or all, when -1)
  1008. uint32_t cell_range_begin = cells.size();
  1009. for (uint32_t i = 0; i < cells.size(); ++i) {
  1010. if (!cells.is_empty(i) && (seq_id == -1 || cells.seq_has(i, seq_id))) {
  1011. ++cell_count;
  1012. if (cell_range_begin == cells.size()) {
  1013. cell_range_begin = i;
  1014. }
  1015. } else {
  1016. if (cell_range_begin != cells.size()) {
  1017. cell_ranges.emplace_back(cell_range_begin, i);
  1018. cell_range_begin = cells.size();
  1019. }
  1020. }
  1021. }
  1022. if (cell_range_begin != cells.size()) {
  1023. cell_ranges.emplace_back(cell_range_begin, cells.size());
  1024. }
  1025. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  1026. uint32_t cell_count_check = 0;
  1027. for (const auto & range : cell_ranges) {
  1028. cell_count_check += range.second - range.first;
  1029. }
  1030. GGML_ASSERT(cell_count == cell_count_check);
  1031. io.write(&cell_count, sizeof(cell_count));
  1032. state_write_meta(io, cell_ranges, seq_id);
  1033. state_write_data(io, cell_ranges);
  1034. }
  1035. void llama_kv_cache_unified::state_read(llama_io_read_i & io, llama_seq_id seq_id) {
  1036. uint32_t cell_count;
  1037. io.read_to(&cell_count, sizeof(cell_count));
  1038. bool res = true;
  1039. res = res && state_read_meta(io, cell_count, seq_id);
  1040. res = res && state_read_data(io, cell_count);
  1041. if (!res) {
  1042. if (seq_id == -1) {
  1043. clear(true);
  1044. } else {
  1045. seq_rm(seq_id, -1, -1);
  1046. }
  1047. throw std::runtime_error("failed to restore kv cache");
  1048. }
  1049. }
  1050. void llama_kv_cache_unified::state_write_meta(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges, llama_seq_id seq_id) const {
  1051. for (const auto & range : cell_ranges) {
  1052. for (uint32_t i = range.first; i < range.second; ++i) {
  1053. std::vector<llama_seq_id> seq_ids;
  1054. for (llama_seq_id cur = 0; cur < (int) n_seq_max; ++cur) {
  1055. if (cur == seq_id || seq_id == -1) {
  1056. if (cells.seq_has(i, cur)) {
  1057. seq_ids.push_back(cur);
  1058. }
  1059. }
  1060. }
  1061. const llama_pos pos = cells.pos_get(i);
  1062. const uint32_t n_seq_id = seq_ids.size();
  1063. io.write(&pos, sizeof(pos));
  1064. io.write(&n_seq_id, sizeof(n_seq_id));
  1065. for (const auto & seq_id : seq_ids) {
  1066. io.write(&seq_id, sizeof(seq_id));
  1067. }
  1068. }
  1069. }
  1070. }
  1071. void llama_kv_cache_unified::state_write_data(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) const {
  1072. const uint32_t v_trans = this->v_trans ? 1 : 0;
  1073. const uint32_t n_layer = layers.size();
  1074. io.write(&v_trans, sizeof(v_trans));
  1075. io.write(&n_layer, sizeof(n_layer));
  1076. std::vector<uint8_t> tmp_buf;
  1077. // Iterate and write all the keys first, each row is a cell
  1078. // Get whole range at a time
  1079. for (const auto & layer : layers) {
  1080. const uint32_t il = layer.il;
  1081. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  1082. // Write key type
  1083. const int32_t k_type_i = (int32_t)layer.k->type;
  1084. io.write(&k_type_i, sizeof(k_type_i));
  1085. // Write row size of key
  1086. const uint64_t k_size_row = ggml_row_size(layer.k->type, n_embd_k_gqa);
  1087. io.write(&k_size_row, sizeof(k_size_row));
  1088. // Read each range of cells of k_size length each into tmp_buf and write out
  1089. for (const auto & range : cell_ranges) {
  1090. const size_t range_size = range.second - range.first;
  1091. const size_t buf_size = range_size * k_size_row;
  1092. io.write_tensor(layer.k, range.first * k_size_row, buf_size);
  1093. }
  1094. }
  1095. if (!v_trans) {
  1096. for (const auto & layer : layers) {
  1097. const uint32_t il = layer.il;
  1098. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  1099. // Write value type
  1100. const int32_t v_type_i = (int32_t)layer.v->type;
  1101. io.write(&v_type_i, sizeof(v_type_i));
  1102. // Write row size of value
  1103. const uint64_t v_size_row = ggml_row_size(layer.v->type, n_embd_v_gqa);
  1104. io.write(&v_size_row, sizeof(v_size_row));
  1105. // Read each range of cells of v_size length each into tmp_buf and write out
  1106. for (const auto & range : cell_ranges) {
  1107. const size_t range_size = range.second - range.first;
  1108. const size_t buf_size = range_size * v_size_row;
  1109. io.write_tensor(layer.v, range.first * v_size_row, buf_size);
  1110. }
  1111. }
  1112. } else {
  1113. // When v is transposed, we also need the element size and get the element ranges from each row
  1114. const uint32_t kv_size = cells.size();
  1115. for (const auto & layer : layers) {
  1116. const uint32_t il = layer.il;
  1117. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  1118. // Write value type
  1119. const int32_t v_type_i = (int32_t)layer.v->type;
  1120. io.write(&v_type_i, sizeof(v_type_i));
  1121. // Write element size
  1122. const uint32_t v_size_el = ggml_type_size(layer.v->type);
  1123. io.write(&v_size_el, sizeof(v_size_el));
  1124. // Write GQA embedding size
  1125. io.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  1126. // For each row, we get the element values of each cell
  1127. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1128. // Read each range of cells of v_size_el length each into tmp_buf and write out
  1129. for (const auto & range : cell_ranges) {
  1130. const size_t range_size = range.second - range.first;
  1131. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  1132. const size_t buf_size = range_size * v_size_el;
  1133. io.write_tensor(layer.v, src_offset, buf_size);
  1134. }
  1135. }
  1136. }
  1137. }
  1138. }
  1139. bool llama_kv_cache_unified::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
  1140. if (dest_seq_id != -1) {
  1141. // single sequence
  1142. seq_rm(dest_seq_id, -1, -1);
  1143. llama_sbatch sbatch;
  1144. llama_ubatch batch = sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  1145. batch.n_tokens = cell_count;
  1146. for (uint32_t i = 0; i < cell_count; ++i) {
  1147. llama_pos pos;
  1148. uint32_t n_seq_id;
  1149. io.read_to(&pos, sizeof(pos));
  1150. io.read_to(&n_seq_id, sizeof(n_seq_id));
  1151. if (n_seq_id != 1) {
  1152. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  1153. return false;
  1154. }
  1155. // read the sequence id, but directly discard it - we will use dest_seq_id instead
  1156. {
  1157. llama_seq_id seq_id;
  1158. io.read_to(&seq_id, sizeof(seq_id));
  1159. }
  1160. batch.pos[i] = pos;
  1161. batch.n_seq_id[i] = n_seq_id;
  1162. batch.seq_id[i] = &dest_seq_id;
  1163. }
  1164. const auto head_cur = find_slot(batch);
  1165. if (head_cur < 0) {
  1166. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  1167. return false;
  1168. }
  1169. apply_ubatch(head_cur, batch);
  1170. // keep the head at the old position because we will read the KV data into it in state_read_data()
  1171. head = head_cur;
  1172. // 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)
  1173. // Assume that this is one contiguous block of cells
  1174. GGML_ASSERT(head_cur + cell_count <= cells.size());
  1175. GGML_ASSERT(cells.pos_get(head_cur) == batch.pos[0]);
  1176. GGML_ASSERT(cells.pos_get(head_cur + cell_count - 1) == batch.pos[cell_count - 1]);
  1177. GGML_ASSERT(cells.seq_has(head_cur, dest_seq_id));
  1178. GGML_ASSERT(cells.seq_has(head_cur + cell_count - 1, dest_seq_id));
  1179. } else {
  1180. // whole KV cache restore
  1181. if (cell_count > cells.size()) {
  1182. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  1183. return false;
  1184. }
  1185. clear(true);
  1186. for (uint32_t i = 0; i < cell_count; ++i) {
  1187. llama_pos pos;
  1188. uint32_t n_seq_id;
  1189. io.read_to(&pos, sizeof(pos));
  1190. io.read_to(&n_seq_id, sizeof(n_seq_id));
  1191. cells.pos_set(i, pos);
  1192. for (uint32_t j = 0; j < n_seq_id; ++j) {
  1193. llama_seq_id seq_id;
  1194. io.read_to(&seq_id, sizeof(seq_id));
  1195. if (seq_id < 0 || (uint32_t) seq_id >= n_seq_max) {
  1196. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, n_seq_max);
  1197. return false;
  1198. }
  1199. cells.seq_add(i, seq_id);
  1200. }
  1201. }
  1202. head = 0;
  1203. }
  1204. return true;
  1205. }
  1206. bool llama_kv_cache_unified::state_read_data(llama_io_read_i & io, uint32_t cell_count) {
  1207. uint32_t v_trans;
  1208. uint32_t n_layer;
  1209. io.read_to(&v_trans, sizeof(v_trans));
  1210. io.read_to(&n_layer, sizeof(n_layer));
  1211. if (n_layer != layers.size()) {
  1212. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, (uint32_t) layers.size());
  1213. return false;
  1214. }
  1215. if (cell_count > cells.size()) {
  1216. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, cells.size());
  1217. return false;
  1218. }
  1219. if (this->v_trans != (bool) v_trans) {
  1220. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  1221. return false;
  1222. }
  1223. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  1224. for (const auto & layer : layers) {
  1225. const uint32_t il = layer.il;
  1226. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  1227. // Read type of key
  1228. int32_t k_type_i_ref;
  1229. io.read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  1230. const int32_t k_type_i = (int32_t) layer.k->type;
  1231. if (k_type_i != k_type_i_ref) {
  1232. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  1233. return false;
  1234. }
  1235. // Read row size of key
  1236. uint64_t k_size_row_ref;
  1237. io.read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  1238. const size_t k_size_row = ggml_row_size(layer.k->type, n_embd_k_gqa);
  1239. if (k_size_row != k_size_row_ref) {
  1240. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  1241. return false;
  1242. }
  1243. if (cell_count) {
  1244. // Read and set the keys for the whole cell range
  1245. ggml_backend_tensor_set(layer.k, io.read(cell_count * k_size_row), head * k_size_row, cell_count * k_size_row);
  1246. }
  1247. }
  1248. if (!this->v_trans) {
  1249. for (const auto & layer : layers) {
  1250. const uint32_t il = layer.il;
  1251. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  1252. // Read type of value
  1253. int32_t v_type_i_ref;
  1254. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1255. const int32_t v_type_i = (int32_t)layer.v->type;
  1256. if (v_type_i != v_type_i_ref) {
  1257. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1258. return false;
  1259. }
  1260. // Read row size of value
  1261. uint64_t v_size_row_ref;
  1262. io.read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  1263. const size_t v_size_row = ggml_row_size(layer.v->type, n_embd_v_gqa);
  1264. if (v_size_row != v_size_row_ref) {
  1265. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  1266. return false;
  1267. }
  1268. if (cell_count) {
  1269. // Read and set the values for the whole cell range
  1270. ggml_backend_tensor_set(layer.v, io.read(cell_count * v_size_row), head * v_size_row, cell_count * v_size_row);
  1271. }
  1272. }
  1273. } else {
  1274. // For each layer, read the values for each cell (transposed)
  1275. for (const auto & layer : layers) {
  1276. const uint32_t il = layer.il;
  1277. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  1278. // Read type of value
  1279. int32_t v_type_i_ref;
  1280. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1281. const int32_t v_type_i = (int32_t)layer.v->type;
  1282. if (v_type_i != v_type_i_ref) {
  1283. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1284. return false;
  1285. }
  1286. // Read element size of value
  1287. uint32_t v_size_el_ref;
  1288. io.read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  1289. const size_t v_size_el = ggml_type_size(layer.v->type);
  1290. if (v_size_el != v_size_el_ref) {
  1291. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  1292. return false;
  1293. }
  1294. // Read GQA embedding size
  1295. uint32_t n_embd_v_gqa_ref;
  1296. io.read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  1297. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  1298. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  1299. return false;
  1300. }
  1301. if (cell_count) {
  1302. // For each row in the transposed matrix, read the values for the whole cell range
  1303. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1304. const size_t dst_offset = (head + j * cells.size()) * v_size_el;
  1305. ggml_backend_tensor_set(layer.v, io.read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  1306. }
  1307. }
  1308. }
  1309. }
  1310. return true;
  1311. }
  1312. //
  1313. // llama_kv_cache_unified_state
  1314. //
  1315. llama_kv_cache_unified_state::llama_kv_cache_unified_state(llama_memory_status status) : status(status) {}
  1316. llama_kv_cache_unified_state::llama_kv_cache_unified_state(
  1317. llama_kv_cache_unified * kv) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv) {
  1318. n_kv = kv->get_size();
  1319. head = 0;
  1320. }
  1321. llama_kv_cache_unified_state::llama_kv_cache_unified_state(
  1322. llama_kv_cache_unified * kv,
  1323. llama_context * lctx,
  1324. bool do_shift,
  1325. defrag_info dinfo) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), lctx(lctx), do_shift(do_shift), dinfo(std::move(dinfo)) {
  1326. if (!do_shift && dinfo.empty()) {
  1327. status = LLAMA_MEMORY_STATUS_NO_UPDATE;
  1328. }
  1329. }
  1330. llama_kv_cache_unified_state::llama_kv_cache_unified_state(
  1331. llama_kv_cache_unified * kv,
  1332. llama_sbatch sbatch,
  1333. llama_kv_cache_unified::ubatch_heads heads,
  1334. std::vector<llama_ubatch> ubatches) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), sbatch(std::move(sbatch)), heads(std::move(heads)), ubatches(std::move(ubatches)) {
  1335. }
  1336. llama_kv_cache_unified_state::~llama_kv_cache_unified_state() = default;
  1337. bool llama_kv_cache_unified_state::next() {
  1338. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1339. if (++i_next >= ubatches.size()) {
  1340. return false;
  1341. }
  1342. return true;
  1343. }
  1344. bool llama_kv_cache_unified_state::apply() {
  1345. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1346. // no ubatches -> this is a KV cache update
  1347. if (ubatches.empty()) {
  1348. kv->update(lctx, do_shift, dinfo);
  1349. return true;
  1350. }
  1351. kv->apply_ubatch(heads[i_next], ubatches[i_next]);
  1352. n_kv = kv->get_n_kv();
  1353. head = heads[i_next];
  1354. return true;
  1355. }
  1356. std::vector<int64_t> & llama_kv_cache_unified_state::out_ids() {
  1357. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1358. return sbatch.out_ids;
  1359. }
  1360. llama_memory_status llama_kv_cache_unified_state::get_status() const {
  1361. return status;
  1362. }
  1363. const llama_ubatch & llama_kv_cache_unified_state::get_ubatch() const {
  1364. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1365. return ubatches[i_next];
  1366. }
  1367. uint32_t llama_kv_cache_unified_state::get_n_kv() const {
  1368. return n_kv;
  1369. }
  1370. ggml_tensor * llama_kv_cache_unified_state::get_k(ggml_context * ctx, int32_t il) const {
  1371. return kv->get_k(ctx, il, n_kv);
  1372. }
  1373. ggml_tensor * llama_kv_cache_unified_state::get_v(ggml_context * ctx, int32_t il) const {
  1374. return kv->get_v(ctx, il, n_kv);
  1375. }
  1376. ggml_tensor * llama_kv_cache_unified_state::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, int32_t il) const {
  1377. return kv->cpy_k(ctx, k_cur, il, head);
  1378. }
  1379. ggml_tensor * llama_kv_cache_unified_state::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, int32_t il) const {
  1380. return kv->cpy_v(ctx, v_cur, il, head);
  1381. }
  1382. void llama_kv_cache_unified_state::set_input_k_shift(ggml_tensor * dst) const {
  1383. kv->set_input_k_shift(dst);
  1384. }
  1385. void llama_kv_cache_unified_state::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
  1386. kv->set_input_kq_mask(dst, ubatch, causal_attn);
  1387. }
  1388. void llama_kv_cache_unified_state::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1389. kv->set_input_pos_bucket(dst, ubatch);
  1390. }
  1391. uint32_t llama_kv_cache_unified::get_padding(const llama_cparams & cparams) {
  1392. // the FA kernels require padding to avoid extra runtime boundary checks
  1393. return cparams.flash_attn ? 256u : 32u;
  1394. }