llama-memory-recurrent.cpp 38 KB

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