llama-memory-recurrent.cpp 36 KB

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