llama-memory-recurrent.cpp 37 KB

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