llama-kv-cache.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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 <limits>
  8. #include <map>
  9. static const llama_kv_cache_slot_info llama_kv_cache_slot_info_failed{false};
  10. uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  11. // the FA kernels require padding to avoid extra runtime boundary checks
  12. return cparams.flash_attn ? 256u : 32u;
  13. }
  14. bool llama_kv_cache_init(
  15. struct llama_kv_cache & cache,
  16. const llama_model & model,
  17. const llama_cparams & cparams,
  18. ggml_type type_k,
  19. ggml_type type_v,
  20. uint32_t kv_size,
  21. bool offload) {
  22. const struct llama_hparams & hparams = model.hparams;
  23. const int32_t n_layer = hparams.n_layer;
  24. cache.has_shift = false;
  25. cache.recurrent = llama_model_is_recurrent(&model);
  26. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  27. cache.can_shift = !cache.recurrent && model.arch != LLM_ARCH_DEEPSEEK2; // not supported due to MLA
  28. LLAMA_LOG_INFO("%s: kv_size = %d, offload = %d, type_k = '%s', type_v = '%s', n_layer = %d, can_shift = %d\n",
  29. __func__, kv_size, offload, ggml_type_name(type_k), ggml_type_name(type_v), n_layer, cache.can_shift);
  30. cache.head = 0;
  31. cache.size = kv_size;
  32. cache.used = 0;
  33. cache.type_k = type_k;
  34. cache.type_v = type_v;
  35. cache.cells.clear();
  36. cache.cells.resize(kv_size);
  37. // create a context for each buffer type
  38. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  39. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  40. auto it = ctx_map.find(buft);
  41. if (it == ctx_map.end()) {
  42. struct ggml_init_params params = {
  43. /*.mem_size =*/ size_t(2u*n_layer*ggml_tensor_overhead()),
  44. /*.mem_buffer =*/ NULL,
  45. /*.no_alloc =*/ true,
  46. };
  47. ggml_context * ctx = ggml_init(params);
  48. if (!ctx) {
  49. return nullptr;
  50. }
  51. ctx_map[buft] = ctx;
  52. cache.ctxs.emplace_back(ctx);
  53. return ctx;
  54. }
  55. return it->second;
  56. };
  57. cache.k_l.reserve(n_layer);
  58. cache.v_l.reserve(n_layer);
  59. for (int i = 0; i < n_layer; i++) {
  60. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  61. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  62. LLAMA_LOG_DEBUG("%s: layer %d: n_embd_k_gqa = %d, n_embd_v_gqa = %d\n", __func__, i, n_embd_k_gqa, n_embd_v_gqa);
  63. ggml_backend_buffer_type_t buft;
  64. if (offload) {
  65. auto * dev = model.dev_layer(i);
  66. buft = ggml_backend_dev_buffer_type(dev);
  67. } else {
  68. buft = ggml_backend_cpu_buffer_type();
  69. }
  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, *v;
  76. // for cross attention layers
  77. if (model.arch == LLM_ARCH_MLLAMA && hparams.cross_attention_layers(i)) {
  78. k = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_k, 6404, hparams.n_head_kv(i));
  79. v = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_v, 6404, hparams.n_head_kv(i));
  80. } else {
  81. k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  82. v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  83. }
  84. ggml_format_name(k, "cache_k_l%d", i);
  85. ggml_format_name(v, "cache_v_l%d", i);
  86. cache.k_l.push_back(k);
  87. cache.v_l.push_back(v);
  88. }
  89. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  90. for (auto it : ctx_map) {
  91. auto * buft = it.first;
  92. auto * ctx = it.second;
  93. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  94. if (!buf) {
  95. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  96. return false;
  97. }
  98. ggml_backend_buffer_clear(buf, 0);
  99. 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);
  100. cache.bufs.emplace_back(buf);
  101. }
  102. return true;
  103. }
  104. struct llama_kv_cache_slot_info llama_kv_cache_find_slot(
  105. struct llama_kv_cache & cache,
  106. const struct llama_ubatch & ubatch) {
  107. const uint32_t n_tokens = ubatch.n_tokens;
  108. const uint32_t n_seqs = ubatch.n_seqs;
  109. const uint32_t n_seq_tokens = ubatch.n_seq_tokens;
  110. if (cache.recurrent) {
  111. // For recurrent state architectures (like Mamba or RWKV),
  112. // each cache cell can store the state for a whole sequence.
  113. // A slot should be always be contiguous.
  114. // can only process batches with an equal number of new tokens in each sequence
  115. GGML_ASSERT(ubatch.equal_seqs);
  116. int32_t min = cache.size - 1;
  117. int32_t max = 0;
  118. // everything should fit if all seq_ids are smaller than the max
  119. for (uint32_t s = 0; s < n_seqs; ++s) {
  120. const uint32_t n_seq_id = ubatch.n_seq_id[s];
  121. for (uint32_t j = 0; j < n_seq_id; ++j) {
  122. const llama_seq_id seq_id = ubatch.seq_id[s][j];
  123. if (seq_id < 0 || (uint32_t) seq_id >= cache.size) {
  124. // too big seq_id
  125. // TODO: would it be possible to resize the cache instead?
  126. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  127. return llama_kv_cache_slot_info_failed;
  128. }
  129. if (j > 0) {
  130. llama_kv_cell & seq = cache.cells[seq_id];
  131. if (seq.tail >= 0) {
  132. llama_kv_cell & cell = cache.cells[seq.tail];
  133. // clear cells from seq_ids that become shared
  134. // (should not normally happen, but let's handle it anyway)
  135. cell.seq_id.erase(seq_id);
  136. seq.tail = -1;
  137. if (cell.seq_id.empty()) {
  138. cell.pos = -1;
  139. cell.src = -1;
  140. cache.used -= 1;
  141. }
  142. }
  143. }
  144. }
  145. }
  146. #ifndef NDEBUG
  147. {
  148. std::vector<int32_t> tails_verif;
  149. tails_verif.assign(cache.size, -1);
  150. for (uint32_t i = 0; i < cache.size; ++i) {
  151. llama_kv_cell & cell = cache.cells[i];
  152. for (llama_seq_id seq_id : cell.seq_id) {
  153. if (tails_verif[seq_id] != -1) {
  154. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  155. }
  156. tails_verif[seq_id] = i;
  157. }
  158. }
  159. for (uint32_t i = 0; i < cache.size; ++i) {
  160. if (tails_verif[i] != cache.cells[i].tail) {
  161. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cache.cells[i].tail, tails_verif[i]);
  162. }
  163. }
  164. }
  165. #endif
  166. // find next empty cell
  167. uint32_t next_empty_cell = cache.head;
  168. for (uint32_t i = 0; i < cache.size; ++i) {
  169. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  170. llama_kv_cell & cell = cache.cells[next_empty_cell];
  171. if (cell.is_empty()) { break; }
  172. next_empty_cell += 1;
  173. }
  174. // find usable cell range
  175. for (uint32_t s = 0; s < n_seqs; ++s) {
  176. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  177. llama_kv_cell & seq_meta = cache.cells[seq_id];
  178. bool has_cell = false;
  179. if (seq_meta.tail >= 0) {
  180. llama_kv_cell & cell = cache.cells[seq_meta.tail];
  181. GGML_ASSERT(cell.has_seq_id(seq_id));
  182. // does this seq_id "own" the cell?
  183. if (cell.seq_id.size() == 1) { has_cell = true; }
  184. }
  185. if (!has_cell) {
  186. llama_kv_cell & empty_cell = cache.cells[next_empty_cell];
  187. GGML_ASSERT(empty_cell.is_empty());
  188. // copy old tail into the empty cell
  189. if (seq_meta.tail >= 0) {
  190. llama_kv_cell & orig_cell = cache.cells[seq_meta.tail];
  191. empty_cell.pos = orig_cell.pos;
  192. empty_cell.src = orig_cell.src;
  193. orig_cell.seq_id.erase(seq_id);
  194. empty_cell.seq_id.insert(seq_id); // will be overwritten
  195. }
  196. seq_meta.tail = next_empty_cell;
  197. // find next empty cell
  198. if (s + 1 < n_seqs) {
  199. next_empty_cell += 1;
  200. for (uint32_t i = 0; i < cache.size; ++i) {
  201. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  202. llama_kv_cell & cell = cache.cells[next_empty_cell];
  203. if (cell.is_empty()) { break; }
  204. next_empty_cell += 1;
  205. }
  206. }
  207. }
  208. if (min > seq_meta.tail) { min = seq_meta.tail; }
  209. if (max < seq_meta.tail) { max = seq_meta.tail; }
  210. }
  211. // gather and re-order
  212. for (uint32_t s = 0; s < n_seqs; ++s) {
  213. int32_t dst_id = s + min;
  214. int32_t src_id = cache.cells[ubatch.seq_id[s][0]].tail;
  215. if (dst_id != src_id) {
  216. llama_kv_cell & dst_cell = cache.cells[dst_id];
  217. llama_kv_cell & src_cell = cache.cells[src_id];
  218. std::swap(dst_cell.pos, src_cell.pos);
  219. std::swap(dst_cell.src, src_cell.src);
  220. std::swap(dst_cell.seq_id, src_cell.seq_id);
  221. // swap tails (assuming they NEVER overlap)
  222. for (const llama_seq_id seq_id : src_cell.seq_id) {
  223. cache.cells[seq_id].tail = src_id;
  224. }
  225. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  226. cache.cells[seq_id].tail = dst_id;
  227. }
  228. }
  229. }
  230. // update the pos of the used seqs
  231. for (uint32_t s = 0; s < n_seqs; ++s) {
  232. const llama_pos last_pos = ubatch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  233. int32_t cell_id = s + min;
  234. llama_kv_cell & cell = cache.cells[cell_id];
  235. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  236. // What should happen when the pos backtracks or skips a value?
  237. // Clearing the state mid-batch would require special-casing which isn't done.
  238. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  239. __func__, last_pos, cell.pos, ubatch.seq_id[s][0], n_seq_tokens);
  240. }
  241. cell.pos = last_pos;
  242. cell.seq_id.clear();
  243. for (int32_t j = 0; j < ubatch.n_seq_id[s]; ++j) {
  244. const llama_seq_id seq_id = ubatch.seq_id[s][j];
  245. cell.seq_id.insert(seq_id);
  246. cache.cells[seq_id].tail = cell_id;
  247. }
  248. }
  249. // allow getting the range of used cells, from head to head + n
  250. cache.head = min;
  251. cache.n = max - min + 1;
  252. cache.used = std::count_if(cache.cells.begin(), cache.cells.end(),
  253. [](const llama_kv_cell& cell){ return !cell.is_empty(); });
  254. // sanity check
  255. return llama_kv_cache_slot_info(cache.n >= n_seqs);
  256. }
  257. // otherwise, one cell per token.
  258. if (n_tokens > cache.size) {
  259. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  260. return llama_kv_cache_slot_info_failed;
  261. }
  262. uint32_t n_tested = 0;
  263. while (true) {
  264. if (cache.head + n_tokens > cache.size) {
  265. n_tested += cache.size - cache.head;
  266. cache.head = 0;
  267. continue;
  268. }
  269. bool found = true;
  270. for (uint32_t i = 0; i < n_tokens; i++) {
  271. if (cache.cells[cache.head + i].pos >= 0) {
  272. found = false;
  273. cache.head += i + 1;
  274. n_tested += i + 1;
  275. break;
  276. }
  277. }
  278. if (found) {
  279. break;
  280. }
  281. if (n_tested >= cache.size) {
  282. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  283. return llama_kv_cache_slot_info_failed;
  284. }
  285. }
  286. for (uint32_t s = 0; s < n_seqs; s++) {
  287. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  288. uint32_t k = s*n_seq_tokens + i;
  289. cache.cells[cache.head + k].pos = ubatch.pos[k];
  290. for (int32_t j = 0; j < ubatch.n_seq_id[s]; j++) {
  291. cache.cells[cache.head + k].seq_id.insert(ubatch.seq_id[s][j]);
  292. }
  293. }
  294. }
  295. cache.used += n_tokens;
  296. return llama_kv_cache_slot_info(cache.head, cache.head + n_tokens);
  297. }
  298. uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  299. for (uint32_t i = cache.size; i > 0; --i) {
  300. const llama_kv_cell & cell = cache.cells[i - 1];
  301. if (cell.pos >= 0 && !cell.is_empty()) {
  302. return i;
  303. }
  304. }
  305. return 0;
  306. }
  307. void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  308. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  309. cache.cells[i].pos = -1;
  310. cache.cells[i].seq_id.clear();
  311. cache.cells[i].src = -1;
  312. cache.cells[i].tail = -1;
  313. }
  314. cache.head = 0;
  315. cache.used = 0;
  316. for (auto & buf : cache.bufs) {
  317. ggml_backend_buffer_clear(buf.get(), 0);
  318. }
  319. }
  320. bool llama_kv_cache_seq_rm(
  321. struct llama_kv_cache & cache,
  322. llama_seq_id seq_id,
  323. llama_pos p0,
  324. llama_pos p1) {
  325. uint32_t new_head = cache.size;
  326. if (p0 < 0) p0 = 0;
  327. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  328. // models like Mamba or RWKV can't have a state partially erased
  329. if (cache.recurrent) {
  330. if (seq_id >= (int64_t) cache.size) {
  331. // could be fatal
  332. return false;
  333. }
  334. if (0 <= seq_id) {
  335. int32_t & tail_id = cache.cells[seq_id].tail;
  336. if (tail_id >= 0) {
  337. const llama_kv_cell & cell = cache.cells[tail_id];
  338. // partial intersection is invalid
  339. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  340. return false;
  341. }
  342. // invalidate tails which will be cleared
  343. if (p0 <= cell.pos && cell.pos < p1) {
  344. tail_id = -1;
  345. }
  346. }
  347. } else {
  348. // seq_id is negative, then the range should include everything or nothing
  349. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  350. return false;
  351. }
  352. }
  353. }
  354. for (uint32_t i = 0; i < cache.size; ++i) {
  355. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  356. if (seq_id < 0) {
  357. cache.cells[i].seq_id.clear();
  358. } else if (cache.cells[i].has_seq_id(seq_id)) {
  359. cache.cells[i].seq_id.erase(seq_id);
  360. } else {
  361. continue;
  362. }
  363. if (cache.cells[i].is_empty()) {
  364. // keep count of the number of used cells
  365. if (cache.cells[i].pos >= 0) cache.used--;
  366. cache.cells[i].pos = -1;
  367. cache.cells[i].src = -1;
  368. if (new_head == cache.size) new_head = i;
  369. }
  370. }
  371. }
  372. // If we freed up a slot, set head to it so searching can start there.
  373. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  374. return true;
  375. }
  376. void llama_kv_cache_seq_cp(
  377. struct llama_kv_cache & cache,
  378. llama_seq_id seq_id_src,
  379. llama_seq_id seq_id_dst,
  380. llama_pos p0,
  381. llama_pos p1) {
  382. if (p0 < 0) p0 = 0;
  383. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  384. if (cache.recurrent) {
  385. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  386. llama_kv_cell & tail_src = cache.cells[seq_id_src];
  387. llama_kv_cell & tail_dst = cache.cells[seq_id_dst];
  388. if (tail_dst.tail >= 0) {
  389. // clear destination seq_id if it wasn't empty
  390. llama_kv_cell & cell_dst = cache.cells[tail_dst.tail];
  391. cell_dst.seq_id.erase(seq_id_dst);
  392. tail_dst.tail = -1;
  393. if (cell_dst.seq_id.empty()) {
  394. cell_dst.pos = -1;
  395. cell_dst.delta = -1;
  396. cell_dst.src = -1;
  397. cache.used -= 1;
  398. }
  399. }
  400. if (tail_src.tail >= 0) {
  401. llama_kv_cell & cell_src = cache.cells[tail_src.tail];
  402. cell_src.seq_id.insert(seq_id_dst);
  403. tail_dst.tail = tail_src.tail;
  404. }
  405. }
  406. return;
  407. }
  408. // otherwise, this is the KV cache of a Transformer-like model
  409. cache.head = 0;
  410. for (uint32_t i = 0; i < cache.size; ++i) {
  411. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  412. cache.cells[i].seq_id.insert(seq_id_dst);
  413. }
  414. }
  415. }
  416. void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  417. uint32_t new_head = cache.size;
  418. for (uint32_t i = 0; i < cache.size; ++i) {
  419. if (cache.recurrent && (llama_seq_id) i != seq_id) {
  420. cache.cells[i].tail = -1;
  421. }
  422. if (!cache.cells[i].has_seq_id(seq_id)) {
  423. if (cache.cells[i].pos >= 0) cache.used--;
  424. cache.cells[i].pos = -1;
  425. cache.cells[i].src = -1;
  426. cache.cells[i].seq_id.clear();
  427. if (new_head == cache.size) new_head = i;
  428. } else {
  429. cache.cells[i].seq_id.clear();
  430. cache.cells[i].seq_id.insert(seq_id);
  431. }
  432. }
  433. // If we freed up a slot, set head to it so searching can start there.
  434. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  435. }
  436. void llama_kv_cache_seq_add(
  437. struct llama_kv_cache & cache,
  438. llama_seq_id seq_id,
  439. llama_pos p0,
  440. llama_pos p1,
  441. llama_pos delta) {
  442. uint32_t new_head = cache.size;
  443. if (p0 < 0) p0 = 0;
  444. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  445. // If there is no range then return early to avoid looping over the cache.
  446. if (p0 == p1) return;
  447. if (cache.recurrent) {
  448. // for Mamba-like or RWKV models, only the pos needs to be shifted
  449. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  450. const int32_t tail_id = cache.cells[seq_id].tail;
  451. if (tail_id >= 0) {
  452. llama_kv_cell & cell = cache.cells[tail_id];
  453. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  454. cell.pos += delta;
  455. }
  456. }
  457. }
  458. return;
  459. }
  460. for (uint32_t i = 0; i < cache.size; ++i) {
  461. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  462. cache.has_shift = true;
  463. cache.cells[i].pos += delta;
  464. cache.cells[i].delta += delta;
  465. if (cache.cells[i].pos < 0) {
  466. if (!cache.cells[i].is_empty()) {
  467. cache.used--;
  468. }
  469. cache.cells[i].pos = -1;
  470. cache.cells[i].seq_id.clear();
  471. if (new_head == cache.size) {
  472. new_head = i;
  473. }
  474. }
  475. }
  476. }
  477. // If we freed up a slot, set head to it so searching can start there.
  478. // Otherwise we just start the next search from the beginning.
  479. cache.head = new_head != cache.size ? new_head : 0;
  480. }
  481. void llama_kv_cache_seq_div(
  482. struct llama_kv_cache & cache,
  483. llama_seq_id seq_id,
  484. llama_pos p0,
  485. llama_pos p1,
  486. int d) {
  487. if (p0 < 0) p0 = 0;
  488. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  489. // If there is no range then return early to avoid looping over the cache.
  490. if (p0 == p1) return;
  491. if (cache.recurrent) {
  492. // for Mamba-like or RWKV models, only the pos needs to be changed
  493. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  494. const int32_t tail_id = cache.cells[seq_id].tail;
  495. if (tail_id >= 0) {
  496. llama_kv_cell & cell = cache.cells[tail_id];
  497. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  498. cell.pos /= d;
  499. }
  500. }
  501. }
  502. return;
  503. }
  504. for (uint32_t i = 0; i < cache.size; ++i) {
  505. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  506. cache.has_shift = true;
  507. {
  508. llama_pos p_old = cache.cells[i].pos;
  509. cache.cells[i].pos /= d;
  510. cache.cells[i].delta += cache.cells[i].pos - p_old;
  511. }
  512. }
  513. }
  514. }
  515. llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  516. llama_pos result = 0;
  517. for (uint32_t i = 0; i < cache.size; ++i) {
  518. if (cache.cells[i].has_seq_id(seq_id)) {
  519. result = std::max(result, cache.cells[i].pos);
  520. }
  521. }
  522. return result;
  523. }
  524. void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  525. if (!cache.recurrent) {
  526. cache.do_defrag = true;
  527. }
  528. }
  529. int32_t llama_get_kv_cache_token_count(const struct llama_kv_cache & kv) {
  530. int result = 0;
  531. for (uint32_t i = 0; i < kv.size; i++) {
  532. result += kv.cells[i].seq_id.size();
  533. }
  534. return result;
  535. }
  536. int32_t llama_get_kv_cache_used_cells(const struct llama_kv_cache & kv) {
  537. return kv.used;
  538. }
  539. bool llama_kv_cache_can_shift(const struct llama_kv_cache & kv) {
  540. return kv.can_shift;
  541. }
  542. //
  543. // kv cache view
  544. //
  545. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_kv_cache & kv, int32_t n_seq_max) {
  546. struct llama_kv_cache_view result = {
  547. /*.n_cells = */ 0,
  548. /*.n_seq_max = */ n_seq_max,
  549. /*.token_count = */ 0,
  550. /*.used_cells = */ llama_get_kv_cache_used_cells(kv),
  551. /*.max_contiguous = */ 0,
  552. /*.max_contiguous_idx = */ -1,
  553. /*.cells = */ nullptr,
  554. /*.cells_sequences = */ nullptr,
  555. };
  556. return result;
  557. }
  558. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  559. if (view->cells != nullptr) {
  560. free(view->cells);
  561. view->cells = nullptr;
  562. }
  563. if (view->cells_sequences != nullptr) {
  564. free(view->cells_sequences);
  565. view->cells_sequences = nullptr;
  566. }
  567. }
  568. void llama_kv_cache_view_update(struct llama_kv_cache_view * view, const struct llama_kv_cache & kv) {
  569. if (uint32_t(view->n_cells) < kv.size || view->cells == nullptr) {
  570. view->n_cells = int32_t(kv.size);
  571. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  572. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  573. view->cells = (struct llama_kv_cache_view_cell *)p;
  574. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  575. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  576. view->cells_sequences = (llama_seq_id *)p;
  577. }
  578. const std::vector<llama_kv_cell> & kv_cells = kv.cells;
  579. llama_kv_cache_view_cell * c_curr = view->cells;
  580. llama_seq_id * cs_curr = view->cells_sequences;
  581. int32_t used_cells = 0;
  582. int32_t token_count = 0;
  583. int32_t curr_contig_idx = -1;
  584. uint32_t max_contig = 0;
  585. int32_t max_contig_idx = -1;
  586. for (int32_t i = 0; i < int32_t(kv.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  587. const size_t curr_size = kv_cells[i].seq_id.size();
  588. token_count += curr_size;
  589. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  590. if (curr_size > 0) {
  591. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  592. max_contig = i - curr_contig_idx;
  593. max_contig_idx = curr_contig_idx;
  594. }
  595. curr_contig_idx = -1;
  596. } else if (curr_contig_idx < 0) {
  597. curr_contig_idx = i;
  598. }
  599. int seq_idx = 0;
  600. for (const llama_seq_id it : kv_cells[i].seq_id) {
  601. if (seq_idx >= view->n_seq_max) {
  602. break;
  603. }
  604. cs_curr[seq_idx] = it;
  605. seq_idx++;
  606. }
  607. if (seq_idx != 0) {
  608. used_cells++;
  609. }
  610. for (; seq_idx < view->n_seq_max; seq_idx++) {
  611. cs_curr[seq_idx] = -1;
  612. }
  613. }
  614. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  615. max_contig_idx = curr_contig_idx;
  616. max_contig = kv_cells.size() - curr_contig_idx;
  617. }
  618. view->max_contiguous = max_contig;
  619. view->max_contiguous_idx = max_contig_idx;
  620. view->token_count = token_count;
  621. view->used_cells = used_cells;
  622. if (uint32_t(used_cells) != kv.used) {
  623. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  624. __func__, kv.used, used_cells);
  625. }
  626. }