llama-memory-recurrent.cpp 37 KB

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