llama-kv-cache.h 12 KB

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