llama-memory-recurrent.cpp 36 KB

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