llama-kv-cache-unified.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406
  1. #include "llama-kv-cache-unified.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 <limits>
  10. #include <map>
  11. #include <stdexcept>
  12. //
  13. // llama_kv_cache_unified
  14. //
  15. llama_kv_cache_unified::llama_kv_cache_unified(
  16. const llama_model & model,
  17. layer_filter_cb && filter,
  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. model(model), hparams(model.hparams), v_trans(v_trans),
  29. 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) {
  30. GGML_ASSERT(kv_size % n_pad == 0);
  31. // TODO: this is temporary until we support passing reuse layer filters [KV_REUSE]
  32. auto n_layer_cache = hparams.n_layer;
  33. if (model.arch == LLM_ARCH_GEMMA3N) {
  34. n_layer_cache = 20;
  35. }
  36. if (model.arch == LLM_ARCH_GLM4_MOE) {
  37. // GLM-4.5: Only process up to last layer, skip final NextN layer
  38. n_layer_cache = hparams.n_layer - hparams.nextn_predict_layers;
  39. }
  40. // create a context for each buffer type
  41. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  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_cache*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[buft] = ctx;
  55. ctxs.emplace_back(ctx);
  56. return ctx;
  57. }
  58. return it->second;
  59. };
  60. GGML_ASSERT(n_stream == 1 || n_stream == n_seq_max);
  61. v_heads.resize(n_stream);
  62. for (uint32_t s = 0; s < n_stream; ++s) {
  63. v_heads[s] = 0;
  64. }
  65. v_cells.resize(n_stream);
  66. for (uint32_t s = 0; s < n_stream; ++s) {
  67. v_cells[s].resize(kv_size);
  68. }
  69. // by default, all sequence ids are mapped to the 0th stream
  70. seq_to_stream.resize(LLAMA_MAX_SEQ, 0);
  71. if (n_stream > 1) {
  72. seq_to_stream.resize(n_stream, 0);
  73. for (uint32_t s = 0; s < n_stream; ++s) {
  74. seq_to_stream[s] = s;
  75. }
  76. }
  77. // [TAG_V_CACHE_VARIABLE]
  78. if (v_trans && hparams.is_n_embd_v_gqa_variable()) {
  79. LLAMA_LOG_WARN("%s: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to %d\n",
  80. __func__, hparams.n_embd_v_gqa_max());
  81. }
  82. for (uint32_t il = 0; il < n_layer_cache; il++) {
  83. if (filter && !filter(il)) {
  84. LLAMA_LOG_DEBUG("%s: layer %3d: skipped\n", __func__, il);
  85. continue;
  86. }
  87. // [TAG_V_CACHE_VARIABLE]
  88. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  89. const uint32_t n_embd_v_gqa = !v_trans ? hparams.n_embd_v_gqa(il) : hparams.n_embd_v_gqa_max();
  90. const char * dev_name = "CPU";
  91. ggml_backend_buffer_type_t buft = ggml_backend_cpu_buffer_type();
  92. if (offload) {
  93. auto * dev = model.dev_layer(il);
  94. buft = ggml_backend_dev_buffer_type(dev);
  95. dev_name = ggml_backend_dev_name(dev);
  96. }
  97. LLAMA_LOG_DEBUG("%s: layer %3d: dev = %s\n", __func__, il, dev_name);
  98. ggml_context * ctx = ctx_for_buft(buft);
  99. if (!ctx) {
  100. throw std::runtime_error("failed to create ggml context for kv cache");
  101. }
  102. ggml_tensor * k;
  103. ggml_tensor * v;
  104. k = ggml_new_tensor_3d(ctx, type_k, n_embd_k_gqa, kv_size, n_stream);
  105. v = ggml_new_tensor_3d(ctx, type_v, n_embd_v_gqa, kv_size, n_stream);
  106. ggml_format_name(k, "cache_k_l%d", il);
  107. ggml_format_name(v, "cache_v_l%d", il);
  108. std::vector<ggml_tensor *> k_stream;
  109. std::vector<ggml_tensor *> v_stream;
  110. for (uint32_t s = 0; s < n_stream; ++s) {
  111. k_stream.push_back(ggml_view_2d(ctx, k, n_embd_k_gqa, kv_size, k->nb[1], s*k->nb[2]));
  112. v_stream.push_back(ggml_view_2d(ctx, v, n_embd_v_gqa, kv_size, v->nb[1], s*v->nb[2]));
  113. }
  114. map_layer_ids[il] = layers.size();
  115. layers.push_back({ il, k, v, k_stream, v_stream, });
  116. }
  117. // TODO: this is temporary until we support passing reuse layer filters [KV_REUSE]
  118. if (model.arch == LLM_ARCH_GEMMA3N) {
  119. LLAMA_LOG_DEBUG("%s: GEMMA3N: reuse layers [%d, %d]\n", __func__, n_layer_cache, hparams.n_layer - 1);
  120. for (uint32_t il = n_layer_cache; il < hparams.n_layer; il++) {
  121. if (filter && !filter(il)) {
  122. LLAMA_LOG_DEBUG("%s: layer %3d: skipped\n", __func__, il);
  123. continue;
  124. }
  125. const bool is_swa = hparams.is_swa(il);
  126. const uint32_t il_reuse = n_layer_cache - (is_swa ? 2 : 1);
  127. GGML_ASSERT(map_layer_ids.find(il_reuse) != map_layer_ids.end());
  128. map_layer_ids[il] = map_layer_ids[il_reuse];
  129. LLAMA_LOG_DEBUG("%s: layer %3d: reuse layer %d, isw = %d\n", __func__, il, il_reuse, is_swa);
  130. }
  131. }
  132. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  133. for (auto it : ctx_map) {
  134. auto * buft = it.first;
  135. auto * ctx = it.second;
  136. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  137. if (!buf) {
  138. throw std::runtime_error("failed to allocate buffer for kv cache");
  139. }
  140. 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);
  141. ggml_backend_buffer_clear(buf, 0);
  142. bufs.emplace_back(buf);
  143. }
  144. {
  145. const size_t memory_size_k = size_k_bytes();
  146. const size_t memory_size_v = size_v_bytes();
  147. 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__,
  148. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f), kv_size, (int) layers.size(), n_seq_max, n_stream,
  149. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  150. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  151. }
  152. const char * LLAMA_KV_CACHE_DEBUG = getenv("LLAMA_KV_CACHE_DEBUG");
  153. debug = LLAMA_KV_CACHE_DEBUG ? atoi(LLAMA_KV_CACHE_DEBUG) : 0;
  154. const char * LLAMA_SET_ROWS = getenv("LLAMA_SET_ROWS");
  155. supports_set_rows = LLAMA_SET_ROWS ? atoi(LLAMA_SET_ROWS) != 0 : supports_set_rows;
  156. if (!supports_set_rows) {
  157. // ref: https://github.com/ggml-org/llama.cpp/pull/14363
  158. GGML_ASSERT(unified && "cannot use non-unified KV cache without ggml_set_rows() support");
  159. }
  160. if (!supports_set_rows) {
  161. LLAMA_LOG_WARN("%s: LLAMA_SET_ROWS=0, using old ggml_cpy() method for backwards compatibility\n", __func__);
  162. }
  163. }
  164. void llama_kv_cache_unified::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 : bufs) {
  171. ggml_backend_buffer_clear(buf.get(), 0);
  172. }
  173. }
  174. }
  175. bool llama_kv_cache_unified::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_unified::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. if (shift != 0) {
  270. pos -= shift;
  271. assert(pos >= 0);
  272. }
  273. v_cells[s1].pos_set(i, pos);
  274. v_cells[s1].seq_add(i, seq_id_dst);
  275. if (shift != 0) {
  276. v_cells[s1].pos_add(i, shift);
  277. }
  278. }
  279. }
  280. v_heads[s1] = v_heads[s0];
  281. //for (uint32_t s = 0; s < n_stream; ++s) {
  282. // 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));
  283. //}
  284. }
  285. void llama_kv_cache_unified::seq_keep(llama_seq_id seq_id) {
  286. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  287. auto & cells = v_cells[seq_to_stream[seq_id]];
  288. auto & head = v_heads[seq_to_stream[seq_id]];
  289. uint32_t new_head = cells.size();
  290. for (uint32_t i = 0; i < cells.size(); ++i) {
  291. if (cells.seq_keep(i, seq_id)) {
  292. if (new_head == cells.size()) {
  293. new_head = i;
  294. }
  295. }
  296. }
  297. // If we freed up a slot, set head to it so searching can start there.
  298. if (new_head != cells.size() && new_head < head) {
  299. head = new_head;
  300. }
  301. }
  302. void llama_kv_cache_unified::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) {
  303. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  304. auto & cells = v_cells[seq_to_stream[seq_id]];
  305. auto & head = v_heads[seq_to_stream[seq_id]];
  306. if (shift == 0) {
  307. return;
  308. }
  309. uint32_t new_head = cells.size();
  310. if (p0 < 0) {
  311. p0 = 0;
  312. }
  313. if (p1 < 0) {
  314. p1 = std::numeric_limits<llama_pos>::max();
  315. }
  316. // If there is no range then return early to avoid looping over all cells.
  317. if (p0 == p1) {
  318. return;
  319. }
  320. for (uint32_t i = 0; i < cells.size(); ++i) {
  321. if (!cells.pos_in(i, p0, p1)) {
  322. continue;
  323. }
  324. if (cells.seq_has(i, seq_id)) {
  325. if (cells.pos_add(i, shift)) {
  326. if (new_head == cells.size()) {
  327. new_head = i;
  328. }
  329. }
  330. }
  331. }
  332. // If we freed up a slot, set head to it so searching can start there.
  333. // Otherwise we just start the next search from the beginning.
  334. head = new_head != cells.size() ? new_head : 0;
  335. }
  336. void llama_kv_cache_unified::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  337. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  338. auto & cells = v_cells[seq_to_stream[seq_id]];
  339. if (d == 1) {
  340. return;
  341. }
  342. if (p0 < 0) {
  343. p0 = 0;
  344. }
  345. if (p1 < 0) {
  346. p1 = std::numeric_limits<llama_pos>::max();
  347. }
  348. // If there is no range then return early to avoid looping over the cache.
  349. if (p0 == p1) {
  350. return;
  351. }
  352. for (uint32_t i = 0; i < cells.size(); ++i) {
  353. if (!cells.pos_in(i, p0, p1)) {
  354. continue;
  355. }
  356. if (cells.seq_has(i, seq_id)) {
  357. cells.pos_div(i, d);
  358. }
  359. }
  360. }
  361. llama_pos llama_kv_cache_unified::seq_pos_min(llama_seq_id seq_id) const {
  362. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  363. const auto & cells = v_cells[seq_to_stream[seq_id]];
  364. return cells.seq_pos_min(seq_id);
  365. }
  366. llama_pos llama_kv_cache_unified::seq_pos_max(llama_seq_id seq_id) const {
  367. GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
  368. const auto & cells = v_cells[seq_to_stream[seq_id]];
  369. return cells.seq_pos_max(seq_id);
  370. }
  371. llama_memory_context_ptr llama_kv_cache_unified::init_batch(
  372. llama_batch_allocr & balloc,
  373. uint32_t n_ubatch,
  374. bool embd_all) {
  375. GGML_UNUSED(embd_all);
  376. do {
  377. balloc.split_reset();
  378. std::vector<llama_ubatch> ubatches;
  379. while (true) {
  380. auto ubatch = n_stream == 1 ? balloc.split_simple(n_ubatch) : balloc.split_equal(n_ubatch, true);
  381. if (ubatch.n_tokens == 0) {
  382. break;
  383. }
  384. ubatches.push_back(std::move(ubatch)); // NOLINT
  385. }
  386. if (balloc.get_n_used() < balloc.get_n_tokens()) {
  387. // failed to find a suitable split
  388. break;
  389. }
  390. auto sinfos = prepare(ubatches);
  391. if (sinfos.empty()) {
  392. break;
  393. }
  394. return std::make_unique<llama_kv_cache_unified_context>(
  395. this, std::move(sinfos), std::move(ubatches));
  396. } while (false);
  397. return std::make_unique<llama_kv_cache_unified_context>(LLAMA_MEMORY_STATUS_FAILED_PREPARE);
  398. }
  399. llama_memory_context_ptr llama_kv_cache_unified::init_full() {
  400. return std::make_unique<llama_kv_cache_unified_context>(this);
  401. }
  402. llama_memory_context_ptr llama_kv_cache_unified::init_update(llama_context * lctx, bool optimize) {
  403. bool do_shift = get_has_shift();
  404. defrag_info dinfo;
  405. // see if we need to defrag
  406. if (n_stream == 1) {
  407. // note : for now do not consider defrag for n_stream > 1
  408. const auto & cells = v_cells[seq_to_stream[0]];
  409. bool do_defrag = optimize;
  410. const auto thold = lctx->get_cparams().defrag_thold;
  411. if (!do_defrag && thold > 0.0f) {
  412. const auto n_kv = cells.used_max_p1();
  413. // - do not defrag small contexts (i.e. < 2048 tokens)
  414. // - count the padding towards the number of used tokens
  415. const float fragmentation = n_kv >= 2048 ? std::max(0.0f, 1.0f - (float(cells.get_used() + n_pad)/n_kv)) : 0.0f;
  416. if (fragmentation > thold) {
  417. LLAMA_LOG_DEBUG("%s: fragmentation: %.2f - requesting defrag\n", __func__, fragmentation);
  418. do_defrag = true;
  419. }
  420. }
  421. if (do_defrag) {
  422. dinfo = defrag_prepare(lctx->graph_max_nodes());
  423. }
  424. }
  425. return std::make_unique<llama_kv_cache_unified_context>(this, lctx, do_shift, std::move(dinfo), std::move(sc_info));
  426. }
  427. llama_kv_cache_unified::slot_info_vec_t llama_kv_cache_unified::prepare(const std::vector<llama_ubatch> & ubatches) {
  428. llama_kv_cache_unified::slot_info_vec_t res;
  429. struct state_t {
  430. slot_info sinfo; // slot info for the ubatch
  431. std::vector<uint32_t> v_heads_old; // old positions of the heads, before placing the ubatch
  432. std::vector<llama_kv_cells_unified> v_cells; // copy of the old cells, before placing the ubatch
  433. };
  434. // remember the old state of the cells so we can restore it in the end
  435. std::vector<state_t> states;
  436. bool success = true;
  437. for (const auto & ubatch : ubatches) {
  438. // non-continuous slots require support for ggml_set_rows()
  439. const bool cont = supports_set_rows ? false : true;
  440. // only find a suitable slot for the ubatch. don't modify the cells yet
  441. const auto sinfo_new = find_slot(ubatch, cont);
  442. if (sinfo_new.empty()) {
  443. success = false;
  444. break;
  445. }
  446. // remeber the position that we found
  447. res.push_back(sinfo_new);
  448. // store the old state of the cells in the recovery stack
  449. {
  450. state_t state = { sinfo_new, v_heads, {} };
  451. for (uint32_t s = 0; s < sinfo_new.n_stream(); ++s) {
  452. auto & cells = v_cells[sinfo_new.strm[s]];
  453. state.v_cells.push_back(cells.cp(sinfo_new.idxs[s]));
  454. }
  455. states.push_back(std::move(state));
  456. }
  457. // now emplace the ubatch
  458. apply_ubatch(sinfo_new, ubatch);
  459. }
  460. GGML_ASSERT(!states.empty() || !success);
  461. // iterate backwards and restore the cells to their original state
  462. for (auto it = states.rbegin(); it != states.rend(); ++it) {
  463. const auto & sinfo = it->sinfo;
  464. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  465. auto & cells = v_cells[sinfo.strm[s]];
  466. auto & head = v_heads[sinfo.strm[s]];
  467. cells.set(sinfo.idxs[s], it->v_cells[s]);
  468. head = it->v_heads_old[s];
  469. }
  470. }
  471. if (!success) {
  472. return {};
  473. }
  474. return res;
  475. }
  476. bool llama_kv_cache_unified::update(llama_context * lctx, bool do_shift, const defrag_info & dinfo, const stream_copy_info & sc_info) {
  477. bool updated = false;
  478. auto * sched = lctx->get_sched();
  479. if (!sc_info.empty()) {
  480. assert(n_stream > 1 && "stream copy should never happen with a single stream");
  481. llama_synchronize(lctx);
  482. const size_t n_copy = sc_info.ssrc.size();
  483. for (size_t i = 0; i < n_copy; ++i) {
  484. const auto ssrc = sc_info.ssrc[i];
  485. const auto sdst = sc_info.sdst[i];
  486. assert(ssrc < n_stream);
  487. assert(sdst < n_stream);
  488. LLAMA_LOG_DEBUG("%s: copying KV buffer: stream %d to stream %d\n", __func__, ssrc, sdst);
  489. assert(ssrc != sdst);
  490. for (uint32_t il = 0; il < layers.size(); ++il) {
  491. const auto & layer = layers[il];
  492. ggml_backend_tensor_copy(layer.k_stream[ssrc], layer.k_stream[sdst]);
  493. ggml_backend_tensor_copy(layer.v_stream[ssrc], layer.v_stream[sdst]);
  494. }
  495. }
  496. }
  497. if (do_shift) {
  498. if (!get_can_shift()) {
  499. GGML_ABORT("The current KV cache / model configuration does not support K-shift");
  500. }
  501. LLAMA_LOG_DEBUG("%s: applying K-shift\n", __func__);
  502. // apply K-shift if needed
  503. if (hparams.rope_type != LLAMA_ROPE_TYPE_NONE) {
  504. ggml_backend_sched_reset(sched);
  505. auto * res = lctx->get_gf_res_reserve();
  506. res->reset();
  507. auto * gf = build_graph_shift(res, lctx);
  508. if (!ggml_backend_sched_alloc_graph(sched, gf)) {
  509. LLAMA_LOG_ERROR("%s: failed to allocate compute graph for K-shift\n", __func__);
  510. return updated;
  511. }
  512. res->set_inputs(nullptr);
  513. if (lctx->graph_compute(gf, false) != GGML_STATUS_SUCCESS) {
  514. LLAMA_LOG_ERROR("%s: failed to compute K-shift\n", __func__);
  515. return updated;
  516. }
  517. updated = true;
  518. }
  519. for (uint32_t s = 0; s < n_stream; ++s) {
  520. auto & cells = v_cells[s];
  521. cells.reset_shift();
  522. }
  523. }
  524. if (!dinfo.empty()) {
  525. LLAMA_LOG_DEBUG("%s: defragmenting KV cache\n", __func__);
  526. // note: for now do not consider defrag for n_stream > 1
  527. auto & cells = v_cells[seq_to_stream[0]];
  528. auto & head = v_heads[seq_to_stream[0]];
  529. // apply moves:
  530. {
  531. const auto n_kv = dinfo.ids.size();
  532. for (uint32_t i = 0; i < n_kv; ++i) {
  533. assert(dinfo.ids[i] <= n_kv);
  534. if (dinfo.ids[i] == n_kv || dinfo.ids[i] == i) {
  535. continue;
  536. }
  537. cells.mv(i, dinfo.ids[i]);
  538. }
  539. // reset the head so we can find the first free slot during the next ubatch
  540. head = 0;
  541. }
  542. ggml_backend_sched_reset(sched);
  543. auto * res = lctx->get_gf_res_reserve();
  544. res->reset();
  545. auto * gf = build_graph_defrag(res, lctx, dinfo);
  546. if (!ggml_backend_sched_alloc_graph(sched, gf)) {
  547. LLAMA_LOG_ERROR("%s: failed to allocate compute graph for defrag\n", __func__);
  548. return updated;
  549. }
  550. res->set_inputs(nullptr);
  551. if (lctx->graph_compute(gf, false) != GGML_STATUS_SUCCESS) {
  552. LLAMA_LOG_ERROR("%s: failed to compute defrag\n", __func__);
  553. return updated;
  554. }
  555. updated = true;
  556. }
  557. return updated;
  558. }
  559. llama_kv_cache_unified::slot_info llama_kv_cache_unified::find_slot(const llama_ubatch & ubatch, bool cont) const {
  560. if (debug > 0) {
  561. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  562. const auto seq_id = ubatch.seq_id_unq[s];
  563. const auto stream_id = seq_to_stream[seq_id];
  564. const auto & cells = v_cells[stream_id];
  565. const uint32_t head_cur = v_heads[stream_id];
  566. LLAMA_LOG_DEBUG("%s: stream[%d], n = %5d, used = %5d, head = %5d, size = %5d, n_swa = %5d\n",
  567. __func__, stream_id, cells.used_max_p1(), cells.get_used(), head_cur, get_size(), n_swa);
  568. if ((debug == 2 && n_swa > 0) || debug > 2) {
  569. std::string ss;
  570. for (uint32_t i = 0; i < cells.size(); ++i) {
  571. if (cells.is_empty(i)) {
  572. ss += '.';
  573. } else {
  574. assert(cells.seq_count(i) >= 1);
  575. if (cells.seq_count(i) == 1) {
  576. ss += std::to_string(cells.seq_get(i));
  577. } else {
  578. ss += 'M';
  579. }
  580. }
  581. if (i%256 == 255) {
  582. ss += " *";
  583. ss += '\n';
  584. }
  585. }
  586. LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
  587. }
  588. if ((debug == 2 && n_swa > 0) || debug > 2) {
  589. std::string ss;
  590. for (uint32_t i = 0; i < cells.size(); ++i) {
  591. std::string cur;
  592. if (cells.is_empty(i)) {
  593. cur = '.';
  594. } else {
  595. cur = std::to_string(cells.pos_get(i));
  596. }
  597. const int n = cur.size();
  598. for (int j = 0; j < 5 - n; ++j) {
  599. cur += ' ';
  600. }
  601. ss += cur;
  602. if (i%256 == 255) {
  603. ss += " *";
  604. }
  605. if (i%64 == 63) {
  606. ss += '\n';
  607. }
  608. }
  609. LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
  610. }
  611. for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
  612. if (cells.seq_pos_min(s) < 0) {
  613. continue;
  614. }
  615. 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));
  616. }
  617. }
  618. }
  619. uint32_t n_tokens = ubatch.n_tokens;
  620. uint32_t n_seqs = 1;
  621. if (n_stream > 1) {
  622. GGML_ASSERT(n_tokens % ubatch.n_seqs_unq == 0);
  623. n_seqs = ubatch.n_seqs_unq;
  624. n_tokens = n_tokens / n_seqs;
  625. }
  626. slot_info res = {
  627. /*.s0 =*/ LLAMA_MAX_SEQ,
  628. /*.s1 =*/ 0,
  629. /*.strm =*/ { },
  630. /*.idxs =*/ { },
  631. };
  632. res.resize(n_seqs);
  633. for (uint32_t s = 0; s < n_seqs; ++s) {
  634. const auto seq_id = ubatch.seq_id_unq[s];
  635. if (n_stream > 1) {
  636. GGML_ASSERT(ubatch.n_seq_id[s*n_tokens] == 1);
  637. GGML_ASSERT(ubatch.seq_id [s*n_tokens][0] == seq_id);
  638. }
  639. res.s0 = std::min<llama_seq_id>(res.s0, seq_to_stream[seq_id]);
  640. res.s1 = std::max<llama_seq_id>(res.s1, seq_to_stream[seq_id]);
  641. res.strm[s] = seq_to_stream[seq_id];
  642. res.idxs[s].reserve(n_tokens);
  643. const auto & cells = v_cells[seq_to_stream[seq_id]];
  644. uint32_t head_cur = v_heads[seq_to_stream[seq_id]];
  645. // if we have enough unused cells before the current head ->
  646. // better to start searching from the beginning of the cache, hoping to fill it
  647. if (head_cur > cells.get_used() + 2*n_tokens) {
  648. head_cur = 0;
  649. }
  650. if (n_tokens > cells.size()) {
  651. LLAMA_LOG_ERROR("%s: n_tokens = %d > size = %u\n", __func__, n_tokens, cells.size());
  652. return { };
  653. }
  654. uint32_t n_tested = 0;
  655. // for continuous slots, we test that all tokens in the ubatch fit, starting from the current head
  656. // for non-continuous slots, we test the tokens one by one
  657. const uint32_t n_test = cont ? n_tokens : 1;
  658. while (true) {
  659. if (head_cur + n_test > cells.size()) {
  660. n_tested += cells.size() - head_cur;
  661. head_cur = 0;
  662. continue;
  663. }
  664. for (uint32_t i = 0; i < n_test; i++) {
  665. const auto idx = head_cur;
  666. head_cur++;
  667. n_tested++;
  668. //const llama_pos pos = ubatch.pos[i];
  669. //const llama_seq_id seq_id = ubatch.seq_id[i][0];
  670. // can we use this cell? either:
  671. // - the cell is empty
  672. // - the cell is occupied only by one sequence:
  673. // - (disabled) mask causally, if the sequence is the same as the one we are inserting
  674. // - mask SWA, using current max pos for that sequence in the cache
  675. // always insert in the cell with minimum pos
  676. bool can_use = cells.is_empty(idx);
  677. if (!can_use && cells.seq_count(idx) == 1) {
  678. const llama_pos pos_cell = cells.pos_get(idx);
  679. // (disabled) causal mask
  680. // note: it's better to purge any "future" tokens beforehand
  681. //if (cells.seq_has(idx, seq_id)) {
  682. // can_use = pos_cell >= pos;
  683. //}
  684. if (!can_use) {
  685. const llama_seq_id seq_id_cell = cells.seq_get(idx);
  686. // SWA mask
  687. if (is_masked_swa(pos_cell, cells.seq_pos_max(seq_id_cell) + 1)) {
  688. can_use = true;
  689. }
  690. }
  691. }
  692. if (can_use) {
  693. res.idxs[s].push_back(idx);
  694. } else {
  695. if (cont) {
  696. break;
  697. }
  698. }
  699. }
  700. if (res.idxs[s].size() == n_tokens) {
  701. break;
  702. }
  703. if (cont) {
  704. res.idxs[s].clear();
  705. }
  706. if (n_tested >= cells.size()) {
  707. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  708. return { };
  709. }
  710. }
  711. // we didn't find a suitable slot - return empty result
  712. if (res.idxs[s].size() < n_tokens) {
  713. return { };
  714. }
  715. }
  716. assert(res.s1 >= res.s0);
  717. return res;
  718. }
  719. void llama_kv_cache_unified::apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch) {
  720. // keep track of the max sequence position that we would overwrite with this ubatch
  721. // for non-SWA cache, this would be always empty
  722. llama_seq_id seq_pos_max_rm[LLAMA_MAX_SEQ];
  723. for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) {
  724. seq_pos_max_rm[s] = -1;
  725. }
  726. assert(ubatch.n_tokens == sinfo.n_stream()*sinfo.size());
  727. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  728. for (uint32_t ii = 0; ii < sinfo.size(); ++ii) {
  729. const uint32_t i = s*sinfo.size() + ii;
  730. auto & cells = v_cells[sinfo.strm[s]];
  731. const auto idx = sinfo.idxs[s][ii];
  732. if (!cells.is_empty(idx)) {
  733. assert(cells.seq_count(idx) == 1);
  734. const llama_seq_id seq_id = cells.seq_get(idx);
  735. const llama_pos pos = cells.pos_get(idx);
  736. seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos);
  737. cells.rm(idx);
  738. }
  739. cells.pos_set(idx, ubatch.pos[i]);
  740. for (int32_t s = 0; s < ubatch.n_seq_id[i]; s++) {
  741. cells.seq_add(idx, ubatch.seq_id[i][s]);
  742. }
  743. }
  744. }
  745. // note: we want to preserve the invariant that all positions between [pos_min, pos_max] for each sequence
  746. // will be present in the cache. so we have to purge any position which is less than those we would overwrite
  747. // ref: https://github.com/ggml-org/llama.cpp/pull/13746#issuecomment-2916057092
  748. for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) {
  749. if (seq_pos_max_rm[s] == -1) {
  750. continue;
  751. }
  752. GGML_ASSERT(s < seq_to_stream.size());
  753. auto & cells = v_cells[seq_to_stream[s]];
  754. if (cells.seq_pos_min(s) <= seq_pos_max_rm[s]) {
  755. LLAMA_LOG_DEBUG("%s: purging positions [%d, %d] of sequence %d from KV cache\n",
  756. __func__, cells.seq_pos_min(s), seq_pos_max_rm[s], s);
  757. seq_rm(s, cells.seq_pos_min(s), seq_pos_max_rm[s] + 1);
  758. }
  759. }
  760. // move the head at the end of the slot
  761. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  762. auto & head = v_heads[sinfo.strm[s]];
  763. head = sinfo.idxs[s].back() + 1;
  764. }
  765. }
  766. bool llama_kv_cache_unified::get_can_shift() const {
  767. return true;
  768. }
  769. uint32_t llama_kv_cache_unified::get_size() const {
  770. const auto & cells = v_cells[seq_to_stream[0]];
  771. return cells.size();
  772. }
  773. uint32_t llama_kv_cache_unified::get_n_stream() const {
  774. return n_stream;
  775. }
  776. bool llama_kv_cache_unified::get_has_shift() const {
  777. bool result = false;
  778. for (uint32_t s = 0; s < n_stream; ++s) {
  779. result |= v_cells[s].get_has_shift();
  780. }
  781. return result;
  782. }
  783. uint32_t llama_kv_cache_unified::get_n_kv() const {
  784. uint32_t result = 0;
  785. for (uint32_t s = 0; s < n_stream; ++s) {
  786. const auto & cells = v_cells[s];
  787. result = std::max(std::min(cells.size(), std::max(n_pad, GGML_PAD(cells.used_max_p1(), n_pad))), result);
  788. }
  789. return result;
  790. }
  791. bool llama_kv_cache_unified::get_supports_set_rows() const {
  792. return supports_set_rows;
  793. }
  794. ggml_tensor * llama_kv_cache_unified::get_k(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const {
  795. const int32_t ikv = map_layer_ids.at(il);
  796. auto * k = layers[ikv].k;
  797. const uint64_t kv_size = get_size();
  798. const uint64_t n_embd_k_gqa = k->ne[0];
  799. assert(n_embd_k_gqa == hparams.n_embd_k_gqa(il));
  800. const uint32_t ns = sinfo.s1 - sinfo.s0 + 1;
  801. return ggml_view_4d(ctx, k,
  802. hparams.n_embd_head_k, hparams.n_head_kv(il), n_kv, ns,
  803. ggml_row_size(k->type, hparams.n_embd_head_k),
  804. ggml_row_size(k->type, n_embd_k_gqa),
  805. ggml_row_size(k->type, n_embd_k_gqa*kv_size),
  806. ggml_row_size(k->type, n_embd_k_gqa*kv_size)*sinfo.s0);
  807. }
  808. ggml_tensor * llama_kv_cache_unified::get_v(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const {
  809. const int32_t ikv = map_layer_ids.at(il);
  810. auto * v = layers[ikv].v;
  811. const uint64_t kv_size = get_size();
  812. const uint64_t n_embd_v_gqa = v->ne[0];
  813. // [TAG_V_CACHE_VARIABLE]
  814. assert(n_embd_v_gqa >= hparams.n_embd_v_gqa(il));
  815. const uint32_t ns = sinfo.s1 - sinfo.s0 + 1;
  816. if (!v_trans) {
  817. // note: v->nb[1] <= v->nb[2]
  818. return ggml_view_4d(ctx, v,
  819. hparams.n_embd_head_v, hparams.n_head_kv(il), n_kv, ns,
  820. ggml_row_size(v->type, hparams.n_embd_head_v), // v->nb[1]
  821. ggml_row_size(v->type, n_embd_v_gqa), // v->nb[2]
  822. ggml_row_size(v->type, n_embd_v_gqa*kv_size), // v->nb[3]
  823. ggml_row_size(v->type, n_embd_v_gqa*kv_size)*sinfo.s0);
  824. }
  825. // note: v->nb[1] > v->nb[2]
  826. return ggml_view_4d(ctx, v,
  827. n_kv, hparams.n_head_kv(il), hparams.n_embd_head_v, ns,
  828. ggml_row_size(v->type, kv_size*hparams.n_embd_head_v), // v->nb[1]
  829. ggml_row_size(v->type, kv_size), // v->nb[2]
  830. ggml_row_size(v->type, kv_size*n_embd_v_gqa), // v->nb[3]
  831. ggml_row_size(v->type, kv_size*n_embd_v_gqa)*sinfo.s0);
  832. }
  833. ggml_tensor * llama_kv_cache_unified::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il, const slot_info & sinfo) const {
  834. const int32_t ikv = map_layer_ids.at(il);
  835. auto * k = layers[ikv].k;
  836. const int64_t n_embd_k_gqa = k->ne[0];
  837. const int64_t n_tokens = k_cur->ne[2];
  838. k_cur = ggml_reshape_2d(ctx, k_cur, k->ne[0], n_tokens);
  839. if (k_idxs && supports_set_rows) {
  840. if (k->ne[2] > 1) {
  841. k = ggml_reshape_2d(ctx, k, k->ne[0], k->ne[1]*k->ne[2]);
  842. }
  843. return ggml_set_rows(ctx, k, k_cur, k_idxs);
  844. }
  845. // TODO: fallback to old ggml_cpy() method for backwards compatibility
  846. // will be removed when ggml_set_rows() is adopted by all backends
  847. GGML_ASSERT(n_stream == 1 && "n_stream > 1 not supported without LLAMA_SET_ROWS");
  848. ggml_tensor * k_view = ggml_view_1d(ctx, k,
  849. n_tokens*n_embd_k_gqa,
  850. ggml_row_size(k->type, n_embd_k_gqa)*sinfo.head());
  851. return ggml_cpy(ctx, k_cur, k_view);
  852. }
  853. ggml_tensor * llama_kv_cache_unified::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il, const slot_info & sinfo) const {
  854. const int32_t ikv = map_layer_ids.at(il);
  855. auto * v = layers[ikv].v;
  856. const int64_t n_embd_v_gqa = v_cur->ne[0]*v_cur->ne[1];
  857. const int64_t n_tokens = v_cur->ne[2];
  858. v_cur = ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens);
  859. if (v_idxs && supports_set_rows) {
  860. if (!v_trans) {
  861. if (v->ne[2] > 1) {
  862. v = ggml_reshape_2d(ctx, v, v->ne[0], v->ne[1]*v->ne[2]);
  863. }
  864. return ggml_set_rows(ctx, v, v_cur, v_idxs);
  865. }
  866. // [TAG_V_CACHE_VARIABLE]
  867. if (n_embd_v_gqa < v->ne[0]) {
  868. v_cur = ggml_pad(ctx, v_cur, v->ne[0] - n_embd_v_gqa, 0, 0, 0);
  869. }
  870. // the row becomes a single element
  871. ggml_tensor * v_view = ggml_reshape_2d(ctx, v, 1, v->ne[0]*v->ne[1]*v->ne[2]);
  872. v_cur = ggml_reshape_2d(ctx, v_cur, 1, v_cur->ne[0]*v_cur->ne[1]);
  873. return ggml_set_rows(ctx, v_view, v_cur, v_idxs);
  874. }
  875. // TODO: fallback to old ggml_cpy() method for backwards compatibility
  876. // will be removed when ggml_set_rows() is adopted by all backends
  877. GGML_ASSERT(n_stream == 1 && "n_stream > 1 not supported without LLAMA_SET_ROWS");
  878. ggml_tensor * v_view = nullptr;
  879. if (!v_trans) {
  880. v_view = ggml_view_1d(ctx, v,
  881. n_tokens*n_embd_v_gqa,
  882. ggml_row_size(v->type, n_embd_v_gqa)*sinfo.head());
  883. } else {
  884. v_cur = ggml_transpose(ctx, v_cur);
  885. v_view = ggml_view_2d(ctx, v, n_tokens, n_embd_v_gqa,
  886. (v->ne[1] )*ggml_element_size(v),
  887. (sinfo.head())*ggml_element_size(v));
  888. }
  889. return ggml_cpy(ctx, v_cur, v_view);
  890. }
  891. ggml_tensor * llama_kv_cache_unified::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  892. const uint32_t n_tokens = ubatch.n_tokens;
  893. ggml_tensor * k_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens);
  894. ggml_set_input(k_idxs);
  895. return k_idxs;
  896. }
  897. ggml_tensor * llama_kv_cache_unified::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  898. const uint32_t n_tokens = ubatch.n_tokens;
  899. ggml_tensor * v_idxs;
  900. if (!v_trans) {
  901. v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens);
  902. } else {
  903. v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens*hparams.n_embd_v_gqa_max());
  904. }
  905. ggml_set_input(v_idxs);
  906. return v_idxs;
  907. }
  908. void llama_kv_cache_unified::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const {
  909. if (!supports_set_rows) {
  910. return;
  911. }
  912. const uint32_t n_tokens = ubatch->n_tokens;
  913. GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream());
  914. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  915. int64_t * data = (int64_t *) dst->data;
  916. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  917. const int64_t offs = sinfo.strm[s]*get_size();
  918. for (uint32_t i = 0; i < sinfo.size(); ++i) {
  919. data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i];
  920. }
  921. }
  922. }
  923. void llama_kv_cache_unified::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const {
  924. if (!supports_set_rows) {
  925. return;
  926. }
  927. const uint32_t n_tokens = ubatch->n_tokens;
  928. GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream());
  929. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  930. int64_t * data = (int64_t *) dst->data;
  931. if (!v_trans) {
  932. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  933. const int64_t offs = sinfo.strm[s]*get_size();
  934. for (uint32_t i = 0; i < sinfo.size(); ++i) {
  935. data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i];
  936. }
  937. }
  938. } else {
  939. // note: the V cache is transposed when not using flash attention
  940. const int64_t kv_size = get_size();
  941. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa_max();
  942. for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
  943. const int64_t offs = sinfo.strm[s]*kv_size*n_embd_v_gqa;
  944. for (uint32_t i = 0; i < sinfo.size(); ++i) {
  945. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  946. data[s*sinfo.size()*n_embd_v_gqa + i*n_embd_v_gqa + j] = offs + j*kv_size + sinfo.idxs[s][i];
  947. }
  948. }
  949. }
  950. }
  951. }
  952. void llama_kv_cache_unified::set_input_k_shift(ggml_tensor * dst) const {
  953. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  954. int32_t * data = (int32_t *) dst->data;
  955. for (uint32_t s = 0; s < n_stream; ++s) {
  956. const auto & cells = v_cells[s];
  957. for (uint32_t i = 0; i < cells.size(); ++i) {
  958. data[s*cells.size() + i] = cells.is_empty(i) ? 0 : cells.get_shift(i);
  959. }
  960. }
  961. }
  962. void llama_kv_cache_unified::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
  963. const uint32_t n_tokens = ubatch->n_tokens;
  964. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  965. float * data = (float *) dst->data;
  966. const int64_t n_kv = dst->ne[0];
  967. const int64_t n_stream = dst->ne[3]; // num streams in the current ubatch
  968. GGML_ASSERT(n_tokens%n_stream == 0);
  969. // n_tps == n_tokens_per_stream
  970. const int64_t n_tps = n_tokens/n_stream;
  971. const int64_t n_tps_pad = GGML_PAD(n_tps, GGML_KQ_MASK_PAD);
  972. std::fill(data, data + ggml_nelements(dst), -INFINITY);
  973. // Use only the previous KV cells of the correct sequence for each token of the ubatch.
  974. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  975. // Example with a cache of 10 tokens, 2 tokens populated in cache and 3 tokens in batch:
  976. // Causal mask:
  977. // xxx-------
  978. // xxxx------
  979. // xxxxx-----
  980. // Non-causal mask:
  981. // xxxxx-----
  982. // xxxxx-----
  983. // xxxxx-----
  984. // To visualize the mask, see https://github.com/ggml-org/llama.cpp/pull/12615
  985. // TODO: optimize this section
  986. for (uint32_t h = 0; h < 1; ++h) {
  987. for (uint32_t s = 0; s < n_stream; ++s) {
  988. for (uint32_t ii = 0; ii < n_tps; ++ii) {
  989. const uint32_t i = s*n_tps + ii;
  990. const llama_seq_id seq_id = ubatch->seq_id[i][0];
  991. const auto & cells = v_cells[seq_to_stream[seq_id]];
  992. const llama_pos p1 = ubatch->pos[i];
  993. const uint64_t idst = n_kv*(h*n_stream*n_tps_pad + s*n_tps_pad + ii);
  994. for (uint32_t j = 0; j < n_kv; ++j) {
  995. if (cells.is_empty(j)) {
  996. continue;
  997. }
  998. // mask the token if not the same sequence
  999. if (!cells.seq_has(j, seq_id)) {
  1000. continue;
  1001. }
  1002. const llama_pos p0 = cells.pos_get(j);
  1003. // mask future tokens
  1004. if (causal_attn && p0 > p1) {
  1005. continue;
  1006. }
  1007. // apply SWA if any
  1008. if (is_masked_swa(p0, p1)) {
  1009. continue;
  1010. }
  1011. data[idst + j] = hparams.use_alibi ? -std::abs(p0 - p1) : 0.0f;
  1012. }
  1013. }
  1014. }
  1015. }
  1016. }
  1017. void llama_kv_cache_unified::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1018. const int64_t n_tokens = ubatch->n_tokens;
  1019. GGML_ASSERT(n_stream == 1 && "TODO: support multiple streams");
  1020. const auto & cells = v_cells[0];
  1021. GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
  1022. GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing
  1023. int32_t * data = (int32_t *) dst->data;
  1024. const int32_t n_kv = dst->ne[0];
  1025. for (int h = 0; h < 1; ++h) {
  1026. for (int i = 0; i < n_tokens; ++i) {
  1027. for (int j = 0; j < n_kv; ++j) {
  1028. // the position when the cells is empty is irrelevant - it will be masked out later in the attention
  1029. const llama_pos p0 = cells.is_empty(j) ? -1 : cells.pos_get(j);
  1030. data[h*(n_kv*n_tokens) + i*n_kv + j] = llama_relative_position_bucket(p0, ubatch->pos[i], hparams.n_rel_attn_bkts, false);
  1031. }
  1032. }
  1033. }
  1034. }
  1035. size_t llama_kv_cache_unified::total_size() const {
  1036. size_t size = 0;
  1037. for (const auto & buf : bufs) {
  1038. size += ggml_backend_buffer_get_size(buf.get());
  1039. }
  1040. return size;
  1041. }
  1042. size_t llama_kv_cache_unified::size_k_bytes() const {
  1043. size_t size_k_bytes = 0;
  1044. for (const auto & layer : layers) {
  1045. size_k_bytes += ggml_nbytes(layer.k);
  1046. }
  1047. return size_k_bytes;
  1048. }
  1049. size_t llama_kv_cache_unified::size_v_bytes() const {
  1050. size_t size_v_bytes = 0;
  1051. for (const auto & layer : layers) {
  1052. size_v_bytes += ggml_nbytes(layer.v);
  1053. }
  1054. return size_v_bytes;
  1055. }
  1056. ggml_tensor * llama_kv_cache_unified::build_rope_shift(
  1057. const llama_cparams & cparams,
  1058. ggml_context * ctx,
  1059. ggml_tensor * cur,
  1060. ggml_tensor * shift,
  1061. ggml_tensor * factors,
  1062. float freq_base,
  1063. float freq_scale) const {
  1064. const auto & n_ctx_orig = cparams.n_ctx_orig_yarn;
  1065. const auto & yarn_ext_factor = cparams.yarn_ext_factor;
  1066. const auto & yarn_beta_fast = cparams.yarn_beta_fast;
  1067. const auto & yarn_beta_slow = cparams.yarn_beta_slow;
  1068. const auto & n_rot = hparams.n_rot;
  1069. const auto & rope_type = hparams.rope_type == LLAMA_ROPE_TYPE_MROPE
  1070. // @ngxson : this is a workaround
  1071. // for M-RoPE, we want to rotate the whole vector when doing KV shift
  1072. // a normal RoPE should work, we just need to use the correct ordering
  1073. // ref: https://github.com/ggml-org/llama.cpp/pull/13870
  1074. ? LLAMA_ROPE_TYPE_NEOX
  1075. : hparams.rope_type;
  1076. // See llm_build_deepseek2() for why attn_factor has to be scaled for YaRN RoPE to work correctly.
  1077. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  1078. const float yarn_attn_factor = model.arch == LLM_ARCH_DEEPSEEK2
  1079. ? 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale))
  1080. : cparams.yarn_attn_factor;
  1081. ggml_tensor * tmp;
  1082. if (ggml_is_quantized(cur->type)) {
  1083. // dequantize to f32 -> RoPE -> quantize back
  1084. tmp = ggml_cast(ctx, cur, GGML_TYPE_F32);
  1085. tmp = ggml_rope_ext(ctx, tmp,
  1086. shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1087. yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
  1088. tmp = ggml_cpy(ctx, tmp, cur);
  1089. } else {
  1090. // we rotate only the first n_rot dimensions
  1091. tmp = ggml_rope_ext_inplace(ctx, cur,
  1092. shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1093. yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
  1094. }
  1095. return tmp;
  1096. }
  1097. class llm_graph_input_k_shift : public llm_graph_input_i {
  1098. public:
  1099. llm_graph_input_k_shift(const llama_kv_cache_unified * kv_self) : kv_self(kv_self) {}
  1100. virtual ~llm_graph_input_k_shift() = default;
  1101. void set_input(const llama_ubatch * ubatch) override;
  1102. ggml_tensor * k_shift; // I32 [kv_size*n_stream]
  1103. const llama_kv_cache_unified * kv_self;
  1104. };
  1105. void llm_graph_input_k_shift::set_input(const llama_ubatch * ubatch) {
  1106. GGML_UNUSED(ubatch);
  1107. if (k_shift) {
  1108. kv_self->set_input_k_shift(k_shift);
  1109. }
  1110. }
  1111. ggml_cgraph * llama_kv_cache_unified::build_graph_shift(llm_graph_result * res, llama_context * lctx) const {
  1112. auto * ctx = res->get_ctx();
  1113. auto * gf = res->get_gf();
  1114. const auto & n_embd_head_k = hparams.n_embd_head_k;
  1115. //const auto & n_embd_head_v = hparams.n_embd_head_v;
  1116. auto inp = std::make_unique<llm_graph_input_k_shift>(this);
  1117. inp->k_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, (int64_t) get_size()*n_stream);
  1118. ggml_set_input(inp->k_shift);
  1119. const auto & cparams = lctx->get_cparams();
  1120. for (const auto & layer : layers) {
  1121. const uint32_t il = layer.il;
  1122. const int64_t n_head_kv = hparams.n_head_kv(il);
  1123. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1124. const float freq_base_l = model.get_rope_freq_base (cparams, il);
  1125. const float freq_scale_l = model.get_rope_freq_scale(cparams, il);
  1126. ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);
  1127. ggml_tensor * k =
  1128. ggml_view_3d(ctx, layer.k,
  1129. n_embd_head_k, n_head_kv, get_size()*n_stream,
  1130. ggml_row_size(layer.k->type, n_embd_head_k),
  1131. ggml_row_size(layer.k->type, n_embd_k_gqa),
  1132. 0);
  1133. ggml_tensor * cur = build_rope_shift(cparams, ctx, k, inp->k_shift, rope_factors, freq_base_l, freq_scale_l);
  1134. ggml_build_forward_expand(gf, cur);
  1135. }
  1136. res->add_input(std::move(inp));
  1137. return gf;
  1138. }
  1139. ggml_cgraph * llama_kv_cache_unified::build_graph_defrag(
  1140. llm_graph_result * res,
  1141. llama_context * lctx,
  1142. const defrag_info & dinfo) const {
  1143. auto * ctx = res->get_ctx();
  1144. auto * gf = res->get_gf();
  1145. GGML_ASSERT(n_stream == 1 && "n_stream > 1 does not support defrag");
  1146. const auto & cells = v_cells[0];
  1147. const auto & ids = dinfo.ids;
  1148. const auto & cparams = lctx->get_cparams();
  1149. #if 0
  1150. // CPU defrag
  1151. //
  1152. // TODO: optimizations are possible:
  1153. // - multiple threads
  1154. // - avoid copying to the host memory when already there
  1155. //
  1156. // likely not worth the effort, as we have ggml_graph based defrag
  1157. //
  1158. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1159. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1160. const uint32_t kv_size = size;
  1161. std::vector<uint8_t> buf_k;
  1162. std::vector<uint8_t> buf_v;
  1163. for (uint32_t il = 0; il < n_layer; ++il) {
  1164. const size_t k_size_row = ggml_row_size(k_l[il]->type, n_embd_k_gqa);
  1165. const size_t k_size = ggml_row_size(k_l[il]->type, n_embd_k_gqa*kv_size);
  1166. const size_t v_size_el = ggml_type_size(v_l[il]->type);
  1167. const size_t v_size = ggml_row_size (v_l[il]->type, n_embd_v_gqa*kv_size);
  1168. buf_k.resize(k_size);
  1169. buf_v.resize(v_size);
  1170. ggml_backend_tensor_get(k_l[il], buf_k.data(), 0, buf_k.size());
  1171. ggml_backend_tensor_get(v_l[il], buf_v.data(), 0, buf_v.size());
  1172. // batch move [i, i+nm) to [id, id+nm)
  1173. // note: cells can move only to a lower index
  1174. for (uint32_t i = 0; i < n_kv; ++i) {
  1175. const uint32_t id = ids[i];
  1176. if (i == id || id == n_kv) {
  1177. continue;
  1178. }
  1179. uint32_t nm = 1;
  1180. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  1181. nm++;
  1182. }
  1183. // move keys
  1184. {
  1185. const int64_t os = i*k_size_row;
  1186. const int64_t od = id*k_size_row;
  1187. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  1188. }
  1189. // move values (note: they are transposed)
  1190. {
  1191. const int64_t os = i;
  1192. const int64_t od = id;
  1193. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1194. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  1195. }
  1196. }
  1197. i += nm - 1;
  1198. }
  1199. ggml_backend_tensor_set(k_l[il], buf_k.data(), 0, buf_k.size());
  1200. ggml_backend_tensor_set(v_l[il], buf_v.data(), 0, buf_v.size());
  1201. }
  1202. #else
  1203. for (uint32_t i = 0; i < ids.size(); ++i) {
  1204. const uint32_t id = ids[i];
  1205. if (i == id || id == ids.size()) {
  1206. continue;
  1207. }
  1208. uint32_t nm = 1;
  1209. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  1210. nm++;
  1211. }
  1212. for (const auto & layer : layers) {
  1213. const uint32_t il = layer.il;
  1214. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1215. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1216. ggml_tensor * view_k_src = ggml_view_2d(ctx, layer.k,
  1217. n_embd_k_gqa, nm,
  1218. ggml_row_size(layer.k->type, n_embd_k_gqa),
  1219. ggml_row_size(layer.k->type, n_embd_k_gqa*i));
  1220. ggml_tensor * view_k_dst = ggml_view_2d(ctx, layer.k,
  1221. n_embd_k_gqa, nm,
  1222. ggml_row_size(layer.k->type, n_embd_k_gqa),
  1223. ggml_row_size(layer.k->type, n_embd_k_gqa*id));
  1224. ggml_tensor * view_v_src;
  1225. ggml_tensor * view_v_dst;
  1226. if (cparams.flash_attn) {
  1227. // NOTE: the V cache is not transposed when using flash attention
  1228. view_v_src = ggml_view_2d(ctx, layer.v,
  1229. n_embd_v_gqa, nm,
  1230. ggml_row_size(layer.v->type, n_embd_v_gqa),
  1231. ggml_row_size(layer.v->type, n_embd_v_gqa*i));
  1232. view_v_dst = ggml_view_2d(ctx, layer.v,
  1233. n_embd_v_gqa, nm,
  1234. ggml_row_size(layer.v->type, n_embd_v_gqa),
  1235. ggml_row_size(layer.v->type, n_embd_v_gqa*id));
  1236. } else {
  1237. view_v_src = ggml_view_2d(ctx, layer.v,
  1238. nm, n_embd_v_gqa,
  1239. ggml_row_size(layer.v->type, cells.size()),
  1240. ggml_row_size(layer.v->type, i));
  1241. view_v_dst = ggml_view_2d(ctx, layer.v,
  1242. nm, n_embd_v_gqa,
  1243. ggml_row_size(layer.v->type, cells.size()),
  1244. ggml_row_size(layer.v->type, id));
  1245. }
  1246. ggml_build_forward_expand(gf, ggml_cpy(ctx, view_k_src, view_k_dst));
  1247. ggml_build_forward_expand(gf, ggml_cpy(ctx, view_v_src, view_v_dst));
  1248. }
  1249. i += nm - 1;
  1250. }
  1251. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  1252. #endif
  1253. return gf;
  1254. }
  1255. llama_kv_cache_unified::defrag_info llama_kv_cache_unified::defrag_prepare(int32_t n_max_nodes) const {
  1256. GGML_ASSERT(n_stream == 1 && "n_stream > 1 does not support defrag");
  1257. const auto & cells = v_cells[0];
  1258. const uint32_t n_layer = layers.size();
  1259. const uint32_t n_kv = cells.used_max_p1();
  1260. const uint32_t n_used = cells.get_used();
  1261. assert(n_used <= n_kv);
  1262. //const int64_t t_start = ggml_time_us();
  1263. // number of cells moved
  1264. uint32_t n_moves = 0;
  1265. // each move requires 6*n_layer tensors (see graph_build_kv_self_defrag)
  1266. // - source view, destination view, copy operation
  1267. // - x2 for keys and values
  1268. //const uint32_t max_moves = max_nodes()/(6*n_layer);
  1269. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  1270. const uint32_t max_moves = (n_max_nodes - 2*n_layer)/(6*n_layer);
  1271. // determine which KV cells to move where
  1272. defrag_info res;
  1273. auto & ids = res.ids;
  1274. ids.resize(n_kv, n_kv);
  1275. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  1276. if (!cells.is_empty(i0)) {
  1277. ids[i0] = i0;
  1278. continue;
  1279. }
  1280. // found a hole - fill it with data from the end of the cache
  1281. uint32_t nh = 1;
  1282. // determine the size of the hole
  1283. while (i0 + nh < n_used && cells.is_empty(i0 + nh)) {
  1284. nh++;
  1285. }
  1286. uint32_t nf = 0;
  1287. uint32_t is = n_kv - 1;
  1288. // starting from the end, find nh non-empty cells
  1289. for (; is > i0; --is) {
  1290. if (cells.is_empty(is) || ids[is] != n_kv) {
  1291. continue;
  1292. }
  1293. // non-empty cell which is not yet moved
  1294. nf++;
  1295. if (nf == nh) {
  1296. break;
  1297. }
  1298. }
  1299. // this can only happen if `n_used` is not accurate, which would be a bug
  1300. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  1301. nf = 0;
  1302. uint32_t i1 = is;
  1303. // are we moving a continuous block of memory?
  1304. bool cont = false;
  1305. // should we stop searching for the next move?
  1306. bool stop = false;
  1307. // go back and move the nf cells to the hole
  1308. for (; i1 < n_kv; ++i1) {
  1309. if (cells.is_empty(i1) || ids[i1] != n_kv) {
  1310. if (n_moves == max_moves) {
  1311. stop = true;
  1312. break;
  1313. }
  1314. cont = false;
  1315. continue;
  1316. }
  1317. // this cell goes to (i0 + nf)
  1318. ids[i1] = i0 + nf;
  1319. if (!cont) {
  1320. n_moves++;
  1321. cont = true;
  1322. }
  1323. nf++;
  1324. if (nf == nh) {
  1325. break;
  1326. }
  1327. }
  1328. if (stop || n_moves == max_moves) {
  1329. break;
  1330. }
  1331. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  1332. i0 += nh - 1;
  1333. }
  1334. if (n_moves == 0) {
  1335. return {};
  1336. }
  1337. LLAMA_LOG_DEBUG("%s: (tmp log) KV defrag cell moves: %u\n", __func__, n_moves);
  1338. LLAMA_LOG_DEBUG("%s: expected gf nodes: %u\n", __func__, 6*n_moves*n_layer);
  1339. return res;
  1340. }
  1341. bool llama_kv_cache_unified::is_masked_swa(llama_pos p0, llama_pos p1) const {
  1342. assert(p0 >= 0 && p1 >= 0);
  1343. switch (swa_type) {
  1344. case LLAMA_SWA_TYPE_NONE:
  1345. {
  1346. } break;
  1347. case LLAMA_SWA_TYPE_STANDARD:
  1348. {
  1349. if (p1 - p0 >= (int32_t) n_swa) {
  1350. return true;
  1351. }
  1352. } break;
  1353. case LLAMA_SWA_TYPE_CHUNKED:
  1354. {
  1355. const llama_pos pos_chunk_start = (p1 / n_swa) * n_swa;
  1356. if (p0 < pos_chunk_start) {
  1357. return true;
  1358. }
  1359. } break;
  1360. }
  1361. return false;
  1362. }
  1363. void llama_kv_cache_unified::state_write(llama_io_write_i & io, llama_seq_id seq_id) const {
  1364. io.write(&n_stream, sizeof(n_stream));
  1365. for (uint32_t s = 0; s < n_stream; ++s) {
  1366. cell_ranges_t cr { s, {} };
  1367. uint32_t cell_count = 0;
  1368. const auto & cells = v_cells[s];
  1369. // Count the number of cells with the specified seq_id
  1370. // Find all the ranges of cells with this seq id (or all, when -1)
  1371. uint32_t cell_range_begin = cells.size();
  1372. for (uint32_t i = 0; i < cells.size(); ++i) {
  1373. if (!cells.is_empty(i) && (seq_id == -1 || cells.seq_has(i, seq_id))) {
  1374. ++cell_count;
  1375. if (cell_range_begin == cells.size()) {
  1376. cell_range_begin = i;
  1377. }
  1378. } else {
  1379. if (cell_range_begin != cells.size()) {
  1380. cr.data.emplace_back(cell_range_begin, i);
  1381. cell_range_begin = cells.size();
  1382. }
  1383. }
  1384. }
  1385. if (cell_range_begin != cells.size()) {
  1386. cr.data.emplace_back(cell_range_begin, cells.size());
  1387. }
  1388. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  1389. uint32_t cell_count_check = 0;
  1390. for (const auto & range : cr.data) {
  1391. cell_count_check += range.second - range.first;
  1392. }
  1393. GGML_ASSERT(cell_count == cell_count_check);
  1394. io.write(&cell_count, sizeof(cell_count));
  1395. // skip empty streams
  1396. if (cell_count == 0) {
  1397. continue;
  1398. }
  1399. state_write_meta(io, cr, seq_id);
  1400. state_write_data(io, cr);
  1401. }
  1402. }
  1403. void llama_kv_cache_unified::state_read(llama_io_read_i & io, llama_seq_id seq_id) {
  1404. GGML_ASSERT(seq_id == -1 || (seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()));
  1405. uint32_t n_stream_cur;
  1406. io.read_to(&n_stream_cur, sizeof(n_stream_cur));
  1407. if (n_stream_cur != n_stream) {
  1408. throw std::runtime_error("n_stream mismatch");
  1409. }
  1410. for (uint32_t s = 0; s < n_stream; ++s) {
  1411. uint32_t cell_count;
  1412. io.read_to(&cell_count, sizeof(cell_count));
  1413. if (cell_count == 0) {
  1414. continue;
  1415. }
  1416. const uint32_t strm = seq_id == -1 ? s : seq_to_stream[seq_id];
  1417. bool res = true;
  1418. res = res && state_read_meta(io, strm, cell_count, seq_id);
  1419. res = res && state_read_data(io, strm, cell_count);
  1420. if (!res) {
  1421. if (seq_id == -1) {
  1422. clear(true);
  1423. } else {
  1424. seq_rm(seq_id, -1, -1);
  1425. }
  1426. throw std::runtime_error("failed to restore kv cache");
  1427. }
  1428. }
  1429. }
  1430. void llama_kv_cache_unified::state_write_meta(llama_io_write_i & io, const cell_ranges_t & cr, llama_seq_id seq_id) const {
  1431. const auto & cells = v_cells[cr.strm];
  1432. for (const auto & range : cr.data) {
  1433. for (uint32_t i = range.first; i < range.second; ++i) {
  1434. std::vector<llama_seq_id> seq_ids;
  1435. for (llama_seq_id cur = 0; cur < (int) n_seq_max; ++cur) {
  1436. if (cur == seq_id || seq_id == -1) {
  1437. if (cells.seq_has(i, cur)) {
  1438. seq_ids.push_back(cur);
  1439. }
  1440. }
  1441. }
  1442. const llama_pos pos = cells.pos_get(i);
  1443. const uint32_t n_seq_id = seq_ids.size();
  1444. io.write(&pos, sizeof(pos));
  1445. io.write(&n_seq_id, sizeof(n_seq_id));
  1446. for (const auto & seq_id : seq_ids) {
  1447. io.write(&seq_id, sizeof(seq_id));
  1448. }
  1449. }
  1450. }
  1451. }
  1452. void llama_kv_cache_unified::state_write_data(llama_io_write_i & io, const cell_ranges_t & cr) const {
  1453. const auto & cells = v_cells[cr.strm];
  1454. const uint32_t v_trans = this->v_trans ? 1 : 0;
  1455. const uint32_t n_layer = layers.size();
  1456. io.write(&v_trans, sizeof(v_trans));
  1457. io.write(&n_layer, sizeof(n_layer));
  1458. std::vector<uint8_t> tmp_buf;
  1459. // Iterate and write all the keys first, each row is a cell
  1460. // Get whole range at a time
  1461. for (const auto & layer : layers) {
  1462. const uint32_t il = layer.il;
  1463. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1464. auto * k = layer.k_stream[cr.strm];
  1465. // Write key type
  1466. const int32_t k_type_i = (int32_t) k->type;
  1467. io.write(&k_type_i, sizeof(k_type_i));
  1468. // Write row size of key
  1469. const uint64_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
  1470. io.write(&k_size_row, sizeof(k_size_row));
  1471. // Read each range of cells of k_size length each into tmp_buf and write out
  1472. for (const auto & range : cr.data) {
  1473. const size_t range_size = range.second - range.first;
  1474. const size_t buf_size = range_size * k_size_row;
  1475. io.write_tensor(k, range.first * k_size_row, buf_size);
  1476. }
  1477. }
  1478. if (!v_trans) {
  1479. for (const auto & layer : layers) {
  1480. const uint32_t il = layer.il;
  1481. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1482. auto * v = layer.v_stream[cr.strm];
  1483. // Write value type
  1484. const int32_t v_type_i = (int32_t) v->type;
  1485. io.write(&v_type_i, sizeof(v_type_i));
  1486. // Write row size of value
  1487. const uint64_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
  1488. io.write(&v_size_row, sizeof(v_size_row));
  1489. // Read each range of cells of v_size length each into tmp_buf and write out
  1490. for (const auto & range : cr.data) {
  1491. const size_t range_size = range.second - range.first;
  1492. const size_t buf_size = range_size * v_size_row;
  1493. io.write_tensor(v, range.first * v_size_row, buf_size);
  1494. }
  1495. }
  1496. } else {
  1497. // When v is transposed, we also need the element size and get the element ranges from each row
  1498. const uint32_t kv_size = cells.size();
  1499. for (const auto & layer : layers) {
  1500. const uint32_t il = layer.il;
  1501. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1502. auto * v = layer.v_stream[cr.strm];
  1503. // Write value type
  1504. const int32_t v_type_i = (int32_t) v->type;
  1505. io.write(&v_type_i, sizeof(v_type_i));
  1506. // Write element size
  1507. const uint32_t v_size_el = ggml_type_size(v->type);
  1508. io.write(&v_size_el, sizeof(v_size_el));
  1509. // Write GQA embedding size
  1510. io.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  1511. // For each row, we get the element values of each cell
  1512. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1513. // Read each range of cells of v_size_el length each into tmp_buf and write out
  1514. for (const auto & range : cr.data) {
  1515. const size_t range_size = range.second - range.first;
  1516. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  1517. const size_t buf_size = range_size * v_size_el;
  1518. io.write_tensor(v, src_offset, buf_size);
  1519. }
  1520. }
  1521. }
  1522. }
  1523. }
  1524. bool llama_kv_cache_unified::state_read_meta(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, llama_seq_id dest_seq_id) {
  1525. auto & cells = v_cells[strm];
  1526. auto & head = v_heads[strm];
  1527. if (dest_seq_id != -1) {
  1528. // single sequence
  1529. seq_rm(dest_seq_id, -1, -1);
  1530. llama_batch_allocr balloc(hparams.n_pos_per_embd());
  1531. llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
  1532. ubatch.seq_id_unq[0] = dest_seq_id;
  1533. for (uint32_t i = 0; i < cell_count; ++i) {
  1534. llama_pos pos;
  1535. uint32_t n_seq_id;
  1536. io.read_to(&pos, sizeof(pos));
  1537. io.read_to(&n_seq_id, sizeof(n_seq_id));
  1538. if (n_seq_id != 1) {
  1539. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  1540. return false;
  1541. }
  1542. // read the sequence id, but directly discard it - we will use dest_seq_id instead
  1543. {
  1544. llama_seq_id seq_id;
  1545. io.read_to(&seq_id, sizeof(seq_id));
  1546. }
  1547. ubatch.pos[i] = pos;
  1548. ubatch.n_seq_id[i] = n_seq_id;
  1549. ubatch.seq_id[i] = &dest_seq_id;
  1550. }
  1551. const auto sinfo = find_slot(ubatch, true);
  1552. if (sinfo.empty()) {
  1553. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  1554. return false;
  1555. }
  1556. apply_ubatch(sinfo, ubatch);
  1557. const auto head_cur = sinfo.head();
  1558. // keep the head at the old position because we will read the KV data into it in state_read_data()
  1559. head = head_cur;
  1560. 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);
  1561. // 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)
  1562. // Assume that this is one contiguous block of cells
  1563. GGML_ASSERT(head_cur + cell_count <= cells.size());
  1564. GGML_ASSERT(cells.pos_get(head_cur) == ubatch.pos[0]);
  1565. GGML_ASSERT(cells.pos_get(head_cur + cell_count - 1) == ubatch.pos[cell_count - 1]);
  1566. GGML_ASSERT(cells.seq_has(head_cur, dest_seq_id));
  1567. GGML_ASSERT(cells.seq_has(head_cur + cell_count - 1, dest_seq_id));
  1568. } else {
  1569. // whole KV cache restore
  1570. if (cell_count > cells.size()) {
  1571. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  1572. return false;
  1573. }
  1574. clear(true);
  1575. for (uint32_t i = 0; i < cell_count; ++i) {
  1576. llama_pos pos;
  1577. uint32_t n_seq_id;
  1578. io.read_to(&pos, sizeof(pos));
  1579. io.read_to(&n_seq_id, sizeof(n_seq_id));
  1580. cells.pos_set(i, pos);
  1581. for (uint32_t j = 0; j < n_seq_id; ++j) {
  1582. llama_seq_id seq_id;
  1583. io.read_to(&seq_id, sizeof(seq_id));
  1584. if (seq_id < 0 || (uint32_t) seq_id >= n_seq_max) {
  1585. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, n_seq_max);
  1586. return false;
  1587. }
  1588. cells.seq_add(i, seq_id);
  1589. }
  1590. }
  1591. head = 0;
  1592. }
  1593. return true;
  1594. }
  1595. bool llama_kv_cache_unified::state_read_data(llama_io_read_i & io, uint32_t strm, uint32_t cell_count) {
  1596. auto & cells = v_cells[strm];
  1597. auto & head = v_heads[strm];
  1598. uint32_t v_trans;
  1599. uint32_t n_layer;
  1600. io.read_to(&v_trans, sizeof(v_trans));
  1601. io.read_to(&n_layer, sizeof(n_layer));
  1602. if (n_layer != layers.size()) {
  1603. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, (uint32_t) layers.size());
  1604. return false;
  1605. }
  1606. if (cell_count > cells.size()) {
  1607. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, cells.size());
  1608. return false;
  1609. }
  1610. if (this->v_trans != (bool) v_trans) {
  1611. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  1612. return false;
  1613. }
  1614. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  1615. for (const auto & layer : layers) {
  1616. const uint32_t il = layer.il;
  1617. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1618. auto * k = layer.k_stream[strm];
  1619. // Read type of key
  1620. int32_t k_type_i_ref;
  1621. io.read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  1622. const int32_t k_type_i = (int32_t) k->type;
  1623. if (k_type_i != k_type_i_ref) {
  1624. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  1625. return false;
  1626. }
  1627. // Read row size of key
  1628. uint64_t k_size_row_ref;
  1629. io.read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  1630. const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
  1631. if (k_size_row != k_size_row_ref) {
  1632. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  1633. return false;
  1634. }
  1635. if (cell_count) {
  1636. // Read and set the keys for the whole cell range
  1637. ggml_backend_tensor_set(k, io.read(cell_count * k_size_row), head * k_size_row, cell_count * k_size_row);
  1638. }
  1639. }
  1640. if (!this->v_trans) {
  1641. for (const auto & layer : layers) {
  1642. const uint32_t il = layer.il;
  1643. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1644. auto * v = layer.v_stream[strm];
  1645. // Read type of value
  1646. int32_t v_type_i_ref;
  1647. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1648. const int32_t v_type_i = (int32_t) v->type;
  1649. if (v_type_i != v_type_i_ref) {
  1650. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1651. return false;
  1652. }
  1653. // Read row size of value
  1654. uint64_t v_size_row_ref;
  1655. io.read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  1656. const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
  1657. if (v_size_row != v_size_row_ref) {
  1658. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  1659. return false;
  1660. }
  1661. if (cell_count) {
  1662. // Read and set the values for the whole cell range
  1663. ggml_backend_tensor_set(v, io.read(cell_count * v_size_row), head * v_size_row, cell_count * v_size_row);
  1664. }
  1665. }
  1666. } else {
  1667. // For each layer, read the values for each cell (transposed)
  1668. for (const auto & layer : layers) {
  1669. const uint32_t il = layer.il;
  1670. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1671. auto * v = layer.v_stream[strm];
  1672. // Read type of value
  1673. int32_t v_type_i_ref;
  1674. io.read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  1675. const int32_t v_type_i = (int32_t) v->type;
  1676. if (v_type_i != v_type_i_ref) {
  1677. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  1678. return false;
  1679. }
  1680. // Read element size of value
  1681. uint32_t v_size_el_ref;
  1682. io.read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  1683. const size_t v_size_el = ggml_type_size(v->type);
  1684. if (v_size_el != v_size_el_ref) {
  1685. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  1686. return false;
  1687. }
  1688. // Read GQA embedding size
  1689. uint32_t n_embd_v_gqa_ref;
  1690. io.read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  1691. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  1692. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  1693. return false;
  1694. }
  1695. if (cell_count) {
  1696. // For each row in the transposed matrix, read the values for the whole cell range
  1697. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  1698. const size_t dst_offset = (head + j * cells.size()) * v_size_el;
  1699. ggml_backend_tensor_set(v, io.read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  1700. }
  1701. }
  1702. }
  1703. }
  1704. return true;
  1705. }
  1706. //
  1707. // llama_kv_cache_unified_context
  1708. //
  1709. llama_kv_cache_unified_context::llama_kv_cache_unified_context(llama_memory_status status) : status(status) {}
  1710. llama_kv_cache_unified_context::llama_kv_cache_unified_context(
  1711. llama_kv_cache_unified * kv) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv) {
  1712. n_kv = kv->get_size();
  1713. const uint32_t n_stream = kv->get_n_stream();
  1714. // create a dummy slot info - the actual data is irrelevant. we just need to build the graph
  1715. sinfos.resize(1);
  1716. sinfos[0].s0 = 0;
  1717. sinfos[0].s1 = n_stream - 1;
  1718. sinfos[0].idxs.resize(n_stream);
  1719. for (uint32_t s = 0; s < n_stream; ++s) {
  1720. sinfos[0].strm.push_back(s);
  1721. sinfos[0].idxs[s].resize(1, 0);
  1722. }
  1723. }
  1724. llama_kv_cache_unified_context::llama_kv_cache_unified_context(
  1725. llama_kv_cache_unified * kv,
  1726. llama_context * lctx,
  1727. bool do_shift,
  1728. defrag_info dinfo,
  1729. stream_copy_info sc_info) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), lctx(lctx), do_shift(do_shift), dinfo(std::move(dinfo)), sc_info(std::move(sc_info)) {
  1730. if (!do_shift && this->dinfo.empty() && this->sc_info.empty()) {
  1731. status = LLAMA_MEMORY_STATUS_NO_UPDATE;
  1732. }
  1733. }
  1734. llama_kv_cache_unified_context::llama_kv_cache_unified_context(
  1735. llama_kv_cache_unified * kv,
  1736. llama_kv_cache_unified::slot_info_vec_t sinfos,
  1737. std::vector<llama_ubatch> ubatches) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), sinfos(std::move(sinfos)), ubatches(std::move(ubatches)) {
  1738. }
  1739. llama_kv_cache_unified_context::~llama_kv_cache_unified_context() = default;
  1740. bool llama_kv_cache_unified_context::next() {
  1741. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1742. if (++i_cur >= ubatches.size()) {
  1743. return false;
  1744. }
  1745. return true;
  1746. }
  1747. bool llama_kv_cache_unified_context::apply() {
  1748. assert(!llama_memory_status_is_fail(status));
  1749. // no ubatches -> this is a KV cache update
  1750. if (ubatches.empty()) {
  1751. kv->update(lctx, do_shift, dinfo, sc_info);
  1752. return true;
  1753. }
  1754. kv->apply_ubatch(sinfos[i_cur], ubatches[i_cur]);
  1755. n_kv = kv->get_n_kv();
  1756. return true;
  1757. }
  1758. llama_memory_status llama_kv_cache_unified_context::get_status() const {
  1759. return status;
  1760. }
  1761. const llama_ubatch & llama_kv_cache_unified_context::get_ubatch() const {
  1762. assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
  1763. return ubatches[i_cur];
  1764. }
  1765. uint32_t llama_kv_cache_unified_context::get_n_kv() const {
  1766. return n_kv;
  1767. }
  1768. bool llama_kv_cache_unified_context::get_supports_set_rows() const {
  1769. return kv->get_supports_set_rows();
  1770. }
  1771. ggml_tensor * llama_kv_cache_unified_context::get_k(ggml_context * ctx, int32_t il) const {
  1772. return kv->get_k(ctx, il, n_kv, sinfos[i_cur]);
  1773. }
  1774. ggml_tensor * llama_kv_cache_unified_context::get_v(ggml_context * ctx, int32_t il) const {
  1775. return kv->get_v(ctx, il, n_kv, sinfos[i_cur]);
  1776. }
  1777. ggml_tensor * llama_kv_cache_unified_context::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il) const {
  1778. return kv->cpy_k(ctx, k_cur, k_idxs, il, sinfos[i_cur]);
  1779. }
  1780. ggml_tensor * llama_kv_cache_unified_context::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il) const {
  1781. return kv->cpy_v(ctx, v_cur, v_idxs, il, sinfos[i_cur]);
  1782. }
  1783. ggml_tensor * llama_kv_cache_unified_context::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  1784. return kv->build_input_k_idxs(ctx, ubatch);
  1785. }
  1786. ggml_tensor * llama_kv_cache_unified_context::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
  1787. return kv->build_input_v_idxs(ctx, ubatch);
  1788. }
  1789. void llama_kv_cache_unified_context::set_input_k_shift(ggml_tensor * dst) const {
  1790. kv->set_input_k_shift(dst);
  1791. }
  1792. void llama_kv_cache_unified_context::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1793. kv->set_input_k_idxs(dst, ubatch, sinfos[i_cur]);
  1794. }
  1795. void llama_kv_cache_unified_context::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1796. kv->set_input_v_idxs(dst, ubatch, sinfos[i_cur]);
  1797. }
  1798. void llama_kv_cache_unified_context::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
  1799. kv->set_input_kq_mask(dst, ubatch, causal_attn);
  1800. }
  1801. void llama_kv_cache_unified_context::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
  1802. kv->set_input_pos_bucket(dst, ubatch);
  1803. }
  1804. uint32_t llama_kv_cache_unified::get_padding(const llama_cparams & cparams) {
  1805. // the FA kernels require padding to avoid extra runtime boundary checks
  1806. return cparams.flash_attn ? 256u : 32u;
  1807. }