llama-memory-recurrent.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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_context_ptr llama_memory_recurrent::init_batch(llama_batch_allocr & balloc, uint32_t n_ubatch, bool embd_all) {
  301. do {
  302. balloc.split_reset();
  303. std::vector<llama_ubatch> ubatches;
  304. while (true) {
  305. llama_ubatch ubatch;
  306. if (embd_all) {
  307. // if all tokens are output, split by sequence
  308. ubatch = balloc.split_seq(n_ubatch);
  309. } else {
  310. ubatch = balloc.split_equal(n_ubatch);
  311. }
  312. if (ubatch.n_tokens == 0) {
  313. break;
  314. }
  315. ubatches.push_back(std::move(ubatch)); // NOLINT
  316. }
  317. if (!prepare(ubatches)) {
  318. break;
  319. }
  320. return std::make_unique<llama_memory_recurrent_context>(this, std::move(ubatches));
  321. } while (false);
  322. return std::make_unique<llama_memory_recurrent_context>(LLAMA_MEMORY_STATUS_FAILED_PREPARE);
  323. }
  324. llama_memory_context_ptr llama_memory_recurrent::init_full() {
  325. return std::make_unique<llama_memory_recurrent_context>(this);
  326. }
  327. llama_memory_context_ptr llama_memory_recurrent::init_update(llama_context * lctx, bool optimize) {
  328. GGML_UNUSED(lctx);
  329. GGML_UNUSED(optimize);
  330. return std::make_unique<llama_memory_recurrent_context>(LLAMA_MEMORY_STATUS_NO_UPDATE);
  331. }
  332. bool llama_memory_recurrent::prepare(const std::vector<llama_ubatch> & ubatches) {
  333. // simply remember the full state because it is very small for this type of cache
  334. // TODO: optimize
  335. auto org_cells = cells;
  336. auto org_used = used;
  337. auto org_head = head;
  338. bool success = true;
  339. for (const auto & ubatch : ubatches) {
  340. if (!find_slot(ubatch)) {
  341. success = false;
  342. break;
  343. }
  344. }
  345. // restore the original state
  346. cells = std::move(org_cells);
  347. used = org_used;
  348. head = org_head;
  349. return success;
  350. }
  351. bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
  352. const uint32_t n_seq_tokens = ubatch.n_seq_tokens;
  353. const uint32_t n_seqs = ubatch.n_seqs;
  354. // if we have enough unused cells before the current head ->
  355. // better to start searching from the beginning of the cache, hoping to fill it
  356. if (head > used + 2*n_seqs) {
  357. head = 0;
  358. }
  359. // For recurrent state architectures (like Mamba or RWKV),
  360. // each cache cell can store the state for a whole sequence.
  361. // A slot should be always be contiguous.
  362. // can only process batches with an equal number of new tokens in each sequence
  363. GGML_ASSERT(ubatch.equal_seqs);
  364. int32_t min = size - 1;
  365. int32_t max = 0;
  366. // everything should fit if all seq_ids are smaller than the max
  367. for (uint32_t s = 0; s < n_seqs; ++s) {
  368. const uint32_t i = s*n_seq_tokens; // first token of sequence set s
  369. const uint32_t n_seq_id = ubatch.n_seq_id[i];
  370. for (uint32_t j = 0; j < n_seq_id; ++j) {
  371. const llama_seq_id seq_id = ubatch.seq_id[i][j];
  372. if (seq_id < 0 || (uint32_t) seq_id >= size) {
  373. // too big seq_id
  374. // TODO: would it be possible to resize the cache instead?
  375. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%u Try using a bigger --parallel value\n", __func__, seq_id, n_seq_max);
  376. return false;
  377. }
  378. if (j > 0) {
  379. auto & seq = cells[seq_id];
  380. if (seq.tail >= 0) {
  381. auto & cell = cells[seq.tail];
  382. // clear cells from seq_ids that become shared
  383. // (should not normally happen, but let's handle it anyway)
  384. cell.seq_id.erase(seq_id);
  385. seq.tail = -1;
  386. if (cell.seq_id.empty()) {
  387. cell.pos = -1;
  388. cell.src = -1;
  389. used -= 1;
  390. }
  391. }
  392. }
  393. }
  394. }
  395. #ifndef NDEBUG
  396. {
  397. std::vector<int32_t> tails_verif;
  398. tails_verif.assign(size, -1);
  399. for (uint32_t i = 0; i < size; ++i) {
  400. auto & cell = cells[i];
  401. for (llama_seq_id seq_id : cell.seq_id) {
  402. if (tails_verif[seq_id] != -1) {
  403. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  404. }
  405. tails_verif[seq_id] = i;
  406. }
  407. }
  408. for (uint32_t i = 0; i < size; ++i) {
  409. if (tails_verif[i] != cells[i].tail) {
  410. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cells[i].tail, tails_verif[i]);
  411. }
  412. }
  413. }
  414. #endif
  415. // find next empty cell
  416. uint32_t next_empty_cell = head;
  417. for (uint32_t i = 0; i < size; ++i) {
  418. if (next_empty_cell >= size) { next_empty_cell -= size; }
  419. auto & cell = cells[next_empty_cell];
  420. if (cell.is_empty()) { break; }
  421. next_empty_cell += 1;
  422. }
  423. // find usable cell range
  424. for (uint32_t s = 0; s < n_seqs; ++s) {
  425. const uint32_t i = s*n_seq_tokens;
  426. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  427. auto & seq_meta = cells[seq_id];
  428. bool has_cell = false;
  429. if (seq_meta.tail >= 0) {
  430. auto & cell = cells[seq_meta.tail];
  431. GGML_ASSERT(cell.has_seq_id(seq_id));
  432. // does this seq_id "own" the cell?
  433. if (cell.seq_id.size() == 1) { has_cell = true; }
  434. }
  435. if (!has_cell) {
  436. auto & empty_cell = cells[next_empty_cell];
  437. GGML_ASSERT(empty_cell.is_empty());
  438. // copy old tail into the empty cell
  439. if (seq_meta.tail >= 0) {
  440. auto & orig_cell = cells[seq_meta.tail];
  441. empty_cell.pos = orig_cell.pos;
  442. empty_cell.src = orig_cell.src;
  443. orig_cell.seq_id.erase(seq_id);
  444. empty_cell.seq_id.insert(seq_id); // will be overwritten
  445. GGML_ASSERT(!orig_cell.is_empty()); // has at least one remaining seq_id
  446. }
  447. seq_meta.tail = next_empty_cell;
  448. // find next empty cell
  449. if (s + 1 < n_seqs) {
  450. for (uint32_t j = 0; j < size; ++j) {
  451. next_empty_cell += 1;
  452. if (next_empty_cell >= size) { next_empty_cell -= size; }
  453. auto & cell = cells[next_empty_cell];
  454. if (cell.is_empty()) { break; }
  455. }
  456. }
  457. }
  458. if (min > seq_meta.tail) { min = seq_meta.tail; }
  459. if (max < seq_meta.tail) { max = seq_meta.tail; }
  460. }
  461. // gather and re-order
  462. for (uint32_t s = 0; s < n_seqs; ++s) {
  463. const uint32_t i = s*n_seq_tokens;
  464. const int32_t dst_id = s + min;
  465. const int32_t src_id = cells[ubatch.seq_id[i][0]].tail;
  466. if (dst_id != src_id) {
  467. auto & dst_cell = cells[dst_id];
  468. auto & src_cell = cells[src_id];
  469. std::swap(dst_cell.pos, src_cell.pos);
  470. std::swap(dst_cell.src, src_cell.src);
  471. std::swap(dst_cell.seq_id, src_cell.seq_id);
  472. // swap tails
  473. for (uint32_t j = 0; j < size; ++j) {
  474. int32_t & tail = cells[j].tail;
  475. if (tail == src_id) {
  476. tail = dst_id;
  477. } else if (tail == dst_id) {
  478. tail = src_id;
  479. }
  480. }
  481. }
  482. }
  483. // update the pos of the used seqs
  484. for (uint32_t s = 0; s < n_seqs; ++s) {
  485. const uint32_t i = s*n_seq_tokens;
  486. const llama_pos last_pos = ubatch.pos[i + n_seq_tokens - 1];
  487. const int32_t cell_id = s + min;
  488. auto & cell = cells[cell_id];
  489. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  490. // What should happen when the pos backtracks or skips a value?
  491. // Clearing the state mid-batch would require special-casing which isn't done.
  492. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  493. __func__, last_pos, cell.pos, ubatch.seq_id[i][0], n_seq_tokens);
  494. }
  495. cell.pos = last_pos;
  496. cell.seq_id.clear();
  497. for (int32_t j = 0; j < ubatch.n_seq_id[i]; ++j) {
  498. const llama_seq_id seq_id = ubatch.seq_id[i][j];
  499. cell.seq_id.insert(seq_id);
  500. cells[seq_id].tail = cell_id;
  501. }
  502. }
  503. // Find first cell without src refs, to use as the zero-ed state
  504. {
  505. // TODO: bake-in src refcounts in the cell metadata
  506. std::vector<int32_t> refcounts(size, 0);
  507. for (size_t i = 0; i < size; ++i) {
  508. const int32_t src = cells[i].src;
  509. if (src >= 0) {
  510. refcounts[src] += 1;
  511. }
  512. }
  513. rs_z = -1;
  514. for (int i = min; i <= max; ++i) {
  515. if (refcounts[i] == 0) {
  516. rs_z = i;
  517. break;
  518. }
  519. }
  520. for (int i = min; i <= max; ++i) {
  521. if (cells[i].src < 0) {
  522. GGML_ASSERT(rs_z >= 0);
  523. cells[i].src0 = rs_z;
  524. } else {
  525. // Stage the source ids for all used cells to allow correct seq_* behavior
  526. // and still make these values available when setting the inputs
  527. cells[i].src0 = cells[i].src;
  528. }
  529. cells[i].src = i; // avoid moving or clearing twice
  530. }
  531. }
  532. // allow getting the range of used cells, from head to head + n
  533. head = min;
  534. n = max - min + 1;
  535. used = std::count_if(cells.begin(), cells.end(),
  536. [](const mem_cell & cell){ return !cell.is_empty(); });
  537. // sanity check
  538. return n >= n_seqs;
  539. }
  540. bool llama_memory_recurrent::get_can_shift() const {
  541. // shifting the pos is trivial for recurrent models
  542. return true;
  543. }
  544. size_t llama_memory_recurrent::total_size() const {
  545. size_t size = 0;
  546. for (const auto & buf : bufs) {
  547. size += ggml_backend_buffer_get_size(buf.get());
  548. }
  549. return size;
  550. }
  551. size_t llama_memory_recurrent::size_r_bytes() const {
  552. size_t size_r_bytes = 0;
  553. for (const auto & r : r_l) {
  554. if (r != nullptr) {
  555. size_r_bytes += ggml_nbytes(r);
  556. }
  557. }
  558. return size_r_bytes;
  559. }
  560. size_t llama_memory_recurrent::size_s_bytes() const {
  561. size_t size_s_bytes = 0;
  562. for (const auto & s : s_l) {
  563. if (s != nullptr) {
  564. size_s_bytes += ggml_nbytes(s);
  565. }
  566. }
  567. return size_s_bytes;
  568. }
  569. void llama_memory_recurrent::state_write(llama_io_write_i & io, llama_seq_id seq_id) const {
  570. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  571. uint32_t cell_count = 0;
  572. // Count the number of cells with the specified seq_id
  573. // Find all the ranges of cells with this seq id (or all, when -1)
  574. uint32_t cell_range_begin = size;
  575. for (uint32_t i = 0; i < size; ++i) {
  576. const auto & cell = cells[i];
  577. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  578. ++cell_count;
  579. if (cell_range_begin == size) {
  580. cell_range_begin = i;
  581. }
  582. } else {
  583. if (cell_range_begin != size) {
  584. cell_ranges.emplace_back(cell_range_begin, i);
  585. cell_range_begin = size;
  586. }
  587. }
  588. }
  589. if (cell_range_begin != size) {
  590. cell_ranges.emplace_back(cell_range_begin, size);
  591. }
  592. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  593. uint32_t cell_count_check = 0;
  594. for (const auto & range : cell_ranges) {
  595. cell_count_check += range.second - range.first;
  596. }
  597. GGML_ASSERT(cell_count == cell_count_check);
  598. io.write(&cell_count, sizeof(cell_count));
  599. state_write_meta(io, cell_ranges, seq_id);
  600. state_write_data(io, cell_ranges);
  601. }
  602. void llama_memory_recurrent::state_read(llama_io_read_i & io, llama_seq_id seq_id) {
  603. uint32_t cell_count;
  604. io.read_to(&cell_count, sizeof(cell_count));
  605. bool res = true;
  606. res = res && state_read_meta(io, cell_count, seq_id);
  607. res = res && state_read_data(io, cell_count);
  608. if (!res) {
  609. if (seq_id == -1) {
  610. clear(true);
  611. } else {
  612. seq_rm(seq_id, -1, -1);
  613. }
  614. throw std::runtime_error("failed to restore kv cache");
  615. }
  616. }
  617. 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 {
  618. for (const auto & range : cell_ranges) {
  619. for (uint32_t i = range.first; i < range.second; ++i) {
  620. const auto & cell = cells[i];
  621. const llama_pos pos = cell.pos;
  622. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  623. io.write(&pos, sizeof(pos));
  624. io.write(&n_seq_id, sizeof(n_seq_id));
  625. if (n_seq_id) {
  626. for (auto seq_id : cell.seq_id) {
  627. io.write(&seq_id, sizeof(seq_id));
  628. }
  629. }
  630. }
  631. }
  632. }
  633. void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) const {
  634. const uint32_t s_trans = 0;
  635. const uint32_t n_layer = hparams.n_layer;
  636. io.write(&s_trans, sizeof(s_trans));
  637. io.write(&n_layer, sizeof(n_layer));
  638. std::vector<uint8_t> tmp_buf;
  639. // Iterate and write all the keys first, each row is a cell
  640. // Get whole range at a time
  641. for (uint32_t il = 0; il < n_layer; ++il) {
  642. // Write key type
  643. const int32_t r_type_i = (int32_t)r_l[il]->type;
  644. io.write(&r_type_i, sizeof(r_type_i));
  645. // Write row size of key
  646. const uint64_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
  647. io.write(&r_size_row, sizeof(r_size_row));
  648. // Read each range of cells of k_size length each into tmp_buf and write out
  649. for (const auto & range : cell_ranges) {
  650. const size_t range_size = range.second - range.first;
  651. const size_t buf_size = range_size * r_size_row;
  652. io.write_tensor(r_l[il], range.first * r_size_row, buf_size);
  653. }
  654. }
  655. if (!s_trans) {
  656. for (uint32_t il = 0; il < n_layer; ++il) {
  657. // Write value type
  658. const int32_t s_type_i = (int32_t)s_l[il]->type;
  659. io.write(&s_type_i, sizeof(s_type_i));
  660. // Write row size of value
  661. const uint64_t s_size_row = ggml_row_size(s_l[il]->type, hparams.n_embd_s());
  662. io.write(&s_size_row, sizeof(s_size_row));
  663. // Read each range of cells of s_size length each into tmp_buf and write out
  664. for (const auto & range : cell_ranges) {
  665. const size_t range_size = range.second - range.first;
  666. const size_t buf_size = range_size * s_size_row;
  667. io.write_tensor(s_l[il], range.first * s_size_row, buf_size);
  668. }
  669. }
  670. } else {
  671. // When v is transposed, we also need the element size and get the element ranges from each row
  672. const uint32_t mem_size = size;
  673. for (uint32_t il = 0; il < n_layer; ++il) {
  674. const uint32_t n_embd_s = hparams.n_embd_s();
  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 element size
  679. const uint32_t s_size_el = ggml_type_size(s_l[il]->type);
  680. io.write(&s_size_el, sizeof(s_size_el));
  681. // Write GQA embedding size
  682. io.write(&n_embd_s, sizeof(n_embd_s));
  683. // For each row, we get the element values of each cell
  684. for (uint32_t j = 0; j < n_embd_s; ++j) {
  685. // Read each range of cells of v_size_el length each into tmp_buf and write out
  686. for (const auto & range : cell_ranges) {
  687. const size_t range_size = range.second - range.first;
  688. const size_t src_offset = (range.first + j * mem_size) * s_size_el;
  689. const size_t buf_size = range_size * s_size_el;
  690. io.write_tensor(s_l[il], src_offset, buf_size);
  691. }
  692. }
  693. }
  694. }
  695. }
  696. bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
  697. if (dest_seq_id != -1) {
  698. // single sequence
  699. seq_rm(dest_seq_id, -1, -1);
  700. llama_batch_allocr balloc(hparams.n_pos_per_embd());
  701. llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
  702. for (uint32_t i = 0; i < cell_count; ++i) {
  703. llama_pos pos;
  704. uint32_t n_seq_id;
  705. io.read_to(&pos, sizeof(pos));
  706. io.read_to(&n_seq_id, sizeof(n_seq_id));
  707. if (n_seq_id != 0) {
  708. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  709. return false;
  710. }
  711. ubatch.pos[i] = pos;
  712. }
  713. ubatch.n_seq_id[0] = 1;
  714. ubatch.seq_id[0] = &dest_seq_id;
  715. if (!find_slot(ubatch)) {
  716. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  717. return false;
  718. }
  719. // 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)
  720. // Assume that this is one contiguous block of cells
  721. GGML_ASSERT(head + cell_count <= size);
  722. GGML_ASSERT(cells[head].pos == ubatch.pos[0]);
  723. GGML_ASSERT(cells[head + cell_count - 1].pos == ubatch.pos[cell_count - 1]);
  724. GGML_ASSERT(cells[head].has_seq_id(dest_seq_id));
  725. GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id));
  726. } else {
  727. // whole KV cache restore
  728. if (cell_count > size) {
  729. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  730. return false;
  731. }
  732. clear(true);
  733. for (uint32_t i = 0; i < cell_count; ++i) {
  734. auto & cell = cells[i];
  735. llama_pos pos;
  736. uint32_t n_seq_id;
  737. io.read_to(&pos, sizeof(pos));
  738. io.read_to(&n_seq_id, sizeof(n_seq_id));
  739. cell.pos = pos;
  740. for (uint32_t j = 0; j < n_seq_id; ++j) {
  741. llama_seq_id seq_id;
  742. io.read_to(&seq_id, sizeof(seq_id));
  743. // TODO: llama_memory_recurrent should have a notion of max sequences
  744. //if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  745. if (seq_id < 0) {
  746. //LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  747. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, inf)\n", __func__, seq_id);
  748. return false;
  749. }
  750. cell.seq_id.insert(seq_id);
  751. int32_t & tail = cells[seq_id].tail;
  752. if (tail != -1) {
  753. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  754. return false;
  755. }
  756. tail = i;
  757. }
  758. }
  759. head = 0;
  760. used = cell_count;
  761. }
  762. for (uint32_t i = 0; i < cell_count; ++i) {
  763. uint32_t cell_id = head + i;
  764. // make sure the recurrent states will keep their restored state
  765. cells[cell_id].src = cell_id;
  766. }
  767. return true;
  768. }
  769. bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell_count) {
  770. uint32_t s_trans;
  771. uint32_t n_layer;
  772. io.read_to(&s_trans, sizeof(s_trans));
  773. io.read_to(&n_layer, sizeof(n_layer));
  774. if (n_layer != hparams.n_layer) {
  775. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  776. return false;
  777. }
  778. if (cell_count > size) {
  779. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, size);
  780. return false;
  781. }
  782. if (false != (bool) s_trans) {
  783. LLAMA_LOG_ERROR("%s: incompatible s transposition\n", __func__);
  784. return false;
  785. }
  786. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  787. for (uint32_t il = 0; il < n_layer; ++il) {
  788. // Read type of key
  789. int32_t r_type_i_ref;
  790. io.read_to(&r_type_i_ref, sizeof(r_type_i_ref));
  791. const int32_t r_type_i = (int32_t) r_l[il]->type;
  792. if (r_type_i != r_type_i_ref) {
  793. LLAMA_LOG_ERROR("%s: mismatched r type (%d != %d, layer %d)\n", __func__, r_type_i, r_type_i_ref, il);
  794. return false;
  795. }
  796. // Read row size of key
  797. uint64_t r_size_row_ref;
  798. io.read_to(&r_size_row_ref, sizeof(r_size_row_ref));
  799. const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
  800. if (r_size_row != r_size_row_ref) {
  801. LLAMA_LOG_ERROR("%s: mismatched r row size (%zu != %zu, layer %d)\n", __func__, r_size_row, (size_t) r_size_row_ref, il);
  802. return false;
  803. }
  804. if (cell_count) {
  805. // Read and set the keys for the whole cell range
  806. ggml_backend_tensor_set(r_l[il], io.read(cell_count * r_size_row), head * r_size_row, cell_count * r_size_row);
  807. }
  808. }
  809. if (!s_trans) {
  810. for (uint32_t il = 0; il < n_layer; ++il) {
  811. // Read type of value
  812. int32_t s_type_i_ref;
  813. io.read_to(&s_type_i_ref, sizeof(s_type_i_ref));
  814. const int32_t s_type_i = (int32_t)s_l[il]->type;
  815. if (s_type_i != s_type_i_ref) {
  816. LLAMA_LOG_ERROR("%s: mismatched s type (%d != %d, layer %d)\n", __func__, s_type_i, s_type_i_ref, il);
  817. return false;
  818. }
  819. // Read row size of value
  820. uint64_t s_size_row_ref;
  821. io.read_to(&s_size_row_ref, sizeof(s_size_row_ref));
  822. const size_t s_size_row = ggml_row_size(s_l[il]->type, hparams.n_embd_s());
  823. if (s_size_row != s_size_row_ref) {
  824. LLAMA_LOG_ERROR("%s: mismatched s row size (%zu != %zu, layer %d)\n", __func__, s_size_row, (size_t) s_size_row_ref, il);
  825. return false;
  826. }
  827. if (cell_count) {
  828. // Read and set the values for the whole cell range
  829. ggml_backend_tensor_set(s_l[il], io.read(cell_count * s_size_row), head * s_size_row, cell_count * s_size_row);
  830. }
  831. }
  832. } else {
  833. // For each layer, read the values for each cell (transposed)
  834. for (uint32_t il = 0; il < n_layer; ++il) {
  835. const uint32_t n_embd_s = hparams.n_embd_s();
  836. // Read type of value
  837. int32_t s_type_i_ref;
  838. io.read_to(&s_type_i_ref, sizeof(s_type_i_ref));
  839. const int32_t s_type_i = (int32_t)s_l[il]->type;
  840. if (s_type_i != s_type_i_ref) {
  841. LLAMA_LOG_ERROR("%s: mismatched s type (%d != %d, layer %d)\n", __func__, s_type_i, s_type_i_ref, il);
  842. return false;
  843. }
  844. // Read element size of value
  845. uint32_t s_size_el_ref;
  846. io.read_to(&s_size_el_ref, sizeof(s_size_el_ref));
  847. const size_t s_size_el = ggml_type_size(s_l[il]->type);
  848. if (s_size_el != s_size_el_ref) {
  849. LLAMA_LOG_ERROR("%s: mismatched s element size (%zu != %zu, layer %d)\n", __func__, s_size_el, (size_t) s_size_el_ref, il);
  850. return false;
  851. }
  852. // Read state embedding size
  853. uint32_t n_embd_s_ref;
  854. io.read_to(&n_embd_s_ref, sizeof(n_embd_s_ref));
  855. if (n_embd_s != n_embd_s_ref) {
  856. LLAMA_LOG_ERROR("%s: mismatched s embedding size (%u != %u, layer %d)\n", __func__, n_embd_s, n_embd_s_ref, il);
  857. return false;
  858. }
  859. if (cell_count) {
  860. // For each row in the transposed matrix, read the values for the whole cell range
  861. for (uint32_t j = 0; j < n_embd_s; ++j) {
  862. const size_t dst_offset = (head + j * size) * s_size_el;
  863. ggml_backend_tensor_set(s_l[il], io.read(cell_count * s_size_el), dst_offset, cell_count * s_size_el);
  864. }
  865. }
  866. }
  867. }
  868. return true;
  869. }
  870. //
  871. // llama_memory_recurrent_context
  872. //
  873. llama_memory_recurrent_context::llama_memory_recurrent_context(llama_memory_status status) : status(status) {}
  874. llama_memory_recurrent_context::llama_memory_recurrent_context(
  875. llama_memory_recurrent * mem) : status(LLAMA_MEMORY_STATUS_SUCCESS), mem(mem), is_full(true) {
  876. }
  877. llama_memory_recurrent_context::llama_memory_recurrent_context(
  878. llama_memory_recurrent * mem,
  879. std::vector<llama_ubatch> ubatches) : status(LLAMA_MEMORY_STATUS_SUCCESS), mem(mem), ubatches(std::move(ubatches)) {}
  880. llama_memory_recurrent_context::~llama_memory_recurrent_context() = default;
  881. bool llama_memory_recurrent_context::next() {
  882. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  883. if (++i_next >= ubatches.size()) {
  884. return false;
  885. }
  886. return true;
  887. }
  888. bool llama_memory_recurrent_context::apply() {
  889. assert(!llama_memory_status_is_fail(status));
  890. // no ubatches -> this is an update
  891. if (ubatches.empty()) {
  892. // recurrent cache never performs updates
  893. assert(status == LLAMA_MEMORY_STATUS_NO_UPDATE);
  894. return true;
  895. }
  896. mem->find_slot(ubatches[i_next]);
  897. return true;
  898. }
  899. llama_memory_status llama_memory_recurrent_context::get_status() const {
  900. return status;
  901. }
  902. const llama_ubatch & llama_memory_recurrent_context::get_ubatch() const {
  903. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  904. return ubatches[i_next];
  905. }
  906. uint32_t llama_memory_recurrent_context::get_n_rs() const {
  907. return is_full ? mem->size : mem->n;
  908. }
  909. uint32_t llama_memory_recurrent_context::get_head() const {
  910. return is_full ? 0 : mem->head;
  911. }
  912. int32_t llama_memory_recurrent_context::get_rs_z() const {
  913. return is_full ? 0 : mem->rs_z;
  914. }
  915. uint32_t llama_memory_recurrent_context::get_size() const {
  916. return mem->size;
  917. }
  918. ggml_tensor * llama_memory_recurrent_context::get_r_l(int32_t il) const {
  919. return mem->r_l[il];
  920. }
  921. ggml_tensor * llama_memory_recurrent_context::get_s_l(int32_t il) const {
  922. return mem->s_l[il];
  923. }
  924. int32_t llama_memory_recurrent_context::s_copy(int i) const {
  925. return mem->cells[i + mem->head].src0;
  926. }