llama-kv-cache-recurrent.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. #include "llama-kv-cache-recurrent.h"
  2. #include "llama-impl.h"
  3. #include "llama-io.h"
  4. #include "llama-batch.h"
  5. #include "llama-model.h"
  6. #include <algorithm>
  7. #include <cassert>
  8. #include <limits>
  9. #include <map>
  10. #include <stdexcept>
  11. //
  12. // llama_kv_cache_recurrent
  13. //
  14. llama_kv_cache_recurrent::llama_kv_cache_recurrent(
  15. const llama_model & model,
  16. ggml_type type_k,
  17. ggml_type type_v,
  18. bool offload,
  19. uint32_t kv_size,
  20. uint32_t n_seq_max) : hparams(model.hparams), n_seq_max(n_seq_max) {
  21. const int32_t n_layer = hparams.n_layer;
  22. LLAMA_LOG_INFO("%s: kv_size = %u, n_seq_max = %u, type_k = '%s', type_v = '%s', n_layer = %d\n",
  23. __func__, kv_size, n_seq_max, ggml_type_name(type_k), ggml_type_name(type_v), n_layer);
  24. head = 0;
  25. size = kv_size;
  26. used = 0;
  27. cells.clear();
  28. cells.resize(kv_size);
  29. // create a context for each buffer type
  30. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  31. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  32. auto it = ctx_map.find(buft);
  33. if (it == ctx_map.end()) {
  34. ggml_init_params params = {
  35. /*.mem_size =*/ size_t(2u*n_layer*ggml_tensor_overhead()),
  36. /*.mem_buffer =*/ NULL,
  37. /*.no_alloc =*/ true,
  38. };
  39. ggml_context * ctx = ggml_init(params);
  40. if (!ctx) {
  41. return nullptr;
  42. }
  43. ctx_map[buft] = ctx;
  44. ctxs.emplace_back(ctx);
  45. return ctx;
  46. }
  47. return it->second;
  48. };
  49. k_l.reserve(n_layer);
  50. v_l.reserve(n_layer);
  51. for (int i = 0; i < n_layer; i++) {
  52. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  53. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  54. const char * dev_name = "CPU";
  55. ggml_backend_buffer_type_t buft = ggml_backend_cpu_buffer_type();
  56. if (offload) {
  57. auto * dev = model.dev_layer(i);
  58. buft = ggml_backend_dev_buffer_type(dev);
  59. dev_name = ggml_backend_dev_name(dev);
  60. }
  61. LLAMA_LOG_DEBUG("%s, layer %3d: dev = %s\n", __func__, i, dev_name);
  62. ggml_context * ctx = ctx_for_buft(buft);
  63. if (!ctx) {
  64. throw std::runtime_error("failed to create ggml context for kv cache");
  65. }
  66. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  67. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  68. ggml_format_name(k, "cache_k_l%d", i);
  69. ggml_format_name(v, "cache_v_l%d", i);
  70. k_l.push_back(k);
  71. v_l.push_back(v);
  72. }
  73. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  74. for (auto it : ctx_map) {
  75. auto * buft = it.first;
  76. auto * ctx = it.second;
  77. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  78. if (!buf) {
  79. throw std::runtime_error("failed to allocate buffer for kv cache");
  80. }
  81. ggml_backend_buffer_clear(buf, 0);
  82. 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);
  83. bufs.emplace_back(buf);
  84. }
  85. {
  86. const size_t memory_size_k = size_k_bytes();
  87. const size_t memory_size_v = size_v_bytes();
  88. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  89. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  90. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  91. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  92. }
  93. }
  94. void llama_kv_cache_recurrent::clear(bool data) {
  95. for (int32_t i = 0; i < (int32_t) size; ++i) {
  96. cells[i].pos = -1;
  97. cells[i].seq_id.clear();
  98. cells[i].src = -1;
  99. cells[i].tail = -1;
  100. }
  101. head = 0;
  102. used = 0;
  103. if (data) {
  104. for (auto & buf : bufs) {
  105. ggml_backend_buffer_clear(buf.get(), 0);
  106. }
  107. }
  108. }
  109. bool llama_kv_cache_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  110. uint32_t new_head = size;
  111. if (p0 < 0) {
  112. p0 = 0;
  113. }
  114. if (p1 < 0) {
  115. p1 = std::numeric_limits<llama_pos>::max();
  116. }
  117. // models like Mamba or RWKV can't have a state partially erased
  118. if (seq_id >= (int64_t) size) {
  119. // could be fatal
  120. return false;
  121. }
  122. if (0 <= seq_id) {
  123. int32_t & tail_id = cells[seq_id].tail;
  124. if (tail_id >= 0) {
  125. const kv_cell & cell = cells[tail_id];
  126. // partial intersection is invalid
  127. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  128. return false;
  129. }
  130. // invalidate tails which will be cleared
  131. if (p0 <= cell.pos && cell.pos < p1) {
  132. tail_id = -1;
  133. }
  134. }
  135. } else {
  136. // seq_id is negative, then the range should include everything or nothing
  137. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  138. return false;
  139. }
  140. }
  141. for (uint32_t i = 0; i < size; ++i) {
  142. if (cells[i].pos >= p0 && cells[i].pos < p1) {
  143. if (seq_id < 0) {
  144. cells[i].seq_id.clear();
  145. } else if (cells[i].has_seq_id(seq_id)) {
  146. cells[i].seq_id.erase(seq_id);
  147. } else {
  148. continue;
  149. }
  150. if (cells[i].is_empty()) {
  151. // keep count of the number of used cells
  152. if (cells[i].pos >= 0) {
  153. used--;
  154. }
  155. cells[i].pos = -1;
  156. cells[i].src = -1;
  157. if (new_head == size) {
  158. new_head = i;
  159. }
  160. }
  161. }
  162. }
  163. // If we freed up a slot, set head to it so searching can start there.
  164. if (new_head != size && new_head < head) {
  165. head = new_head;
  166. }
  167. return true;
  168. }
  169. void llama_kv_cache_recurrent::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
  170. if (seq_id_src == seq_id_dst) {
  171. return;
  172. }
  173. if (p0 < 0) {
  174. p0 = 0;
  175. }
  176. if (p1 < 0) {
  177. p1 = std::numeric_limits<llama_pos>::max();
  178. }
  179. if ((uint32_t) seq_id_dst < size && (uint32_t) seq_id_src < size) {
  180. kv_cell & tail_src = cells[seq_id_src];
  181. kv_cell & tail_dst = cells[seq_id_dst];
  182. if (tail_dst.tail >= 0) {
  183. // clear destination seq_id if it wasn't empty
  184. kv_cell & cell_dst = cells[tail_dst.tail];
  185. cell_dst.seq_id.erase(seq_id_dst);
  186. tail_dst.tail = -1;
  187. if (cell_dst.seq_id.empty()) {
  188. cell_dst.pos = -1;
  189. cell_dst.src = -1;
  190. used -= 1;
  191. }
  192. }
  193. if (tail_src.tail >= 0) {
  194. kv_cell & cell_src = cells[tail_src.tail];
  195. cell_src.seq_id.insert(seq_id_dst);
  196. tail_dst.tail = tail_src.tail;
  197. }
  198. }
  199. }
  200. void llama_kv_cache_recurrent::seq_keep(llama_seq_id seq_id) {
  201. uint32_t new_head = size;
  202. for (uint32_t i = 0; i < size; ++i) {
  203. if ((llama_seq_id) i != seq_id) {
  204. cells[i].tail = -1;
  205. }
  206. if (!cells[i].has_seq_id(seq_id)) {
  207. if (cells[i].pos >= 0) {
  208. used--;
  209. }
  210. cells[i].pos = -1;
  211. cells[i].src = -1;
  212. cells[i].seq_id.clear();
  213. if (new_head == size){
  214. new_head = i;
  215. }
  216. } else {
  217. cells[i].seq_id.clear();
  218. cells[i].seq_id.insert(seq_id);
  219. }
  220. }
  221. // If we freed up a slot, set head to it so searching can start there.
  222. if (new_head != size && new_head < head) {
  223. head = new_head;
  224. }
  225. }
  226. void llama_kv_cache_recurrent::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) {
  227. if (shift == 0) {
  228. return;
  229. }
  230. if (p0 < 0) {
  231. p0 = 0;
  232. }
  233. if (p1 < 0) {
  234. p1 = std::numeric_limits<llama_pos>::max();
  235. }
  236. // If there is no range then return early to avoid looping over the
  237. if (p0 == p1) {
  238. return;
  239. }
  240. // for Mamba-like or RWKV models, only the pos needs to be shifted
  241. if (0 <= seq_id && seq_id < (int64_t) size) {
  242. const int32_t tail_id = cells[seq_id].tail;
  243. if (tail_id >= 0) {
  244. kv_cell & cell = cells[tail_id];
  245. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  246. cell.pos += shift;
  247. }
  248. }
  249. }
  250. }
  251. void llama_kv_cache_recurrent::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  252. if (d == 1) {
  253. return;
  254. }
  255. if (p0 < 0) {
  256. p0 = 0;
  257. }
  258. if (p1 < 0) {
  259. p1 = std::numeric_limits<llama_pos>::max();
  260. }
  261. // If there is no range then return early to avoid looping over the cache.
  262. if (p0 == p1) {
  263. return;
  264. }
  265. // for Mamba-like or RWKV models, only the pos needs to be changed
  266. if (0 <= seq_id && seq_id < (int64_t) size) {
  267. const int32_t tail_id = cells[seq_id].tail;
  268. if (tail_id >= 0) {
  269. kv_cell & cell = cells[tail_id];
  270. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  271. cell.pos /= d;
  272. }
  273. }
  274. }
  275. }
  276. llama_pos llama_kv_cache_recurrent::seq_pos_min(llama_seq_id seq_id) const {
  277. llama_pos result = std::numeric_limits<llama_pos>::max();
  278. for (uint32_t i = 0; i < size; ++i) {
  279. if (cells[i].has_seq_id(seq_id)) {
  280. result = std::min(result, cells[i].pos);
  281. }
  282. }
  283. if (result == std::numeric_limits<llama_pos>::max()) {
  284. result = -1;
  285. }
  286. return result;
  287. }
  288. llama_pos llama_kv_cache_recurrent::seq_pos_max(llama_seq_id seq_id) const {
  289. llama_pos result = -1;
  290. for (uint32_t i = 0; i < size; ++i) {
  291. if (cells[i].has_seq_id(seq_id)) {
  292. result = std::max(result, cells[i].pos);
  293. }
  294. }
  295. return result;
  296. }
  297. llama_memory_state_ptr llama_kv_cache_recurrent::init_batch(const llama_batch & batch, uint32_t n_ubatch, bool embd_all) {
  298. auto sbatch = llama_sbatch(batch, hparams.n_embd, false);
  299. std::vector<llama_ubatch> ubatches;
  300. while (sbatch.n_tokens > 0) {
  301. llama_ubatch ubatch;
  302. if (embd_all) {
  303. // if all tokens are output, split by sequence
  304. ubatch = sbatch.split_seq(n_ubatch);
  305. } else {
  306. ubatch = sbatch.split_equal(n_ubatch);
  307. }
  308. ubatches.push_back(ubatch);
  309. }
  310. if (!prepare(ubatches)) {
  311. return std::make_unique<llama_kv_cache_recurrent_state>(LLAMA_MEMORY_STATUS_FAILED_PREPARE);
  312. }
  313. return std::make_unique<llama_kv_cache_recurrent_state>(LLAMA_MEMORY_STATUS_SUCCESS, this, std::move(sbatch), std::move(ubatches));
  314. }
  315. llama_memory_state_ptr llama_kv_cache_recurrent::init_full() {
  316. return std::make_unique<llama_kv_cache_recurrent_state>(LLAMA_MEMORY_STATUS_SUCCESS, this);
  317. }
  318. llama_memory_state_ptr llama_kv_cache_recurrent::init_update(llama_context * lctx, bool optimize) {
  319. GGML_UNUSED(lctx);
  320. GGML_UNUSED(optimize);
  321. return std::make_unique<llama_kv_cache_recurrent_state>(LLAMA_MEMORY_STATUS_NO_UPDATE);
  322. }
  323. bool llama_kv_cache_recurrent::prepare(const std::vector<llama_ubatch> & ubatches) {
  324. // simply remember the full state because it is very small for this type of cache
  325. // TODO: optimize
  326. auto org_cells = cells;
  327. auto org_used = used;
  328. auto org_head = head;
  329. bool success = true;
  330. for (const auto & ubatch : ubatches) {
  331. if (!find_slot(ubatch)) {
  332. success = false;
  333. break;
  334. }
  335. }
  336. // restore the original state
  337. cells = std::move(org_cells);
  338. used = org_used;
  339. head = org_head;
  340. return success;
  341. }
  342. bool llama_kv_cache_recurrent::find_slot(const llama_ubatch & ubatch) {
  343. const uint32_t n_seqs = ubatch.n_seqs;
  344. const uint32_t n_seq_tokens = ubatch.n_seq_tokens;
  345. // if we have enough unused cells before the current head ->
  346. // better to start searching from the beginning of the cache, hoping to fill it
  347. if (head > used + 2*n_seqs) {
  348. head = 0;
  349. }
  350. // For recurrent state architectures (like Mamba or RWKV),
  351. // each cache cell can store the state for a whole sequence.
  352. // A slot should be always be contiguous.
  353. // can only process batches with an equal number of new tokens in each sequence
  354. GGML_ASSERT(ubatch.equal_seqs);
  355. int32_t min = size - 1;
  356. int32_t max = 0;
  357. // everything should fit if all seq_ids are smaller than the max
  358. for (uint32_t s = 0; s < n_seqs; ++s) {
  359. const uint32_t n_seq_id = ubatch.n_seq_id[s];
  360. for (uint32_t j = 0; j < n_seq_id; ++j) {
  361. const llama_seq_id seq_id = ubatch.seq_id[s][j];
  362. if (seq_id < 0 || (uint32_t) seq_id >= size) {
  363. // too big seq_id
  364. // TODO: would it be possible to resize the cache instead?
  365. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%u Try using a bigger --parallel value\n", __func__, seq_id, n_seq_max);
  366. return false;
  367. }
  368. if (j > 0) {
  369. kv_cell & seq = cells[seq_id];
  370. if (seq.tail >= 0) {
  371. kv_cell & cell = cells[seq.tail];
  372. // clear cells from seq_ids that become shared
  373. // (should not normally happen, but let's handle it anyway)
  374. cell.seq_id.erase(seq_id);
  375. seq.tail = -1;
  376. if (cell.seq_id.empty()) {
  377. cell.pos = -1;
  378. cell.src = -1;
  379. used -= 1;
  380. }
  381. }
  382. }
  383. }
  384. }
  385. #ifndef NDEBUG
  386. {
  387. std::vector<int32_t> tails_verif;
  388. tails_verif.assign(size, -1);
  389. for (uint32_t i = 0; i < size; ++i) {
  390. kv_cell & cell = cells[i];
  391. for (llama_seq_id seq_id : cell.seq_id) {
  392. if (tails_verif[seq_id] != -1) {
  393. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  394. }
  395. tails_verif[seq_id] = i;
  396. }
  397. }
  398. for (uint32_t i = 0; i < size; ++i) {
  399. if (tails_verif[i] != cells[i].tail) {
  400. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cells[i].tail, tails_verif[i]);
  401. }
  402. }
  403. }
  404. #endif
  405. // find next empty cell
  406. uint32_t next_empty_cell = head;
  407. for (uint32_t i = 0; i < size; ++i) {
  408. if (next_empty_cell >= size) { next_empty_cell -= size; }
  409. kv_cell & cell = cells[next_empty_cell];
  410. if (cell.is_empty()) { break; }
  411. next_empty_cell += 1;
  412. }
  413. // find usable cell range
  414. for (uint32_t s = 0; s < n_seqs; ++s) {
  415. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  416. kv_cell & seq_meta = cells[seq_id];
  417. bool has_cell = false;
  418. if (seq_meta.tail >= 0) {
  419. kv_cell & cell = cells[seq_meta.tail];
  420. GGML_ASSERT(cell.has_seq_id(seq_id));
  421. // does this seq_id "own" the cell?
  422. if (cell.seq_id.size() == 1) { has_cell = true; }
  423. }
  424. if (!has_cell) {
  425. kv_cell & empty_cell = cells[next_empty_cell];
  426. GGML_ASSERT(empty_cell.is_empty());
  427. // copy old tail into the empty cell
  428. if (seq_meta.tail >= 0) {
  429. kv_cell & orig_cell = cells[seq_meta.tail];
  430. empty_cell.pos = orig_cell.pos;
  431. empty_cell.src = orig_cell.src;
  432. orig_cell.seq_id.erase(seq_id);
  433. empty_cell.seq_id.insert(seq_id); // will be overwritten
  434. GGML_ASSERT(!orig_cell.is_empty()); // has at least one remaining seq_id
  435. }
  436. seq_meta.tail = next_empty_cell;
  437. // find next empty cell
  438. if (s + 1 < n_seqs) {
  439. for (uint32_t i = 0; i < size; ++i) {
  440. next_empty_cell += 1;
  441. if (next_empty_cell >= size) { next_empty_cell -= size; }
  442. kv_cell & cell = cells[next_empty_cell];
  443. if (cell.is_empty()) { break; }
  444. }
  445. }
  446. }
  447. if (min > seq_meta.tail) { min = seq_meta.tail; }
  448. if (max < seq_meta.tail) { max = seq_meta.tail; }
  449. }
  450. // gather and re-order
  451. for (uint32_t s = 0; s < n_seqs; ++s) {
  452. const int32_t dst_id = s + min;
  453. const int32_t src_id = cells[ubatch.seq_id[s][0]].tail;
  454. if (dst_id != src_id) {
  455. kv_cell & dst_cell = cells[dst_id];
  456. kv_cell & src_cell = cells[src_id];
  457. std::swap(dst_cell.pos, src_cell.pos);
  458. std::swap(dst_cell.src, src_cell.src);
  459. std::swap(dst_cell.seq_id, src_cell.seq_id);
  460. // swap tails
  461. for (uint32_t i = 0; i < size; ++i) {
  462. int32_t & tail = cells[i].tail;
  463. if (tail == src_id) {
  464. tail = dst_id;
  465. } else if (tail == dst_id) {
  466. tail = src_id;
  467. }
  468. }
  469. }
  470. }
  471. // update the pos of the used seqs
  472. for (uint32_t s = 0; s < n_seqs; ++s) {
  473. const llama_pos last_pos = ubatch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  474. const int32_t cell_id = s + min;
  475. kv_cell & cell = cells[cell_id];
  476. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  477. // What should happen when the pos backtracks or skips a value?
  478. // Clearing the state mid-batch would require special-casing which isn't done.
  479. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  480. __func__, last_pos, cell.pos, ubatch.seq_id[s][0], n_seq_tokens);
  481. }
  482. cell.pos = last_pos;
  483. cell.seq_id.clear();
  484. for (int32_t j = 0; j < ubatch.n_seq_id[s]; ++j) {
  485. const llama_seq_id seq_id = ubatch.seq_id[s][j];
  486. cell.seq_id.insert(seq_id);
  487. cells[seq_id].tail = cell_id;
  488. }
  489. }
  490. // Find first cell without src refs, to use as the zero-ed state
  491. {
  492. // TODO: bake-in src refcounts in the cell metadata
  493. std::vector<int32_t> refcounts(size, 0);
  494. for (size_t i = 0; i < size; ++i) {
  495. const int32_t src = cells[i].src;
  496. if (src >= 0) {
  497. refcounts[src] += 1;
  498. }
  499. }
  500. rs_z = -1;
  501. for (int i = min; i <= max; ++i) {
  502. if (refcounts[i] == 0) {
  503. rs_z = i;
  504. break;
  505. }
  506. }
  507. for (int i = min; i <= max; ++i) {
  508. if (cells[i].src < 0) {
  509. GGML_ASSERT(rs_z >= 0);
  510. cells[i].src0 = rs_z;
  511. } else {
  512. // Stage the source ids for all used cells to allow correct seq_* behavior
  513. // and still make these values available when setting the inputs
  514. cells[i].src0 = cells[i].src;
  515. }
  516. cells[i].src = i; // avoid moving or clearing twice
  517. }
  518. }
  519. // allow getting the range of used cells, from head to head + n
  520. head = min;
  521. n = max - min + 1;
  522. used = std::count_if(cells.begin(), cells.end(),
  523. [](const kv_cell & cell){ return !cell.is_empty(); });
  524. // sanity check
  525. return n >= n_seqs;
  526. }
  527. bool llama_kv_cache_recurrent::get_can_shift() const {
  528. // shifting the pos is trivial for recurrent models
  529. return true;
  530. }
  531. size_t llama_kv_cache_recurrent::total_size() const {
  532. size_t size = 0;
  533. for (const auto & buf : bufs) {
  534. size += ggml_backend_buffer_get_size(buf.get());
  535. }
  536. return size;
  537. }
  538. size_t llama_kv_cache_recurrent::size_k_bytes() const {
  539. size_t size_k_bytes = 0;
  540. for (const auto & k : k_l) {
  541. size_k_bytes += ggml_nbytes(k);
  542. }
  543. return size_k_bytes;
  544. }
  545. size_t llama_kv_cache_recurrent::size_v_bytes() const {
  546. size_t size_v_bytes = 0;
  547. for (const auto & v : v_l) {
  548. size_v_bytes += ggml_nbytes(v);
  549. }
  550. return size_v_bytes;
  551. }
  552. void llama_kv_cache_recurrent::state_write(llama_io_write_i & io, llama_seq_id seq_id) const {
  553. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  554. uint32_t cell_count = 0;
  555. // Count the number of cells with the specified seq_id
  556. // Find all the ranges of cells with this seq id (or all, when -1)
  557. uint32_t cell_range_begin = size;
  558. for (uint32_t i = 0; i < size; ++i) {
  559. const auto & cell = cells[i];
  560. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  561. ++cell_count;
  562. if (cell_range_begin == size) {
  563. cell_range_begin = i;
  564. }
  565. } else {
  566. if (cell_range_begin != size) {
  567. cell_ranges.emplace_back(cell_range_begin, i);
  568. cell_range_begin = size;
  569. }
  570. }
  571. }
  572. if (cell_range_begin != size) {
  573. cell_ranges.emplace_back(cell_range_begin, size);
  574. }
  575. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  576. uint32_t cell_count_check = 0;
  577. for (const auto & range : cell_ranges) {
  578. cell_count_check += range.second - range.first;
  579. }
  580. GGML_ASSERT(cell_count == cell_count_check);
  581. io.write(&cell_count, sizeof(cell_count));
  582. state_write_meta(io, cell_ranges, seq_id);
  583. state_write_data(io, cell_ranges);
  584. }
  585. void llama_kv_cache_recurrent::state_read(llama_io_read_i & io, llama_seq_id seq_id) {
  586. uint32_t cell_count;
  587. io.read_to(&cell_count, sizeof(cell_count));
  588. bool res = true;
  589. res = res && state_read_meta(io, cell_count, seq_id);
  590. res = res && state_read_data(io, cell_count);
  591. if (!res) {
  592. if (seq_id == -1) {
  593. clear(true);
  594. } else {
  595. seq_rm(seq_id, -1, -1);
  596. }
  597. throw std::runtime_error("failed to restore kv cache");
  598. }
  599. }
  600. void llama_kv_cache_recurrent::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 {
  601. for (const auto & range : cell_ranges) {
  602. for (uint32_t i = range.first; i < range.second; ++i) {
  603. const auto & cell = cells[i];
  604. const llama_pos pos = cell.pos;
  605. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  606. io.write(&pos, sizeof(pos));
  607. io.write(&n_seq_id, sizeof(n_seq_id));
  608. if (n_seq_id) {
  609. for (auto seq_id : cell.seq_id) {
  610. io.write(&seq_id, sizeof(seq_id));
  611. }
  612. }
  613. }
  614. }
  615. }
  616. void llama_kv_cache_recurrent::state_write_data(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) const {
  617. const uint32_t v_trans = 0;
  618. const uint32_t n_layer = hparams.n_layer;
  619. io.write(&v_trans, sizeof(v_trans));
  620. io.write(&n_layer, sizeof(n_layer));
  621. std::vector<uint8_t> tmp_buf;
  622. // Iterate and write all the keys first, each row is a cell
  623. // Get whole range at a time
  624. for (uint32_t il = 0; il < n_layer; ++il) {
  625. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  626. // Write key type
  627. const int32_t k_type_i = (int32_t)k_l[il]->type;
  628. io.write(&k_type_i, sizeof(k_type_i));
  629. // Write row size of key
  630. const uint64_t k_size_row = ggml_row_size(k_l[il]->type, n_embd_k_gqa);
  631. io.write(&k_size_row, sizeof(k_size_row));
  632. // Read each range of cells of k_size length each into tmp_buf and write out
  633. for (const auto & range : cell_ranges) {
  634. const size_t range_size = range.second - range.first;
  635. const size_t buf_size = range_size * k_size_row;
  636. io.write_tensor(k_l[il], range.first * k_size_row, buf_size);
  637. }
  638. }
  639. if (!v_trans) {
  640. for (uint32_t il = 0; il < n_layer; ++il) {
  641. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  642. // Write value type
  643. const int32_t v_type_i = (int32_t)v_l[il]->type;
  644. io.write(&v_type_i, sizeof(v_type_i));
  645. // Write row size of value
  646. const uint64_t v_size_row = ggml_row_size(v_l[il]->type, n_embd_v_gqa);
  647. io.write(&v_size_row, sizeof(v_size_row));
  648. // Read each range of cells of v_size length each into tmp_buf and write out
  649. for (const auto & range : cell_ranges) {
  650. const size_t range_size = range.second - range.first;
  651. const size_t buf_size = range_size * v_size_row;
  652. io.write_tensor(v_l[il], range.first * v_size_row, buf_size);
  653. }
  654. }
  655. } else {
  656. // When v is transposed, we also need the element size and get the element ranges from each row
  657. const uint32_t kv_size = size;
  658. for (uint32_t il = 0; il < n_layer; ++il) {
  659. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  660. // Write value type
  661. const int32_t v_type_i = (int32_t)v_l[il]->type;
  662. io.write(&v_type_i, sizeof(v_type_i));
  663. // Write element size
  664. const uint32_t v_size_el = ggml_type_size(v_l[il]->type);
  665. io.write(&v_size_el, sizeof(v_size_el));
  666. // Write GQA embedding size
  667. io.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  668. // For each row, we get the element values of each cell
  669. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  670. // Read each range of cells of v_size_el length each into tmp_buf and write out
  671. for (const auto & range : cell_ranges) {
  672. const size_t range_size = range.second - range.first;
  673. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  674. const size_t buf_size = range_size * v_size_el;
  675. io.write_tensor(v_l[il], src_offset, buf_size);
  676. }
  677. }
  678. }
  679. }
  680. }
  681. bool llama_kv_cache_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
  682. if (dest_seq_id != -1) {
  683. // single sequence
  684. seq_rm(dest_seq_id, -1, -1);
  685. llama_sbatch sbatch;
  686. llama_ubatch batch = sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  687. batch.n_tokens = cell_count;
  688. batch.n_seq_tokens = cell_count;
  689. batch.n_seqs = 1;
  690. for (uint32_t i = 0; i < cell_count; ++i) {
  691. llama_pos pos;
  692. uint32_t n_seq_id;
  693. io.read_to(&pos, sizeof(pos));
  694. io.read_to(&n_seq_id, sizeof(n_seq_id));
  695. if (n_seq_id != 0) {
  696. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  697. return false;
  698. }
  699. batch.pos[i] = pos;
  700. }
  701. batch.n_seq_id[0] = 1;
  702. batch.seq_id[0] = &dest_seq_id;
  703. if (!find_slot(batch)) {
  704. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  705. return false;
  706. }
  707. // 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)
  708. // Assume that this is one contiguous block of cells
  709. GGML_ASSERT(head + cell_count <= size);
  710. GGML_ASSERT(cells[head].pos == batch.pos[0]);
  711. GGML_ASSERT(cells[head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  712. GGML_ASSERT(cells[head].has_seq_id(dest_seq_id));
  713. GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id));
  714. } else {
  715. // whole KV cache restore
  716. if (cell_count > size) {
  717. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  718. return false;
  719. }
  720. clear(true);
  721. for (uint32_t i = 0; i < cell_count; ++i) {
  722. kv_cell & cell = cells[i];
  723. llama_pos pos;
  724. uint32_t n_seq_id;
  725. io.read_to(&pos, sizeof(pos));
  726. io.read_to(&n_seq_id, sizeof(n_seq_id));
  727. cell.pos = pos;
  728. for (uint32_t j = 0; j < n_seq_id; ++j) {
  729. llama_seq_id seq_id;
  730. io.read_to(&seq_id, sizeof(seq_id));
  731. // TODO: llama_kv_cache_recurrent should have a notion of max sequences
  732. //if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  733. if (seq_id < 0) {
  734. //LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  735. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, inf)\n", __func__, seq_id);
  736. return false;
  737. }
  738. cell.seq_id.insert(seq_id);
  739. int32_t & tail = cells[seq_id].tail;
  740. if (tail != -1) {
  741. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  742. return false;
  743. }
  744. tail = i;
  745. }
  746. }
  747. head = 0;
  748. used = cell_count;
  749. }
  750. for (uint32_t i = 0; i < cell_count; ++i) {
  751. uint32_t cell_id = head + i;
  752. // make sure the recurrent states will keep their restored state
  753. cells[cell_id].src = cell_id;
  754. }
  755. return true;
  756. }
  757. bool llama_kv_cache_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell_count) {
  758. uint32_t v_trans;
  759. uint32_t n_layer;
  760. io.read_to(&v_trans, sizeof(v_trans));
  761. io.read_to(&n_layer, sizeof(n_layer));
  762. if (n_layer != hparams.n_layer) {
  763. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  764. return false;
  765. }
  766. if (cell_count > size) {
  767. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, size);
  768. return false;
  769. }
  770. if (false != (bool) v_trans) {
  771. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  772. return false;
  773. }
  774. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  775. for (uint32_t il = 0; il < n_layer; ++il) {
  776. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  777. // Read type of key
  778. int32_t k_type_i_ref;
  779. io.read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  780. const int32_t k_type_i = (int32_t) k_l[il]->type;
  781. if (k_type_i != k_type_i_ref) {
  782. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  783. return false;
  784. }
  785. // Read row size of key
  786. uint64_t k_size_row_ref;
  787. io.read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  788. const size_t k_size_row = ggml_row_size(k_l[il]->type, n_embd_k_gqa);
  789. if (k_size_row != k_size_row_ref) {
  790. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  791. return false;
  792. }
  793. if (cell_count) {
  794. // Read and set the keys for the whole cell range
  795. ggml_backend_tensor_set(k_l[il], io.read(cell_count * k_size_row), head * k_size_row, cell_count * k_size_row);
  796. }
  797. }
  798. if (!v_trans) {
  799. for (uint32_t il = 0; il < n_layer; ++il) {
  800. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  801. // Read type of value
  802. int32_t v_type_i_ref;
  803. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  804. const int32_t v_type_i = (int32_t)v_l[il]->type;
  805. if (v_type_i != v_type_i_ref) {
  806. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  807. return false;
  808. }
  809. // Read row size of value
  810. uint64_t v_size_row_ref;
  811. io.read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  812. const size_t v_size_row = ggml_row_size(v_l[il]->type, n_embd_v_gqa);
  813. if (v_size_row != v_size_row_ref) {
  814. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  815. return false;
  816. }
  817. if (cell_count) {
  818. // Read and set the values for the whole cell range
  819. ggml_backend_tensor_set(v_l[il], io.read(cell_count * v_size_row), head * v_size_row, cell_count * v_size_row);
  820. }
  821. }
  822. } else {
  823. // For each layer, read the values for each cell (transposed)
  824. for (uint32_t il = 0; il < n_layer; ++il) {
  825. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  826. // Read type of value
  827. int32_t v_type_i_ref;
  828. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  829. const int32_t v_type_i = (int32_t)v_l[il]->type;
  830. if (v_type_i != v_type_i_ref) {
  831. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  832. return false;
  833. }
  834. // Read element size of value
  835. uint32_t v_size_el_ref;
  836. io.read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  837. const size_t v_size_el = ggml_type_size(v_l[il]->type);
  838. if (v_size_el != v_size_el_ref) {
  839. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  840. return false;
  841. }
  842. // Read GQA embedding size
  843. uint32_t n_embd_v_gqa_ref;
  844. io.read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  845. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  846. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  847. return false;
  848. }
  849. if (cell_count) {
  850. // For each row in the transposed matrix, read the values for the whole cell range
  851. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  852. const size_t dst_offset = (head + j * size) * v_size_el;
  853. ggml_backend_tensor_set(v_l[il], io.read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  854. }
  855. }
  856. }
  857. }
  858. return true;
  859. }
  860. //
  861. // llama_kv_cache_recurrent_state
  862. //
  863. llama_kv_cache_recurrent_state::llama_kv_cache_recurrent_state(llama_memory_status status) : status(status) {}
  864. llama_kv_cache_recurrent_state::llama_kv_cache_recurrent_state(
  865. llama_memory_status status,
  866. llama_kv_cache_recurrent * kv) : status(status), kv(kv), is_full(true) {
  867. }
  868. llama_kv_cache_recurrent_state::llama_kv_cache_recurrent_state(
  869. llama_memory_status status,
  870. llama_kv_cache_recurrent * kv,
  871. llama_sbatch sbatch,
  872. std::vector<llama_ubatch> ubatches) : status(status), kv(kv), sbatch(std::move(sbatch)), ubatches(std::move(ubatches)) {}
  873. llama_kv_cache_recurrent_state::~llama_kv_cache_recurrent_state() = default;
  874. bool llama_kv_cache_recurrent_state::next() {
  875. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  876. if (++i_next >= ubatches.size()) {
  877. return false;
  878. }
  879. return true;
  880. }
  881. bool llama_kv_cache_recurrent_state::apply() {
  882. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  883. kv->find_slot(ubatches[i_next]);
  884. return true;
  885. }
  886. std::vector<int64_t> & llama_kv_cache_recurrent_state::out_ids() {
  887. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  888. return sbatch.out_ids;
  889. }
  890. llama_memory_status llama_kv_cache_recurrent_state::get_status() const {
  891. return status;
  892. }
  893. const llama_ubatch & llama_kv_cache_recurrent_state::get_ubatch() const {
  894. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  895. return ubatches[i_next];
  896. }
  897. uint32_t llama_kv_cache_recurrent_state::get_n_kv() const {
  898. return is_full ? kv->size : kv->n;
  899. }
  900. uint32_t llama_kv_cache_recurrent_state::get_head() const {
  901. return is_full ? 0 : kv->head;
  902. }
  903. int32_t llama_kv_cache_recurrent_state::get_rs_z() const {
  904. return is_full ? 0 : kv->rs_z;
  905. }
  906. uint32_t llama_kv_cache_recurrent_state::get_size() const {
  907. return kv->size;
  908. }
  909. ggml_tensor * llama_kv_cache_recurrent_state::get_k_l(int32_t il) const {
  910. return kv->k_l[il];
  911. }
  912. ggml_tensor * llama_kv_cache_recurrent_state::get_v_l(int32_t il) const {
  913. return kv->v_l[il];
  914. }
  915. int32_t llama_kv_cache_recurrent_state::s_copy(int i) const {
  916. return kv->cells[i + kv->head].src0;
  917. }