llama-kv-cache.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  1. #include "llama-kv-cache.h"
  2. #include "llama-impl.h"
  3. #include "llama-batch.h"
  4. #include "llama-cparams.h"
  5. #include "llama-model.h"
  6. #include <algorithm>
  7. #include <cassert>
  8. #include <limits>
  9. #include <map>
  10. #include <stdexcept>
  11. llama_kv_cache_unified::llama_kv_cache_unified(const llama_hparams & hparams, callbacks cbs) : hparams(hparams), cbs(std::move(cbs)) {
  12. }
  13. bool llama_kv_cache_unified::init(
  14. const llama_model & model,
  15. const llama_cparams & cparams,
  16. ggml_type type_k,
  17. ggml_type type_v,
  18. uint32_t kv_size,
  19. bool offload) {
  20. const int32_t n_layer = hparams.n_layer;
  21. has_shift = false;
  22. recurrent = llama_model_is_recurrent(&model);
  23. v_trans = !recurrent && !cparams.flash_attn;
  24. can_shift = !recurrent;
  25. LLAMA_LOG_INFO("%s: kv_size = %d, offload = %d, type_k = '%s', type_v = '%s', n_layer = %d, can_shift = %d\n",
  26. __func__, kv_size, offload, ggml_type_name(type_k), ggml_type_name(type_v), n_layer, can_shift);
  27. head = 0;
  28. size = kv_size;
  29. used = 0;
  30. this->type_k = type_k;
  31. this->type_v = type_v;
  32. cells.clear();
  33. cells.resize(kv_size);
  34. // create a context for each buffer type
  35. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  36. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  37. auto it = ctx_map.find(buft);
  38. if (it == ctx_map.end()) {
  39. ggml_init_params params = {
  40. /*.mem_size =*/ size_t(2u*n_layer*ggml_tensor_overhead()),
  41. /*.mem_buffer =*/ NULL,
  42. /*.no_alloc =*/ true,
  43. };
  44. ggml_context * ctx = ggml_init(params);
  45. if (!ctx) {
  46. return nullptr;
  47. }
  48. ctx_map[buft] = ctx;
  49. ctxs.emplace_back(ctx);
  50. return ctx;
  51. }
  52. return it->second;
  53. };
  54. k_l.reserve(n_layer);
  55. v_l.reserve(n_layer);
  56. for (int i = 0; i < n_layer; i++) {
  57. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  58. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  59. const char * dev_name = "CPU";
  60. ggml_backend_buffer_type_t buft;
  61. if (offload) {
  62. auto * dev = model.dev_layer(i);
  63. buft = ggml_backend_dev_buffer_type(dev);
  64. dev_name = ggml_backend_dev_name(dev);
  65. } else {
  66. buft = ggml_backend_cpu_buffer_type();
  67. }
  68. LLAMA_LOG_DEBUG("%s: layer %3d: n_embd_k_gqa = %d, n_embd_v_gqa = %d, dev = %s\n", __func__,
  69. i, n_embd_k_gqa, n_embd_v_gqa, dev_name);
  70. ggml_context * ctx = ctx_for_buft(buft);
  71. if (!ctx) {
  72. LLAMA_LOG_ERROR("%s: failed to create ggml context for kv cache\n", __func__);
  73. return false;
  74. }
  75. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  76. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  77. ggml_format_name(k, "cache_k_l%d", i);
  78. ggml_format_name(v, "cache_v_l%d", i);
  79. k_l.push_back(k);
  80. v_l.push_back(v);
  81. }
  82. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  83. for (auto it : ctx_map) {
  84. auto * buft = it.first;
  85. auto * ctx = it.second;
  86. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  87. if (!buf) {
  88. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  89. return false;
  90. }
  91. ggml_backend_buffer_clear(buf, 0);
  92. 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);
  93. bufs.emplace_back(buf);
  94. }
  95. return true;
  96. }
  97. int32_t llama_kv_cache_unified::get_n_tokens() const {
  98. int32_t result = 0;
  99. for (uint32_t i = 0; i < size; i++) {
  100. result += cells[i].seq_id.size();
  101. }
  102. return result;
  103. }
  104. int32_t llama_kv_cache_unified::get_used_cells() const {
  105. return used;
  106. }
  107. size_t llama_kv_cache_unified::total_size() const {
  108. size_t size = 0;
  109. for (const auto & buf : bufs) {
  110. size += ggml_backend_buffer_get_size(buf.get());
  111. }
  112. return size;
  113. }
  114. llama_pos llama_kv_cache_unified::pos_max() const {
  115. llama_pos pos_max = -1;
  116. for (const auto & cell : cells) {
  117. pos_max = std::max(pos_max, cell.pos);
  118. }
  119. return pos_max;
  120. }
  121. void llama_kv_cache_unified::clear() {
  122. for (int32_t i = 0; i < (int32_t) size; ++i) {
  123. cells[i].pos = -1;
  124. cells[i].seq_id.clear();
  125. cells[i].src = -1;
  126. cells[i].tail = -1;
  127. }
  128. head = 0;
  129. used = 0;
  130. for (auto & buf : bufs) {
  131. ggml_backend_buffer_clear(buf.get(), 0);
  132. }
  133. }
  134. bool llama_kv_cache_unified::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  135. uint32_t new_head = size;
  136. if (p0 < 0) {
  137. p0 = 0;
  138. }
  139. if (p1 < 0) {
  140. p1 = std::numeric_limits<llama_pos>::max();
  141. }
  142. // models like Mamba or RWKV can't have a state partially erased
  143. if (recurrent) {
  144. if (seq_id >= (int64_t) size) {
  145. // could be fatal
  146. return false;
  147. }
  148. if (0 <= seq_id) {
  149. int32_t & tail_id = cells[seq_id].tail;
  150. if (tail_id >= 0) {
  151. const llama_kv_cell & cell = cells[tail_id];
  152. // partial intersection is invalid
  153. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  154. return false;
  155. }
  156. // invalidate tails which will be cleared
  157. if (p0 <= cell.pos && cell.pos < p1) {
  158. tail_id = -1;
  159. }
  160. }
  161. } else {
  162. // seq_id is negative, then the range should include everything or nothing
  163. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  164. return false;
  165. }
  166. }
  167. return true;
  168. }
  169. for (uint32_t i = 0; i < size; ++i) {
  170. if (cells[i].pos >= p0 && cells[i].pos < p1) {
  171. if (seq_id < 0) {
  172. cells[i].seq_id.clear();
  173. } else if (cells[i].has_seq_id(seq_id)) {
  174. cells[i].seq_id.erase(seq_id);
  175. } else {
  176. continue;
  177. }
  178. if (cells[i].is_empty()) {
  179. // keep count of the number of used cells
  180. if (cells[i].pos >= 0) {
  181. used--;
  182. }
  183. cells[i].pos = -1;
  184. cells[i].src = -1;
  185. if (new_head == size) {
  186. new_head = i;
  187. }
  188. }
  189. }
  190. }
  191. // If we freed up a slot, set head to it so searching can start there.
  192. if (new_head != size && new_head < head) {
  193. head = new_head;
  194. }
  195. return true;
  196. }
  197. void llama_kv_cache_unified::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
  198. if (seq_id_src == seq_id_dst) {
  199. return;
  200. }
  201. if (p0 < 0) {
  202. p0 = 0;
  203. }
  204. if (p1 < 0) {
  205. p1 = std::numeric_limits<llama_pos>::max();
  206. }
  207. if (recurrent) {
  208. if ((uint32_t) seq_id_dst < size && (uint32_t) seq_id_src < size) {
  209. llama_kv_cell & tail_src = cells[seq_id_src];
  210. llama_kv_cell & tail_dst = cells[seq_id_dst];
  211. if (tail_dst.tail >= 0) {
  212. // clear destination seq_id if it wasn't empty
  213. llama_kv_cell & cell_dst = cells[tail_dst.tail];
  214. cell_dst.seq_id.erase(seq_id_dst);
  215. tail_dst.tail = -1;
  216. if (cell_dst.seq_id.empty()) {
  217. cell_dst.pos = -1;
  218. cell_dst.delta = -1;
  219. cell_dst.src = -1;
  220. used -= 1;
  221. }
  222. }
  223. if (tail_src.tail >= 0) {
  224. llama_kv_cell & cell_src = cells[tail_src.tail];
  225. cell_src.seq_id.insert(seq_id_dst);
  226. tail_dst.tail = tail_src.tail;
  227. }
  228. }
  229. return;
  230. }
  231. // otherwise, this is the KV of a Transformer-like model
  232. head = 0;
  233. for (uint32_t i = 0; i < size; ++i) {
  234. if (cells[i].has_seq_id(seq_id_src) && cells[i].pos >= p0 && cells[i].pos < p1) {
  235. cells[i].seq_id.insert(seq_id_dst);
  236. }
  237. }
  238. }
  239. void llama_kv_cache_unified::seq_keep(llama_seq_id seq_id) {
  240. uint32_t new_head = size;
  241. for (uint32_t i = 0; i < size; ++i) {
  242. if (recurrent && (llama_seq_id) i != seq_id) {
  243. cells[i].tail = -1;
  244. }
  245. if (!cells[i].has_seq_id(seq_id)) {
  246. if (cells[i].pos >= 0) {
  247. used--;
  248. }
  249. cells[i].pos = -1;
  250. cells[i].src = -1;
  251. cells[i].seq_id.clear();
  252. if (new_head == size){
  253. new_head = i;
  254. }
  255. } else {
  256. cells[i].seq_id.clear();
  257. cells[i].seq_id.insert(seq_id);
  258. }
  259. }
  260. // If we freed up a slot, set head to it so searching can start there.
  261. if (new_head != size && new_head < head) {
  262. head = new_head;
  263. }
  264. }
  265. void llama_kv_cache_unified::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  266. if (delta == 0) {
  267. return;
  268. }
  269. uint32_t new_head = size;
  270. if (p0 < 0) {
  271. p0 = 0;
  272. }
  273. if (p1 < 0) {
  274. p1 = std::numeric_limits<llama_pos>::max();
  275. }
  276. // If there is no range then return early to avoid looping over the
  277. if (p0 == p1) {
  278. return;
  279. }
  280. if (recurrent) {
  281. // for Mamba-like or RWKV models, only the pos needs to be shifted
  282. if (0 <= seq_id && seq_id < (int64_t) size) {
  283. const int32_t tail_id = cells[seq_id].tail;
  284. if (tail_id >= 0) {
  285. llama_kv_cell & cell = cells[tail_id];
  286. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  287. cell.pos += delta;
  288. }
  289. }
  290. }
  291. return;
  292. }
  293. for (uint32_t i = 0; i < size; ++i) {
  294. if (cells[i].has_seq_id(seq_id) && cells[i].pos >= p0 && cells[i].pos < p1) {
  295. has_shift = true;
  296. cells[i].pos += delta;
  297. cells[i].delta += delta;
  298. if (cells[i].pos < 0) {
  299. if (!cells[i].is_empty()) {
  300. used--;
  301. }
  302. cells[i].pos = -1;
  303. cells[i].seq_id.clear();
  304. if (new_head == size) {
  305. new_head = i;
  306. }
  307. }
  308. }
  309. }
  310. // If we freed up a slot, set head to it so searching can start there.
  311. // Otherwise we just start the next search from the beginning.
  312. head = new_head != size ? new_head : 0;
  313. }
  314. void llama_kv_cache_unified::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  315. if (d == 1) {
  316. return;
  317. }
  318. if (p0 < 0) {
  319. p0 = 0;
  320. }
  321. if (p1 < 0) {
  322. p1 = std::numeric_limits<llama_pos>::max();
  323. }
  324. // If there is no range then return early to avoid looping over the cache.
  325. if (p0 == p1) {
  326. return;
  327. }
  328. if (recurrent) {
  329. // for Mamba-like or RWKV models, only the pos needs to be changed
  330. if (0 <= seq_id && seq_id < (int64_t) size) {
  331. const int32_t tail_id = cells[seq_id].tail;
  332. if (tail_id >= 0) {
  333. llama_kv_cell & cell = cells[tail_id];
  334. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  335. cell.pos /= d;
  336. }
  337. }
  338. }
  339. return;
  340. }
  341. for (uint32_t i = 0; i < size; ++i) {
  342. if (cells[i].has_seq_id(seq_id) && cells[i].pos >= p0 && cells[i].pos < p1) {
  343. has_shift = true;
  344. {
  345. llama_pos p_old = cells[i].pos;
  346. cells[i].pos /= d;
  347. cells[i].delta += cells[i].pos - p_old;
  348. }
  349. }
  350. }
  351. }
  352. llama_pos llama_kv_cache_unified::seq_pos_max(llama_seq_id seq_id) const {
  353. llama_pos result = 0;
  354. for (uint32_t i = 0; i < size; ++i) {
  355. if (cells[i].has_seq_id(seq_id)) {
  356. result = std::max(result, cells[i].pos);
  357. }
  358. }
  359. return result;
  360. }
  361. void llama_kv_cache_unified::defrag() {
  362. if (!recurrent) {
  363. do_defrag = true;
  364. }
  365. }
  366. void llama_kv_cache_unified::restore() {
  367. if (pending.ranges.empty()) {
  368. return;
  369. }
  370. // TODO: tmp - move to llama_kv_cache_recurrent
  371. if (recurrent) {
  372. seq_rm(-1, -1, -1);
  373. return;
  374. }
  375. uint32_t new_head = size;
  376. for (auto & range : pending.ranges) {
  377. for (uint32_t i = range.c0; i < range.c1; ++i) {
  378. cells[i].seq_id.clear();
  379. // keep count of the number of used cells
  380. if (cells[i].pos >= 0) {
  381. used--;
  382. }
  383. cells[i].pos = -1;
  384. cells[i].src = -1;
  385. }
  386. new_head = std::min(new_head, range.c0);
  387. }
  388. if (new_head != size && new_head < head) {
  389. head = new_head;
  390. }
  391. }
  392. void llama_kv_cache_unified::commit() {
  393. // TODO: tmp - move to llama_kv_cache_recurrent
  394. if (recurrent) {
  395. return;
  396. }
  397. if (pending.ranges.empty()) {
  398. LLAMA_LOG_WARN("%s: no pending KV cache updates to commit - might indicate a bug (ref: %s)\n",
  399. __func__, "https://github.com/ggml-org/llama.cpp/pull/12695");
  400. return;
  401. }
  402. pending.ranges.clear();
  403. }
  404. bool llama_kv_cache_unified::get_can_shift() const {
  405. return can_shift;
  406. }
  407. bool llama_kv_cache_unified::find_slot(
  408. const llama_ubatch & ubatch) {
  409. const uint32_t n_tokens = ubatch.n_tokens;
  410. const uint32_t n_seqs = ubatch.n_seqs;
  411. const uint32_t n_seq_tokens = ubatch.n_seq_tokens;
  412. // if we have enough unused cells before the current head ->
  413. // better to start searching from the beginning of the cache, hoping to fill it
  414. if (head > used + 2*ubatch.n_tokens) {
  415. head = 0;
  416. }
  417. if (recurrent) {
  418. // For recurrent state architectures (like Mamba or RWKV),
  419. // each cache cell can store the state for a whole sequence.
  420. // A slot should be always be contiguous.
  421. // can only process batches with an equal number of new tokens in each sequence
  422. GGML_ASSERT(ubatch.equal_seqs);
  423. int32_t min = size - 1;
  424. int32_t max = 0;
  425. // everything should fit if all seq_ids are smaller than the max
  426. for (uint32_t s = 0; s < n_seqs; ++s) {
  427. const uint32_t n_seq_id = ubatch.n_seq_id[s];
  428. for (uint32_t j = 0; j < n_seq_id; ++j) {
  429. const llama_seq_id seq_id = ubatch.seq_id[s][j];
  430. if (seq_id < 0 || (uint32_t) seq_id >= size) {
  431. // too big seq_id
  432. // TODO: would it be possible to resize the cache instead?
  433. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, size);
  434. return false;
  435. }
  436. if (j > 0) {
  437. llama_kv_cell & seq = cells[seq_id];
  438. if (seq.tail >= 0) {
  439. llama_kv_cell & cell = cells[seq.tail];
  440. // clear cells from seq_ids that become shared
  441. // (should not normally happen, but let's handle it anyway)
  442. cell.seq_id.erase(seq_id);
  443. seq.tail = -1;
  444. if (cell.seq_id.empty()) {
  445. cell.pos = -1;
  446. cell.src = -1;
  447. used -= 1;
  448. }
  449. }
  450. }
  451. }
  452. }
  453. #ifndef NDEBUG
  454. {
  455. std::vector<int32_t> tails_verif;
  456. tails_verif.assign(size, -1);
  457. for (uint32_t i = 0; i < size; ++i) {
  458. llama_kv_cell & cell = cells[i];
  459. for (llama_seq_id seq_id : cell.seq_id) {
  460. if (tails_verif[seq_id] != -1) {
  461. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  462. }
  463. tails_verif[seq_id] = i;
  464. }
  465. }
  466. for (uint32_t i = 0; i < size; ++i) {
  467. if (tails_verif[i] != cells[i].tail) {
  468. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cells[i].tail, tails_verif[i]);
  469. }
  470. }
  471. }
  472. #endif
  473. // find next empty cell
  474. uint32_t next_empty_cell = head;
  475. for (uint32_t i = 0; i < size; ++i) {
  476. if (next_empty_cell >= size) { next_empty_cell -= size; }
  477. llama_kv_cell & cell = cells[next_empty_cell];
  478. if (cell.is_empty()) { break; }
  479. next_empty_cell += 1;
  480. }
  481. // find usable cell range
  482. for (uint32_t s = 0; s < n_seqs; ++s) {
  483. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  484. llama_kv_cell & seq_meta = cells[seq_id];
  485. bool has_cell = false;
  486. if (seq_meta.tail >= 0) {
  487. llama_kv_cell & cell = cells[seq_meta.tail];
  488. GGML_ASSERT(cell.has_seq_id(seq_id));
  489. // does this seq_id "own" the cell?
  490. if (cell.seq_id.size() == 1) { has_cell = true; }
  491. }
  492. if (!has_cell) {
  493. llama_kv_cell & empty_cell = cells[next_empty_cell];
  494. GGML_ASSERT(empty_cell.is_empty());
  495. // copy old tail into the empty cell
  496. if (seq_meta.tail >= 0) {
  497. llama_kv_cell & orig_cell = cells[seq_meta.tail];
  498. empty_cell.pos = orig_cell.pos;
  499. empty_cell.src = orig_cell.src;
  500. orig_cell.seq_id.erase(seq_id);
  501. empty_cell.seq_id.insert(seq_id); // will be overwritten
  502. }
  503. seq_meta.tail = next_empty_cell;
  504. // find next empty cell
  505. if (s + 1 < n_seqs) {
  506. next_empty_cell += 1;
  507. for (uint32_t i = 0; i < size; ++i) {
  508. if (next_empty_cell >= size) { next_empty_cell -= size; }
  509. llama_kv_cell & cell = cells[next_empty_cell];
  510. if (cell.is_empty()) { break; }
  511. next_empty_cell += 1;
  512. }
  513. }
  514. }
  515. if (min > seq_meta.tail) { min = seq_meta.tail; }
  516. if (max < seq_meta.tail) { max = seq_meta.tail; }
  517. }
  518. // gather and re-order
  519. for (uint32_t s = 0; s < n_seqs; ++s) {
  520. int32_t dst_id = s + min;
  521. int32_t src_id = cells[ubatch.seq_id[s][0]].tail;
  522. if (dst_id != src_id) {
  523. llama_kv_cell & dst_cell = cells[dst_id];
  524. llama_kv_cell & src_cell = cells[src_id];
  525. std::swap(dst_cell.pos, src_cell.pos);
  526. std::swap(dst_cell.src, src_cell.src);
  527. std::swap(dst_cell.seq_id, src_cell.seq_id);
  528. // swap tails (assuming they NEVER overlap)
  529. for (const llama_seq_id seq_id : src_cell.seq_id) {
  530. cells[seq_id].tail = src_id;
  531. }
  532. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  533. cells[seq_id].tail = dst_id;
  534. }
  535. }
  536. }
  537. // update the pos of the used seqs
  538. for (uint32_t s = 0; s < n_seqs; ++s) {
  539. const llama_pos last_pos = ubatch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  540. int32_t cell_id = s + min;
  541. llama_kv_cell & cell = cells[cell_id];
  542. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  543. // What should happen when the pos backtracks or skips a value?
  544. // Clearing the state mid-batch would require special-casing which isn't done.
  545. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  546. __func__, last_pos, cell.pos, ubatch.seq_id[s][0], n_seq_tokens);
  547. }
  548. cell.pos = last_pos;
  549. cell.seq_id.clear();
  550. for (int32_t j = 0; j < ubatch.n_seq_id[s]; ++j) {
  551. const llama_seq_id seq_id = ubatch.seq_id[s][j];
  552. cell.seq_id.insert(seq_id);
  553. cells[seq_id].tail = cell_id;
  554. }
  555. }
  556. // allow getting the range of used cells, from head to head + n
  557. head = min;
  558. n = max - min + 1;
  559. used = std::count_if(cells.begin(), cells.end(),
  560. [](const llama_kv_cell& cell){ return !cell.is_empty(); });
  561. // sanity check
  562. return n >= n_seqs;
  563. }
  564. // otherwise, one cell per token.
  565. if (n_tokens > size) {
  566. LLAMA_LOG_ERROR("%s: n_tokens = %d > size = %d\n", __func__, n_tokens, size);
  567. return false;
  568. }
  569. uint32_t n_tested = 0;
  570. while (true) {
  571. if (head + n_tokens > size) {
  572. n_tested += size - head;
  573. head = 0;
  574. continue;
  575. }
  576. bool found = true;
  577. for (uint32_t i = 0; i < n_tokens; i++) {
  578. if (cells[head + i].pos >= 0) {
  579. found = false;
  580. head += i + 1;
  581. n_tested += i + 1;
  582. break;
  583. }
  584. }
  585. if (found) {
  586. break;
  587. }
  588. if (n_tested >= size) {
  589. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  590. return false;
  591. }
  592. }
  593. for (uint32_t s = 0; s < n_seqs; s++) {
  594. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  595. uint32_t k = s*n_seq_tokens + i;
  596. cells[head + k].pos = ubatch.pos[k];
  597. for (int32_t j = 0; j < ubatch.n_seq_id[s]; j++) {
  598. cells[head + k].seq_id.insert(ubatch.seq_id[s][j]);
  599. }
  600. }
  601. }
  602. used += n_tokens;
  603. pending.ranges.push_back({head, head + n_tokens});
  604. return true;
  605. }
  606. uint32_t llama_kv_cache_unified::get_padding(const llama_cparams & cparams) const {
  607. // the FA kernels require padding to avoid extra runtime boundary checks
  608. return cparams.flash_attn ? 256u : 32u;
  609. }
  610. uint32_t llama_kv_cache_unified::cell_max() const {
  611. for (uint32_t i = size; i > 0; --i) {
  612. const llama_kv_cell & cell = cells[i - 1];
  613. if (cell.pos >= 0 && !cell.is_empty()) {
  614. return i;
  615. }
  616. }
  617. return 0;
  618. }
  619. size_t llama_kv_cache_unified::size_k_bytes() const {
  620. size_t size_k_bytes = 0;
  621. for (const auto & k : k_l) {
  622. size_k_bytes += ggml_nbytes(k);
  623. }
  624. return size_k_bytes;
  625. }
  626. size_t llama_kv_cache_unified::size_v_bytes() const {
  627. size_t size_v_bytes = 0;
  628. for (const auto & v : v_l) {
  629. size_v_bytes += ggml_nbytes(v);
  630. }
  631. return size_v_bytes;
  632. }
  633. bool llama_kv_cache_unified::defrag_prepare(int32_t n_max_nodes) {
  634. const uint32_t n_layer = hparams.n_layer;
  635. const uint32_t n_kv = cell_max();
  636. const uint32_t n_used = used;
  637. assert(n_used <= n_kv);
  638. //const int64_t t_start = ggml_time_us();
  639. // number of cells moved
  640. uint32_t n_moves = 0;
  641. // each move requires 6*n_layer tensors (see graph_build_kv_self_defrag)
  642. // - source view, destination view, copy operation
  643. // - x2 for keys and values
  644. //const uint32_t max_moves = max_nodes()/(6*n_layer);
  645. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  646. const uint32_t max_moves = (n_max_nodes - 2*n_layer)/(6*n_layer);
  647. // determine which KV cells to move where
  648. //
  649. // cell i moves to ids[i]
  650. //
  651. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  652. //
  653. auto & ids = defrag_info.ids;
  654. ids.clear();
  655. ids.resize(n_kv, n_kv);
  656. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  657. const auto & cell0 = cells[i0];
  658. if (!cell0.is_empty()) {
  659. ids[i0] = i0;
  660. continue;
  661. }
  662. // found a hole - fill it with data from the end of the cache
  663. uint32_t nh = 1;
  664. // determine the size of the hole
  665. while (i0 + nh < n_used && cells[i0 + nh].is_empty()) {
  666. nh++;
  667. }
  668. uint32_t nf = 0;
  669. uint32_t is = n_kv - 1;
  670. // starting from the end, find nh non-empty cells
  671. for (; is > i0; --is) {
  672. const auto & cell1 = cells[is];
  673. if (cell1.is_empty() || ids[is] != n_kv) {
  674. continue;
  675. }
  676. // non-empty cell which is not yet moved
  677. nf++;
  678. if (nf == nh) {
  679. break;
  680. }
  681. }
  682. // this can only happen if `n_used` is not accurate, which would be a bug
  683. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  684. nf = 0;
  685. uint32_t i1 = is;
  686. // are we moving a continuous block of memory?
  687. bool cont = false;
  688. // should we stop searching for the next move?
  689. bool stop = false;
  690. // go back and move the nf cells to the hole
  691. for (; i1 < n_kv; ++i1) {
  692. auto & cell1 = cells[i1];
  693. if (cell1.is_empty() || ids[i1] != n_kv) {
  694. if (n_moves == max_moves) {
  695. stop = true;
  696. break;
  697. }
  698. cont = false;
  699. continue;
  700. }
  701. // this cell goes to (i0 + nf)
  702. ids[i1] = i0 + nf;
  703. // move the cell meta data
  704. cells[i0 + nf] = cell1;
  705. // clear the old cell and move the head there
  706. cell1 = llama_kv_cell();
  707. head = n_used;
  708. if (!cont) {
  709. n_moves++;
  710. cont = true;
  711. }
  712. nf++;
  713. if (nf == nh) {
  714. break;
  715. }
  716. }
  717. if (stop || n_moves == max_moves) {
  718. break;
  719. }
  720. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  721. i0 += nh - 1;
  722. }
  723. if (n_moves == 0) {
  724. return false;
  725. }
  726. LLAMA_LOG_DEBUG("(tmp log) KV defrag cell moves: %u\n", n_moves);
  727. LLAMA_LOG_DEBUG("expected gf nodes: %u\n", 6*n_moves*n_layer);
  728. return true;
  729. }
  730. void llama_kv_cache_unified::state_write(llama_io_write_i & io, llama_seq_id seq_id) const {
  731. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  732. uint32_t cell_count = 0;
  733. // Count the number of cells with the specified seq_id
  734. // Find all the ranges of cells with this seq id (or all, when -1)
  735. uint32_t cell_range_begin = size;
  736. for (uint32_t i = 0; i < size; ++i) {
  737. const auto & cell = cells[i];
  738. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  739. ++cell_count;
  740. if (cell_range_begin == size) {
  741. cell_range_begin = i;
  742. }
  743. } else {
  744. if (cell_range_begin != size) {
  745. cell_ranges.emplace_back(cell_range_begin, i);
  746. cell_range_begin = size;
  747. }
  748. }
  749. }
  750. if (cell_range_begin != size) {
  751. cell_ranges.emplace_back(cell_range_begin, size);
  752. }
  753. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  754. uint32_t cell_count_check = 0;
  755. for (const auto & range : cell_ranges) {
  756. cell_count_check += range.second - range.first;
  757. }
  758. GGML_ASSERT(cell_count == cell_count_check);
  759. io.write(&cell_count, sizeof(cell_count));
  760. state_write_meta(io, cell_ranges, seq_id);
  761. state_write_data(io, cell_ranges);
  762. }
  763. void llama_kv_cache_unified::state_read(llama_io_read_i & io, llama_seq_id seq_id) {
  764. uint32_t cell_count;
  765. io.read_to(&cell_count, sizeof(cell_count));
  766. bool res = true;
  767. res = res && state_read_meta(io, cell_count, seq_id);
  768. res = res && state_read_data(io, cell_count);
  769. if (!res) {
  770. if (seq_id == -1) {
  771. clear();
  772. } else {
  773. seq_rm(seq_id, -1, -1);
  774. }
  775. throw std::runtime_error("failed to restore kv cache");
  776. }
  777. }
  778. void llama_kv_cache_unified::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 {
  779. for (const auto & range : cell_ranges) {
  780. for (uint32_t i = range.first; i < range.second; ++i) {
  781. const auto & cell = cells[i];
  782. const llama_pos pos = cell.pos;
  783. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  784. io.write(&pos, sizeof(pos));
  785. io.write(&n_seq_id, sizeof(n_seq_id));
  786. if (n_seq_id) {
  787. for (auto seq_id : cell.seq_id) {
  788. io.write(&seq_id, sizeof(seq_id));
  789. }
  790. }
  791. }
  792. }
  793. }
  794. void llama_kv_cache_unified::state_write_data(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) const {
  795. const uint32_t v_trans = this->v_trans ? 1 : 0;
  796. const uint32_t n_layer = hparams.n_layer;
  797. io.write(&v_trans, sizeof(v_trans));
  798. io.write(&n_layer, sizeof(n_layer));
  799. std::vector<uint8_t> tmp_buf;
  800. // Iterate and write all the keys first, each row is a cell
  801. // Get whole range at a time
  802. for (uint32_t il = 0; il < n_layer; ++il) {
  803. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  804. // Write key type
  805. const int32_t k_type_i = (int32_t)k_l[il]->type;
  806. io.write(&k_type_i, sizeof(k_type_i));
  807. // Write row size of key
  808. const uint64_t k_size_row = ggml_row_size(k_l[il]->type, n_embd_k_gqa);
  809. io.write(&k_size_row, sizeof(k_size_row));
  810. // Read each range of cells of k_size length each into tmp_buf and write out
  811. for (const auto & range : cell_ranges) {
  812. const size_t range_size = range.second - range.first;
  813. const size_t buf_size = range_size * k_size_row;
  814. io.write_tensor(k_l[il], range.first * k_size_row, buf_size);
  815. }
  816. }
  817. if (!v_trans) {
  818. for (uint32_t il = 0; il < n_layer; ++il) {
  819. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  820. // Write value type
  821. const int32_t v_type_i = (int32_t)v_l[il]->type;
  822. io.write(&v_type_i, sizeof(v_type_i));
  823. // Write row size of value
  824. const uint64_t v_size_row = ggml_row_size(v_l[il]->type, n_embd_v_gqa);
  825. io.write(&v_size_row, sizeof(v_size_row));
  826. // Read each range of cells of v_size length each into tmp_buf and write out
  827. for (const auto & range : cell_ranges) {
  828. const size_t range_size = range.second - range.first;
  829. const size_t buf_size = range_size * v_size_row;
  830. io.write_tensor(v_l[il], range.first * v_size_row, buf_size);
  831. }
  832. }
  833. } else {
  834. // When v is transposed, we also need the element size and get the element ranges from each row
  835. const uint32_t kv_size = size;
  836. for (uint32_t il = 0; il < n_layer; ++il) {
  837. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  838. // Write value type
  839. const int32_t v_type_i = (int32_t)v_l[il]->type;
  840. io.write(&v_type_i, sizeof(v_type_i));
  841. // Write element size
  842. const uint32_t v_size_el = ggml_type_size(v_l[il]->type);
  843. io.write(&v_size_el, sizeof(v_size_el));
  844. // Write GQA embedding size
  845. io.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  846. // For each row, we get the element values of each cell
  847. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  848. // Read each range of cells of v_size_el length each into tmp_buf and write out
  849. for (const auto & range : cell_ranges) {
  850. const size_t range_size = range.second - range.first;
  851. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  852. const size_t buf_size = range_size * v_size_el;
  853. io.write_tensor(v_l[il], src_offset, buf_size);
  854. }
  855. }
  856. }
  857. }
  858. }
  859. bool llama_kv_cache_unified::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
  860. if (dest_seq_id != -1) {
  861. // single sequence
  862. seq_rm(dest_seq_id, -1, -1);
  863. llama_sbatch sbatch;
  864. llama_ubatch batch = sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  865. batch.n_tokens = cell_count;
  866. batch.n_seq_tokens = cell_count;
  867. batch.n_seqs = 1;
  868. for (uint32_t i = 0; i < cell_count; ++i) {
  869. llama_pos pos;
  870. uint32_t n_seq_id;
  871. io.read_to(&pos, sizeof(pos));
  872. io.read_to(&n_seq_id, sizeof(n_seq_id));
  873. if (n_seq_id != 0) {
  874. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  875. return false;
  876. }
  877. batch.pos[i] = pos;
  878. }
  879. batch.n_seq_id[0] = 1;
  880. batch.seq_id[0] = &dest_seq_id;
  881. if (!find_slot(batch)) {
  882. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  883. return false;
  884. }
  885. commit();
  886. // 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)
  887. // Assume that this is one contiguous block of cells
  888. GGML_ASSERT(head + cell_count <= size);
  889. GGML_ASSERT(cells[head].pos == batch.pos[0]);
  890. GGML_ASSERT(cells[head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  891. GGML_ASSERT(cells[head].has_seq_id(dest_seq_id));
  892. GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id));
  893. } else {
  894. // whole KV cache restore
  895. if (cell_count > size) {
  896. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  897. return false;
  898. }
  899. clear();
  900. for (uint32_t i = 0; i < cell_count; ++i) {
  901. llama_kv_cell & cell = cells[i];
  902. llama_pos pos;
  903. uint32_t n_seq_id;
  904. io.read_to(&pos, sizeof(pos));
  905. io.read_to(&n_seq_id, sizeof(n_seq_id));
  906. cell.pos = pos;
  907. for (uint32_t j = 0; j < n_seq_id; ++j) {
  908. llama_seq_id seq_id;
  909. io.read_to(&seq_id, sizeof(seq_id));
  910. // TODO: llama_kv_cache_unified should have a notion of max sequences
  911. //if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  912. if (seq_id < 0) {
  913. //LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  914. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, inf)\n", __func__, seq_id);
  915. return false;
  916. }
  917. cell.seq_id.insert(seq_id);
  918. if (recurrent) {
  919. int32_t & tail = cells[seq_id].tail;
  920. if (tail != -1) {
  921. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  922. return false;
  923. }
  924. tail = i;
  925. }
  926. }
  927. }
  928. head = 0;
  929. used = cell_count;
  930. }
  931. if (recurrent) {
  932. for (uint32_t i = 0; i < cell_count; ++i) {
  933. uint32_t cell_id = head + i;
  934. // make sure the recurrent states will keep their restored state
  935. cells[cell_id].src = cell_id;
  936. }
  937. }
  938. return true;
  939. }
  940. bool llama_kv_cache_unified::state_read_data(llama_io_read_i & io, uint32_t cell_count) {
  941. uint32_t v_trans;
  942. uint32_t n_layer;
  943. io.read_to(&v_trans, sizeof(v_trans));
  944. io.read_to(&n_layer, sizeof(n_layer));
  945. if (n_layer != hparams.n_layer) {
  946. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  947. return false;
  948. }
  949. if (cell_count > size) {
  950. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, size);
  951. return false;
  952. }
  953. if (v_trans != (bool) v_trans) {
  954. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  955. return false;
  956. }
  957. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  958. for (uint32_t il = 0; il < n_layer; ++il) {
  959. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  960. // Read type of key
  961. int32_t k_type_i_ref;
  962. io.read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  963. const int32_t k_type_i = (int32_t) k_l[il]->type;
  964. if (k_type_i != k_type_i_ref) {
  965. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  966. return false;
  967. }
  968. // Read row size of key
  969. uint64_t k_size_row_ref;
  970. io.read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  971. const size_t k_size_row = ggml_row_size(k_l[il]->type, n_embd_k_gqa);
  972. if (k_size_row != k_size_row_ref) {
  973. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  974. return false;
  975. }
  976. if (cell_count) {
  977. // Read and set the keys for the whole cell range
  978. ggml_backend_tensor_set(k_l[il], io.read(cell_count * k_size_row), head * k_size_row, cell_count * k_size_row);
  979. }
  980. }
  981. if (!v_trans) {
  982. for (uint32_t il = 0; il < n_layer; ++il) {
  983. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  984. // Read type of value
  985. int32_t v_type_i_ref;
  986. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  987. const int32_t v_type_i = (int32_t)v_l[il]->type;
  988. if (v_type_i != v_type_i_ref) {
  989. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  990. return false;
  991. }
  992. // Read row size of value
  993. uint64_t v_size_row_ref;
  994. io.read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  995. const size_t v_size_row = ggml_row_size(v_l[il]->type, n_embd_v_gqa);
  996. if (v_size_row != v_size_row_ref) {
  997. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  998. return false;
  999. }
  1000. if (cell_count) {
  1001. // Read and set the values for the whole cell range
  1002. ggml_backend_tensor_set(v_l[il], io.read(cell_count * v_size_row), head * v_size_row, cell_count * v_size_row);
  1003. }
  1004. }
  1005. } else {
  1006. // For each layer, read the values for each cell (transposed)
  1007. for (uint32_t il = 0; il < n_layer; ++il) {
  1008. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  1009. // Read type of value
  1010. int32_t v_type_i_ref;
  1011. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1012. const int32_t v_type_i = (int32_t)v_l[il]->type;
  1013. if (v_type_i != v_type_i_ref) {
  1014. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1015. return false;
  1016. }
  1017. // Read element size of value
  1018. uint32_t v_size_el_ref;
  1019. io.read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  1020. const size_t v_size_el = ggml_type_size(v_l[il]->type);
  1021. if (v_size_el != v_size_el_ref) {
  1022. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  1023. return false;
  1024. }
  1025. // Read GQA embedding size
  1026. uint32_t n_embd_v_gqa_ref;
  1027. io.read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  1028. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  1029. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  1030. return false;
  1031. }
  1032. if (cell_count) {
  1033. // For each row in the transposed matrix, read the values for the whole cell range
  1034. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1035. const size_t dst_offset = (head + j * size) * v_size_el;
  1036. ggml_backend_tensor_set(v_l[il], io.read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. return true;
  1042. }
  1043. //
  1044. // kv cache view
  1045. //
  1046. llama_kv_cache_view llama_kv_cache_view_init(const llama_kv_cache & kv, int32_t n_seq_max) {
  1047. llama_kv_cache_view result = {
  1048. /*.n_cells = */ 0,
  1049. /*.n_seq_max = */ n_seq_max,
  1050. /*.token_count = */ 0,
  1051. /*.used_cells = */ kv.get_used_cells(),
  1052. /*.max_contiguous = */ 0,
  1053. /*.max_contiguous_idx = */ -1,
  1054. /*.cells = */ nullptr,
  1055. /*.cells_sequences = */ nullptr,
  1056. };
  1057. return result;
  1058. }
  1059. void llama_kv_cache_view_free(llama_kv_cache_view * view) {
  1060. if (view->cells != nullptr) {
  1061. free(view->cells);
  1062. view->cells = nullptr;
  1063. }
  1064. if (view->cells_sequences != nullptr) {
  1065. free(view->cells_sequences);
  1066. view->cells_sequences = nullptr;
  1067. }
  1068. }
  1069. void llama_kv_cache_view_update(llama_kv_cache_view * view, const llama_kv_cache * kv) {
  1070. // TODO: rework this in the future, for now quick hack
  1071. const llama_kv_cache_unified * kvu = dynamic_cast<const llama_kv_cache_unified *>(kv);
  1072. if (kvu == nullptr) {
  1073. LLAMA_LOG_ERROR("%s: the kv_cache_view currently works only with llama_kv_cache_unified\n", __func__);
  1074. return;
  1075. }
  1076. if (uint32_t(view->n_cells) < kvu->size || view->cells == nullptr) {
  1077. view->n_cells = int32_t(kvu->size);
  1078. void * p = realloc(view->cells, sizeof(llama_kv_cache_view_cell) * view->n_cells);
  1079. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  1080. view->cells = (llama_kv_cache_view_cell *)p;
  1081. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  1082. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  1083. view->cells_sequences = (llama_seq_id *)p;
  1084. }
  1085. const std::vector<llama_kv_cell> & kv_cells = kvu->cells;
  1086. llama_kv_cache_view_cell * c_curr = view->cells;
  1087. llama_seq_id * cs_curr = view->cells_sequences;
  1088. int32_t used_cells = 0;
  1089. int32_t token_count = 0;
  1090. int32_t curr_contig_idx = -1;
  1091. uint32_t max_contig = 0;
  1092. int32_t max_contig_idx = -1;
  1093. for (int32_t i = 0; i < int32_t(kvu->size); i++, c_curr++, cs_curr += view->n_seq_max) {
  1094. const size_t curr_size = kv_cells[i].seq_id.size();
  1095. token_count += curr_size;
  1096. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  1097. if (curr_size > 0) {
  1098. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  1099. max_contig = i - curr_contig_idx;
  1100. max_contig_idx = curr_contig_idx;
  1101. }
  1102. curr_contig_idx = -1;
  1103. } else if (curr_contig_idx < 0) {
  1104. curr_contig_idx = i;
  1105. }
  1106. int seq_idx = 0;
  1107. for (const llama_seq_id it : kv_cells[i].seq_id) {
  1108. if (seq_idx >= view->n_seq_max) {
  1109. break;
  1110. }
  1111. cs_curr[seq_idx] = it;
  1112. seq_idx++;
  1113. }
  1114. if (seq_idx != 0) {
  1115. used_cells++;
  1116. }
  1117. for (; seq_idx < view->n_seq_max; seq_idx++) {
  1118. cs_curr[seq_idx] = -1;
  1119. }
  1120. }
  1121. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  1122. max_contig_idx = curr_contig_idx;
  1123. max_contig = kv_cells.size() - curr_contig_idx;
  1124. }
  1125. view->max_contiguous = max_contig;
  1126. view->max_contiguous_idx = max_contig_idx;
  1127. view->token_count = token_count;
  1128. view->used_cells = used_cells;
  1129. if (uint32_t(used_cells) != kvu->used) {
  1130. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  1131. __func__, kvu->used, used_cells);
  1132. }
  1133. }