llama-kv-cache.cpp 27 KB

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