llama-kv-cache.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. #pragma once
  2. #include "llama.h"
  3. #include "llama-io.h"
  4. #include "llama-graph.h"
  5. #include "llama-memory.h"
  6. #include "ggml-cpp.h"
  7. #include <set>
  8. #include <vector>
  9. struct llama_cparams;
  10. struct llama_hparams;
  11. struct llama_ubatch;
  12. struct llama_sbatch;
  13. struct llama_model;
  14. struct llama_context;
  15. struct llama_kv_cache : public llama_memory_i {
  16. virtual ~llama_kv_cache() = default;
  17. // call if batch processing fails - restores the cache state
  18. virtual void restore() = 0;
  19. // call after successful batch processing - clears any pending state
  20. virtual void commit() = 0;
  21. // process any pending defrag/shift/etc. operations
  22. // optionally call once before processing a new batch
  23. virtual bool update(llama_context & lctx) = 0;
  24. // schedule a defrag if the fragmentation threshold is exceeded. otherwise, do nothing
  25. virtual void defrag_sched(float thold) = 0;
  26. // simulate full cache, used for allocating worst-case compute buffers
  27. virtual void set_full() = 0;
  28. //
  29. // batch processing
  30. //
  31. virtual llama_sbatch sbatch_init(const llama_batch & batch, bool logits_all) = 0;
  32. // different KV caches require different batch splitting strategies
  33. virtual llama_ubatch ubatch_next(llama_sbatch & sbatch, uint32_t n_ubatch, bool embd_pooled) const = 0;
  34. // find an empty slot of size "n_tokens" in the cache
  35. virtual bool find_slot(const llama_ubatch & batch) = 0;
  36. // getters
  37. virtual int32_t get_n_tokens() const = 0;
  38. virtual int32_t get_used_cells() const = 0; // TODO: remove, this is too-specific to the unified cache
  39. virtual llama_pos get_pos_max() const = 0;
  40. virtual bool get_can_shift() const = 0;
  41. bool get_can_edit() const override { return get_can_shift(); }
  42. //
  43. // state write/read
  44. //
  45. virtual void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1) const = 0;
  46. virtual void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1) = 0;
  47. };
  48. //
  49. // llama_kv_cache_guard
  50. //
  51. struct llama_kv_cache_guard {
  52. llama_kv_cache_guard(llama_kv_cache * kv) : kv(kv) {}
  53. ~llama_kv_cache_guard() {
  54. kv->restore();
  55. }
  56. void commit() {
  57. kv->commit();
  58. }
  59. private:
  60. llama_kv_cache * kv;
  61. };
  62. //
  63. // llama_kv_cache_unified
  64. //
  65. // TODO: add notion of max sequences
  66. class llama_kv_cache_unified : public llama_kv_cache {
  67. public:
  68. struct kv_cell {
  69. llama_pos pos = -1;
  70. llama_pos delta = 0;
  71. std::set<llama_seq_id> seq_id;
  72. bool has_seq_id(const llama_seq_id & id) const {
  73. return seq_id.find(id) != seq_id.end();
  74. }
  75. bool is_empty() const {
  76. return seq_id.empty();
  77. }
  78. bool is_same_seq(const kv_cell & other) const {
  79. return seq_id == other.seq_id;
  80. }
  81. };
  82. static uint32_t get_padding(const llama_cparams & cparams);
  83. llama_kv_cache_unified(
  84. const llama_model & model,
  85. ggml_type type_k,
  86. ggml_type type_v,
  87. bool v_trans,
  88. bool offload,
  89. uint32_t kv_size,
  90. uint32_t padding);
  91. ~llama_kv_cache_unified() = default;
  92. //
  93. // llama_memory_i
  94. //
  95. void clear() override;
  96. bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override;
  97. void seq_cp (llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) override;
  98. void seq_keep(llama_seq_id seq_id) override;
  99. void seq_add (llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) override;
  100. void seq_div (llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) override;
  101. llama_pos seq_pos_max(llama_seq_id seq_id) const override;
  102. //
  103. // llama_kv_cache
  104. //
  105. void restore() override;
  106. void commit() override;
  107. bool update(llama_context & ctx) override;
  108. void defrag_sched(float thold) override;
  109. void set_full() override;
  110. llama_sbatch sbatch_init(const llama_batch & batch, bool logits_all) override;
  111. llama_ubatch ubatch_next(llama_sbatch & sbatch, uint32_t n_ubatch, bool embd_pooled) const override;
  112. // updates the cache head
  113. // Note: On success, it's important that cache.head points
  114. // to the first cell of the slot.
  115. bool find_slot(const llama_ubatch & batch) override;
  116. int32_t get_n_tokens() const override;
  117. int32_t get_used_cells() const override;
  118. // TODO: better data structures to reduce the cost of this operation
  119. llama_pos get_pos_max() const override;
  120. bool get_can_shift() const override;
  121. // state write/load
  122. void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1) const override;
  123. void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1) override;
  124. // Note: The value of head isn't only used to optimize searching
  125. // for a free KV slot. llama_decode_impl also uses it, so it
  126. // cannot be freely changed after a slot has been allocated.
  127. uint32_t head = 0;
  128. uint32_t size = 0;
  129. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  130. // computed before each graph build
  131. uint32_t n = 0;
  132. std::vector<kv_cell> cells;
  133. std::vector<ggml_tensor *> k_l; // per layer
  134. std::vector<ggml_tensor *> v_l;
  135. private:
  136. const llama_model & model;
  137. const llama_hparams & hparams;
  138. bool has_shift = false;
  139. bool do_defrag = false;
  140. bool v_trans = true; // the value tensor is transposed
  141. bool can_shift = false;
  142. // required padding
  143. uint32_t padding = 1;
  144. ggml_type type_k = GGML_TYPE_F16;
  145. ggml_type type_v = GGML_TYPE_F16;
  146. std::vector<ggml_context_ptr> ctxs;
  147. std::vector<ggml_backend_buffer_ptr> bufs;
  148. // defrag
  149. struct {
  150. std::vector<uint32_t> ids;
  151. } defrag_info;
  152. // return true if cells have been moved
  153. bool defrag_prepare(int32_t n_max_nodes);
  154. // commit/restore cache
  155. struct slot_range {
  156. uint32_t c0 = 0; // note: these are cell indices, not sequence positions
  157. uint32_t c1 = 0;
  158. };
  159. // pending cell updates that are not yet committed
  160. struct {
  161. std::vector<slot_range> ranges;
  162. } pending;
  163. // find how many cells are currently in use
  164. uint32_t cell_max() const;
  165. size_t total_size() const;
  166. size_t size_k_bytes() const;
  167. size_t size_v_bytes() const;
  168. ggml_tensor * build_rope_shift(
  169. const llama_cparams & cparams,
  170. ggml_context * ctx,
  171. ggml_tensor * cur,
  172. ggml_tensor * shift,
  173. ggml_tensor * factors,
  174. float freq_base,
  175. float freq_scale) const;
  176. llm_graph_result_ptr build_graph_shift(
  177. const llama_cparams & cparams,
  178. ggml_context * ctx,
  179. ggml_cgraph * gf) const;
  180. llm_graph_result_ptr build_graph_defrag(
  181. const llama_cparams & cparams,
  182. ggml_context * ctx,
  183. ggml_cgraph * gf) const;
  184. void state_write_meta(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges, llama_seq_id seq_id = -1) const;
  185. void state_write_data(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) const;
  186. bool state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id = -1);
  187. bool state_read_data(llama_io_read_i & io, uint32_t cell_count);
  188. };
  189. //
  190. // llama_kv_cache_recurrent
  191. //
  192. class llama_kv_cache_recurrent : public llama_kv_cache {
  193. public:
  194. struct kv_cell {
  195. llama_pos pos = -1;
  196. int32_t src = -1; // used to copy states
  197. int32_t tail = -1;
  198. std::set<llama_seq_id> seq_id;
  199. bool has_seq_id(const llama_seq_id & id) const {
  200. return seq_id.find(id) != seq_id.end();
  201. }
  202. bool is_empty() const {
  203. return seq_id.empty();
  204. }
  205. bool is_same_seq(const kv_cell & other) const {
  206. return seq_id == other.seq_id;
  207. }
  208. };
  209. llama_kv_cache_recurrent(
  210. const llama_model & model,
  211. ggml_type type_k,
  212. ggml_type type_v,
  213. bool offload,
  214. uint32_t kv_size);
  215. ~llama_kv_cache_recurrent() = default;
  216. //
  217. // llama_memory_i
  218. //
  219. void clear() override;
  220. bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override;
  221. void seq_cp (llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) override;
  222. void seq_keep(llama_seq_id seq_id) override;
  223. void seq_add (llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) override;
  224. void seq_div (llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) override;
  225. llama_pos seq_pos_max(llama_seq_id seq_id) const override;
  226. //
  227. // llama_kv_cache
  228. //
  229. void restore() override;
  230. void commit() override;
  231. bool update(llama_context & lctx) override;
  232. void defrag_sched(float thold) override;
  233. void set_full() override;
  234. llama_sbatch sbatch_init(const llama_batch & batch, bool logits_all) override;
  235. llama_ubatch ubatch_next(llama_sbatch & sbatch, uint32_t n_ubatch, bool embd_pooled) const override;
  236. bool find_slot(const llama_ubatch & batch) override;
  237. int32_t get_n_tokens() const override;
  238. int32_t get_used_cells() const override;
  239. // TODO: better data structures to reduce the cost of this operation
  240. llama_pos get_pos_max() const override;
  241. bool get_can_shift() const override;
  242. // TODO: temporary methods - they are not really const as they do const_cast<>, fix this
  243. int32_t s_copy(int i) const;
  244. float s_mask(int i) const;
  245. // state write/load
  246. void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1) const override;
  247. void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1) override;
  248. // Note: The value of head isn't only used to optimize searching
  249. // for a free KV slot. llama_decode_impl also uses it, so it
  250. // cannot be freely changed after a slot has been allocated.
  251. uint32_t head = 0;
  252. uint32_t size = 0;
  253. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  254. // computed before each graph build
  255. uint32_t n = 0;
  256. std::vector<kv_cell> cells;
  257. std::vector<ggml_tensor *> k_l; // per layer
  258. std::vector<ggml_tensor *> v_l;
  259. private:
  260. //const llama_model & model;
  261. const llama_hparams & hparams;
  262. // commit/restore cache
  263. // TODO: rework for recurrent cache
  264. struct slot_range {
  265. uint32_t c0 = 0; // note: these are cell indices, not sequence positions
  266. uint32_t c1 = 0;
  267. };
  268. // pending cell updates that are not yet committed
  269. struct {
  270. std::vector<slot_range> ranges;
  271. } pending;
  272. ggml_type type_k = GGML_TYPE_F16;
  273. ggml_type type_v = GGML_TYPE_F16;
  274. std::vector<ggml_context_ptr> ctxs;
  275. std::vector<ggml_backend_buffer_ptr> bufs;
  276. // find how many cells are currently in use
  277. uint32_t cell_max() const;
  278. size_t total_size() const;
  279. size_t size_k_bytes() const;
  280. size_t size_v_bytes() const;
  281. void state_write_meta(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges, llama_seq_id seq_id = -1) const;
  282. void state_write_data(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) const;
  283. bool state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id = -1);
  284. bool state_read_data(llama_io_read_i & io, uint32_t cell_count);
  285. };
  286. //
  287. // kv cache view
  288. //
  289. llama_kv_cache_view llama_kv_cache_view_init(const llama_kv_cache & kv, int32_t n_seq_max);
  290. void llama_kv_cache_view_update(llama_kv_cache_view * view, const llama_kv_cache * kv);