llama-memory-recurrent.cpp 38 KB

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