llama-kv-cache.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063
  1. #include "llama-kv-cache.h"
  2. #include "llama-impl.h"
  3. #include "llama-io.h"
  4. #include "llama-model.h"
  5. #include "llama-context.h"
  6. #include <algorithm>
  7. #include <cassert>
  8. #include <cmath>
  9. #include <cstring>
  10. #include <limits>
  11. #include <map>
  12. #include <stdexcept>
  13. //
  14. // llama_kv_cache
  15. //
  16. llama_kv_cache::llama_kv_cache(
  17. const llama_model & model,
  18. ggml_type type_k,
  19. ggml_type type_v,
  20. bool v_trans,
  21. bool offload,
  22. bool unified,
  23. uint32_t kv_size,
  24. uint32_t n_seq_max,
  25. uint32_t n_pad,
  26. uint32_t n_swa,
  27. llama_swa_type swa_type,
  28. const layer_filter_cb & filter,
  29. const layer_reuse_cb & reuse) :
  30. model(model), hparams(model.hparams), v_trans(v_trans),
  31. n_seq_max(n_seq_max), n_stream(unified ? 1 : n_seq_max), n_pad(n_pad), n_swa(n_swa), swa_type(swa_type) {
  32. GGML_ASSERT(kv_size % n_pad == 0);
  33. const uint32_t n_layer_kv = hparams.n_layer_kv();
  34. // define a comparator for the buft -> ctx map to ensure that the order is well-defined:
  35. struct ggml_backend_buft_comparator {
  36. bool operator()(const ggml_backend_buffer_type_t & lhs, const ggml_backend_buffer_type_t & rhs) const {
  37. return strcmp(ggml_backend_buft_name(lhs), ggml_backend_buft_name(rhs)) < 0;
  38. }
  39. };
  40. std::map<ggml_backend_buffer_type_t, ggml_context_ptr, ggml_backend_buft_comparator> ctx_map;
  41. // create a context for each buffer type
  42. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  43. auto it = ctx_map.find(buft);
  44. if (it == ctx_map.end()) {
  45. ggml_init_params params = {
  46. /*.mem_size =*/ size_t(2u*(1 + n_stream)*n_layer_kv*ggml_tensor_overhead()),
  47. /*.mem_buffer =*/ NULL,
  48. /*.no_alloc =*/ true,
  49. };
  50. ggml_context * ctx = ggml_init(params);
  51. if (!ctx) {
  52. return nullptr;
  53. }
  54. ctx_map.emplace(buft, ctx);
  55. return ctx;
  56. }
  57. return it->second.get();
  58. };
  59. GGML_ASSERT(n_stream == 1 || n_stream == n_seq_max);
  60. v_heads.resize(n_stream);
  61. for (uint32_t s = 0; s < n_stream; ++s) {
  62. v_heads[s] = 0;
  63. }
  64. v_cells.resize(n_stream);
  65. for (uint32_t s = 0; s < n_stream; ++s) {
  66. v_cells[s].resize(kv_size);
  67. }
  68. // by default, all sequence ids are mapped to the 0th stream
  69. seq_to_stream.resize(LLAMA_MAX_SEQ, 0);
  70. if (n_stream > 1) {
  71. seq_to_stream.resize(n_stream, 0);
  72. for (uint32_t s = 0; s < n_stream; ++s) {
  73. seq_to_stream[s] = s;
  74. }
  75. }
  76. // [TAG_V_CACHE_VARIABLE]
  77. if (v_trans && hparams.is_n_embd_v_gqa_variable()) {
  78. LLAMA_LOG_WARN("%s: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to %d\n",
  79. __func__, hparams.n_embd_v_gqa_max());
  80. }
  81. for (uint32_t il = 0; il < hparams.n_layer; il++) {
  82. if (!hparams.has_kv(il)) {
  83. LLAMA_LOG_DEBUG("%s: layer %3d: does not have KV cache\n", __func__, il);
  84. continue;
  85. }
  86. if (filter && !filter(il)) {
  87. LLAMA_LOG_DEBUG("%s: layer %3d: filtered\n", __func__, il);
  88. continue;
  89. }
  90. // [TAG_V_CACHE_VARIABLE]
  91. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  92. const uint32_t n_embd_v_gqa = !v_trans ? hparams.n_embd_v_gqa(il) : hparams.n_embd_v_gqa_max();
  93. const char * dev_name = "CPU";
  94. ggml_backend_buffer_type_t buft = ggml_backend_cpu_buffer_type();
  95. if (offload) {
  96. auto * dev = model.dev_layer(il);
  97. buft = ggml_backend_dev_buffer_type(dev);
  98. dev_name = ggml_backend_dev_name(dev);
  99. }
  100. LLAMA_LOG_DEBUG("%s: layer %3d: dev = %s\n", __func__, il, dev_name);
  101. ggml_context * ctx = ctx_for_buft(buft);
  102. if (!ctx) {
  103. throw std::runtime_error("failed to create ggml context for kv cache");
  104. }
  105. ggml_tensor * k = ggml_new_tensor_3d(ctx, type_k, n_embd_k_gqa, kv_size, n_stream);
  106. ggml_tensor * v = ggml_new_tensor_3d(ctx, type_v, n_embd_v_gqa, kv_size, n_stream);
  107. ggml_format_name(k, "cache_k_l%d", il);
  108. ggml_format_name(v, "cache_v_l%d", il);
  109. std::vector<ggml_tensor *> k_stream;
  110. std::vector<ggml_tensor *> v_stream;
  111. for (uint32_t s = 0; s < n_stream; ++s) {
  112. k_stream.push_back(ggml_view_2d(ctx, k, n_embd_k_gqa, kv_size, k->nb[1], s*k->nb[2]));
  113. v_stream.push_back(ggml_view_2d(ctx, v, n_embd_v_gqa, kv_size, v->nb[1], s*v->nb[2]));
  114. }
  115. map_layer_ids[il] = layers.size();
  116. layers.push_back({ il, k, v, k_stream, v_stream, });
  117. }
  118. if (reuse) {
  119. LLAMA_LOG_DEBUG("%s: reusing layers:\n", __func__);
  120. for (uint32_t il = 0; il < hparams.n_layer; il++) {
  121. const int32_t il_reuse = reuse(il);
  122. if (il_reuse < 0) {
  123. LLAMA_LOG_DEBUG("%s: - layer %3d: no reuse\n", __func__, il);
  124. continue;
  125. }
  126. if (filter && !filter(il)) {
  127. LLAMA_LOG_DEBUG("%s: - layer %3d: filtered\n", __func__, il);
  128. continue;
  129. }
  130. GGML_ASSERT(map_layer_ids.find(il_reuse) != map_layer_ids.end());
  131. map_layer_ids[il] = map_layer_ids[il_reuse];
  132. LLAMA_LOG_DEBUG("%s: - layer %3d: reuse layer %d, is_swa = %d\n", __func__, il, il_reuse, hparams.is_swa(il));
  133. }
  134. }
  135. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  136. for (auto & [buft, ctx] : ctx_map) {
  137. ggml_backend_buffer_t buf;
  138. if (model.hparams.no_alloc) {
  139. buf = ggml_backend_buft_alloc_buffer(buft, /*size =*/ 0); // dummy buffer
  140. for (ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t != nullptr; t = ggml_get_next_tensor(ctx.get(), t)) {
  141. t->buffer = buf; // set dummy buffer for KV cache so that the backend scheduler won't try to allocate it
  142. }
  143. } else {
  144. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx.get(), buft); // real buffer
  145. }
  146. if (!buf) {
  147. throw std::runtime_error("failed to allocate buffer for kv cache");
  148. }
  149. 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);
  150. ggml_backend_buffer_clear(buf, 0);
  151. ctxs_bufs.emplace_back(std::move(ctx), buf);
  152. }
  153. {
  154. const size_t memory_size_k = size_k_bytes();
  155. const size_t memory_size_v = size_v_bytes();
  156. LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u/%u seqs), K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  157. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f), kv_size, (int) layers.size(), n_seq_max, n_stream,
  158. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  159. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  160. }
  161. const char * LLAMA_KV_CACHE_DEBUG = getenv("LLAMA_KV_CACHE_DEBUG");
  162. debug = LLAMA_KV_CACHE_DEBUG ? atoi(LLAMA_KV_CACHE_DEBUG) : 0;
  163. }
  164. void llama_kv_cache::clear(bool data) {
  165. for (uint32_t s = 0; s < n_stream; ++s) {
  166. v_cells[s].reset();
  167. v_heads[s] = 0;
  168. }
  169. if (data) {
  170. for (auto & [_, buf] : ctxs_bufs) {
  171. ggml_backend_buffer_clear(buf.get(), 0);
  172. }
  173. }
  174. }
  175. bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  176. GGML_ASSERT(seq_id == -1 || (seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()));
  177. if (p0 < 0) {
  178. p0 = 0;
  179. }
  180. if (p1 < 0) {
  181. p1 = std::numeric_limits<llama_pos>::max();
  182. }
  183. if (seq_id >= 0) {
  184. auto & cells = v_cells[seq_to_stream[seq_id]];
  185. auto & head = v_heads[seq_to_stream[seq_id]];
  186. uint32_t new_head = cells.size();
  187. for (uint32_t i = 0; i < cells.size(); ++i) {
  188. if (!cells.pos_in(i, p0, p1)) {
  189. continue;
  190. }
  191. if (cells.seq_has(i, seq_id) && cells.seq_rm(i, seq_id)) {
  192. if (new_head == cells.size()) {
  193. new_head = i;
  194. }
  195. }
  196. }
  197. // If we freed up a slot, set head to it so searching can start there.
  198. if (new_head != cells.size() && new_head < head) {
  199. head = new_head;
  200. }
  201. } else {
  202. // match any sequence
  203. for (uint32_t s = 0; s < n_stream; ++s) {
  204. auto & cells = v_cells[s];
  205. auto & head = v_heads[s];
  206. uint32_t new_head = cells.size();
  207. for (uint32_t i = 0; i < cells.size(); ++i) {
  208. if (!cells.pos_in(i, p0, p1)) {
  209. continue;
  210. }
  211. cells.rm(i);
  212. if (new_head == cells.size()) {
  213. new_head = i;
  214. }
  215. }
  216. // If we freed up a slot, set head to it so searching can start there.
  217. if (new_head != cells.size() && new_head < head) {
  218. head = new_head;
  219. }
  220. }
  221. }
  222. return true;
  223. }
  224. void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
  225. GGML_ASSERT(seq_id_src >= 0 && (size_t) seq_id_src < seq_to_stream.size());
  226. GGML_ASSERT(seq_id_dst >= 0 && (size_t) seq_id_dst < seq_to_stream.size());
  227. const auto s0 = seq_to_stream[seq_id_src];
  228. const auto s1 = seq_to_stream[seq_id_dst];
  229. if (s0 == s1) {
  230. // since both sequences are in the same stream, no data copy is necessary
  231. // we just have to update the cells meta data
  232. auto & cells = v_cells[s0];
  233. if (seq_id_src == seq_id_dst) {
  234. return;
  235. }
  236. if (p0 < 0) {
  237. p0 = 0;
  238. }
  239. if (p1 < 0) {
  240. p1 = std::numeric_limits<llama_pos>::max();
  241. }
  242. for (uint32_t i = 0; i < cells.size(); ++i) {
  243. if (!cells.pos_in(i, p0, p1)) {
  244. continue;
  245. }
  246. if (cells.seq_has(i, seq_id_src)) {
  247. cells.seq_add(i, seq_id_dst);
  248. }
  249. }
  250. return;
  251. }
  252. // cross-stream sequence copies require to copy the actual buffer data
  253. bool is_full = true;
  254. if (p0 > 0 && p0 + 1 < (int) get_size()) {
  255. is_full = false;
  256. }
  257. if (p1 > 0 && p1 + 1 < (int) get_size()) {
  258. is_full = false;
  259. }
  260. GGML_ASSERT(is_full && "seq_cp() is only supported for full KV buffers");
  261. // enqueue the copy operation - the buffer copy will be performed during the next update
  262. sc_info.ssrc.push_back(s0);
  263. sc_info.sdst.push_back(s1);
  264. v_cells[s1].reset();
  265. for (uint32_t i = 0; i < v_cells[s0].size(); ++i) {
  266. if (v_cells[s0].seq_has(i, seq_id_src)) {
  267. llama_pos pos = v_cells[s0].pos_get(i);
  268. llama_pos shift = v_cells[s0].get_shift(i);
  269. llama_kv_cell_ext ext = v_cells[s0].ext_get(i);
  270. if (shift != 0) {
  271. pos -= shift;
  272. assert(pos >= 0);
  273. }
  274. v_cells[s1].pos_set(i, pos);
  275. v_cells[s1].seq_add(i, seq_id_dst);
  276. if (shift != 0) {
  277. v_cells[s1].pos_add(i, shift);
  278. }
  279. v_cells[s1].ext_set(i, ext);
  280. }
  281. }
  282. v_heads[s1] = v_heads[s0];
  283. //for (uint32_t s = 0; s < n_stream; ++s) {
  284. // LLAMA_LOG_WARN("%s: seq %d: min = %d, max = %d\n", __func__, s, v_cells[s].seq_pos_min(s), v_cells[s].seq_pos_max(s));
  285. //}
  286. }
  287. void llama_kv_cache::seq_keep(llama_seq_id seq_id) {
  288. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  289. auto & cells = v_cells[seq_to_stream[seq_id]];
  290. auto & head = v_heads[seq_to_stream[seq_id]];
  291. uint32_t new_head = cells.size();
  292. for (uint32_t i = 0; i < cells.size(); ++i) {
  293. if (cells.seq_keep(i, seq_id)) {
  294. if (new_head == cells.size()) {
  295. new_head = i;
  296. }
  297. }
  298. }
  299. // If we freed up a slot, set head to it so searching can start there.
  300. if (new_head != cells.size() && new_head < head) {
  301. head = new_head;
  302. }
  303. }
  304. void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) {
  305. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  306. GGML_ASSERT(hparams.n_pos_per_embd() == 1 && "seq_add() is only supported for n_pos_per_embd() == 1");
  307. auto & cells = v_cells[seq_to_stream[seq_id]];
  308. auto & head = v_heads[seq_to_stream[seq_id]];
  309. if (shift == 0) {
  310. return;
  311. }
  312. uint32_t new_head = cells.size();
  313. if (p0 < 0) {
  314. p0 = 0;
  315. }
  316. if (p1 < 0) {
  317. p1 = std::numeric_limits<llama_pos>::max();
  318. }
  319. // If there is no range then return early to avoid looping over all cells.
  320. if (p0 == p1) {
  321. return;
  322. }
  323. for (uint32_t i = 0; i < cells.size(); ++i) {
  324. if (!cells.pos_in(i, p0, p1)) {
  325. continue;
  326. }
  327. if (cells.seq_has(i, seq_id)) {
  328. if (cells.pos_add(i, shift)) {
  329. if (new_head == cells.size()) {
  330. new_head = i;
  331. }
  332. }
  333. }
  334. }
  335. // If we freed up a slot, set head to it so searching can start there.
  336. // Otherwise we just start the next search from the beginning.
  337. head = new_head != cells.size() ? new_head : 0;
  338. }
  339. void llama_kv_cache::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  340. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  341. GGML_ASSERT(hparams.n_pos_per_embd() == 1 && "seq_div() is only supported for n_pos_per_embd() == 1");
  342. auto & cells = v_cells[seq_to_stream[seq_id]];
  343. if (d == 1) {
  344. return;
  345. }
  346. if (p0 < 0) {
  347. p0 = 0;
  348. }
  349. if (p1 < 0) {
  350. p1 = std::numeric_limits<llama_pos>::max();
  351. }
  352. // If there is no range then return early to avoid looping over the cache.
  353. if (p0 == p1) {
  354. return;
  355. }
  356. for (uint32_t i = 0; i < cells.size(); ++i) {
  357. if (!cells.pos_in(i, p0, p1)) {
  358. continue;
  359. }
  360. if (cells.seq_has(i, seq_id)) {
  361. cells.pos_div(i, d);
  362. }
  363. }
  364. }
  365. llama_pos llama_kv_cache::seq_pos_min(llama_seq_id seq_id) const {
  366. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  367. const auto & cells = v_cells[seq_to_stream[seq_id]];
  368. return cells.seq_pos_min(seq_id);
  369. }
  370. llama_pos llama_kv_cache::seq_pos_max(llama_seq_id seq_id) const {
  371. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  372. const auto & cells = v_cells[seq_to_stream[seq_id]];
  373. return cells.seq_pos_max(seq_id);
  374. }
  375. std::map<ggml_backend_buffer_type_t, size_t> llama_kv_cache::memory_breakdown() const {
  376. std::map<ggml_backend_buffer_type_t, size_t> ret;
  377. for (const auto & [ctx, buf] : ctxs_bufs) {
  378. ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(buf.get());
  379. if (hparams.no_alloc) {
  380. GGML_ASSERT(ggml_backend_buffer_get_base(buf.get()) == nullptr);
  381. ret[buft] += ggml_backend_alloc_ctx_tensors_from_buft_size(ctx.get(), buft);
  382. } else {
  383. // GGML_ASSERT(ggml_backend_buffer_get_base(buf.get()) != nullptr); // multi_buffer does not have a defined base
  384. ret[buft] += ggml_backend_buffer_get_size(buf.get());
  385. }
  386. }
  387. return ret;
  388. }
  389. llama_memory_context_ptr llama_kv_cache::init_batch(
  390. llama_batch_allocr & balloc,
  391. uint32_t n_ubatch,
  392. bool embd_all) {
  393. GGML_UNUSED(embd_all);
  394. do {
  395. balloc.split_reset();
  396. std::vector<llama_ubatch> ubatches;
  397. while (true) {
  398. auto ubatch = n_stream == 1 ? balloc.split_simple(n_ubatch) : balloc.split_equal(n_ubatch, true);
  399. if (ubatch.n_tokens == 0) {
  400. break;
  401. }
  402. ubatches.push_back(std::move(ubatch)); // NOLINT
  403. }
  404. if (balloc.get_n_used() < balloc.get_n_tokens()) {
  405. // failed to find a suitable split
  406. break;
  407. }
  408. auto sinfos = prepare(ubatches);
  409. if (sinfos.empty()) {
  410. break;
  411. }
  412. return std::make_unique<llama_kv_cache_context>(
  413. this, std::move(sinfos), std::move(ubatches));
  414. } while (false);
  415. return std::make_unique<llama_kv_cache_context>(LLAMA_MEMORY_STATUS_FAILED_PREPARE);
  416. }
  417. llama_memory_context_ptr llama_kv_cache::init_full() {
  418. return std::make_unique<llama_kv_cache_context>(this);
  419. }
  420. llama_memory_context_ptr llama_kv_cache::init_update(llama_context * lctx, bool optimize) {
  421. GGML_UNUSED(optimize);
  422. bool do_shift = get_has_shift();
  423. return std::make_unique<llama_kv_cache_context>(this, lctx, do_shift, std::move(sc_info));
  424. }
  425. llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector<llama_ubatch> & ubatches) {
  426. llama_kv_cache::slot_info_vec_t res;
  427. struct state_t {
  428. slot_info sinfo; // slot info for the ubatch
  429. std::vector<uint32_t> v_heads_old; // old positions of the heads, before placing the ubatch
  430. std::vector<llama_kv_cells> v_cells; // copy of the old cells, before placing the ubatch
  431. };
  432. // remember the old state of the cells so we can restore it in the end
  433. std::vector<state_t> states;
  434. bool success = true;
  435. for (const auto & ubatch : ubatches) {
  436. // only find a suitable slot for the ubatch. don't modify the cells yet
  437. const auto sinfo_new = find_slot(ubatch, false);
  438. if (sinfo_new.empty()) {
  439. success = false;
  440. break;
  441. }
  442. // remeber the position that we found
  443. res.push_back(sinfo_new);
  444. // store the old state of the cells in the recovery stack
  445. {
  446. state_t state = { sinfo_new, v_heads, {} };
  447. for (uint32_t s = 0; s < sinfo_new.n_stream(); ++s) {
  448. auto & cells = v_cells[sinfo_new.strm[s]];
  449. state.v_cells.push_back(cells.cp(sinfo_new.idxs[s]));
  450. }
  451. states.push_back(std::move(state));
  452. }
  453. // now emplace the ubatch
  454. apply_ubatch(sinfo_new, ubatch);
  455. }
  456. GGML_ASSERT(!states.empty() || !success);
  457. // iterate backwards and restore the cells to their original state
  458. for (auto it = states.rbegin(); it != states.rend(); ++it) {
  459. const auto & sinfo = it->sinfo;
  460. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  461. auto & cells = v_cells[sinfo.strm[s]];
  462. auto & head = v_heads[sinfo.strm[s]];
  463. cells.set(sinfo.idxs[s], it->v_cells[s]);
  464. head = it->v_heads_old[s];
  465. }
  466. }
  467. if (!success) {
  468. return {};
  469. }
  470. return res;
  471. }
  472. bool llama_kv_cache::update(llama_context * lctx, bool do_shift, const stream_copy_info & sc_info) {
  473. bool updated = false;
  474. auto * sched = lctx->get_sched();
  475. if (!sc_info.empty()) {
  476. assert(n_stream > 1 && "stream copy should never happen with a single stream");
  477. llama_synchronize(lctx);
  478. const size_t n_copy = sc_info.ssrc.size();
  479. for (size_t i = 0; i < n_copy; ++i) {
  480. const auto ssrc = sc_info.ssrc[i];
  481. const auto sdst = sc_info.sdst[i];
  482. assert(ssrc < n_stream);
  483. assert(sdst < n_stream);
  484. LLAMA_LOG_DEBUG("%s: copying KV buffer: stream %d to stream %d\n", __func__, ssrc, sdst);
  485. assert(ssrc != sdst);
  486. for (uint32_t il = 0; il < layers.size(); ++il) {
  487. const auto & layer = layers[il];
  488. ggml_backend_tensor_copy(layer.k_stream[ssrc], layer.k_stream[sdst]);
  489. ggml_backend_tensor_copy(layer.v_stream[ssrc], layer.v_stream[sdst]);
  490. }
  491. }
  492. }
  493. if (do_shift) {
  494. if (!get_can_shift()) {
  495. GGML_ABORT("The current KV cache / model configuration does not support K-shift");
  496. }
  497. LLAMA_LOG_DEBUG("%s: applying K-shift\n", __func__);
  498. // apply K-shift if needed
  499. if (hparams.rope_type != LLAMA_ROPE_TYPE_NONE) {
  500. ggml_backend_sched_reset(sched);
  501. auto * res = lctx->get_gf_res_reserve();
  502. res->reset();
  503. auto * gf = build_graph_shift(res, lctx);
  504. if (!ggml_backend_sched_alloc_graph(sched, gf)) {
  505. LLAMA_LOG_ERROR("%s: failed to allocate compute graph for K-shift\n", __func__);
  506. return updated;
  507. }
  508. res->set_inputs(nullptr);
  509. if (lctx->graph_compute(gf, false) != GGML_STATUS_SUCCESS) {
  510. LLAMA_LOG_ERROR("%s: failed to compute K-shift\n", __func__);
  511. return updated;
  512. }
  513. updated = true;
  514. }
  515. for (uint32_t s = 0; s < n_stream; ++s) {
  516. auto & cells = v_cells[s];
  517. cells.reset_shift();
  518. }
  519. }
  520. return updated;
  521. }
  522. llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, bool cont) const {
  523. if (debug > 0) {
  524. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  525. const auto seq_id = ubatch.seq_id_unq[s];
  526. const auto stream_id = seq_to_stream[seq_id];
  527. const auto & cells = v_cells[stream_id];
  528. const uint32_t head_cur = v_heads[stream_id];
  529. LLAMA_LOG_DEBUG("%s: stream[%d], n = %5d, used = %5d, head = %5d, size = %5d, n_swa = %5d\n",
  530. __func__, stream_id, cells.used_max_p1(), cells.get_used(), head_cur, get_size(), n_swa);
  531. if ((debug == 2 && n_swa > 0) || debug > 2) {
  532. std::string ss;
  533. for (uint32_t i = 0; i < cells.size(); ++i) {
  534. if (cells.is_empty(i)) {
  535. ss += '.';
  536. } else {
  537. assert(cells.seq_count(i) >= 1);
  538. if (cells.seq_count(i) == 1) {
  539. ss += std::to_string(cells.seq_get(i));
  540. } else {
  541. ss += 'M';
  542. }
  543. }
  544. if (i%256 == 255) {
  545. ss += " *";
  546. ss += '\n';
  547. }
  548. }
  549. LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
  550. }
  551. if ((debug == 2 && n_swa > 0) || debug > 2) {
  552. std::string ss;
  553. for (uint32_t i = 0; i < cells.size(); ++i) {
  554. std::string cur;
  555. if (cells.is_empty(i)) {
  556. cur = '.';
  557. } else {
  558. cur = std::to_string(cells.pos_get(i));
  559. }
  560. const int n = cur.size();
  561. for (int j = 0; j < 5 - n; ++j) {
  562. cur += ' ';
  563. }
  564. ss += cur;
  565. if (i%256 == 255) {
  566. ss += " *";
  567. }
  568. if (i%64 == 63) {
  569. ss += '\n';
  570. }
  571. }
  572. LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
  573. }
  574. for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
  575. if (cells.seq_pos_min(s) < 0) {
  576. continue;
  577. }
  578. LLAMA_LOG_DEBUG("%s: stream[%d] min[%d] = %5d, max[%d] = %5d\n", __func__, stream_id, s, cells.seq_pos_min(s), s, cells.seq_pos_max(s));
  579. }
  580. }
  581. }
  582. uint32_t n_tokens = ubatch.n_tokens;
  583. uint32_t n_seqs = 1;
  584. if (n_stream > 1) {
  585. GGML_ASSERT(n_tokens % ubatch.n_seqs_unq == 0);
  586. n_seqs = ubatch.n_seqs_unq;
  587. n_tokens = n_tokens / n_seqs;
  588. }
  589. slot_info res = {
  590. /*.s0 =*/ LLAMA_MAX_SEQ,
  591. /*.s1 =*/ 0,
  592. /*.strm =*/ { },
  593. /*.idxs =*/ { },
  594. };
  595. res.resize(n_seqs);
  596. for (uint32_t s = 0; s < n_seqs; ++s) {
  597. const auto seq_id = ubatch.seq_id_unq[s];
  598. if (n_stream > 1) {
  599. GGML_ASSERT(ubatch.n_seq_id[s*n_tokens] == 1);
  600. GGML_ASSERT(ubatch.seq_id [s*n_tokens][0] == seq_id);
  601. }
  602. res.s0 = std::min<uint32_t>(res.s0, seq_to_stream[seq_id]);
  603. res.s1 = std::max<uint32_t>(res.s1, seq_to_stream[seq_id]);
  604. res.strm[s] = seq_to_stream[seq_id];
  605. res.idxs[s].reserve(n_tokens);
  606. const auto & cells = v_cells[seq_to_stream[seq_id]];
  607. uint32_t head_cur = v_heads[seq_to_stream[seq_id]];
  608. // if we have enough unused cells before the current head ->
  609. // better to start searching from the beginning of the cache, hoping to fill it
  610. if (head_cur > cells.get_used() + 2*n_tokens) {
  611. head_cur = 0;
  612. }
  613. if (n_tokens > cells.size()) {
  614. LLAMA_LOG_ERROR("%s: n_tokens = %d > size = %u\n", __func__, n_tokens, cells.size());
  615. return { };
  616. }
  617. uint32_t n_tested = 0;
  618. // for continuous slots, we test that all tokens in the ubatch fit, starting from the current head
  619. // for non-continuous slots, we test the tokens one by one
  620. const uint32_t n_test = cont ? n_tokens : 1;
  621. while (true) {
  622. if (head_cur + n_test > cells.size()) {
  623. n_tested += cells.size() - head_cur;
  624. head_cur = 0;
  625. continue;
  626. }
  627. for (uint32_t i = 0; i < n_test; i++) {
  628. const auto idx = head_cur;
  629. head_cur++;
  630. n_tested++;
  631. //const llama_pos pos = ubatch.pos[i];
  632. //const llama_seq_id seq_id = ubatch.seq_id[i][0];
  633. // can we use this cell? either:
  634. // - the cell is empty
  635. // - the cell is occupied only by one sequence:
  636. // - (disabled) mask causally, if the sequence is the same as the one we are inserting
  637. // - mask SWA, using current max pos for that sequence in the cache
  638. // always insert in the cell with minimum pos
  639. bool can_use = cells.is_empty(idx);
  640. if (!can_use && cells.seq_count(idx) == 1) {
  641. const llama_pos pos_cell = cells.pos_get(idx);
  642. // (disabled) causal mask
  643. // note: it's better to purge any "future" tokens beforehand
  644. //if (cells.seq_has(idx, seq_id)) {
  645. // can_use = pos_cell >= pos;
  646. //}
  647. if (!can_use) {
  648. const llama_seq_id seq_id_cell = cells.seq_get(idx);
  649. // SWA mask
  650. if (is_masked_swa(pos_cell, cells.seq_pos_max(seq_id_cell) + 1)) {
  651. can_use = true;
  652. }
  653. }
  654. }
  655. if (can_use) {
  656. res.idxs[s].push_back(idx);
  657. } else {
  658. if (cont) {
  659. break;
  660. }
  661. }
  662. }
  663. if (res.idxs[s].size() == n_tokens) {
  664. break;
  665. }
  666. if (cont) {
  667. res.idxs[s].clear();
  668. }
  669. if (n_tested >= cells.size()) {
  670. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  671. return { };
  672. }
  673. }
  674. // we didn't find a suitable slot - return empty result
  675. if (res.idxs[s].size() < n_tokens) {
  676. return { };
  677. }
  678. }
  679. assert(res.s1 >= res.s0);
  680. return res;
  681. }
  682. void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch) {
  683. // keep track of the max sequence position that we would overwrite with this ubatch
  684. // for non-SWA cache, this would be always empty
  685. llama_seq_id seq_pos_max_rm[LLAMA_MAX_SEQ];
  686. for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) {
  687. seq_pos_max_rm[s] = -1;
  688. }
  689. assert(ubatch.n_tokens == sinfo.n_stream()*sinfo.size());
  690. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  691. for (uint32_t ii = 0; ii < sinfo.size(); ++ii) {
  692. const uint32_t i = s*sinfo.size() + ii;
  693. auto & cells = v_cells[sinfo.strm[s]];
  694. const auto idx = sinfo.idxs[s][ii];
  695. if (!cells.is_empty(idx)) {
  696. assert(cells.seq_count(idx) == 1);
  697. const llama_seq_id seq_id = cells.seq_get(idx);
  698. const llama_pos pos = cells.pos_get(idx);
  699. seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos);
  700. cells.rm(idx);
  701. }
  702. cells.pos_set(idx, ubatch.pos[i]);
  703. if (ubatch.is_pos_2d()) {
  704. llama_kv_cell_ext ext {
  705. /*.x =*/ ubatch.pos[i + ubatch.n_tokens*2],
  706. /*.y =*/ ubatch.pos[i + ubatch.n_tokens],
  707. };
  708. cells.ext_set(idx, ext);
  709. }
  710. for (int32_t s = 0; s < ubatch.n_seq_id[i]; s++) {
  711. cells.seq_add(idx, ubatch.seq_id[i][s]);
  712. }
  713. }
  714. }
  715. // note: we want to preserve the invariant that all positions between [pos_min, pos_max] for each sequence
  716. // will be present in the cache. so we have to purge any position which is less than those we would overwrite
  717. // ref: https://github.com/ggml-org/llama.cpp/pull/13746#issuecomment-2916057092
  718. for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) {
  719. if (seq_pos_max_rm[s] == -1) {
  720. continue;
  721. }
  722. GGML_ASSERT(s < seq_to_stream.size());
  723. auto & cells = v_cells[seq_to_stream[s]];
  724. if (cells.seq_pos_min(s) <= seq_pos_max_rm[s]) {
  725. LLAMA_LOG_DEBUG("%s: purging positions [%d, %d] of sequence %d from KV cache\n",
  726. __func__, cells.seq_pos_min(s), seq_pos_max_rm[s], s);
  727. seq_rm(s, cells.seq_pos_min(s), seq_pos_max_rm[s] + 1);
  728. }
  729. }
  730. // move the head at the end of the slot
  731. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  732. auto & head = v_heads[sinfo.strm[s]];
  733. head = sinfo.idxs[s].back() + 1;
  734. }
  735. }
  736. bool llama_kv_cache::get_can_shift() const {
  737. return true;
  738. }
  739. uint32_t llama_kv_cache::get_size() const {
  740. const auto & cells = v_cells[seq_to_stream[0]];
  741. return cells.size();
  742. }
  743. uint32_t llama_kv_cache::get_n_stream() const {
  744. return n_stream;
  745. }
  746. bool llama_kv_cache::get_has_shift() const {
  747. bool result = false;
  748. for (uint32_t s = 0; s < n_stream; ++s) {
  749. result |= v_cells[s].get_has_shift();
  750. }
  751. return result;
  752. }
  753. uint32_t llama_kv_cache::get_n_kv(const slot_info & sinfo) const {
  754. uint32_t result = 0;
  755. // pad the n_kv value so that the graph remains constant across batches and can be reused
  756. // note: this also helps some backends with performance (f.ex https://github.com/ggml-org/llama.cpp/pull/16812#issuecomment-3455112220)
  757. const uint32_t n_pad_cur = std::max(n_pad, 256u);
  758. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  759. const auto & cells = v_cells[sinfo.strm[s]];
  760. result = std::max(std::min(cells.size(), std::max(n_pad_cur, GGML_PAD(cells.used_max_p1(), n_pad_cur))), result);
  761. }
  762. return result;
  763. }
  764. ggml_tensor * llama_kv_cache::get_k(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const {
  765. const int32_t ikv = map_layer_ids.at(il);
  766. auto * k = layers[ikv].k;
  767. const uint64_t kv_size = get_size();
  768. const uint64_t n_embd_k_gqa = k->ne[0];
  769. assert(n_embd_k_gqa == hparams.n_embd_k_gqa(il));
  770. const uint32_t ns = sinfo.s1 - sinfo.s0 + 1;
  771. return ggml_view_4d(ctx, k,
  772. hparams.n_embd_head_k, hparams.n_head_kv(il), n_kv, ns,
  773. ggml_row_size(k->type, hparams.n_embd_head_k),
  774. ggml_row_size(k->type, n_embd_k_gqa),
  775. ggml_row_size(k->type, n_embd_k_gqa*kv_size),
  776. ggml_row_size(k->type, n_embd_k_gqa*kv_size)*sinfo.s0);
  777. }
  778. ggml_tensor * llama_kv_cache::get_v(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const {
  779. const int32_t ikv = map_layer_ids.at(il);
  780. auto * v = layers[ikv].v;
  781. const uint64_t kv_size = get_size();
  782. const uint64_t n_embd_v_gqa = v->ne[0];
  783. // [TAG_V_CACHE_VARIABLE]
  784. assert(n_embd_v_gqa >= hparams.n_embd_v_gqa(il));
  785. const uint32_t ns = sinfo.s1 - sinfo.s0 + 1;
  786. if (!v_trans) {
  787. // note: v->nb[1] <= v->nb[2]
  788. return ggml_view_4d(ctx, v,
  789. hparams.n_embd_head_v, hparams.n_head_kv(il), n_kv, ns,
  790. ggml_row_size(v->type, hparams.n_embd_head_v), // v->nb[1]
  791. ggml_row_size(v->type, n_embd_v_gqa), // v->nb[2]
  792. ggml_row_size(v->type, n_embd_v_gqa*kv_size), // v->nb[3]
  793. ggml_row_size(v->type, n_embd_v_gqa*kv_size)*sinfo.s0);
  794. }
  795. // note: v->nb[1] > v->nb[2]
  796. return ggml_view_4d(ctx, v,
  797. n_kv, hparams.n_head_kv(il), hparams.n_embd_head_v, ns,
  798. ggml_row_size(v->type, kv_size*hparams.n_embd_head_v), // v->nb[1]
  799. ggml_row_size(v->type, kv_size), // v->nb[2]
  800. ggml_row_size(v->type, kv_size*n_embd_v_gqa), // v->nb[3]
  801. ggml_row_size(v->type, kv_size*n_embd_v_gqa)*sinfo.s0);
  802. }
  803. ggml_tensor * llama_kv_cache::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il, const slot_info & sinfo) const {
  804. GGML_UNUSED(sinfo);
  805. const int32_t ikv = map_layer_ids.at(il);
  806. ggml_tensor * k = layers[ikv].k;
  807. const int64_t n_embd_head = k_cur->ne[0];
  808. const int64_t n_head = k_cur->ne[1];
  809. const int64_t n_tokens = k_cur->ne[2];
  810. const int64_t n_embd_gqa = n_embd_head*n_head;
  811. // we can merge dims 0 and 1
  812. // TODO: add ggml helper function for this?
  813. GGML_ASSERT(ggml_row_size(k_cur->type, n_embd_head) == k_cur->nb[1]);
  814. k_cur = ggml_view_2d(ctx, k_cur, n_embd_gqa, n_tokens, k_cur->nb[2], 0);
  815. const int64_t n_stream = k->ne[2];
  816. if (n_stream > 1) {
  817. const int64_t kv_size = get_size();
  818. assert(n_embd_gqa == k->ne[0]);
  819. assert(kv_size == k->ne[1]);
  820. // merge the buffer across all streams because the idxs are global
  821. k = ggml_reshape_2d(ctx, k, n_embd_gqa, kv_size*n_stream);
  822. }
  823. // store the current K values into the cache
  824. return ggml_set_rows(ctx, k, k_cur, k_idxs);
  825. }
  826. ggml_tensor * llama_kv_cache::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il, const slot_info & sinfo) const {
  827. GGML_UNUSED(sinfo);
  828. const int32_t ikv = map_layer_ids.at(il);
  829. auto * v = layers[ikv].v;
  830. const int64_t n_embd_head = v_cur->ne[0];
  831. const int64_t n_head = v_cur->ne[1];
  832. const int64_t n_tokens = v_cur->ne[2];
  833. const int64_t n_embd_gqa = n_embd_head*n_head;
  834. // we can merge dims 0 and 1
  835. GGML_ASSERT(ggml_row_size(v_cur->type, n_embd_head) == v_cur->nb[1]);
  836. const int64_t n_stream = v->ne[2];
  837. // take this branch when FA is enabled (the V cache is not transposed)
  838. if (!v_trans) {
  839. v_cur = ggml_view_2d(ctx, v_cur, n_embd_gqa, n_tokens, v_cur->nb[2], 0);
  840. if (n_stream > 1) {
  841. const int64_t kv_size = get_size();
  842. assert(n_embd_gqa == v->ne[0]);
  843. assert(kv_size == v->ne[1]);
  844. // merge the buffer across all streams because the idxs are global
  845. v = ggml_reshape_2d(ctx, v, n_embd_gqa, kv_size*n_stream);
  846. }
  847. return ggml_set_rows(ctx, v, v_cur, v_idxs);
  848. }
  849. if (ggml_row_size(v_cur->type, n_embd_gqa) == v_cur->nb[2]) {
  850. // we can merge dims 0, 1 and 2
  851. v_cur = ggml_reshape_2d(ctx, v_cur, n_embd_gqa, n_tokens);
  852. } else {
  853. // otherwise -> make a copy to get contiguous data
  854. v_cur = ggml_cont_2d (ctx, v_cur, n_embd_gqa, n_tokens);
  855. }
  856. // [TAG_V_CACHE_VARIABLE]
  857. if (n_embd_gqa < v->ne[0]) {
  858. v_cur = ggml_pad(ctx, v_cur, v->ne[0] - n_embd_gqa, 0, 0, 0);
  859. }
  860. // in this branch the v_idxs are constructed in such a way that each row is a single head element
  861. ggml_tensor * v_view = ggml_reshape_2d(ctx, v, 1, ggml_nelements(v));
  862. v_cur = ggml_reshape_2d(ctx, v_cur, 1, ggml_nelements(v_cur));
  863. return ggml_set_rows(ctx, v_view, v_cur, v_idxs);
  864. }
  865. ggml_tensor * llama_kv_cache::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  866. const uint32_t n_tokens = ubatch.n_tokens;
  867. ggml_tensor * k_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens);
  868. ggml_set_input(k_idxs);
  869. return k_idxs;
  870. }
  871. ggml_tensor * llama_kv_cache::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  872. const uint32_t n_tokens = ubatch.n_tokens;
  873. ggml_tensor * v_idxs;
  874. if (!v_trans) {
  875. v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens);
  876. } else {
  877. v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens*hparams.n_embd_v_gqa_max());
  878. }
  879. ggml_set_input(v_idxs);
  880. return v_idxs;
  881. }
  882. void llama_kv_cache::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const {
  883. const uint32_t n_tokens = ubatch->n_tokens;
  884. GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream());
  885. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  886. int64_t * data = (int64_t *) dst->data;
  887. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  888. const int64_t offs = sinfo.strm[s]*get_size();
  889. for (uint32_t i = 0; i < sinfo.size(); ++i) {
  890. data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i];
  891. }
  892. }
  893. }
  894. void llama_kv_cache::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const {
  895. const uint32_t n_tokens = ubatch->n_tokens;
  896. GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream());
  897. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  898. int64_t * data = (int64_t *) dst->data;
  899. if (!v_trans) {
  900. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  901. const int64_t offs = sinfo.strm[s]*get_size();
  902. for (uint32_t i = 0; i < sinfo.size(); ++i) {
  903. data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i];
  904. }
  905. }
  906. } else {
  907. // note: the V cache is transposed when not using flash attention
  908. const int64_t kv_size = get_size();
  909. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa_max();
  910. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  911. const int64_t offs = sinfo.strm[s]*kv_size*n_embd_v_gqa;
  912. for (uint32_t i = 0; i < sinfo.size(); ++i) {
  913. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  914. data[s*sinfo.size()*n_embd_v_gqa + i*n_embd_v_gqa + j] = offs + j*kv_size + sinfo.idxs[s][i];
  915. }
  916. }
  917. }
  918. }
  919. }
  920. void llama_kv_cache::set_input_k_shift(ggml_tensor * dst) const {
  921. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  922. int32_t * data = (int32_t *) dst->data;
  923. for (uint32_t s = 0; s < n_stream; ++s) {
  924. const auto & cells = v_cells[s];
  925. for (uint32_t i = 0; i < cells.size(); ++i) {
  926. data[s*cells.size() + i] = cells.is_empty(i) ? 0 : cells.get_shift(i);
  927. }
  928. }
  929. }
  930. void llama_kv_cache::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
  931. const uint32_t n_tokens = ubatch->n_tokens;
  932. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  933. float * data = (float *) dst->data;
  934. const int64_t n_kv = dst->ne[0];
  935. const int64_t n_stream = dst->ne[3]; // num streams in the current ubatch
  936. GGML_ASSERT(n_tokens%n_stream == 0);
  937. // n_tps == n_tokens_per_stream
  938. const int64_t n_tps = n_tokens/n_stream;
  939. std::fill(data, data + ggml_nelements(dst), -INFINITY);
  940. // Use only the previous KV cells of the correct sequence for each token of the ubatch.
  941. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  942. // Example with a cache of 10 tokens, 2 tokens populated in cache and 3 tokens in batch:
  943. // Causal mask:
  944. // xxx-------
  945. // xxxx------
  946. // xxxxx-----
  947. // Non-causal mask:
  948. // xxxxx-----
  949. // xxxxx-----
  950. // xxxxx-----
  951. // To visualize the mask, see https://github.com/ggml-org/llama.cpp/pull/12615
  952. // TODO: optimize this section
  953. for (uint32_t h = 0; h < 1; ++h) {
  954. for (uint32_t s = 0; s < n_stream; ++s) {
  955. for (uint32_t ii = 0; ii < n_tps; ++ii) {
  956. const uint32_t i = s*n_tps + ii;
  957. const llama_seq_id seq_id = ubatch->seq_id[i][0];
  958. const auto & cells = v_cells[seq_to_stream[seq_id]];
  959. const llama_pos p1 = ubatch->pos[i];
  960. // for M-RoPE
  961. const bool is_2d = ubatch->is_pos_2d();
  962. const llama_pos p1_x = is_2d ? ubatch->pos[i + ubatch->n_tokens*2] : 0;
  963. const llama_pos p1_y = is_2d ? ubatch->pos[i + ubatch->n_tokens] : 0;
  964. const uint64_t idst = n_kv*(h*n_stream*n_tps + s*n_tps + ii);
  965. for (uint32_t j = 0; j < n_kv; ++j) {
  966. if (cells.is_empty(j)) {
  967. continue;
  968. }
  969. // mask the token if not the same sequence
  970. if (!cells.seq_has(j, seq_id)) {
  971. continue;
  972. }
  973. const llama_pos p0 = cells.pos_get(j);
  974. // mask future tokens
  975. if (causal_attn && p0 > p1) {
  976. continue;
  977. }
  978. // M-RoPE causal mask
  979. if (causal_attn && is_2d && p0 == p1) {
  980. const auto & p0_ext = cells.ext_get(j);
  981. if (p0_ext.is_2d_gt(p1_x, p1_y)) {
  982. continue;
  983. }
  984. }
  985. // apply SWA if any
  986. if (is_masked_swa(p0, p1)) {
  987. continue;
  988. }
  989. data[idst + j] = hparams.use_alibi ? -std::abs(p0 - p1) : 0.0f;
  990. }
  991. }
  992. }
  993. }
  994. }
  995. void llama_kv_cache::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  996. const int64_t n_tokens = ubatch->n_tokens;
  997. GGML_ASSERT(n_stream == 1 && "TODO: support multiple streams");
  998. const auto & cells = v_cells[0];
  999. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  1000. GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing
  1001. int32_t * data = (int32_t *) dst->data;
  1002. const int32_t n_kv = dst->ne[0];
  1003. for (int h = 0; h < 1; ++h) {
  1004. for (int i = 0; i < n_tokens; ++i) {
  1005. for (int j = 0; j < n_kv; ++j) {
  1006. // the position when the cells is empty is irrelevant - it will be masked out later in the attention
  1007. const llama_pos p0 = cells.is_empty(j) ? -1 : cells.pos_get(j);
  1008. data[h*(n_kv*n_tokens) + i*n_kv + j] = llama_relative_position_bucket(p0, ubatch->pos[i], hparams.n_rel_attn_bkts, false);
  1009. }
  1010. }
  1011. }
  1012. }
  1013. size_t llama_kv_cache::total_size() const {
  1014. size_t size = 0;
  1015. for (const auto & [_, buf] : ctxs_bufs) {
  1016. size += ggml_backend_buffer_get_size(buf.get());
  1017. }
  1018. return size;
  1019. }
  1020. size_t llama_kv_cache::size_k_bytes() const {
  1021. size_t size_k_bytes = 0;
  1022. for (const auto & layer : layers) {
  1023. size_k_bytes += ggml_nbytes(layer.k);
  1024. }
  1025. return size_k_bytes;
  1026. }
  1027. size_t llama_kv_cache::size_v_bytes() const {
  1028. size_t size_v_bytes = 0;
  1029. for (const auto & layer : layers) {
  1030. size_v_bytes += ggml_nbytes(layer.v);
  1031. }
  1032. return size_v_bytes;
  1033. }
  1034. ggml_tensor * llama_kv_cache::build_rope_shift(
  1035. const llama_cparams & cparams,
  1036. ggml_context * ctx,
  1037. ggml_tensor * cur,
  1038. ggml_tensor * shift,
  1039. ggml_tensor * factors,
  1040. float freq_base,
  1041. float freq_scale) const {
  1042. const auto & n_ctx_orig = cparams.n_ctx_orig_yarn;
  1043. const auto & yarn_ext_factor = cparams.yarn_ext_factor;
  1044. const auto & yarn_beta_fast = cparams.yarn_beta_fast;
  1045. const auto & yarn_beta_slow = cparams.yarn_beta_slow;
  1046. const auto & yarn_attn_factor = cparams.yarn_attn_factor;
  1047. const auto & n_rot = hparams.n_rot;
  1048. const auto & rope_type = hparams.rope_type == LLAMA_ROPE_TYPE_MROPE || hparams.rope_type == LLAMA_ROPE_TYPE_IMROPE
  1049. // @ngxson : this is a workaround
  1050. // for M-RoPE, we want to rotate the whole vector when doing KV shift
  1051. // a normal RoPE should work, we just need to use the correct ordering
  1052. // ref: https://github.com/ggml-org/llama.cpp/pull/13870
  1053. ? LLAMA_ROPE_TYPE_NEOX
  1054. : hparams.rope_type;
  1055. ggml_tensor * tmp;
  1056. if (ggml_is_quantized(cur->type)) {
  1057. // dequantize to f32 -> RoPE -> quantize back
  1058. tmp = ggml_cast(ctx, cur, GGML_TYPE_F32);
  1059. tmp = ggml_rope_ext(ctx, tmp,
  1060. shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1061. yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
  1062. tmp = ggml_cpy(ctx, tmp, cur);
  1063. } else {
  1064. // we rotate only the first n_rot dimensions
  1065. tmp = ggml_rope_ext_inplace(ctx, cur,
  1066. shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1067. yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
  1068. }
  1069. return tmp;
  1070. }
  1071. class llm_graph_input_k_shift : public llm_graph_input_i {
  1072. public:
  1073. llm_graph_input_k_shift(const llama_kv_cache * kv_self) : kv_self(kv_self) {}
  1074. virtual ~llm_graph_input_k_shift() = default;
  1075. void set_input(const llama_ubatch * ubatch) override;
  1076. ggml_tensor * k_shift; // I32 [kv_size*n_stream]
  1077. const llama_kv_cache * kv_self;
  1078. };
  1079. void llm_graph_input_k_shift::set_input(const llama_ubatch * ubatch) {
  1080. GGML_UNUSED(ubatch);
  1081. if (k_shift) {
  1082. kv_self->set_input_k_shift(k_shift);
  1083. }
  1084. }
  1085. ggml_cgraph * llama_kv_cache::build_graph_shift(llm_graph_result * res, llama_context * lctx) const {
  1086. auto * ctx = res->get_ctx();
  1087. auto * gf = res->get_gf();
  1088. const auto & n_embd_head_k = hparams.n_embd_head_k;
  1089. //const auto & n_embd_head_v = hparams.n_embd_head_v;
  1090. auto inp = std::make_unique<llm_graph_input_k_shift>(this);
  1091. inp->k_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, (int64_t) get_size()*n_stream);
  1092. ggml_set_input(inp->k_shift);
  1093. const auto & cparams = lctx->get_cparams();
  1094. for (const auto & layer : layers) {
  1095. const uint32_t il = layer.il;
  1096. const int64_t n_head_kv = hparams.n_head_kv(il);
  1097. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1098. const float freq_base_l = model.get_rope_freq_base (cparams, il);
  1099. const float freq_scale_l = model.get_rope_freq_scale(cparams, il);
  1100. ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);
  1101. ggml_tensor * k =
  1102. ggml_view_3d(ctx, layer.k,
  1103. n_embd_head_k, n_head_kv, get_size()*n_stream,
  1104. ggml_row_size(layer.k->type, n_embd_head_k),
  1105. ggml_row_size(layer.k->type, n_embd_k_gqa),
  1106. 0);
  1107. ggml_tensor * cur = build_rope_shift(cparams, ctx, k, inp->k_shift, rope_factors, freq_base_l, freq_scale_l);
  1108. ggml_build_forward_expand(gf, cur);
  1109. }
  1110. res->add_input(std::move(inp));
  1111. return gf;
  1112. }
  1113. bool llama_kv_cache::is_masked_swa(llama_pos p0, llama_pos p1) const {
  1114. return llama_hparams::is_masked_swa(n_swa, swa_type, p0, p1);
  1115. }
  1116. void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const {
  1117. GGML_UNUSED(flags);
  1118. io.write(&n_stream, sizeof(n_stream));
  1119. for (uint32_t s = 0; s < n_stream; ++s) {
  1120. cell_ranges_t cr { s, {} };
  1121. uint32_t cell_count = 0;
  1122. const auto & cells = v_cells[s];
  1123. // Count the number of cells with the specified seq_id
  1124. // Find all the ranges of cells with this seq id (or all, when -1)
  1125. uint32_t cell_range_begin = cells.size();
  1126. for (uint32_t i = 0; i < cells.size(); ++i) {
  1127. if (!cells.is_empty(i) && (seq_id == -1 || cells.seq_has(i, seq_id))) {
  1128. ++cell_count;
  1129. if (cell_range_begin == cells.size()) {
  1130. cell_range_begin = i;
  1131. }
  1132. } else {
  1133. if (cell_range_begin != cells.size()) {
  1134. cr.data.emplace_back(cell_range_begin, i);
  1135. cell_range_begin = cells.size();
  1136. }
  1137. }
  1138. }
  1139. if (cell_range_begin != cells.size()) {
  1140. cr.data.emplace_back(cell_range_begin, cells.size());
  1141. }
  1142. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  1143. uint32_t cell_count_check = 0;
  1144. for (const auto & range : cr.data) {
  1145. cell_count_check += range.second - range.first;
  1146. }
  1147. GGML_ASSERT(cell_count == cell_count_check);
  1148. io.write(&cell_count, sizeof(cell_count));
  1149. // skip empty streams
  1150. if (cell_count == 0) {
  1151. continue;
  1152. }
  1153. state_write_meta(io, cr, seq_id);
  1154. state_write_data(io, cr);
  1155. }
  1156. }
  1157. void llama_kv_cache::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
  1158. GGML_UNUSED(flags);
  1159. GGML_ASSERT(seq_id == -1 || (seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()));
  1160. uint32_t n_stream_cur;
  1161. io.read_to(&n_stream_cur, sizeof(n_stream_cur));
  1162. if (n_stream_cur != n_stream) {
  1163. throw std::runtime_error("n_stream mismatch");
  1164. }
  1165. for (uint32_t s = 0; s < n_stream; ++s) {
  1166. uint32_t cell_count;
  1167. io.read_to(&cell_count, sizeof(cell_count));
  1168. if (cell_count == 0) {
  1169. continue;
  1170. }
  1171. const uint32_t strm = seq_id == -1 ? s : seq_to_stream[seq_id];
  1172. bool res = true;
  1173. res = res && state_read_meta(io, strm, cell_count, seq_id);
  1174. res = res && state_read_data(io, strm, cell_count);
  1175. if (!res) {
  1176. if (seq_id == -1) {
  1177. clear(true);
  1178. } else {
  1179. seq_rm(seq_id, -1, -1);
  1180. }
  1181. throw std::runtime_error("failed to restore kv cache");
  1182. }
  1183. }
  1184. }
  1185. void llama_kv_cache::state_write_meta(llama_io_write_i & io, const cell_ranges_t & cr, llama_seq_id seq_id) const {
  1186. const auto & cells = v_cells[cr.strm];
  1187. for (const auto & range : cr.data) {
  1188. for (uint32_t i = range.first; i < range.second; ++i) {
  1189. std::vector<llama_seq_id> seq_ids;
  1190. for (llama_seq_id cur = 0; cur < (int) n_seq_max; ++cur) {
  1191. if (cur == seq_id || seq_id == -1) {
  1192. if (cells.seq_has(i, cur)) {
  1193. seq_ids.push_back(cur);
  1194. }
  1195. }
  1196. }
  1197. const llama_pos pos = cells.pos_get(i);
  1198. const uint32_t n_seq_id = seq_ids.size();
  1199. io.write(&pos, sizeof(pos));
  1200. io.write(&n_seq_id, sizeof(n_seq_id));
  1201. // TODO: we also need to save llama_kv_cell_ext when apply_ubatch() support loading it
  1202. // see: https://github.com/ggml-org/llama.cpp/pull/16825#issuecomment-3460868350
  1203. for (const auto & seq_id : seq_ids) {
  1204. io.write(&seq_id, sizeof(seq_id));
  1205. }
  1206. }
  1207. }
  1208. }
  1209. void llama_kv_cache::state_write_data(llama_io_write_i & io, const cell_ranges_t & cr) const {
  1210. const auto & cells = v_cells[cr.strm];
  1211. const uint32_t v_trans = this->v_trans ? 1 : 0;
  1212. const uint32_t n_layer = layers.size();
  1213. io.write(&v_trans, sizeof(v_trans));
  1214. io.write(&n_layer, sizeof(n_layer));
  1215. std::vector<uint8_t> tmp_buf;
  1216. // Iterate and write all the keys first, each row is a cell
  1217. // Get whole range at a time
  1218. for (const auto & layer : layers) {
  1219. const uint32_t il = layer.il;
  1220. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1221. auto * k = layer.k_stream[cr.strm];
  1222. // Write key type
  1223. const int32_t k_type_i = (int32_t) k->type;
  1224. io.write(&k_type_i, sizeof(k_type_i));
  1225. // Write row size of key
  1226. const uint64_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
  1227. io.write(&k_size_row, sizeof(k_size_row));
  1228. // Read each range of cells of k_size length each into tmp_buf and write out
  1229. for (const auto & range : cr.data) {
  1230. const size_t range_size = range.second - range.first;
  1231. const size_t buf_size = range_size * k_size_row;
  1232. io.write_tensor(k, range.first * k_size_row, buf_size);
  1233. }
  1234. }
  1235. if (!v_trans) {
  1236. for (const auto & layer : layers) {
  1237. const uint32_t il = layer.il;
  1238. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1239. auto * v = layer.v_stream[cr.strm];
  1240. // Write value type
  1241. const int32_t v_type_i = (int32_t) v->type;
  1242. io.write(&v_type_i, sizeof(v_type_i));
  1243. // Write row size of value
  1244. const uint64_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
  1245. io.write(&v_size_row, sizeof(v_size_row));
  1246. // Read each range of cells of v_size length each into tmp_buf and write out
  1247. for (const auto & range : cr.data) {
  1248. const size_t range_size = range.second - range.first;
  1249. const size_t buf_size = range_size * v_size_row;
  1250. io.write_tensor(v, range.first * v_size_row, buf_size);
  1251. }
  1252. }
  1253. } else {
  1254. // When v is transposed, we also need the element size and get the element ranges from each row
  1255. const uint32_t kv_size = cells.size();
  1256. for (const auto & layer : layers) {
  1257. const uint32_t il = layer.il;
  1258. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1259. auto * v = layer.v_stream[cr.strm];
  1260. // Write value type
  1261. const int32_t v_type_i = (int32_t) v->type;
  1262. io.write(&v_type_i, sizeof(v_type_i));
  1263. // Write element size
  1264. const uint32_t v_size_el = ggml_type_size(v->type);
  1265. io.write(&v_size_el, sizeof(v_size_el));
  1266. // Write GQA embedding size
  1267. io.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  1268. // For each row, we get the element values of each cell
  1269. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1270. // Read each range of cells of v_size_el length each into tmp_buf and write out
  1271. for (const auto & range : cr.data) {
  1272. const size_t range_size = range.second - range.first;
  1273. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  1274. const size_t buf_size = range_size * v_size_el;
  1275. io.write_tensor(v, src_offset, buf_size);
  1276. }
  1277. }
  1278. }
  1279. }
  1280. }
  1281. bool llama_kv_cache::state_read_meta(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, llama_seq_id dest_seq_id) {
  1282. auto & cells = v_cells[strm];
  1283. auto & head = v_heads[strm];
  1284. if (dest_seq_id != -1) {
  1285. // single sequence
  1286. seq_rm(dest_seq_id, -1, -1);
  1287. llama_batch_allocr balloc(hparams.n_pos_per_embd());
  1288. llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
  1289. ubatch.seq_id_unq[0] = dest_seq_id;
  1290. for (uint32_t i = 0; i < cell_count; ++i) {
  1291. llama_pos pos;
  1292. uint32_t n_seq_id;
  1293. io.read_to(&pos, sizeof(pos));
  1294. io.read_to(&n_seq_id, sizeof(n_seq_id));
  1295. if (n_seq_id != 1) {
  1296. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  1297. return false;
  1298. }
  1299. // read the sequence id, but directly discard it - we will use dest_seq_id instead
  1300. {
  1301. llama_seq_id seq_id;
  1302. io.read_to(&seq_id, sizeof(seq_id));
  1303. }
  1304. ubatch.pos[i] = pos;
  1305. ubatch.n_seq_id[i] = n_seq_id;
  1306. ubatch.seq_id[i] = &dest_seq_id;
  1307. }
  1308. const auto sinfo = find_slot(ubatch, true);
  1309. if (sinfo.empty()) {
  1310. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  1311. return false;
  1312. }
  1313. // TODO: we cannot yet restore llama_kv_cell_ext as the apply_ubatch() does not support it yet
  1314. // see: https://github.com/ggml-org/llama.cpp/pull/16825#issuecomment-3460868350
  1315. apply_ubatch(sinfo, ubatch);
  1316. const auto head_cur = sinfo.head();
  1317. // keep the head at the old position because we will read the KV data into it in state_read_data()
  1318. head = head_cur;
  1319. LLAMA_LOG_DEBUG("%s: head_cur = %d, head = %d, cell_count = %d, dest_seq_id = %d\n", __func__, head_cur, head, cell_count, dest_seq_id);
  1320. // DEBUG CHECK: head_cur should be our first cell, head_cur + cell_count - 1 should be our last cell (verify seq_id and pos values)
  1321. // Assume that this is one contiguous block of cells
  1322. GGML_ASSERT(head_cur + cell_count <= cells.size());
  1323. GGML_ASSERT(cells.pos_get(head_cur) == ubatch.pos[0]);
  1324. GGML_ASSERT(cells.pos_get(head_cur + cell_count - 1) == ubatch.pos[cell_count - 1]);
  1325. GGML_ASSERT(cells.seq_has(head_cur, dest_seq_id));
  1326. GGML_ASSERT(cells.seq_has(head_cur + cell_count - 1, dest_seq_id));
  1327. } else {
  1328. // whole KV cache restore
  1329. if (cell_count > cells.size()) {
  1330. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  1331. return false;
  1332. }
  1333. clear(true);
  1334. for (uint32_t i = 0; i < cell_count; ++i) {
  1335. llama_pos pos;
  1336. uint32_t n_seq_id;
  1337. io.read_to(&pos, sizeof(pos));
  1338. io.read_to(&n_seq_id, sizeof(n_seq_id));
  1339. cells.pos_set(i, pos);
  1340. for (uint32_t j = 0; j < n_seq_id; ++j) {
  1341. llama_seq_id seq_id;
  1342. io.read_to(&seq_id, sizeof(seq_id));
  1343. if (seq_id < 0 || (uint32_t) seq_id >= n_seq_max) {
  1344. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, n_seq_max);
  1345. return false;
  1346. }
  1347. cells.seq_add(i, seq_id);
  1348. }
  1349. }
  1350. head = 0;
  1351. }
  1352. return true;
  1353. }
  1354. bool llama_kv_cache::state_read_data(llama_io_read_i & io, uint32_t strm, uint32_t cell_count) {
  1355. auto & cells = v_cells[strm];
  1356. auto & head = v_heads[strm];
  1357. uint32_t v_trans;
  1358. uint32_t n_layer;
  1359. io.read_to(&v_trans, sizeof(v_trans));
  1360. io.read_to(&n_layer, sizeof(n_layer));
  1361. if (n_layer != layers.size()) {
  1362. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, (uint32_t) layers.size());
  1363. return false;
  1364. }
  1365. if (cell_count > cells.size()) {
  1366. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, cells.size());
  1367. return false;
  1368. }
  1369. if (this->v_trans != (bool) v_trans) {
  1370. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  1371. return false;
  1372. }
  1373. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  1374. for (const auto & layer : layers) {
  1375. const uint32_t il = layer.il;
  1376. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1377. auto * k = layer.k_stream[strm];
  1378. // Read type of key
  1379. int32_t k_type_i_ref;
  1380. io.read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  1381. const int32_t k_type_i = (int32_t) k->type;
  1382. if (k_type_i != k_type_i_ref) {
  1383. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  1384. return false;
  1385. }
  1386. // Read row size of key
  1387. uint64_t k_size_row_ref;
  1388. io.read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  1389. const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
  1390. if (k_size_row != k_size_row_ref) {
  1391. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  1392. return false;
  1393. }
  1394. if (cell_count) {
  1395. // Read and set the keys for the whole cell range
  1396. ggml_backend_tensor_set(k, io.read(cell_count * k_size_row), head * k_size_row, cell_count * k_size_row);
  1397. }
  1398. }
  1399. if (!this->v_trans) {
  1400. for (const auto & layer : layers) {
  1401. const uint32_t il = layer.il;
  1402. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1403. auto * v = layer.v_stream[strm];
  1404. // Read type of value
  1405. int32_t v_type_i_ref;
  1406. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1407. const int32_t v_type_i = (int32_t) v->type;
  1408. if (v_type_i != v_type_i_ref) {
  1409. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1410. return false;
  1411. }
  1412. // Read row size of value
  1413. uint64_t v_size_row_ref;
  1414. io.read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  1415. const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
  1416. if (v_size_row != v_size_row_ref) {
  1417. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  1418. return false;
  1419. }
  1420. if (cell_count) {
  1421. // Read and set the values for the whole cell range
  1422. ggml_backend_tensor_set(v, io.read(cell_count * v_size_row), head * v_size_row, cell_count * v_size_row);
  1423. }
  1424. }
  1425. } else {
  1426. // For each layer, read the values for each cell (transposed)
  1427. for (const auto & layer : layers) {
  1428. const uint32_t il = layer.il;
  1429. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1430. auto * v = layer.v_stream[strm];
  1431. // Read type of value
  1432. int32_t v_type_i_ref;
  1433. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1434. const int32_t v_type_i = (int32_t) v->type;
  1435. if (v_type_i != v_type_i_ref) {
  1436. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1437. return false;
  1438. }
  1439. // Read element size of value
  1440. uint32_t v_size_el_ref;
  1441. io.read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  1442. const size_t v_size_el = ggml_type_size(v->type);
  1443. if (v_size_el != v_size_el_ref) {
  1444. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  1445. return false;
  1446. }
  1447. // Read GQA embedding size
  1448. uint32_t n_embd_v_gqa_ref;
  1449. io.read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  1450. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  1451. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  1452. return false;
  1453. }
  1454. if (cell_count) {
  1455. // For each row in the transposed matrix, read the values for the whole cell range
  1456. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1457. const size_t dst_offset = (head + j * cells.size()) * v_size_el;
  1458. ggml_backend_tensor_set(v, io.read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  1459. }
  1460. }
  1461. }
  1462. }
  1463. return true;
  1464. }
  1465. //
  1466. // llama_kv_cache_context
  1467. //
  1468. llama_kv_cache_context::llama_kv_cache_context(llama_memory_status status) : status(status) {}
  1469. llama_kv_cache_context::llama_kv_cache_context(
  1470. llama_kv_cache * kv) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv) {
  1471. n_kv = kv->get_size();
  1472. const uint32_t n_stream = kv->get_n_stream();
  1473. // create a dummy slot info - the actual data is irrelevant. we just need to build the graph
  1474. sinfos.resize(1);
  1475. sinfos[0].s0 = 0;
  1476. sinfos[0].s1 = n_stream - 1;
  1477. sinfos[0].idxs.resize(n_stream);
  1478. for (uint32_t s = 0; s < n_stream; ++s) {
  1479. sinfos[0].strm.push_back(s);
  1480. sinfos[0].idxs[s].resize(1, 0);
  1481. }
  1482. }
  1483. llama_kv_cache_context::llama_kv_cache_context(
  1484. llama_kv_cache * kv,
  1485. llama_context * lctx,
  1486. bool do_shift,
  1487. stream_copy_info sc_info) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), lctx(lctx), do_shift(do_shift), sc_info(std::move(sc_info)) {
  1488. if (!do_shift && this->sc_info.empty()) {
  1489. status = LLAMA_MEMORY_STATUS_NO_UPDATE;
  1490. }
  1491. }
  1492. llama_kv_cache_context::llama_kv_cache_context(
  1493. llama_kv_cache * kv,
  1494. llama_kv_cache::slot_info_vec_t sinfos,
  1495. std::vector<llama_ubatch> ubatches) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), sinfos(std::move(sinfos)), ubatches(std::move(ubatches)) {
  1496. }
  1497. llama_kv_cache_context::~llama_kv_cache_context() = default;
  1498. bool llama_kv_cache_context::next() {
  1499. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1500. if (++i_cur >= ubatches.size()) {
  1501. return false;
  1502. }
  1503. return true;
  1504. }
  1505. bool llama_kv_cache_context::apply() {
  1506. assert(!llama_memory_status_is_fail(status));
  1507. // no ubatches -> this is a KV cache update
  1508. if (ubatches.empty()) {
  1509. kv->update(lctx, do_shift, sc_info);
  1510. return true;
  1511. }
  1512. kv->apply_ubatch(sinfos[i_cur], ubatches[i_cur]);
  1513. n_kv = kv->get_n_kv(sinfos[i_cur]);
  1514. return true;
  1515. }
  1516. llama_memory_status llama_kv_cache_context::get_status() const {
  1517. return status;
  1518. }
  1519. const llama_ubatch & llama_kv_cache_context::get_ubatch() const {
  1520. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1521. return ubatches[i_cur];
  1522. }
  1523. uint32_t llama_kv_cache_context::get_n_kv() const {
  1524. return n_kv;
  1525. }
  1526. ggml_tensor * llama_kv_cache_context::get_k(ggml_context * ctx, int32_t il) const {
  1527. return kv->get_k(ctx, il, n_kv, sinfos[i_cur]);
  1528. }
  1529. ggml_tensor * llama_kv_cache_context::get_v(ggml_context * ctx, int32_t il) const {
  1530. return kv->get_v(ctx, il, n_kv, sinfos[i_cur]);
  1531. }
  1532. ggml_tensor * llama_kv_cache_context::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il) const {
  1533. return kv->cpy_k(ctx, k_cur, k_idxs, il, sinfos[i_cur]);
  1534. }
  1535. ggml_tensor * llama_kv_cache_context::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il) const {
  1536. return kv->cpy_v(ctx, v_cur, v_idxs, il, sinfos[i_cur]);
  1537. }
  1538. ggml_tensor * llama_kv_cache_context::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  1539. return kv->build_input_k_idxs(ctx, ubatch);
  1540. }
  1541. ggml_tensor * llama_kv_cache_context::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  1542. return kv->build_input_v_idxs(ctx, ubatch);
  1543. }
  1544. void llama_kv_cache_context::set_input_k_shift(ggml_tensor * dst) const {
  1545. kv->set_input_k_shift(dst);
  1546. }
  1547. void llama_kv_cache_context::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1548. kv->set_input_k_idxs(dst, ubatch, sinfos[i_cur]);
  1549. }
  1550. void llama_kv_cache_context::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1551. kv->set_input_v_idxs(dst, ubatch, sinfos[i_cur]);
  1552. }
  1553. void llama_kv_cache_context::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
  1554. kv->set_input_kq_mask(dst, ubatch, causal_attn);
  1555. }
  1556. void llama_kv_cache_context::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1557. kv->set_input_pos_bucket(dst, ubatch);
  1558. }