llama-kv-cache.cpp 45 KB

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