llama-kv-cache-unified.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. #pragma once
  2. #include "llama-batch.h"
  3. #include "llama-graph.h"
  4. #include "llama-kv-cells.h"
  5. #include "llama-memory.h"
  6. #include <unordered_map>
  7. #include <vector>
  8. struct llama_cparams;
  9. struct llama_hparams;
  10. struct llama_model;
  11. struct llama_context;
  12. //
  13. // llama_kv_cache_unified
  14. //
  15. class llama_kv_cache_unified : public llama_memory_i {
  16. public:
  17. static uint32_t get_padding(const llama_cparams & cparams);
  18. // this callback is used to filter out layers that should not be included in the cache
  19. using layer_filter_cb = std::function<bool(int32_t il)>;
  20. struct defrag_info {
  21. bool empty() const {
  22. return ids.empty();
  23. }
  24. // contains information about which cell moves where:
  25. // - cell i moves to ids[i]
  26. // - if ids[i] == i || ids[i] == ids.size(), then cell i is not moved
  27. std::vector<uint32_t> ids;
  28. };
  29. struct stream_copy_info {
  30. bool empty() const {
  31. assert(ssrc.size() == sdst.size());
  32. return ssrc.empty();
  33. }
  34. std::vector<uint32_t> ssrc;
  35. std::vector<uint32_t> sdst;
  36. };
  37. // for each ubatch, create a slot_info that contains information about where the ubatch should be inserted in the
  38. // KV cells. for example, cell indices for each token, such that: token[i] -> goes to cells[idxs[i]]
  39. struct slot_info {
  40. // data for ggml_set_rows
  41. using idx_vec_t = std::vector<uint32_t>;
  42. // number of streams: ns = s1 - s0 + 1
  43. llama_seq_id s0;
  44. llama_seq_id s1;
  45. std::vector<llama_seq_id> strm; // [ns]
  46. std::vector<idx_vec_t> idxs; // [ns]
  47. uint32_t head() const {
  48. GGML_ASSERT(idxs.size() == 1);
  49. GGML_ASSERT(!idxs[0].empty());
  50. return idxs[0][0];
  51. }
  52. void resize(size_t n) {
  53. strm.resize(n);
  54. idxs.resize(n);
  55. }
  56. size_t size() const {
  57. GGML_ASSERT(idxs.size() == strm.size());
  58. GGML_ASSERT(!idxs.empty());
  59. return idxs[0].size();
  60. }
  61. size_t n_stream() const {
  62. return strm.size();
  63. }
  64. bool empty() const {
  65. return idxs.empty();
  66. }
  67. void clear() {
  68. idxs.clear();
  69. }
  70. };
  71. using slot_info_vec_t = std::vector<slot_info>;
  72. llama_kv_cache_unified(
  73. const llama_model & model,
  74. layer_filter_cb && filter,
  75. ggml_type type_k,
  76. ggml_type type_v,
  77. bool v_trans,
  78. bool offload,
  79. bool unified,
  80. uint32_t kv_size,
  81. uint32_t n_seq_max,
  82. uint32_t n_pad,
  83. uint32_t n_swa,
  84. llama_swa_type swa_type);
  85. ~llama_kv_cache_unified() = default;
  86. //
  87. // llama_memory_i
  88. //
  89. llama_memory_context_ptr init_batch(
  90. llama_batch_allocr & balloc,
  91. uint32_t n_ubatch,
  92. bool embd_all) override;
  93. llama_memory_context_ptr init_full() override;
  94. llama_memory_context_ptr init_update(llama_context * lctx, bool optimize) override;
  95. bool get_can_shift() const override;
  96. void clear(bool data) override;
  97. bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override;
  98. void seq_cp (llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) override;
  99. void seq_keep(llama_seq_id seq_id) override;
  100. void seq_add (llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) override;
  101. void seq_div (llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) override;
  102. llama_pos seq_pos_min(llama_seq_id seq_id) const override;
  103. llama_pos seq_pos_max(llama_seq_id seq_id) const override;
  104. // state write/load
  105. void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1) const override;
  106. void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1) override;
  107. //
  108. // llama_kv_cache_unified specific API
  109. //
  110. uint32_t get_size() const;
  111. uint32_t get_n_stream() const;
  112. bool get_has_shift() const;
  113. //
  114. // graph_build API
  115. //
  116. uint32_t get_n_kv() const;
  117. // TODO: temporary
  118. bool get_supports_set_rows() const;
  119. // get views of the current state of the cache
  120. ggml_tensor * get_k(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const;
  121. ggml_tensor * get_v(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const;
  122. // store k_cur and v_cur in the cache based on the provided head location
  123. ggml_tensor * cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il, const slot_info & sinfo) const;
  124. ggml_tensor * cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il, const slot_info & sinfo) const;
  125. //
  126. // preparation API
  127. //
  128. // find places for the provided ubatches in the cache, returns the slot infos
  129. // return empty vector on failure
  130. slot_info_vec_t prepare(const std::vector<llama_ubatch> & ubatches);
  131. bool update(llama_context * lctx, bool do_shift, const defrag_info & dinfo, const stream_copy_info & sc_info);
  132. // find a slot of kv cells that can hold the ubatch
  133. // if cont == true, then the slot must be continuous
  134. // return empty slot_info on failure
  135. slot_info find_slot(const llama_ubatch & ubatch, bool cont) const;
  136. // emplace the ubatch context into slot: [sinfo.idxs[0...ubatch.n_tokens - 1]]
  137. void apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch);
  138. //
  139. // input API
  140. //
  141. ggml_tensor * build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const;
  142. ggml_tensor * build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const;
  143. void set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const;
  144. void set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const;
  145. void set_input_k_shift(ggml_tensor * dst) const;
  146. void set_input_kq_mask (ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const;
  147. void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const;
  148. private:
  149. const llama_model & model;
  150. const llama_hparams & hparams;
  151. struct kv_layer {
  152. // layer index in the model
  153. // note: can be different from the layer index in the KV cache
  154. uint32_t il;
  155. ggml_tensor * k;
  156. ggml_tensor * v;
  157. std::vector<ggml_tensor *> k_stream;
  158. std::vector<ggml_tensor *> v_stream;
  159. };
  160. bool v_trans = true; // the value tensor is transposed
  161. const uint32_t n_seq_max = 1;
  162. const uint32_t n_stream = 1;
  163. // required padding
  164. const uint32_t n_pad = 1;
  165. // SWA
  166. const uint32_t n_swa = 0;
  167. // env: LLAMA_KV_CACHE_DEBUG
  168. int debug = 0;
  169. // env: LLAMA_SET_ROWS (temporary)
  170. // ref: https://github.com/ggml-org/llama.cpp/pull/14285
  171. bool supports_set_rows = false;
  172. const llama_swa_type swa_type = LLAMA_SWA_TYPE_NONE;
  173. std::vector<ggml_context_ptr> ctxs;
  174. std::vector<ggml_backend_buffer_ptr> bufs;
  175. // the current index from where we start searching for a free slot in the ring buffer of KV cells (see find_slot())
  176. // note: this is not part of the KV state and it's only used to speed-up the find_slot() method
  177. std::vector<uint32_t> v_heads;
  178. std::vector<llama_kv_cells_unified> v_cells;
  179. // maps from a sequence id to a stream id
  180. std::vector<uint32_t> seq_to_stream;
  181. // pending stream copies that will be applied during the next update
  182. stream_copy_info sc_info;
  183. std::vector<kv_layer> layers;
  184. // model layer id -> KV cache layer id
  185. std::unordered_map<int32_t, int32_t> map_layer_ids;
  186. // return non-empty vector if cells have been moved
  187. defrag_info defrag_prepare(int32_t n_max_nodes) const;
  188. size_t total_size() const;
  189. size_t size_k_bytes() const;
  190. size_t size_v_bytes() const;
  191. bool is_masked_swa(llama_pos p0, llama_pos p1) const;
  192. ggml_tensor * build_rope_shift(
  193. const llama_cparams & cparams,
  194. ggml_context * ctx,
  195. ggml_tensor * cur,
  196. ggml_tensor * shift,
  197. ggml_tensor * factors,
  198. float freq_base,
  199. float freq_scale) const;
  200. ggml_cgraph * build_graph_shift(
  201. llm_graph_result * res,
  202. llama_context * lctx) const;
  203. ggml_cgraph * build_graph_defrag(
  204. llm_graph_result * res,
  205. llama_context * lctx,
  206. const defrag_info & dinfo) const;
  207. struct cell_ranges_t {
  208. uint32_t strm;
  209. std::vector<std::pair<uint32_t, uint32_t>> data; // ranges, from inclusive, to exclusive
  210. };
  211. void state_write_meta(llama_io_write_i & io, const cell_ranges_t & cr, llama_seq_id seq_id = -1) const;
  212. void state_write_data(llama_io_write_i & io, const cell_ranges_t & cr) const;
  213. bool state_read_meta(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, llama_seq_id dest_seq_id = -1);
  214. bool state_read_data(llama_io_read_i & io, uint32_t strm, uint32_t cell_count);
  215. };
  216. class llama_kv_cache_unified_context : public llama_memory_context_i {
  217. public:
  218. // some shorthands
  219. using slot_info_vec_t = llama_kv_cache_unified::slot_info_vec_t;
  220. using defrag_info = llama_kv_cache_unified::defrag_info;
  221. using stream_copy_info = llama_kv_cache_unified::stream_copy_info;
  222. // used for errors
  223. llama_kv_cache_unified_context(llama_memory_status status);
  224. // used to create a full-cache context
  225. llama_kv_cache_unified_context(
  226. llama_kv_cache_unified * kv);
  227. // used to create an update context
  228. llama_kv_cache_unified_context(
  229. llama_kv_cache_unified * kv,
  230. llama_context * lctx,
  231. bool do_shift,
  232. defrag_info dinfo,
  233. stream_copy_info sc_info);
  234. // used to create a batch procesing context from a batch
  235. llama_kv_cache_unified_context(
  236. llama_kv_cache_unified * kv,
  237. slot_info_vec_t sinfos,
  238. std::vector<llama_ubatch> ubatches);
  239. virtual ~llama_kv_cache_unified_context();
  240. //
  241. // llama_memory_context_i
  242. //
  243. bool next() override;
  244. bool apply() override;
  245. llama_memory_status get_status() const override;
  246. const llama_ubatch & get_ubatch() const override;
  247. //
  248. // llama_kv_cache_unified_context specific API
  249. //
  250. uint32_t get_n_kv() const;
  251. // TODO: temporary
  252. bool get_supports_set_rows() const;
  253. // get views of the current state of the cache
  254. ggml_tensor * get_k(ggml_context * ctx, int32_t il) const;
  255. ggml_tensor * get_v(ggml_context * ctx, int32_t il) const;
  256. // store k_cur and v_cur in the cache based on the provided head location
  257. ggml_tensor * cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il) const;
  258. ggml_tensor * cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il) const;
  259. ggml_tensor * build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const;
  260. ggml_tensor * build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const;
  261. void set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const;
  262. void set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const;
  263. void set_input_k_shift (ggml_tensor * dst) const;
  264. void set_input_kq_mask (ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const;
  265. void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const;
  266. private:
  267. llama_memory_status status;
  268. llama_kv_cache_unified * kv;
  269. llama_context * lctx;
  270. //
  271. // update context
  272. //
  273. bool do_shift = false;
  274. defrag_info dinfo;
  275. stream_copy_info sc_info;
  276. //
  277. // batch processing context
  278. //
  279. // the index of the cur ubatch to process
  280. size_t i_cur = 0;
  281. slot_info_vec_t sinfos;
  282. std::vector<llama_ubatch> ubatches;
  283. //
  284. // data needed for building the compute graph for the current ubatch:
  285. //
  286. // a heuristic, to avoid attending the full cache if it is not yet utilized
  287. // as the cache gets filled, the benefit from this heuristic disappears
  288. int32_t n_kv;
  289. };