llama-kv-cache.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  1. #include "llama-kv-cache.h"
  2. #include "llama-impl.h"
  3. #include "llama-batch.h"
  4. #include "llama-cparams.h"
  5. #include "llama-model.h"
  6. #include <algorithm>
  7. #include <cassert>
  8. #include <limits>
  9. #include <map>
  10. #include <stdexcept>
  11. llama_kv_cache_unified::llama_kv_cache_unified(const llama_hparams & hparams, callbacks cbs) : hparams(hparams), cbs(std::move(cbs)) {
  12. }
  13. bool llama_kv_cache_unified::init(
  14. const llama_model & model,
  15. const llama_cparams & cparams,
  16. ggml_type type_k,
  17. ggml_type type_v,
  18. uint32_t kv_size,
  19. bool offload) {
  20. const int32_t n_layer = hparams.n_layer;
  21. has_shift = false;
  22. recurrent = llama_model_is_recurrent(&model);
  23. v_trans = !recurrent && !cparams.flash_attn;
  24. can_shift = !recurrent && model.arch != LLM_ARCH_DEEPSEEK2; // not supported due to MLA
  25. LLAMA_LOG_INFO("%s: kv_size = %d, offload = %d, type_k = '%s', type_v = '%s', n_layer = %d, can_shift = %d\n",
  26. __func__, kv_size, offload, ggml_type_name(type_k), ggml_type_name(type_v), n_layer, can_shift);
  27. head = 0;
  28. size = kv_size;
  29. used = 0;
  30. this->type_k = type_k;
  31. this->type_v = type_v;
  32. cells.clear();
  33. cells.resize(kv_size);
  34. // create a context for each buffer type
  35. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  36. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  37. auto it = ctx_map.find(buft);
  38. if (it == ctx_map.end()) {
  39. ggml_init_params params = {
  40. /*.mem_size =*/ size_t(2u*n_layer*ggml_tensor_overhead()),
  41. /*.mem_buffer =*/ NULL,
  42. /*.no_alloc =*/ true,
  43. };
  44. ggml_context * ctx = ggml_init(params);
  45. if (!ctx) {
  46. return nullptr;
  47. }
  48. ctx_map[buft] = ctx;
  49. ctxs.emplace_back(ctx);
  50. return ctx;
  51. }
  52. return it->second;
  53. };
  54. k_l.reserve(n_layer);
  55. v_l.reserve(n_layer);
  56. for (int i = 0; i < n_layer; i++) {
  57. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  58. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  59. const char * dev_name = "CPU";
  60. ggml_backend_buffer_type_t buft;
  61. if (offload) {
  62. auto * dev = model.dev_layer(i);
  63. buft = ggml_backend_dev_buffer_type(dev);
  64. dev_name = ggml_backend_dev_name(dev);
  65. } else {
  66. buft = ggml_backend_cpu_buffer_type();
  67. }
  68. LLAMA_LOG_DEBUG("%s: layer %3d: n_embd_k_gqa = %d, n_embd_v_gqa = %d, dev = %s\n", __func__,
  69. i, n_embd_k_gqa, n_embd_v_gqa, dev_name);
  70. ggml_context * ctx = ctx_for_buft(buft);
  71. if (!ctx) {
  72. LLAMA_LOG_ERROR("%s: failed to create ggml context for kv cache\n", __func__);
  73. return false;
  74. }
  75. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  76. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  77. ggml_format_name(k, "cache_k_l%d", i);
  78. ggml_format_name(v, "cache_v_l%d", i);
  79. k_l.push_back(k);
  80. v_l.push_back(v);
  81. }
  82. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  83. for (auto it : ctx_map) {
  84. auto * buft = it.first;
  85. auto * ctx = it.second;
  86. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  87. if (!buf) {
  88. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  89. return false;
  90. }
  91. ggml_backend_buffer_clear(buf, 0);
  92. 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);
  93. bufs.emplace_back(buf);
  94. }
  95. return true;
  96. }
  97. int32_t llama_kv_cache_unified::get_n_tokens() const {
  98. int32_t result = 0;
  99. for (uint32_t i = 0; i < size; i++) {
  100. result += cells[i].seq_id.size();
  101. }
  102. return result;
  103. }
  104. uint32_t llama_kv_cache_unified::get_used_cells() const {
  105. return used;
  106. }
  107. size_t llama_kv_cache_unified::total_size() const {
  108. size_t size = 0;
  109. for (const auto & buf : bufs) {
  110. size += ggml_backend_buffer_get_size(buf.get());
  111. }
  112. return size;
  113. }
  114. llama_pos llama_kv_cache_unified::pos_max() const {
  115. llama_pos pos_max = -1;
  116. for (const auto & cell : cells) {
  117. pos_max = std::max(pos_max, cell.pos);
  118. }
  119. return pos_max;
  120. }
  121. void llama_kv_cache_unified::clear() {
  122. for (int32_t i = 0; i < (int32_t) size; ++i) {
  123. cells[i].pos = -1;
  124. cells[i].seq_id.clear();
  125. cells[i].src = -1;
  126. cells[i].tail = -1;
  127. }
  128. head = 0;
  129. used = 0;
  130. for (auto & buf : bufs) {
  131. ggml_backend_buffer_clear(buf.get(), 0);
  132. }
  133. }
  134. bool llama_kv_cache_unified::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  135. uint32_t new_head = size;
  136. if (p0 < 0) {
  137. p0 = 0;
  138. }
  139. if (p1 < 0) {
  140. p1 = std::numeric_limits<llama_pos>::max();
  141. }
  142. // models like Mamba or RWKV can't have a state partially erased
  143. if (recurrent) {
  144. if (seq_id >= (int64_t) size) {
  145. // could be fatal
  146. return false;
  147. }
  148. if (0 <= seq_id) {
  149. int32_t & tail_id = cells[seq_id].tail;
  150. if (tail_id >= 0) {
  151. const llama_kv_cell & cell = cells[tail_id];
  152. // partial intersection is invalid
  153. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  154. return false;
  155. }
  156. // invalidate tails which will be cleared
  157. if (p0 <= cell.pos && cell.pos < p1) {
  158. tail_id = -1;
  159. }
  160. }
  161. } else {
  162. // seq_id is negative, then the range should include everything or nothing
  163. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  164. return false;
  165. }
  166. }
  167. return true;
  168. }
  169. for (uint32_t i = 0; i < size; ++i) {
  170. if (cells[i].pos >= p0 && cells[i].pos < p1) {
  171. if (seq_id < 0) {
  172. cells[i].seq_id.clear();
  173. } else if (cells[i].has_seq_id(seq_id)) {
  174. cells[i].seq_id.erase(seq_id);
  175. } else {
  176. continue;
  177. }
  178. if (cells[i].is_empty()) {
  179. // keep count of the number of used cells
  180. if (cells[i].pos >= 0) {
  181. used--;
  182. }
  183. cells[i].pos = -1;
  184. cells[i].src = -1;
  185. if (new_head == size) {
  186. new_head = i;
  187. }
  188. }
  189. }
  190. }
  191. // If we freed up a slot, set head to it so searching can start there.
  192. if (new_head != size && new_head < head) {
  193. head = new_head;
  194. }
  195. return true;
  196. }
  197. 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) {
  198. if (seq_id_src == seq_id_dst) {
  199. return;
  200. }
  201. if (p0 < 0) {
  202. p0 = 0;
  203. }
  204. if (p1 < 0) {
  205. p1 = std::numeric_limits<llama_pos>::max();
  206. }
  207. if (recurrent) {
  208. if ((uint32_t) seq_id_dst < size && (uint32_t) seq_id_src < size) {
  209. llama_kv_cell & tail_src = cells[seq_id_src];
  210. llama_kv_cell & tail_dst = cells[seq_id_dst];
  211. if (tail_dst.tail >= 0) {
  212. // clear destination seq_id if it wasn't empty
  213. llama_kv_cell & cell_dst = cells[tail_dst.tail];
  214. cell_dst.seq_id.erase(seq_id_dst);
  215. tail_dst.tail = -1;
  216. if (cell_dst.seq_id.empty()) {
  217. cell_dst.pos = -1;
  218. cell_dst.delta = -1;
  219. cell_dst.src = -1;
  220. used -= 1;
  221. }
  222. }
  223. if (tail_src.tail >= 0) {
  224. llama_kv_cell & cell_src = cells[tail_src.tail];
  225. cell_src.seq_id.insert(seq_id_dst);
  226. tail_dst.tail = tail_src.tail;
  227. }
  228. }
  229. return;
  230. }
  231. // otherwise, this is the KV of a Transformer-like model
  232. head = 0;
  233. for (uint32_t i = 0; i < size; ++i) {
  234. if (cells[i].has_seq_id(seq_id_src) && cells[i].pos >= p0 && cells[i].pos < p1) {
  235. cells[i].seq_id.insert(seq_id_dst);
  236. }
  237. }
  238. }
  239. void llama_kv_cache_unified::seq_keep(llama_seq_id seq_id) {
  240. uint32_t new_head = size;
  241. for (uint32_t i = 0; i < size; ++i) {
  242. if (recurrent && (llama_seq_id) i != seq_id) {
  243. cells[i].tail = -1;
  244. }
  245. if (!cells[i].has_seq_id(seq_id)) {
  246. if (cells[i].pos >= 0) {
  247. used--;
  248. }
  249. cells[i].pos = -1;
  250. cells[i].src = -1;
  251. cells[i].seq_id.clear();
  252. if (new_head == size){
  253. new_head = i;
  254. }
  255. } else {
  256. cells[i].seq_id.clear();
  257. cells[i].seq_id.insert(seq_id);
  258. }
  259. }
  260. // If we freed up a slot, set head to it so searching can start there.
  261. if (new_head != size && new_head < head) {
  262. head = new_head;
  263. }
  264. }
  265. void llama_kv_cache_unified::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  266. if (delta == 0) {
  267. return;
  268. }
  269. uint32_t new_head = size;
  270. if (p0 < 0) {
  271. p0 = 0;
  272. }
  273. if (p1 < 0) {
  274. p1 = std::numeric_limits<llama_pos>::max();
  275. }
  276. // If there is no range then return early to avoid looping over the
  277. if (p0 == p1) {
  278. return;
  279. }
  280. if (recurrent) {
  281. // for Mamba-like or RWKV models, only the pos needs to be shifted
  282. if (0 <= seq_id && seq_id < (int64_t) size) {
  283. const int32_t tail_id = cells[seq_id].tail;
  284. if (tail_id >= 0) {
  285. llama_kv_cell & cell = cells[tail_id];
  286. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  287. cell.pos += delta;
  288. }
  289. }
  290. }
  291. return;
  292. }
  293. for (uint32_t i = 0; i < size; ++i) {
  294. if (cells[i].has_seq_id(seq_id) && cells[i].pos >= p0 && cells[i].pos < p1) {
  295. has_shift = true;
  296. cells[i].pos += delta;
  297. cells[i].delta += delta;
  298. if (cells[i].pos < 0) {
  299. if (!cells[i].is_empty()) {
  300. used--;
  301. }
  302. cells[i].pos = -1;
  303. cells[i].seq_id.clear();
  304. if (new_head == size) {
  305. new_head = i;
  306. }
  307. }
  308. }
  309. }
  310. // If we freed up a slot, set head to it so searching can start there.
  311. // Otherwise we just start the next search from the beginning.
  312. head = new_head != size ? new_head : 0;
  313. }
  314. void llama_kv_cache_unified::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  315. if (d == 1) {
  316. return;
  317. }
  318. if (p0 < 0) {
  319. p0 = 0;
  320. }
  321. if (p1 < 0) {
  322. p1 = std::numeric_limits<llama_pos>::max();
  323. }
  324. // If there is no range then return early to avoid looping over the cache.
  325. if (p0 == p1) {
  326. return;
  327. }
  328. if (recurrent) {
  329. // for Mamba-like or RWKV models, only the pos needs to be changed
  330. if (0 <= seq_id && seq_id < (int64_t) size) {
  331. const int32_t tail_id = cells[seq_id].tail;
  332. if (tail_id >= 0) {
  333. llama_kv_cell & cell = cells[tail_id];
  334. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  335. cell.pos /= d;
  336. }
  337. }
  338. }
  339. return;
  340. }
  341. for (uint32_t i = 0; i < size; ++i) {
  342. if (cells[i].has_seq_id(seq_id) && cells[i].pos >= p0 && cells[i].pos < p1) {
  343. has_shift = true;
  344. {
  345. llama_pos p_old = cells[i].pos;
  346. cells[i].pos /= d;
  347. cells[i].delta += cells[i].pos - p_old;
  348. }
  349. }
  350. }
  351. }
  352. llama_pos llama_kv_cache_unified::seq_pos_max(llama_seq_id seq_id) {
  353. llama_pos result = 0;
  354. for (uint32_t i = 0; i < size; ++i) {
  355. if (cells[i].has_seq_id(seq_id)) {
  356. result = std::max(result, cells[i].pos);
  357. }
  358. }
  359. return result;
  360. }
  361. void llama_kv_cache_unified::defrag() {
  362. if (!recurrent) {
  363. do_defrag = true;
  364. }
  365. }
  366. void llama_kv_cache_unified::restore() {
  367. if (pending.ranges.empty()) {
  368. return;
  369. }
  370. // TODO: tmp - move to llama_kv_cache_recurrent
  371. if (recurrent) {
  372. seq_rm(-1, -1, -1);
  373. return;
  374. }
  375. uint32_t new_head = size;
  376. for (auto & range : pending.ranges) {
  377. for (uint32_t i = range.c0; i < range.c1; ++i) {
  378. cells[i].seq_id.clear();
  379. // keep count of the number of used cells
  380. if (cells[i].pos >= 0) {
  381. used--;
  382. }
  383. cells[i].pos = -1;
  384. cells[i].src = -1;
  385. }
  386. new_head = std::min(new_head, range.c0);
  387. }
  388. if (new_head != size && new_head < head) {
  389. head = new_head;
  390. }
  391. }
  392. void llama_kv_cache_unified::commit() {
  393. if (pending.ranges.empty()) {
  394. LLAMA_LOG_WARN("%s: no pending KV cache updates to commit - might indicate a bug (ref: %s)\n",
  395. __func__, "https://github.com/ggml-org/llama.cpp/pull/12695");
  396. return;
  397. }
  398. pending.ranges.clear();
  399. }
  400. bool llama_kv_cache_unified::get_can_shift() const {
  401. return can_shift;
  402. }
  403. bool llama_kv_cache_unified::find_slot(
  404. const llama_ubatch & ubatch) {
  405. const uint32_t n_tokens = ubatch.n_tokens;
  406. const uint32_t n_seqs = ubatch.n_seqs;
  407. const uint32_t n_seq_tokens = ubatch.n_seq_tokens;
  408. // if we have enough unused cells before the current head ->
  409. // better to start searching from the beginning of the cache, hoping to fill it
  410. if (head > used + 2*ubatch.n_tokens) {
  411. head = 0;
  412. }
  413. if (recurrent) {
  414. // For recurrent state architectures (like Mamba or RWKV),
  415. // each cache cell can store the state for a whole sequence.
  416. // A slot should be always be contiguous.
  417. // can only process batches with an equal number of new tokens in each sequence
  418. GGML_ASSERT(ubatch.equal_seqs);
  419. int32_t min = size - 1;
  420. int32_t max = 0;
  421. // everything should fit if all seq_ids are smaller than the max
  422. for (uint32_t s = 0; s < n_seqs; ++s) {
  423. const uint32_t n_seq_id = ubatch.n_seq_id[s];
  424. for (uint32_t j = 0; j < n_seq_id; ++j) {
  425. const llama_seq_id seq_id = ubatch.seq_id[s][j];
  426. if (seq_id < 0 || (uint32_t) seq_id >= size) {
  427. // too big seq_id
  428. // TODO: would it be possible to resize the cache instead?
  429. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, size);
  430. return false;
  431. }
  432. if (j > 0) {
  433. llama_kv_cell & seq = cells[seq_id];
  434. if (seq.tail >= 0) {
  435. llama_kv_cell & cell = cells[seq.tail];
  436. // clear cells from seq_ids that become shared
  437. // (should not normally happen, but let's handle it anyway)
  438. cell.seq_id.erase(seq_id);
  439. seq.tail = -1;
  440. if (cell.seq_id.empty()) {
  441. cell.pos = -1;
  442. cell.src = -1;
  443. used -= 1;
  444. }
  445. }
  446. }
  447. }
  448. }
  449. #ifndef NDEBUG
  450. {
  451. std::vector<int32_t> tails_verif;
  452. tails_verif.assign(size, -1);
  453. for (uint32_t i = 0; i < size; ++i) {
  454. llama_kv_cell & cell = cells[i];
  455. for (llama_seq_id seq_id : cell.seq_id) {
  456. if (tails_verif[seq_id] != -1) {
  457. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  458. }
  459. tails_verif[seq_id] = i;
  460. }
  461. }
  462. for (uint32_t i = 0; i < size; ++i) {
  463. if (tails_verif[i] != cells[i].tail) {
  464. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cells[i].tail, tails_verif[i]);
  465. }
  466. }
  467. }
  468. #endif
  469. // find next empty cell
  470. uint32_t next_empty_cell = head;
  471. for (uint32_t i = 0; i < size; ++i) {
  472. if (next_empty_cell >= size) { next_empty_cell -= size; }
  473. llama_kv_cell & cell = cells[next_empty_cell];
  474. if (cell.is_empty()) { break; }
  475. next_empty_cell += 1;
  476. }
  477. // find usable cell range
  478. for (uint32_t s = 0; s < n_seqs; ++s) {
  479. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  480. llama_kv_cell & seq_meta = cells[seq_id];
  481. bool has_cell = false;
  482. if (seq_meta.tail >= 0) {
  483. llama_kv_cell & cell = cells[seq_meta.tail];
  484. GGML_ASSERT(cell.has_seq_id(seq_id));
  485. // does this seq_id "own" the cell?
  486. if (cell.seq_id.size() == 1) { has_cell = true; }
  487. }
  488. if (!has_cell) {
  489. llama_kv_cell & empty_cell = cells[next_empty_cell];
  490. GGML_ASSERT(empty_cell.is_empty());
  491. // copy old tail into the empty cell
  492. if (seq_meta.tail >= 0) {
  493. llama_kv_cell & orig_cell = cells[seq_meta.tail];
  494. empty_cell.pos = orig_cell.pos;
  495. empty_cell.src = orig_cell.src;
  496. orig_cell.seq_id.erase(seq_id);
  497. empty_cell.seq_id.insert(seq_id); // will be overwritten
  498. }
  499. seq_meta.tail = next_empty_cell;
  500. // find next empty cell
  501. if (s + 1 < n_seqs) {
  502. next_empty_cell += 1;
  503. for (uint32_t i = 0; i < size; ++i) {
  504. if (next_empty_cell >= size) { next_empty_cell -= size; }
  505. llama_kv_cell & cell = cells[next_empty_cell];
  506. if (cell.is_empty()) { break; }
  507. next_empty_cell += 1;
  508. }
  509. }
  510. }
  511. if (min > seq_meta.tail) { min = seq_meta.tail; }
  512. if (max < seq_meta.tail) { max = seq_meta.tail; }
  513. }
  514. // gather and re-order
  515. for (uint32_t s = 0; s < n_seqs; ++s) {
  516. int32_t dst_id = s + min;
  517. int32_t src_id = cells[ubatch.seq_id[s][0]].tail;
  518. if (dst_id != src_id) {
  519. llama_kv_cell & dst_cell = cells[dst_id];
  520. llama_kv_cell & src_cell = cells[src_id];
  521. std::swap(dst_cell.pos, src_cell.pos);
  522. std::swap(dst_cell.src, src_cell.src);
  523. std::swap(dst_cell.seq_id, src_cell.seq_id);
  524. // swap tails (assuming they NEVER overlap)
  525. for (const llama_seq_id seq_id : src_cell.seq_id) {
  526. cells[seq_id].tail = src_id;
  527. }
  528. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  529. cells[seq_id].tail = dst_id;
  530. }
  531. }
  532. }
  533. // update the pos of the used seqs
  534. for (uint32_t s = 0; s < n_seqs; ++s) {
  535. const llama_pos last_pos = ubatch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  536. int32_t cell_id = s + min;
  537. llama_kv_cell & cell = cells[cell_id];
  538. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  539. // What should happen when the pos backtracks or skips a value?
  540. // Clearing the state mid-batch would require special-casing which isn't done.
  541. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  542. __func__, last_pos, cell.pos, ubatch.seq_id[s][0], n_seq_tokens);
  543. }
  544. cell.pos = last_pos;
  545. cell.seq_id.clear();
  546. for (int32_t j = 0; j < ubatch.n_seq_id[s]; ++j) {
  547. const llama_seq_id seq_id = ubatch.seq_id[s][j];
  548. cell.seq_id.insert(seq_id);
  549. cells[seq_id].tail = cell_id;
  550. }
  551. }
  552. // allow getting the range of used cells, from head to head + n
  553. head = min;
  554. n = max - min + 1;
  555. used = std::count_if(cells.begin(), cells.end(),
  556. [](const llama_kv_cell& cell){ return !cell.is_empty(); });
  557. // sanity check
  558. return n >= n_seqs;
  559. }
  560. // otherwise, one cell per token.
  561. if (n_tokens > size) {
  562. LLAMA_LOG_ERROR("%s: n_tokens = %d > size = %d\n", __func__, n_tokens, size);
  563. return false;
  564. }
  565. uint32_t n_tested = 0;
  566. while (true) {
  567. if (head + n_tokens > size) {
  568. n_tested += size - head;
  569. head = 0;
  570. continue;
  571. }
  572. bool found = true;
  573. for (uint32_t i = 0; i < n_tokens; i++) {
  574. if (cells[head + i].pos >= 0) {
  575. found = false;
  576. head += i + 1;
  577. n_tested += i + 1;
  578. break;
  579. }
  580. }
  581. if (found) {
  582. break;
  583. }
  584. if (n_tested >= size) {
  585. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  586. return false;
  587. }
  588. }
  589. for (uint32_t s = 0; s < n_seqs; s++) {
  590. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  591. uint32_t k = s*n_seq_tokens + i;
  592. cells[head + k].pos = ubatch.pos[k];
  593. for (int32_t j = 0; j < ubatch.n_seq_id[s]; j++) {
  594. cells[head + k].seq_id.insert(ubatch.seq_id[s][j]);
  595. }
  596. }
  597. }
  598. used += n_tokens;
  599. pending.ranges.push_back({head, head + n_tokens});
  600. return true;
  601. }
  602. uint32_t llama_kv_cache_unified::get_padding(const llama_cparams & cparams) const {
  603. // the FA kernels require padding to avoid extra runtime boundary checks
  604. return cparams.flash_attn ? 256u : 32u;
  605. }
  606. uint32_t llama_kv_cache_unified::cell_max() const {
  607. for (uint32_t i = size; i > 0; --i) {
  608. const llama_kv_cell & cell = cells[i - 1];
  609. if (cell.pos >= 0 && !cell.is_empty()) {
  610. return i;
  611. }
  612. }
  613. return 0;
  614. }
  615. size_t llama_kv_cache_unified::size_k_bytes() const {
  616. size_t size_k_bytes = 0;
  617. for (const auto & k : k_l) {
  618. size_k_bytes += ggml_nbytes(k);
  619. }
  620. return size_k_bytes;
  621. }
  622. size_t llama_kv_cache_unified::size_v_bytes() const {
  623. size_t size_v_bytes = 0;
  624. for (const auto & v : v_l) {
  625. size_v_bytes += ggml_nbytes(v);
  626. }
  627. return size_v_bytes;
  628. }
  629. bool llama_kv_cache_unified::defrag_prepare(int32_t n_max_nodes) {
  630. const uint32_t n_layer = hparams.n_layer;
  631. const uint32_t n_kv = cell_max();
  632. const uint32_t n_used = used;
  633. assert(n_used <= n_kv);
  634. //const int64_t t_start = ggml_time_us();
  635. // number of cells moved
  636. uint32_t n_moves = 0;
  637. // each move requires 6*n_layer tensors (see graph_build_kv_self_defrag)
  638. // - source view, destination view, copy operation
  639. // - x2 for keys and values
  640. //const uint32_t max_moves = max_nodes()/(6*n_layer);
  641. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  642. const uint32_t max_moves = (n_max_nodes - 2*n_layer)/(6*n_layer);
  643. // determine which KV cells to move where
  644. //
  645. // cell i moves to ids[i]
  646. //
  647. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  648. //
  649. auto & ids = defrag_info.ids;
  650. ids.clear();
  651. ids.resize(n_kv, n_kv);
  652. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  653. const auto & cell0 = cells[i0];
  654. if (!cell0.is_empty()) {
  655. ids[i0] = i0;
  656. continue;
  657. }
  658. // found a hole - fill it with data from the end of the cache
  659. uint32_t nh = 1;
  660. // determine the size of the hole
  661. while (i0 + nh < n_used && cells[i0 + nh].is_empty()) {
  662. nh++;
  663. }
  664. uint32_t nf = 0;
  665. uint32_t is = n_kv - 1;
  666. // starting from the end, find nh non-empty cells
  667. for (; is > i0; --is) {
  668. const auto & cell1 = cells[is];
  669. if (cell1.is_empty() || ids[is] != n_kv) {
  670. continue;
  671. }
  672. // non-empty cell which is not yet moved
  673. nf++;
  674. if (nf == nh) {
  675. break;
  676. }
  677. }
  678. // this can only happen if `n_used` is not accurate, which would be a bug
  679. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  680. nf = 0;
  681. uint32_t i1 = is;
  682. // are we moving a continuous block of memory?
  683. bool cont = false;
  684. // should we stop searching for the next move?
  685. bool stop = false;
  686. // go back and move the nf cells to the hole
  687. for (; i1 < n_kv; ++i1) {
  688. auto & cell1 = cells[i1];
  689. if (cell1.is_empty() || ids[i1] != n_kv) {
  690. if (n_moves == max_moves) {
  691. stop = true;
  692. break;
  693. }
  694. cont = false;
  695. continue;
  696. }
  697. // this cell goes to (i0 + nf)
  698. ids[i1] = i0 + nf;
  699. // move the cell meta data
  700. cells[i0 + nf] = cell1;
  701. // clear the old cell and move the head there
  702. cell1 = llama_kv_cell();
  703. head = n_used;
  704. if (!cont) {
  705. n_moves++;
  706. cont = true;
  707. }
  708. nf++;
  709. if (nf == nh) {
  710. break;
  711. }
  712. }
  713. if (stop || n_moves == max_moves) {
  714. break;
  715. }
  716. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  717. i0 += nh - 1;
  718. }
  719. if (n_moves == 0) {
  720. return false;
  721. }
  722. LLAMA_LOG_DEBUG("(tmp log) KV defrag cell moves: %u\n", n_moves);
  723. LLAMA_LOG_DEBUG("expected gf nodes: %u\n", 6*n_moves*n_layer);
  724. return true;
  725. }
  726. void llama_kv_cache_unified::state_write(llama_io_write_i & io, llama_seq_id seq_id) const {
  727. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  728. uint32_t cell_count = 0;
  729. // Count the number of cells with the specified seq_id
  730. // Find all the ranges of cells with this seq id (or all, when -1)
  731. uint32_t cell_range_begin = size;
  732. for (uint32_t i = 0; i < size; ++i) {
  733. const auto & cell = cells[i];
  734. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  735. ++cell_count;
  736. if (cell_range_begin == size) {
  737. cell_range_begin = i;
  738. }
  739. } else {
  740. if (cell_range_begin != size) {
  741. cell_ranges.emplace_back(cell_range_begin, i);
  742. cell_range_begin = size;
  743. }
  744. }
  745. }
  746. if (cell_range_begin != size) {
  747. cell_ranges.emplace_back(cell_range_begin, size);
  748. }
  749. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  750. uint32_t cell_count_check = 0;
  751. for (const auto & range : cell_ranges) {
  752. cell_count_check += range.second - range.first;
  753. }
  754. GGML_ASSERT(cell_count == cell_count_check);
  755. io.write(&cell_count, sizeof(cell_count));
  756. state_write_meta(io, cell_ranges, seq_id);
  757. state_write_data(io, cell_ranges);
  758. }
  759. void llama_kv_cache_unified::state_read(llama_io_read_i & io, llama_seq_id seq_id) {
  760. uint32_t cell_count;
  761. io.read_to(&cell_count, sizeof(cell_count));
  762. bool res = true;
  763. res = res && state_read_meta(io, cell_count, seq_id);
  764. res = res && state_read_data(io, cell_count);
  765. if (!res) {
  766. if (seq_id == -1) {
  767. clear();
  768. } else {
  769. seq_rm(seq_id, -1, -1);
  770. }
  771. throw std::runtime_error("failed to restore kv cache");
  772. }
  773. }
  774. 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 {
  775. for (const auto & range : cell_ranges) {
  776. for (uint32_t i = range.first; i < range.second; ++i) {
  777. const auto & cell = cells[i];
  778. const llama_pos pos = cell.pos;
  779. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  780. io.write(&pos, sizeof(pos));
  781. io.write(&n_seq_id, sizeof(n_seq_id));
  782. if (n_seq_id) {
  783. for (auto seq_id : cell.seq_id) {
  784. io.write(&seq_id, sizeof(seq_id));
  785. }
  786. }
  787. }
  788. }
  789. }
  790. 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 {
  791. const uint32_t v_trans = this->v_trans ? 1 : 0;
  792. const uint32_t n_layer = hparams.n_layer;
  793. io.write(&v_trans, sizeof(v_trans));
  794. io.write(&n_layer, sizeof(n_layer));
  795. std::vector<uint8_t> tmp_buf;
  796. // Iterate and write all the keys first, each row is a cell
  797. // Get whole range at a time
  798. for (uint32_t il = 0; il < n_layer; ++il) {
  799. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  800. // Write key type
  801. const int32_t k_type_i = (int32_t)k_l[il]->type;
  802. io.write(&k_type_i, sizeof(k_type_i));
  803. // Write row size of key
  804. const uint64_t k_size_row = ggml_row_size(k_l[il]->type, n_embd_k_gqa);
  805. io.write(&k_size_row, sizeof(k_size_row));
  806. // Read each range of cells of k_size length each into tmp_buf and write out
  807. for (const auto & range : cell_ranges) {
  808. const size_t range_size = range.second - range.first;
  809. const size_t buf_size = range_size * k_size_row;
  810. io.write_tensor(k_l[il], range.first * k_size_row, buf_size);
  811. }
  812. }
  813. if (!v_trans) {
  814. for (uint32_t il = 0; il < n_layer; ++il) {
  815. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  816. // Write value type
  817. const int32_t v_type_i = (int32_t)v_l[il]->type;
  818. io.write(&v_type_i, sizeof(v_type_i));
  819. // Write row size of value
  820. const uint64_t v_size_row = ggml_row_size(v_l[il]->type, n_embd_v_gqa);
  821. io.write(&v_size_row, sizeof(v_size_row));
  822. // Read each range of cells of v_size length each into tmp_buf and write out
  823. for (const auto & range : cell_ranges) {
  824. const size_t range_size = range.second - range.first;
  825. const size_t buf_size = range_size * v_size_row;
  826. io.write_tensor(v_l[il], range.first * v_size_row, buf_size);
  827. }
  828. }
  829. } else {
  830. // When v is transposed, we also need the element size and get the element ranges from each row
  831. const uint32_t kv_size = size;
  832. for (uint32_t il = 0; il < n_layer; ++il) {
  833. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  834. // Write value type
  835. const int32_t v_type_i = (int32_t)v_l[il]->type;
  836. io.write(&v_type_i, sizeof(v_type_i));
  837. // Write element size
  838. const uint32_t v_size_el = ggml_type_size(v_l[il]->type);
  839. io.write(&v_size_el, sizeof(v_size_el));
  840. // Write GQA embedding size
  841. io.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  842. // For each row, we get the element values of each cell
  843. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  844. // Read each range of cells of v_size_el length each into tmp_buf and write out
  845. for (const auto & range : cell_ranges) {
  846. const size_t range_size = range.second - range.first;
  847. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  848. const size_t buf_size = range_size * v_size_el;
  849. io.write_tensor(v_l[il], src_offset, buf_size);
  850. }
  851. }
  852. }
  853. }
  854. }
  855. bool llama_kv_cache_unified::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
  856. if (dest_seq_id != -1) {
  857. // single sequence
  858. seq_rm(dest_seq_id, -1, -1);
  859. llama_sbatch sbatch;
  860. llama_ubatch batch = sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  861. batch.n_tokens = cell_count;
  862. batch.n_seq_tokens = cell_count;
  863. batch.n_seqs = 1;
  864. for (uint32_t i = 0; i < cell_count; ++i) {
  865. llama_pos pos;
  866. uint32_t n_seq_id;
  867. io.read_to(&pos, sizeof(pos));
  868. io.read_to(&n_seq_id, sizeof(n_seq_id));
  869. if (n_seq_id != 0) {
  870. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  871. return false;
  872. }
  873. batch.pos[i] = pos;
  874. }
  875. batch.n_seq_id[0] = 1;
  876. batch.seq_id[0] = &dest_seq_id;
  877. if (!find_slot(batch)) {
  878. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  879. return false;
  880. }
  881. commit();
  882. // DEBUG CHECK: kv.head should be our first cell, kv.head + cell_count - 1 should be our last cell (verify seq_id and pos values)
  883. // Assume that this is one contiguous block of cells
  884. GGML_ASSERT(head + cell_count <= size);
  885. GGML_ASSERT(cells[head].pos == batch.pos[0]);
  886. GGML_ASSERT(cells[head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  887. GGML_ASSERT(cells[head].has_seq_id(dest_seq_id));
  888. GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id));
  889. } else {
  890. // whole KV cache restore
  891. if (cell_count > size) {
  892. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  893. return false;
  894. }
  895. clear();
  896. for (uint32_t i = 0; i < cell_count; ++i) {
  897. llama_kv_cell & cell = cells[i];
  898. llama_pos pos;
  899. uint32_t n_seq_id;
  900. io.read_to(&pos, sizeof(pos));
  901. io.read_to(&n_seq_id, sizeof(n_seq_id));
  902. cell.pos = pos;
  903. for (uint32_t j = 0; j < n_seq_id; ++j) {
  904. llama_seq_id seq_id;
  905. io.read_to(&seq_id, sizeof(seq_id));
  906. // TODO: llama_kv_cache_unified should have a notion of max sequences
  907. //if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  908. if (seq_id < 0) {
  909. //LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  910. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, inf)\n", __func__, seq_id);
  911. return false;
  912. }
  913. cell.seq_id.insert(seq_id);
  914. if (recurrent) {
  915. int32_t & tail = cells[seq_id].tail;
  916. if (tail != -1) {
  917. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  918. return false;
  919. }
  920. tail = i;
  921. }
  922. }
  923. }
  924. head = 0;
  925. used = cell_count;
  926. }
  927. if (recurrent) {
  928. for (uint32_t i = 0; i < cell_count; ++i) {
  929. uint32_t cell_id = head + i;
  930. // make sure the recurrent states will keep their restored state
  931. cells[cell_id].src = cell_id;
  932. }
  933. }
  934. return true;
  935. }
  936. bool llama_kv_cache_unified::state_read_data(llama_io_read_i & io, uint32_t cell_count) {
  937. uint32_t v_trans;
  938. uint32_t n_layer;
  939. io.read_to(&v_trans, sizeof(v_trans));
  940. io.read_to(&n_layer, sizeof(n_layer));
  941. if (n_layer != hparams.n_layer) {
  942. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  943. return false;
  944. }
  945. if (cell_count > size) {
  946. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, size);
  947. return false;
  948. }
  949. if (v_trans != (bool) v_trans) {
  950. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  951. return false;
  952. }
  953. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  954. for (uint32_t il = 0; il < n_layer; ++il) {
  955. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  956. // Read type of key
  957. int32_t k_type_i_ref;
  958. io.read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  959. const int32_t k_type_i = (int32_t) k_l[il]->type;
  960. if (k_type_i != k_type_i_ref) {
  961. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  962. return false;
  963. }
  964. // Read row size of key
  965. uint64_t k_size_row_ref;
  966. io.read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  967. const size_t k_size_row = ggml_row_size(k_l[il]->type, n_embd_k_gqa);
  968. if (k_size_row != k_size_row_ref) {
  969. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  970. return false;
  971. }
  972. if (cell_count) {
  973. // Read and set the keys for the whole cell range
  974. ggml_backend_tensor_set(k_l[il], io.read(cell_count * k_size_row), head * k_size_row, cell_count * k_size_row);
  975. }
  976. }
  977. if (!v_trans) {
  978. for (uint32_t il = 0; il < n_layer; ++il) {
  979. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  980. // Read type of value
  981. int32_t v_type_i_ref;
  982. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  983. const int32_t v_type_i = (int32_t)v_l[il]->type;
  984. if (v_type_i != v_type_i_ref) {
  985. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  986. return false;
  987. }
  988. // Read row size of value
  989. uint64_t v_size_row_ref;
  990. io.read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  991. const size_t v_size_row = ggml_row_size(v_l[il]->type, n_embd_v_gqa);
  992. if (v_size_row != v_size_row_ref) {
  993. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  994. return false;
  995. }
  996. if (cell_count) {
  997. // Read and set the values for the whole cell range
  998. ggml_backend_tensor_set(v_l[il], io.read(cell_count * v_size_row), head * v_size_row, cell_count * v_size_row);
  999. }
  1000. }
  1001. } else {
  1002. // For each layer, read the values for each cell (transposed)
  1003. for (uint32_t il = 0; il < n_layer; ++il) {
  1004. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  1005. // Read type of value
  1006. int32_t v_type_i_ref;
  1007. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1008. const int32_t v_type_i = (int32_t)v_l[il]->type;
  1009. if (v_type_i != v_type_i_ref) {
  1010. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1011. return false;
  1012. }
  1013. // Read element size of value
  1014. uint32_t v_size_el_ref;
  1015. io.read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  1016. const size_t v_size_el = ggml_type_size(v_l[il]->type);
  1017. if (v_size_el != v_size_el_ref) {
  1018. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  1019. return false;
  1020. }
  1021. // Read GQA embedding size
  1022. uint32_t n_embd_v_gqa_ref;
  1023. io.read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  1024. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  1025. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  1026. return false;
  1027. }
  1028. if (cell_count) {
  1029. // For each row in the transposed matrix, read the values for the whole cell range
  1030. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1031. const size_t dst_offset = (head + j * size) * v_size_el;
  1032. ggml_backend_tensor_set(v_l[il], io.read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  1033. }
  1034. }
  1035. }
  1036. }
  1037. return true;
  1038. }
  1039. //
  1040. // interface implementation
  1041. //
  1042. int32_t llama_kv_cache_n_tokens(const llama_kv_cache * kv) {
  1043. if (!kv) {
  1044. return 0;
  1045. }
  1046. return kv->get_n_tokens();
  1047. }
  1048. int32_t llama_kv_cache_used_cells(const llama_kv_cache * kv) {
  1049. if (!kv) {
  1050. return 0;
  1051. }
  1052. return kv->get_used_cells();
  1053. }
  1054. void llama_kv_cache_clear(llama_kv_cache * kv) {
  1055. if (!kv) {
  1056. return;
  1057. }
  1058. kv->clear();
  1059. }
  1060. bool llama_kv_cache_seq_rm(
  1061. llama_kv_cache * kv,
  1062. llama_seq_id seq_id,
  1063. llama_pos p0,
  1064. llama_pos p1) {
  1065. if (!kv) {
  1066. return true;
  1067. }
  1068. return kv->seq_rm(seq_id, p0, p1);
  1069. }
  1070. void llama_kv_cache_seq_cp(
  1071. llama_kv_cache * kv,
  1072. llama_seq_id seq_id_src,
  1073. llama_seq_id seq_id_dst,
  1074. llama_pos p0,
  1075. llama_pos p1) {
  1076. if (!kv) {
  1077. return;
  1078. }
  1079. kv->seq_cp(seq_id_src, seq_id_dst, p0, p1);
  1080. }
  1081. void llama_kv_cache_seq_keep(llama_kv_cache * kv, llama_seq_id seq_id) {
  1082. if (!kv) {
  1083. return;
  1084. }
  1085. kv->seq_keep(seq_id);
  1086. }
  1087. void llama_kv_cache_seq_add(
  1088. llama_kv_cache * kv,
  1089. llama_seq_id seq_id,
  1090. llama_pos p0,
  1091. llama_pos p1,
  1092. llama_pos delta) {
  1093. if (!kv) {
  1094. return;
  1095. }
  1096. kv->seq_add(seq_id, p0, p1, delta);
  1097. }
  1098. void llama_kv_cache_seq_div(
  1099. llama_kv_cache * kv,
  1100. llama_seq_id seq_id,
  1101. llama_pos p0,
  1102. llama_pos p1,
  1103. int d) {
  1104. if (!kv) {
  1105. return;
  1106. }
  1107. kv->seq_div(seq_id, p0, p1, d);
  1108. }
  1109. llama_pos llama_kv_cache_seq_pos_max(llama_kv_cache * kv, llama_seq_id seq_id) {
  1110. if (!kv) {
  1111. return 0;
  1112. }
  1113. return kv->seq_pos_max(seq_id);
  1114. }
  1115. void llama_kv_cache_defrag(llama_kv_cache * kv) {
  1116. if (!kv) {
  1117. return;
  1118. }
  1119. kv->defrag();
  1120. }
  1121. bool llama_kv_cache_can_shift(const llama_kv_cache * kv) {
  1122. if (!kv) {
  1123. return false;
  1124. }
  1125. return kv->get_can_shift();
  1126. }
  1127. //
  1128. // kv cache view
  1129. //
  1130. llama_kv_cache_view llama_kv_cache_view_init(const llama_kv_cache & kv, int32_t n_seq_max) {
  1131. llama_kv_cache_view result = {
  1132. /*.n_cells = */ 0,
  1133. /*.n_seq_max = */ n_seq_max,
  1134. /*.token_count = */ 0,
  1135. /*.used_cells = */ llama_kv_cache_used_cells(&kv),
  1136. /*.max_contiguous = */ 0,
  1137. /*.max_contiguous_idx = */ -1,
  1138. /*.cells = */ nullptr,
  1139. /*.cells_sequences = */ nullptr,
  1140. };
  1141. return result;
  1142. }
  1143. void llama_kv_cache_view_free(llama_kv_cache_view * view) {
  1144. if (view->cells != nullptr) {
  1145. free(view->cells);
  1146. view->cells = nullptr;
  1147. }
  1148. if (view->cells_sequences != nullptr) {
  1149. free(view->cells_sequences);
  1150. view->cells_sequences = nullptr;
  1151. }
  1152. }
  1153. void llama_kv_cache_view_update(llama_kv_cache_view * view, const llama_kv_cache * kv) {
  1154. // TODO: rework this in the future, for now quick hack
  1155. const llama_kv_cache_unified * kvu = dynamic_cast<const llama_kv_cache_unified *>(kv);
  1156. if (kvu == nullptr) {
  1157. LLAMA_LOG_ERROR("%s: the kv_cache_view currently works only with llama_kv_cache_unified\n", __func__);
  1158. return;
  1159. }
  1160. if (uint32_t(view->n_cells) < kvu->size || view->cells == nullptr) {
  1161. view->n_cells = int32_t(kvu->size);
  1162. void * p = realloc(view->cells, sizeof(llama_kv_cache_view_cell) * view->n_cells);
  1163. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  1164. view->cells = (llama_kv_cache_view_cell *)p;
  1165. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  1166. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  1167. view->cells_sequences = (llama_seq_id *)p;
  1168. }
  1169. const std::vector<llama_kv_cell> & kv_cells = kvu->cells;
  1170. llama_kv_cache_view_cell * c_curr = view->cells;
  1171. llama_seq_id * cs_curr = view->cells_sequences;
  1172. int32_t used_cells = 0;
  1173. int32_t token_count = 0;
  1174. int32_t curr_contig_idx = -1;
  1175. uint32_t max_contig = 0;
  1176. int32_t max_contig_idx = -1;
  1177. for (int32_t i = 0; i < int32_t(kvu->size); i++, c_curr++, cs_curr += view->n_seq_max) {
  1178. const size_t curr_size = kv_cells[i].seq_id.size();
  1179. token_count += curr_size;
  1180. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  1181. if (curr_size > 0) {
  1182. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  1183. max_contig = i - curr_contig_idx;
  1184. max_contig_idx = curr_contig_idx;
  1185. }
  1186. curr_contig_idx = -1;
  1187. } else if (curr_contig_idx < 0) {
  1188. curr_contig_idx = i;
  1189. }
  1190. int seq_idx = 0;
  1191. for (const llama_seq_id it : kv_cells[i].seq_id) {
  1192. if (seq_idx >= view->n_seq_max) {
  1193. break;
  1194. }
  1195. cs_curr[seq_idx] = it;
  1196. seq_idx++;
  1197. }
  1198. if (seq_idx != 0) {
  1199. used_cells++;
  1200. }
  1201. for (; seq_idx < view->n_seq_max; seq_idx++) {
  1202. cs_curr[seq_idx] = -1;
  1203. }
  1204. }
  1205. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  1206. max_contig_idx = curr_contig_idx;
  1207. max_contig = kv_cells.size() - curr_contig_idx;
  1208. }
  1209. view->max_contiguous = max_contig;
  1210. view->max_contiguous_idx = max_contig_idx;
  1211. view->token_count = token_count;
  1212. view->used_cells = used_cells;
  1213. if (uint32_t(used_cells) != kvu->used) {
  1214. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  1215. __func__, kvu->used, used_cells);
  1216. }
  1217. }