@fugood/llama.node 1.0.0-beta.5 → 1.0.0-beta.7

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