/src/llama.cpp/src/llama-kv-cache.cpp
Line | Count | Source |
1 | | #include "llama-kv-cache.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 <cstring> |
12 | | #include <limits> |
13 | | #include <map> |
14 | | #include <stdexcept> |
15 | | |
16 | | // |
17 | | // llama_kv_cache |
18 | | // |
19 | | |
20 | | llama_kv_cache::llama_kv_cache( |
21 | | const llama_model & model, |
22 | | ggml_type type_k, |
23 | | ggml_type type_v, |
24 | | bool v_trans, |
25 | | bool offload, |
26 | | bool unified, |
27 | | uint32_t kv_size, |
28 | | uint32_t n_seq_max, |
29 | | uint32_t n_pad, |
30 | | uint32_t n_swa, |
31 | | llama_swa_type swa_type, |
32 | | const layer_filter_cb & filter, |
33 | | const layer_reuse_cb & reuse) : |
34 | 0 | model(model), hparams(model.hparams), v_trans(v_trans), |
35 | 0 | n_seq_max(n_seq_max), n_stream(unified ? 1 : n_seq_max), n_pad(n_pad), n_swa(n_swa), swa_type(swa_type) { |
36 | |
|
37 | 0 | GGML_ASSERT(kv_size % n_pad == 0); |
38 | |
|
39 | 0 | const uint32_t n_layer_kv = hparams.n_layer_kv(); |
40 | | |
41 | | // define a comparator for the buft -> ctx map to ensure that the order is well-defined: |
42 | 0 | struct ggml_backend_buft_comparator { |
43 | 0 | bool operator()(const ggml_backend_buffer_type_t & lhs, const ggml_backend_buffer_type_t & rhs) const { |
44 | 0 | return strcmp(ggml_backend_buft_name(lhs), ggml_backend_buft_name(rhs)) < 0; |
45 | 0 | } |
46 | 0 | }; |
47 | 0 | std::map<ggml_backend_buffer_type_t, ggml_context_ptr, ggml_backend_buft_comparator> ctx_map; |
48 | | |
49 | | // create a context for each buffer type |
50 | 0 | auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * { |
51 | 0 | auto it = ctx_map.find(buft); |
52 | 0 | if (it == ctx_map.end()) { |
53 | 0 | ggml_init_params params = { |
54 | 0 | /*.mem_size =*/ size_t(2u*(1 + n_stream)*n_layer_kv*ggml_tensor_overhead()), |
55 | 0 | /*.mem_buffer =*/ NULL, |
56 | 0 | /*.no_alloc =*/ true, |
57 | 0 | }; |
58 | |
|
59 | 0 | ggml_context * ctx = ggml_init(params); |
60 | 0 | if (!ctx) { |
61 | 0 | return nullptr; |
62 | 0 | } |
63 | | |
64 | 0 | ctx_map.emplace(buft, ctx); |
65 | |
|
66 | 0 | return ctx; |
67 | 0 | } |
68 | | |
69 | 0 | return it->second.get(); |
70 | 0 | }; |
71 | |
|
72 | 0 | GGML_ASSERT(n_stream == 1 || n_stream == n_seq_max); |
73 | |
|
74 | 0 | v_heads.resize(n_stream); |
75 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
76 | 0 | v_heads[s] = 0; |
77 | 0 | } |
78 | |
|
79 | 0 | v_cells.resize(n_stream); |
80 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
81 | 0 | v_cells[s].resize(kv_size); |
82 | 0 | } |
83 | | |
84 | | // by default, all sequence ids are mapped to the 0th stream |
85 | 0 | seq_to_stream.resize(LLAMA_MAX_SEQ, 0); |
86 | |
|
87 | 0 | if (n_stream > 1) { |
88 | 0 | seq_to_stream.resize(n_stream, 0); |
89 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
90 | 0 | seq_to_stream[s] = s; |
91 | 0 | } |
92 | 0 | } |
93 | | |
94 | | // [TAG_V_CACHE_VARIABLE] |
95 | 0 | if (v_trans && hparams.is_n_embd_v_gqa_variable()) { |
96 | 0 | LLAMA_LOG_WARN("%s: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to %d\n", |
97 | 0 | __func__, hparams.n_embd_v_gqa_max()); |
98 | 0 | } |
99 | |
|
100 | 0 | for (uint32_t il = 0; il < hparams.n_layer; il++) { |
101 | 0 | if (!hparams.has_kv(il)) { |
102 | 0 | LLAMA_LOG_DEBUG("%s: layer %3d: does not have KV cache\n", __func__, il); |
103 | 0 | continue; |
104 | 0 | } |
105 | | |
106 | 0 | if (filter && !filter(il)) { |
107 | 0 | LLAMA_LOG_DEBUG("%s: layer %3d: filtered\n", __func__, il); |
108 | 0 | continue; |
109 | 0 | } |
110 | | |
111 | | // [TAG_V_CACHE_VARIABLE] |
112 | 0 | const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il); |
113 | 0 | const uint32_t n_embd_v_gqa = !v_trans ? hparams.n_embd_v_gqa(il) : hparams.n_embd_v_gqa_max(); |
114 | |
|
115 | 0 | const char * dev_name = "CPU"; |
116 | |
|
117 | 0 | ggml_backend_buffer_type_t buft = ggml_backend_cpu_buffer_type(); |
118 | |
|
119 | 0 | if (offload) { |
120 | 0 | auto * dev = model.dev_layer(il); |
121 | 0 | buft = ggml_backend_dev_buffer_type(dev); |
122 | |
|
123 | 0 | dev_name = ggml_backend_dev_name(dev); |
124 | 0 | } |
125 | |
|
126 | 0 | LLAMA_LOG_DEBUG("%s: layer %3d: dev = %s\n", __func__, il, dev_name); |
127 | |
|
128 | 0 | ggml_context * ctx = ctx_for_buft(buft); |
129 | 0 | if (!ctx) { |
130 | 0 | throw std::runtime_error("failed to create ggml context for kv cache"); |
131 | 0 | } |
132 | | |
133 | 0 | ggml_tensor * k = ggml_new_tensor_3d(ctx, type_k, n_embd_k_gqa, kv_size, n_stream); |
134 | 0 | ggml_tensor * v = ggml_new_tensor_3d(ctx, type_v, n_embd_v_gqa, kv_size, n_stream); |
135 | |
|
136 | 0 | ggml_format_name(k, "cache_k_l%d", il); |
137 | 0 | ggml_format_name(v, "cache_v_l%d", il); |
138 | |
|
139 | 0 | std::vector<ggml_tensor *> k_stream; |
140 | 0 | std::vector<ggml_tensor *> v_stream; |
141 | |
|
142 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
143 | 0 | k_stream.push_back(ggml_view_2d(ctx, k, n_embd_k_gqa, kv_size, k->nb[1], s*k->nb[2])); |
144 | 0 | v_stream.push_back(ggml_view_2d(ctx, v, n_embd_v_gqa, kv_size, v->nb[1], s*v->nb[2])); |
145 | 0 | } |
146 | |
|
147 | 0 | map_layer_ids[il] = layers.size(); |
148 | |
|
149 | 0 | layers.push_back({ il, k, v, k_stream, v_stream, }); |
150 | 0 | } |
151 | | |
152 | 0 | if (reuse) { |
153 | 0 | LLAMA_LOG_DEBUG("%s: reusing layers:\n", __func__); |
154 | |
|
155 | 0 | for (uint32_t il = 0; il < hparams.n_layer; il++) { |
156 | 0 | const int32_t il_reuse = reuse(il); |
157 | |
|
158 | 0 | if (il_reuse < 0) { |
159 | 0 | LLAMA_LOG_DEBUG("%s: - layer %3d: no reuse\n", __func__, il); |
160 | 0 | continue; |
161 | 0 | } |
162 | | |
163 | 0 | if (filter && !filter(il)) { |
164 | 0 | LLAMA_LOG_DEBUG("%s: - layer %3d: filtered\n", __func__, il); |
165 | 0 | continue; |
166 | 0 | } |
167 | | |
168 | 0 | GGML_ASSERT(map_layer_ids.find(il_reuse) != map_layer_ids.end()); |
169 | |
|
170 | 0 | map_layer_ids[il] = map_layer_ids[il_reuse]; |
171 | |
|
172 | 0 | LLAMA_LOG_DEBUG("%s: - layer %3d: reuse layer %d, is_swa = %d\n", __func__, il, il_reuse, hparams.is_swa(il)); |
173 | 0 | } |
174 | 0 | } |
175 | | |
176 | | // allocate tensors and initialize the buffers to avoid NaNs in the padding |
177 | 0 | for (auto & [buft, ctx] : ctx_map) { |
178 | 0 | ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx.get(), buft); |
179 | 0 | if (!buf) { |
180 | 0 | throw std::runtime_error("failed to allocate buffer for kv cache"); |
181 | 0 | } |
182 | | |
183 | 0 | 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); |
184 | |
|
185 | 0 | ggml_backend_buffer_clear(buf, 0); |
186 | 0 | ctxs_bufs.emplace_back(std::move(ctx), buf); |
187 | 0 | } |
188 | | |
189 | 0 | { |
190 | 0 | const size_t memory_size_k = size_k_bytes(); |
191 | 0 | const size_t memory_size_v = size_v_bytes(); |
192 | |
|
193 | 0 | LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u/%u seqs), K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__, |
194 | 0 | (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f), kv_size, (int) layers.size(), n_seq_max, n_stream, |
195 | 0 | ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f), |
196 | 0 | ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f)); |
197 | 0 | } |
198 | |
|
199 | 0 | const char * LLAMA_KV_CACHE_DEBUG = getenv("LLAMA_KV_CACHE_DEBUG"); |
200 | 0 | debug = LLAMA_KV_CACHE_DEBUG ? atoi(LLAMA_KV_CACHE_DEBUG) : 0; |
201 | 0 | } |
202 | | |
203 | 0 | void llama_kv_cache::clear(bool data) { |
204 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
205 | 0 | v_cells[s].reset(); |
206 | 0 | v_heads[s] = 0; |
207 | 0 | } |
208 | |
|
209 | 0 | if (data) { |
210 | 0 | for (auto & [_, buf] : ctxs_bufs) { |
211 | 0 | ggml_backend_buffer_clear(buf.get(), 0); |
212 | 0 | } |
213 | 0 | } |
214 | 0 | } |
215 | | |
216 | 0 | bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { |
217 | 0 | GGML_ASSERT(seq_id == -1 || (seq_id >= 0 && (size_t) seq_id < seq_to_stream.size())); |
218 | |
|
219 | 0 | if (p0 < 0) { |
220 | 0 | p0 = 0; |
221 | 0 | } |
222 | |
|
223 | 0 | if (p1 < 0) { |
224 | 0 | p1 = std::numeric_limits<llama_pos>::max(); |
225 | 0 | } |
226 | |
|
227 | 0 | if (seq_id >= 0) { |
228 | 0 | auto & cells = v_cells[seq_to_stream[seq_id]]; |
229 | 0 | auto & head = v_heads[seq_to_stream[seq_id]]; |
230 | |
|
231 | 0 | uint32_t new_head = cells.size(); |
232 | |
|
233 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
234 | 0 | if (!cells.pos_in(i, p0, p1)) { |
235 | 0 | continue; |
236 | 0 | } |
237 | | |
238 | 0 | if (cells.seq_has(i, seq_id) && cells.seq_rm(i, seq_id)) { |
239 | 0 | if (new_head == cells.size()) { |
240 | 0 | new_head = i; |
241 | 0 | } |
242 | 0 | } |
243 | 0 | } |
244 | | |
245 | | // If we freed up a slot, set head to it so searching can start there. |
246 | 0 | if (new_head != cells.size() && new_head < head) { |
247 | 0 | head = new_head; |
248 | 0 | } |
249 | 0 | } else { |
250 | | // match any sequence |
251 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
252 | 0 | auto & cells = v_cells[s]; |
253 | 0 | auto & head = v_heads[s]; |
254 | |
|
255 | 0 | uint32_t new_head = cells.size(); |
256 | |
|
257 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
258 | 0 | if (!cells.pos_in(i, p0, p1)) { |
259 | 0 | continue; |
260 | 0 | } |
261 | | |
262 | 0 | cells.rm(i); |
263 | |
|
264 | 0 | if (new_head == cells.size()) { |
265 | 0 | new_head = i; |
266 | 0 | } |
267 | 0 | } |
268 | | |
269 | | // If we freed up a slot, set head to it so searching can start there. |
270 | 0 | if (new_head != cells.size() && new_head < head) { |
271 | 0 | head = new_head; |
272 | 0 | } |
273 | 0 | } |
274 | 0 | } |
275 | |
|
276 | 0 | return true; |
277 | 0 | } |
278 | | |
279 | 0 | void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) { |
280 | 0 | GGML_ASSERT(seq_id_src >= 0 && (size_t) seq_id_src < seq_to_stream.size()); |
281 | 0 | GGML_ASSERT(seq_id_dst >= 0 && (size_t) seq_id_dst < seq_to_stream.size()); |
282 | |
|
283 | 0 | const auto s0 = seq_to_stream[seq_id_src]; |
284 | 0 | const auto s1 = seq_to_stream[seq_id_dst]; |
285 | |
|
286 | 0 | if (s0 == s1) { |
287 | | // since both sequences are in the same stream, no data copy is necessary |
288 | | // we just have to update the cells meta data |
289 | |
|
290 | 0 | auto & cells = v_cells[s0]; |
291 | |
|
292 | 0 | if (seq_id_src == seq_id_dst) { |
293 | 0 | return; |
294 | 0 | } |
295 | | |
296 | 0 | if (p0 < 0) { |
297 | 0 | p0 = 0; |
298 | 0 | } |
299 | |
|
300 | 0 | if (p1 < 0) { |
301 | 0 | p1 = std::numeric_limits<llama_pos>::max(); |
302 | 0 | } |
303 | |
|
304 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
305 | 0 | if (!cells.pos_in(i, p0, p1)) { |
306 | 0 | continue; |
307 | 0 | } |
308 | | |
309 | 0 | if (cells.seq_has(i, seq_id_src)) { |
310 | 0 | cells.seq_add(i, seq_id_dst); |
311 | 0 | } |
312 | 0 | } |
313 | |
|
314 | 0 | return; |
315 | 0 | } |
316 | | |
317 | | // cross-stream sequence copies require to copy the actual buffer data |
318 | | |
319 | 0 | bool is_full = true; |
320 | |
|
321 | 0 | if (p0 > 0 && p0 + 1 < (int) get_size()) { |
322 | 0 | is_full = false; |
323 | 0 | } |
324 | |
|
325 | 0 | if (p1 > 0 && p1 + 1 < (int) get_size()) { |
326 | 0 | is_full = false; |
327 | 0 | } |
328 | |
|
329 | 0 | GGML_ASSERT(is_full && "seq_cp() is only supported for full KV buffers"); |
330 | | |
331 | | // enqueue the copy operation - the buffer copy will be performed during the next update |
332 | 0 | sc_info.ssrc.push_back(s0); |
333 | 0 | sc_info.sdst.push_back(s1); |
334 | |
|
335 | 0 | v_cells[s1].reset(); |
336 | 0 | for (uint32_t i = 0; i < v_cells[s0].size(); ++i) { |
337 | 0 | if (v_cells[s0].seq_has(i, seq_id_src)) { |
338 | 0 | llama_pos pos = v_cells[s0].pos_get(i); |
339 | 0 | llama_pos shift = v_cells[s0].get_shift(i); |
340 | |
|
341 | 0 | llama_kv_cell_ext ext = v_cells[s0].ext_get(i); |
342 | |
|
343 | 0 | if (shift != 0) { |
344 | 0 | pos -= shift; |
345 | 0 | assert(pos >= 0); |
346 | 0 | } |
347 | |
|
348 | 0 | v_cells[s1].pos_set(i, pos); |
349 | 0 | v_cells[s1].seq_add(i, seq_id_dst); |
350 | |
|
351 | 0 | if (shift != 0) { |
352 | 0 | v_cells[s1].pos_add(i, shift); |
353 | 0 | } |
354 | |
|
355 | 0 | v_cells[s1].ext_set(i, ext); |
356 | 0 | } |
357 | 0 | } |
358 | |
|
359 | 0 | v_heads[s1] = v_heads[s0]; |
360 | | |
361 | | //for (uint32_t s = 0; s < n_stream; ++s) { |
362 | | // LLAMA_LOG_WARN("%s: seq %d: min = %d, max = %d\n", __func__, s, v_cells[s].seq_pos_min(s), v_cells[s].seq_pos_max(s)); |
363 | | //} |
364 | 0 | } |
365 | | |
366 | 0 | void llama_kv_cache::seq_keep(llama_seq_id seq_id) { |
367 | 0 | GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()); |
368 | |
|
369 | 0 | auto & cells = v_cells[seq_to_stream[seq_id]]; |
370 | 0 | auto & head = v_heads[seq_to_stream[seq_id]]; |
371 | |
|
372 | 0 | uint32_t new_head = cells.size(); |
373 | |
|
374 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
375 | 0 | if (cells.seq_keep(i, seq_id)) { |
376 | 0 | if (new_head == cells.size()) { |
377 | 0 | new_head = i; |
378 | 0 | } |
379 | 0 | } |
380 | 0 | } |
381 | | |
382 | | // If we freed up a slot, set head to it so searching can start there. |
383 | 0 | if (new_head != cells.size() && new_head < head) { |
384 | 0 | head = new_head; |
385 | 0 | } |
386 | 0 | } |
387 | | |
388 | 0 | void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) { |
389 | 0 | GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()); |
390 | 0 | GGML_ASSERT(hparams.n_pos_per_embd() == 1 && "seq_add() is only supported for n_pos_per_embd() == 1"); |
391 | |
|
392 | 0 | auto & cells = v_cells[seq_to_stream[seq_id]]; |
393 | 0 | auto & head = v_heads[seq_to_stream[seq_id]]; |
394 | |
|
395 | 0 | if (shift == 0) { |
396 | 0 | return; |
397 | 0 | } |
398 | | |
399 | 0 | uint32_t new_head = cells.size(); |
400 | |
|
401 | 0 | if (p0 < 0) { |
402 | 0 | p0 = 0; |
403 | 0 | } |
404 | |
|
405 | 0 | if (p1 < 0) { |
406 | 0 | p1 = std::numeric_limits<llama_pos>::max(); |
407 | 0 | } |
408 | | |
409 | | // If there is no range then return early to avoid looping over all cells. |
410 | 0 | if (p0 == p1) { |
411 | 0 | return; |
412 | 0 | } |
413 | | |
414 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
415 | 0 | if (!cells.pos_in(i, p0, p1)) { |
416 | 0 | continue; |
417 | 0 | } |
418 | | |
419 | 0 | if (cells.seq_has(i, seq_id)) { |
420 | 0 | if (cells.pos_add(i, shift)) { |
421 | 0 | if (new_head == cells.size()) { |
422 | 0 | new_head = i; |
423 | 0 | } |
424 | 0 | } |
425 | 0 | } |
426 | 0 | } |
427 | | |
428 | | // If we freed up a slot, set head to it so searching can start there. |
429 | | // Otherwise we just start the next search from the beginning. |
430 | 0 | head = new_head != cells.size() ? new_head : 0; |
431 | 0 | } |
432 | | |
433 | 0 | void llama_kv_cache::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) { |
434 | 0 | GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()); |
435 | 0 | GGML_ASSERT(hparams.n_pos_per_embd() == 1 && "seq_div() is only supported for n_pos_per_embd() == 1"); |
436 | |
|
437 | 0 | auto & cells = v_cells[seq_to_stream[seq_id]]; |
438 | |
|
439 | 0 | if (d == 1) { |
440 | 0 | return; |
441 | 0 | } |
442 | | |
443 | 0 | if (p0 < 0) { |
444 | 0 | p0 = 0; |
445 | 0 | } |
446 | |
|
447 | 0 | if (p1 < 0) { |
448 | 0 | p1 = std::numeric_limits<llama_pos>::max(); |
449 | 0 | } |
450 | | |
451 | | // If there is no range then return early to avoid looping over the cache. |
452 | 0 | if (p0 == p1) { |
453 | 0 | return; |
454 | 0 | } |
455 | | |
456 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
457 | 0 | if (!cells.pos_in(i, p0, p1)) { |
458 | 0 | continue; |
459 | 0 | } |
460 | | |
461 | 0 | if (cells.seq_has(i, seq_id)) { |
462 | 0 | cells.pos_div(i, d); |
463 | 0 | } |
464 | 0 | } |
465 | 0 | } |
466 | | |
467 | 0 | llama_pos llama_kv_cache::seq_pos_min(llama_seq_id seq_id) const { |
468 | 0 | GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()); |
469 | |
|
470 | 0 | const auto & cells = v_cells[seq_to_stream[seq_id]]; |
471 | |
|
472 | 0 | return cells.seq_pos_min(seq_id); |
473 | 0 | } |
474 | | |
475 | 0 | llama_pos llama_kv_cache::seq_pos_max(llama_seq_id seq_id) const { |
476 | 0 | GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()); |
477 | |
|
478 | 0 | const auto & cells = v_cells[seq_to_stream[seq_id]]; |
479 | |
|
480 | 0 | return cells.seq_pos_max(seq_id); |
481 | 0 | } |
482 | | |
483 | 0 | std::map<ggml_backend_buffer_type_t, size_t> llama_kv_cache::memory_breakdown() const { |
484 | 0 | std::map<ggml_backend_buffer_type_t, size_t> ret; |
485 | 0 | for (const auto & [_, buf] : ctxs_bufs) { |
486 | 0 | ret[ggml_backend_buffer_get_type(buf.get())] += ggml_backend_buffer_get_size(buf.get()); |
487 | 0 | } |
488 | 0 | return ret; |
489 | 0 | } |
490 | | |
491 | | llama_memory_context_ptr llama_kv_cache::init_batch( |
492 | | llama_batch_allocr & balloc, |
493 | | uint32_t n_ubatch, |
494 | 0 | bool embd_all) { |
495 | 0 | GGML_UNUSED(embd_all); |
496 | |
|
497 | 0 | do { |
498 | 0 | balloc.split_reset(); |
499 | |
|
500 | 0 | std::vector<llama_ubatch> ubatches; |
501 | 0 | while (true) { |
502 | 0 | auto ubatch = n_stream == 1 ? balloc.split_simple(n_ubatch) : balloc.split_equal(n_ubatch, true); |
503 | |
|
504 | 0 | if (ubatch.n_tokens == 0) { |
505 | 0 | break; |
506 | 0 | } |
507 | | |
508 | 0 | ubatches.push_back(std::move(ubatch)); // NOLINT |
509 | 0 | } |
510 | |
|
511 | 0 | if (balloc.get_n_used() < balloc.get_n_tokens()) { |
512 | | // failed to find a suitable split |
513 | 0 | break; |
514 | 0 | } |
515 | | |
516 | 0 | auto sinfos = prepare(ubatches); |
517 | 0 | if (sinfos.empty()) { |
518 | 0 | break; |
519 | 0 | } |
520 | | |
521 | 0 | return std::make_unique<llama_kv_cache_context>( |
522 | 0 | this, std::move(sinfos), std::move(ubatches)); |
523 | 0 | } while (false); |
524 | | |
525 | 0 | return std::make_unique<llama_kv_cache_context>(LLAMA_MEMORY_STATUS_FAILED_PREPARE); |
526 | 0 | } |
527 | | |
528 | 0 | llama_memory_context_ptr llama_kv_cache::init_full() { |
529 | 0 | return std::make_unique<llama_kv_cache_context>(this); |
530 | 0 | } |
531 | | |
532 | 0 | llama_memory_context_ptr llama_kv_cache::init_update(llama_context * lctx, bool optimize) { |
533 | 0 | GGML_UNUSED(optimize); |
534 | |
|
535 | 0 | bool do_shift = get_has_shift(); |
536 | |
|
537 | 0 | return std::make_unique<llama_kv_cache_context>(this, lctx, do_shift, std::move(sc_info)); |
538 | 0 | } |
539 | | |
540 | 0 | llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector<llama_ubatch> & ubatches) { |
541 | 0 | llama_kv_cache::slot_info_vec_t res; |
542 | |
|
543 | 0 | struct state_t { |
544 | 0 | slot_info sinfo; // slot info for the ubatch |
545 | |
|
546 | 0 | std::vector<uint32_t> v_heads_old; // old positions of the heads, before placing the ubatch |
547 | |
|
548 | 0 | std::vector<llama_kv_cells> v_cells; // copy of the old cells, before placing the ubatch |
549 | 0 | }; |
550 | | |
551 | | // remember the old state of the cells so we can restore it in the end |
552 | 0 | std::vector<state_t> states; |
553 | |
|
554 | 0 | bool success = true; |
555 | |
|
556 | 0 | for (const auto & ubatch : ubatches) { |
557 | | // only find a suitable slot for the ubatch. don't modify the cells yet |
558 | 0 | const auto sinfo_new = find_slot(ubatch, false); |
559 | 0 | if (sinfo_new.empty()) { |
560 | 0 | success = false; |
561 | 0 | break; |
562 | 0 | } |
563 | | |
564 | | // remeber the position that we found |
565 | 0 | res.push_back(sinfo_new); |
566 | | |
567 | | // store the old state of the cells in the recovery stack |
568 | 0 | { |
569 | 0 | state_t state = { sinfo_new, v_heads, {} }; |
570 | |
|
571 | 0 | for (uint32_t s = 0; s < sinfo_new.n_stream(); ++s) { |
572 | 0 | auto & cells = v_cells[sinfo_new.strm[s]]; |
573 | |
|
574 | 0 | state.v_cells.push_back(cells.cp(sinfo_new.idxs[s])); |
575 | 0 | } |
576 | |
|
577 | 0 | states.push_back(std::move(state)); |
578 | 0 | } |
579 | | |
580 | | // now emplace the ubatch |
581 | 0 | apply_ubatch(sinfo_new, ubatch); |
582 | 0 | } |
583 | |
|
584 | 0 | GGML_ASSERT(!states.empty() || !success); |
585 | | |
586 | | // iterate backwards and restore the cells to their original state |
587 | 0 | for (auto it = states.rbegin(); it != states.rend(); ++it) { |
588 | 0 | const auto & sinfo = it->sinfo; |
589 | |
|
590 | 0 | for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { |
591 | 0 | auto & cells = v_cells[sinfo.strm[s]]; |
592 | 0 | auto & head = v_heads[sinfo.strm[s]]; |
593 | |
|
594 | 0 | cells.set(sinfo.idxs[s], it->v_cells[s]); |
595 | 0 | head = it->v_heads_old[s]; |
596 | 0 | } |
597 | 0 | } |
598 | |
|
599 | 0 | if (!success) { |
600 | 0 | return {}; |
601 | 0 | } |
602 | | |
603 | 0 | return res; |
604 | 0 | } |
605 | | |
606 | 0 | bool llama_kv_cache::update(llama_context * lctx, bool do_shift, const stream_copy_info & sc_info) { |
607 | 0 | bool updated = false; |
608 | |
|
609 | 0 | auto * sched = lctx->get_sched(); |
610 | |
|
611 | 0 | if (!sc_info.empty()) { |
612 | 0 | assert(n_stream > 1 && "stream copy should never happen with a single stream"); |
613 | |
|
614 | 0 | llama_synchronize(lctx); |
615 | |
|
616 | 0 | const size_t n_copy = sc_info.ssrc.size(); |
617 | |
|
618 | 0 | for (size_t i = 0; i < n_copy; ++i) { |
619 | 0 | const auto ssrc = sc_info.ssrc[i]; |
620 | 0 | const auto sdst = sc_info.sdst[i]; |
621 | |
|
622 | 0 | assert(ssrc < n_stream); |
623 | 0 | assert(sdst < n_stream); |
624 | |
|
625 | 0 | LLAMA_LOG_DEBUG("%s: copying KV buffer: stream %d to stream %d\n", __func__, ssrc, sdst); |
626 | |
|
627 | 0 | assert(ssrc != sdst); |
628 | |
|
629 | 0 | for (uint32_t il = 0; il < layers.size(); ++il) { |
630 | 0 | const auto & layer = layers[il]; |
631 | |
|
632 | 0 | ggml_backend_tensor_copy(layer.k_stream[ssrc], layer.k_stream[sdst]); |
633 | 0 | ggml_backend_tensor_copy(layer.v_stream[ssrc], layer.v_stream[sdst]); |
634 | 0 | } |
635 | 0 | } |
636 | 0 | } |
637 | |
|
638 | 0 | if (do_shift) { |
639 | 0 | if (!get_can_shift()) { |
640 | 0 | GGML_ABORT("The current KV cache / model configuration does not support K-shift"); |
641 | 0 | } |
642 | |
|
643 | 0 | LLAMA_LOG_DEBUG("%s: applying K-shift\n", __func__); |
644 | | |
645 | | // apply K-shift if needed |
646 | 0 | if (hparams.rope_type != LLAMA_ROPE_TYPE_NONE) { |
647 | 0 | ggml_backend_sched_reset(sched); |
648 | |
|
649 | 0 | auto * res = lctx->get_gf_res_reserve(); |
650 | |
|
651 | 0 | res->reset(); |
652 | |
|
653 | 0 | auto * gf = build_graph_shift(res, lctx); |
654 | 0 | if (!ggml_backend_sched_alloc_graph(sched, gf)) { |
655 | 0 | LLAMA_LOG_ERROR("%s: failed to allocate compute graph for K-shift\n", __func__); |
656 | 0 | return updated; |
657 | 0 | } |
658 | | |
659 | 0 | res->set_inputs(nullptr); |
660 | |
|
661 | 0 | if (lctx->graph_compute(gf, false) != GGML_STATUS_SUCCESS) { |
662 | 0 | LLAMA_LOG_ERROR("%s: failed to compute K-shift\n", __func__); |
663 | 0 | return updated; |
664 | 0 | } |
665 | | |
666 | 0 | updated = true; |
667 | 0 | } |
668 | | |
669 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
670 | 0 | auto & cells = v_cells[s]; |
671 | |
|
672 | 0 | cells.reset_shift(); |
673 | 0 | } |
674 | 0 | } |
675 | | |
676 | 0 | return updated; |
677 | 0 | } |
678 | | |
679 | 0 | llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, bool cont) const { |
680 | |
|
681 | 0 | if (debug > 0) { |
682 | 0 | for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) { |
683 | 0 | const auto seq_id = ubatch.seq_id_unq[s]; |
684 | 0 | const auto stream_id = seq_to_stream[seq_id]; |
685 | 0 | const auto & cells = v_cells[stream_id]; |
686 | 0 | const uint32_t head_cur = v_heads[stream_id]; |
687 | |
|
688 | 0 | LLAMA_LOG_DEBUG("%s: stream[%d], n = %5d, used = %5d, head = %5d, size = %5d, n_swa = %5d\n", |
689 | 0 | __func__, stream_id, cells.used_max_p1(), cells.get_used(), head_cur, get_size(), n_swa); |
690 | |
|
691 | 0 | if ((debug == 2 && n_swa > 0) || debug > 2) { |
692 | 0 | std::string ss; |
693 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
694 | 0 | if (cells.is_empty(i)) { |
695 | 0 | ss += '.'; |
696 | 0 | } else { |
697 | 0 | assert(cells.seq_count(i) >= 1); |
698 | |
|
699 | 0 | if (cells.seq_count(i) == 1) { |
700 | 0 | ss += std::to_string(cells.seq_get(i)); |
701 | 0 | } else { |
702 | 0 | ss += 'M'; |
703 | 0 | } |
704 | 0 | } |
705 | 0 | if (i%256 == 255) { |
706 | 0 | ss += " *"; |
707 | 0 | ss += '\n'; |
708 | 0 | } |
709 | 0 | } |
710 | 0 | LLAMA_LOG_DEBUG("\n%s\n", ss.c_str()); |
711 | 0 | } |
712 | |
|
713 | 0 | if ((debug == 2 && n_swa > 0) || debug > 2) { |
714 | 0 | std::string ss; |
715 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
716 | 0 | std::string cur; |
717 | 0 | if (cells.is_empty(i)) { |
718 | 0 | cur = '.'; |
719 | 0 | } else { |
720 | 0 | cur = std::to_string(cells.pos_get(i)); |
721 | 0 | } |
722 | 0 | const int n = cur.size(); |
723 | 0 | for (int j = 0; j < 5 - n; ++j) { |
724 | 0 | cur += ' '; |
725 | 0 | } |
726 | 0 | ss += cur; |
727 | 0 | if (i%256 == 255) { |
728 | 0 | ss += " *"; |
729 | 0 | } |
730 | 0 | if (i%64 == 63) { |
731 | 0 | ss += '\n'; |
732 | 0 | } |
733 | 0 | } |
734 | 0 | LLAMA_LOG_DEBUG("\n%s\n", ss.c_str()); |
735 | 0 | } |
736 | |
|
737 | 0 | for (int s = 0; s < LLAMA_MAX_SEQ; ++s) { |
738 | 0 | if (cells.seq_pos_min(s) < 0) { |
739 | 0 | continue; |
740 | 0 | } |
741 | | |
742 | 0 | LLAMA_LOG_DEBUG("%s: stream[%d] min[%d] = %5d, max[%d] = %5d\n", __func__, stream_id, s, cells.seq_pos_min(s), s, cells.seq_pos_max(s)); |
743 | 0 | } |
744 | 0 | } |
745 | 0 | } |
746 | |
|
747 | 0 | uint32_t n_tokens = ubatch.n_tokens; |
748 | 0 | uint32_t n_seqs = 1; |
749 | |
|
750 | 0 | if (n_stream > 1) { |
751 | 0 | GGML_ASSERT(n_tokens % ubatch.n_seqs_unq == 0); |
752 | |
|
753 | 0 | n_seqs = ubatch.n_seqs_unq; |
754 | 0 | n_tokens = n_tokens / n_seqs; |
755 | 0 | } |
756 | |
|
757 | 0 | slot_info res = { |
758 | 0 | /*.s0 =*/ LLAMA_MAX_SEQ, |
759 | 0 | /*.s1 =*/ 0, |
760 | 0 | /*.strm =*/ { }, |
761 | 0 | /*.idxs =*/ { }, |
762 | 0 | }; |
763 | |
|
764 | 0 | res.resize(n_seqs); |
765 | |
|
766 | 0 | for (uint32_t s = 0; s < n_seqs; ++s) { |
767 | 0 | const auto seq_id = ubatch.seq_id_unq[s]; |
768 | |
|
769 | 0 | if (n_stream > 1) { |
770 | 0 | GGML_ASSERT(ubatch.n_seq_id[s*n_tokens] == 1); |
771 | 0 | GGML_ASSERT(ubatch.seq_id [s*n_tokens][0] == seq_id); |
772 | 0 | } |
773 | |
|
774 | 0 | res.s0 = std::min<uint32_t>(res.s0, seq_to_stream[seq_id]); |
775 | 0 | res.s1 = std::max<uint32_t>(res.s1, seq_to_stream[seq_id]); |
776 | |
|
777 | 0 | res.strm[s] = seq_to_stream[seq_id]; |
778 | 0 | res.idxs[s].reserve(n_tokens); |
779 | |
|
780 | 0 | const auto & cells = v_cells[seq_to_stream[seq_id]]; |
781 | |
|
782 | 0 | uint32_t head_cur = v_heads[seq_to_stream[seq_id]]; |
783 | | |
784 | | // if we have enough unused cells before the current head -> |
785 | | // better to start searching from the beginning of the cache, hoping to fill it |
786 | 0 | if (head_cur > cells.get_used() + 2*n_tokens) { |
787 | 0 | head_cur = 0; |
788 | 0 | } |
789 | |
|
790 | 0 | if (n_tokens > cells.size()) { |
791 | 0 | LLAMA_LOG_ERROR("%s: n_tokens = %d > size = %u\n", __func__, n_tokens, cells.size()); |
792 | 0 | return { }; |
793 | 0 | } |
794 | | |
795 | 0 | uint32_t n_tested = 0; |
796 | | |
797 | | // for continuous slots, we test that all tokens in the ubatch fit, starting from the current head |
798 | | // for non-continuous slots, we test the tokens one by one |
799 | 0 | const uint32_t n_test = cont ? n_tokens : 1; |
800 | |
|
801 | 0 | while (true) { |
802 | 0 | if (head_cur + n_test > cells.size()) { |
803 | 0 | n_tested += cells.size() - head_cur; |
804 | 0 | head_cur = 0; |
805 | 0 | continue; |
806 | 0 | } |
807 | | |
808 | 0 | for (uint32_t i = 0; i < n_test; i++) { |
809 | 0 | const auto idx = head_cur; |
810 | |
|
811 | 0 | head_cur++; |
812 | 0 | n_tested++; |
813 | | |
814 | | //const llama_pos pos = ubatch.pos[i]; |
815 | | //const llama_seq_id seq_id = ubatch.seq_id[i][0]; |
816 | | |
817 | | // can we use this cell? either: |
818 | | // - the cell is empty |
819 | | // - the cell is occupied only by one sequence: |
820 | | // - (disabled) mask causally, if the sequence is the same as the one we are inserting |
821 | | // - mask SWA, using current max pos for that sequence in the cache |
822 | | // always insert in the cell with minimum pos |
823 | 0 | bool can_use = cells.is_empty(idx); |
824 | |
|
825 | 0 | if (!can_use && cells.seq_count(idx) == 1) { |
826 | 0 | const llama_pos pos_cell = cells.pos_get(idx); |
827 | | |
828 | | // (disabled) causal mask |
829 | | // note: it's better to purge any "future" tokens beforehand |
830 | | //if (cells.seq_has(idx, seq_id)) { |
831 | | // can_use = pos_cell >= pos; |
832 | | //} |
833 | |
|
834 | 0 | if (!can_use) { |
835 | 0 | const llama_seq_id seq_id_cell = cells.seq_get(idx); |
836 | | |
837 | | // SWA mask |
838 | 0 | if (is_masked_swa(pos_cell, cells.seq_pos_max(seq_id_cell) + 1)) { |
839 | 0 | can_use = true; |
840 | 0 | } |
841 | 0 | } |
842 | 0 | } |
843 | |
|
844 | 0 | if (can_use) { |
845 | 0 | res.idxs[s].push_back(idx); |
846 | 0 | } else { |
847 | 0 | if (cont) { |
848 | 0 | break; |
849 | 0 | } |
850 | 0 | } |
851 | 0 | } |
852 | |
|
853 | 0 | if (res.idxs[s].size() == n_tokens) { |
854 | 0 | break; |
855 | 0 | } |
856 | | |
857 | 0 | if (cont) { |
858 | 0 | res.idxs[s].clear(); |
859 | 0 | } |
860 | |
|
861 | 0 | if (n_tested >= cells.size()) { |
862 | | //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens); |
863 | 0 | return { }; |
864 | 0 | } |
865 | 0 | } |
866 | | |
867 | | // we didn't find a suitable slot - return empty result |
868 | 0 | if (res.idxs[s].size() < n_tokens) { |
869 | 0 | return { }; |
870 | 0 | } |
871 | 0 | } |
872 | | |
873 | 0 | assert(res.s1 >= res.s0); |
874 | |
|
875 | 0 | return res; |
876 | 0 | } |
877 | | |
878 | 0 | void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch) { |
879 | | // keep track of the max sequence position that we would overwrite with this ubatch |
880 | | // for non-SWA cache, this would be always empty |
881 | 0 | llama_seq_id seq_pos_max_rm[LLAMA_MAX_SEQ]; |
882 | 0 | for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) { |
883 | 0 | seq_pos_max_rm[s] = -1; |
884 | 0 | } |
885 | |
|
886 | 0 | assert(ubatch.n_tokens == sinfo.n_stream()*sinfo.size()); |
887 | |
|
888 | 0 | for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { |
889 | 0 | for (uint32_t ii = 0; ii < sinfo.size(); ++ii) { |
890 | 0 | const uint32_t i = s*sinfo.size() + ii; |
891 | |
|
892 | 0 | auto & cells = v_cells[sinfo.strm[s]]; |
893 | |
|
894 | 0 | const auto idx = sinfo.idxs[s][ii]; |
895 | |
|
896 | 0 | if (!cells.is_empty(idx)) { |
897 | 0 | assert(cells.seq_count(idx) == 1); |
898 | |
|
899 | 0 | const llama_seq_id seq_id = cells.seq_get(idx); |
900 | 0 | const llama_pos pos = cells.pos_get(idx); |
901 | |
|
902 | 0 | seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos); |
903 | |
|
904 | 0 | cells.rm(idx); |
905 | 0 | } |
906 | |
|
907 | 0 | cells.pos_set(idx, ubatch.pos[i]); |
908 | |
|
909 | 0 | if (ubatch.is_pos_2d()) { |
910 | 0 | llama_kv_cell_ext ext { |
911 | 0 | /*.x =*/ ubatch.pos[i + ubatch.n_tokens*2], |
912 | 0 | /*.y =*/ ubatch.pos[i + ubatch.n_tokens], |
913 | 0 | }; |
914 | 0 | cells.ext_set(idx, ext); |
915 | 0 | } |
916 | |
|
917 | 0 | for (int32_t s = 0; s < ubatch.n_seq_id[i]; s++) { |
918 | 0 | cells.seq_add(idx, ubatch.seq_id[i][s]); |
919 | 0 | } |
920 | 0 | } |
921 | 0 | } |
922 | | |
923 | | // note: we want to preserve the invariant that all positions between [pos_min, pos_max] for each sequence |
924 | | // will be present in the cache. so we have to purge any position which is less than those we would overwrite |
925 | | // ref: https://github.com/ggml-org/llama.cpp/pull/13746#issuecomment-2916057092 |
926 | 0 | for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) { |
927 | 0 | if (seq_pos_max_rm[s] == -1) { |
928 | 0 | continue; |
929 | 0 | } |
930 | | |
931 | 0 | GGML_ASSERT(s < seq_to_stream.size()); |
932 | |
|
933 | 0 | auto & cells = v_cells[seq_to_stream[s]]; |
934 | |
|
935 | 0 | if (cells.seq_pos_min(s) <= seq_pos_max_rm[s]) { |
936 | 0 | LLAMA_LOG_DEBUG("%s: purging positions [%d, %d] of sequence %d from KV cache\n", |
937 | 0 | __func__, cells.seq_pos_min(s), seq_pos_max_rm[s], s); |
938 | |
|
939 | 0 | seq_rm(s, cells.seq_pos_min(s), seq_pos_max_rm[s] + 1); |
940 | 0 | } |
941 | 0 | } |
942 | | |
943 | | // move the head at the end of the slot |
944 | 0 | for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { |
945 | 0 | auto & head = v_heads[sinfo.strm[s]]; |
946 | |
|
947 | 0 | head = sinfo.idxs[s].back() + 1; |
948 | 0 | } |
949 | 0 | } |
950 | | |
951 | 0 | bool llama_kv_cache::get_can_shift() const { |
952 | 0 | return true; |
953 | 0 | } |
954 | | |
955 | 0 | uint32_t llama_kv_cache::get_size() const { |
956 | 0 | const auto & cells = v_cells[seq_to_stream[0]]; |
957 | |
|
958 | 0 | return cells.size(); |
959 | 0 | } |
960 | | |
961 | 0 | uint32_t llama_kv_cache::get_n_stream() const { |
962 | 0 | return n_stream; |
963 | 0 | } |
964 | | |
965 | 0 | bool llama_kv_cache::get_has_shift() const { |
966 | 0 | bool result = false; |
967 | |
|
968 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
969 | 0 | result |= v_cells[s].get_has_shift(); |
970 | 0 | } |
971 | |
|
972 | 0 | return result; |
973 | 0 | } |
974 | | |
975 | 0 | uint32_t llama_kv_cache::get_n_kv(const slot_info & sinfo) const { |
976 | 0 | uint32_t result = 0; |
977 | | |
978 | | // pad the n_kv value so that the graph remains constant across batches and can be reused |
979 | | // note: this also helps some backends with performance (f.ex https://github.com/ggml-org/llama.cpp/pull/16812#issuecomment-3455112220) |
980 | 0 | const uint32_t n_pad_cur = std::max(n_pad, 256u); |
981 | |
|
982 | 0 | for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { |
983 | 0 | const auto & cells = v_cells[sinfo.strm[s]]; |
984 | |
|
985 | 0 | result = std::max(std::min(cells.size(), std::max(n_pad_cur, GGML_PAD(cells.used_max_p1(), n_pad_cur))), result); |
986 | 0 | } |
987 | |
|
988 | 0 | return result; |
989 | 0 | } |
990 | | |
991 | 0 | ggml_tensor * llama_kv_cache::get_k(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const { |
992 | 0 | const int32_t ikv = map_layer_ids.at(il); |
993 | |
|
994 | 0 | auto * k = layers[ikv].k; |
995 | |
|
996 | 0 | const uint64_t kv_size = get_size(); |
997 | 0 | const uint64_t n_embd_k_gqa = k->ne[0]; |
998 | |
|
999 | 0 | assert(n_embd_k_gqa == hparams.n_embd_k_gqa(il)); |
1000 | |
|
1001 | 0 | const uint32_t ns = sinfo.s1 - sinfo.s0 + 1; |
1002 | |
|
1003 | 0 | return ggml_view_4d(ctx, k, |
1004 | 0 | hparams.n_embd_head_k, hparams.n_head_kv(il), n_kv, ns, |
1005 | 0 | ggml_row_size(k->type, hparams.n_embd_head_k), |
1006 | 0 | ggml_row_size(k->type, n_embd_k_gqa), |
1007 | 0 | ggml_row_size(k->type, n_embd_k_gqa*kv_size), |
1008 | 0 | ggml_row_size(k->type, n_embd_k_gqa*kv_size)*sinfo.s0); |
1009 | 0 | } |
1010 | | |
1011 | 0 | ggml_tensor * llama_kv_cache::get_v(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const { |
1012 | 0 | const int32_t ikv = map_layer_ids.at(il); |
1013 | |
|
1014 | 0 | auto * v = layers[ikv].v; |
1015 | |
|
1016 | 0 | const uint64_t kv_size = get_size(); |
1017 | 0 | const uint64_t n_embd_v_gqa = v->ne[0]; |
1018 | | |
1019 | | // [TAG_V_CACHE_VARIABLE] |
1020 | 0 | assert(n_embd_v_gqa >= hparams.n_embd_v_gqa(il)); |
1021 | |
|
1022 | 0 | const uint32_t ns = sinfo.s1 - sinfo.s0 + 1; |
1023 | |
|
1024 | 0 | if (!v_trans) { |
1025 | | // note: v->nb[1] <= v->nb[2] |
1026 | 0 | return ggml_view_4d(ctx, v, |
1027 | 0 | hparams.n_embd_head_v, hparams.n_head_kv(il), n_kv, ns, |
1028 | 0 | ggml_row_size(v->type, hparams.n_embd_head_v), // v->nb[1] |
1029 | 0 | ggml_row_size(v->type, n_embd_v_gqa), // v->nb[2] |
1030 | 0 | ggml_row_size(v->type, n_embd_v_gqa*kv_size), // v->nb[3] |
1031 | 0 | ggml_row_size(v->type, n_embd_v_gqa*kv_size)*sinfo.s0); |
1032 | 0 | } |
1033 | | |
1034 | | // note: v->nb[1] > v->nb[2] |
1035 | 0 | return ggml_view_4d(ctx, v, |
1036 | 0 | n_kv, hparams.n_head_kv(il), hparams.n_embd_head_v, ns, |
1037 | 0 | ggml_row_size(v->type, kv_size*hparams.n_embd_head_v), // v->nb[1] |
1038 | 0 | ggml_row_size(v->type, kv_size), // v->nb[2] |
1039 | 0 | ggml_row_size(v->type, kv_size*n_embd_v_gqa), // v->nb[3] |
1040 | 0 | ggml_row_size(v->type, kv_size*n_embd_v_gqa)*sinfo.s0); |
1041 | 0 | } |
1042 | | |
1043 | 0 | ggml_tensor * llama_kv_cache::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il, const slot_info & sinfo) const { |
1044 | 0 | GGML_UNUSED(sinfo); |
1045 | |
|
1046 | 0 | const int32_t ikv = map_layer_ids.at(il); |
1047 | |
|
1048 | 0 | ggml_tensor * k = layers[ikv].k; |
1049 | |
|
1050 | 0 | const int64_t n_embd_head = k_cur->ne[0]; |
1051 | 0 | const int64_t n_head = k_cur->ne[1]; |
1052 | 0 | const int64_t n_tokens = k_cur->ne[2]; |
1053 | |
|
1054 | 0 | const int64_t n_embd_gqa = n_embd_head*n_head; |
1055 | | |
1056 | | // we can merge dims 0 and 1 |
1057 | | // TODO: add ggml helper function for this? |
1058 | 0 | GGML_ASSERT(ggml_row_size(k_cur->type, n_embd_head) == k_cur->nb[1]); |
1059 | |
|
1060 | 0 | k_cur = ggml_view_2d(ctx, k_cur, n_embd_gqa, n_tokens, k_cur->nb[2], 0); |
1061 | |
|
1062 | 0 | const int64_t n_stream = k->ne[2]; |
1063 | |
|
1064 | 0 | if (n_stream > 1) { |
1065 | 0 | const int64_t kv_size = get_size(); |
1066 | |
|
1067 | 0 | assert(n_embd_gqa == k->ne[0]); |
1068 | 0 | assert(kv_size == k->ne[1]); |
1069 | | |
1070 | | // merge the buffer across all streams because the idxs are global |
1071 | 0 | k = ggml_reshape_2d(ctx, k, n_embd_gqa, kv_size*n_stream); |
1072 | 0 | } |
1073 | | |
1074 | | // store the current K values into the cache |
1075 | 0 | return ggml_set_rows(ctx, k, k_cur, k_idxs); |
1076 | 0 | } |
1077 | | |
1078 | 0 | ggml_tensor * llama_kv_cache::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il, const slot_info & sinfo) const { |
1079 | 0 | GGML_UNUSED(sinfo); |
1080 | |
|
1081 | 0 | const int32_t ikv = map_layer_ids.at(il); |
1082 | |
|
1083 | 0 | auto * v = layers[ikv].v; |
1084 | |
|
1085 | 0 | const int64_t n_embd_head = v_cur->ne[0]; |
1086 | 0 | const int64_t n_head = v_cur->ne[1]; |
1087 | 0 | const int64_t n_tokens = v_cur->ne[2]; |
1088 | |
|
1089 | 0 | const int64_t n_embd_gqa = n_embd_head*n_head; |
1090 | | |
1091 | | // we can merge dims 0 and 1 |
1092 | 0 | GGML_ASSERT(ggml_row_size(v_cur->type, n_embd_head) == v_cur->nb[1]); |
1093 | |
|
1094 | 0 | const int64_t n_stream = v->ne[2]; |
1095 | | |
1096 | | // take this branch when FA is enabled (the V cache is not transposed) |
1097 | 0 | if (!v_trans) { |
1098 | 0 | v_cur = ggml_view_2d(ctx, v_cur, n_embd_gqa, n_tokens, v_cur->nb[2], 0); |
1099 | |
|
1100 | 0 | if (n_stream > 1) { |
1101 | 0 | const int64_t kv_size = get_size(); |
1102 | |
|
1103 | 0 | assert(n_embd_gqa == v->ne[0]); |
1104 | 0 | assert(kv_size == v->ne[1]); |
1105 | | |
1106 | | // merge the buffer across all streams because the idxs are global |
1107 | 0 | v = ggml_reshape_2d(ctx, v, n_embd_gqa, kv_size*n_stream); |
1108 | 0 | } |
1109 | |
|
1110 | 0 | return ggml_set_rows(ctx, v, v_cur, v_idxs); |
1111 | 0 | } |
1112 | | |
1113 | 0 | if (ggml_row_size(v_cur->type, n_embd_gqa) == v_cur->nb[2]) { |
1114 | | // we can merge dims 0, 1 and 2 |
1115 | 0 | v_cur = ggml_reshape_2d(ctx, v_cur, n_embd_gqa, n_tokens); |
1116 | 0 | } else { |
1117 | | // otherwise -> make a copy to get contiguous data |
1118 | 0 | v_cur = ggml_cont_2d (ctx, v_cur, n_embd_gqa, n_tokens); |
1119 | 0 | } |
1120 | | |
1121 | | // [TAG_V_CACHE_VARIABLE] |
1122 | 0 | if (n_embd_gqa < v->ne[0]) { |
1123 | 0 | v_cur = ggml_pad(ctx, v_cur, v->ne[0] - n_embd_gqa, 0, 0, 0); |
1124 | 0 | } |
1125 | | |
1126 | | // in this branch the v_idxs are constructed in such a way that each row is a single head element |
1127 | 0 | ggml_tensor * v_view = ggml_reshape_2d(ctx, v, 1, ggml_nelements(v)); |
1128 | |
|
1129 | 0 | v_cur = ggml_reshape_2d(ctx, v_cur, 1, ggml_nelements(v_cur)); |
1130 | |
|
1131 | 0 | return ggml_set_rows(ctx, v_view, v_cur, v_idxs); |
1132 | 0 | } |
1133 | | |
1134 | 0 | ggml_tensor * llama_kv_cache::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const { |
1135 | 0 | const uint32_t n_tokens = ubatch.n_tokens; |
1136 | |
|
1137 | 0 | ggml_tensor * k_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens); |
1138 | |
|
1139 | 0 | ggml_set_input(k_idxs); |
1140 | |
|
1141 | 0 | return k_idxs; |
1142 | 0 | } |
1143 | | |
1144 | 0 | ggml_tensor * llama_kv_cache::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const { |
1145 | 0 | const uint32_t n_tokens = ubatch.n_tokens; |
1146 | |
|
1147 | 0 | ggml_tensor * v_idxs; |
1148 | |
|
1149 | 0 | if (!v_trans) { |
1150 | 0 | v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens); |
1151 | 0 | } else { |
1152 | 0 | v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens*hparams.n_embd_v_gqa_max()); |
1153 | 0 | } |
1154 | |
|
1155 | 0 | ggml_set_input(v_idxs); |
1156 | |
|
1157 | 0 | return v_idxs; |
1158 | 0 | } |
1159 | | |
1160 | 0 | void llama_kv_cache::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const { |
1161 | 0 | const uint32_t n_tokens = ubatch->n_tokens; |
1162 | 0 | GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream()); |
1163 | |
|
1164 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer)); |
1165 | 0 | int64_t * data = (int64_t *) dst->data; |
1166 | |
|
1167 | 0 | for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { |
1168 | 0 | const int64_t offs = sinfo.strm[s]*get_size(); |
1169 | |
|
1170 | 0 | for (uint32_t i = 0; i < sinfo.size(); ++i) { |
1171 | 0 | data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i]; |
1172 | 0 | } |
1173 | 0 | } |
1174 | 0 | } |
1175 | | |
1176 | 0 | void llama_kv_cache::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const { |
1177 | 0 | const uint32_t n_tokens = ubatch->n_tokens; |
1178 | 0 | GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream()); |
1179 | |
|
1180 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer)); |
1181 | 0 | int64_t * data = (int64_t *) dst->data; |
1182 | |
|
1183 | 0 | if (!v_trans) { |
1184 | 0 | for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { |
1185 | 0 | const int64_t offs = sinfo.strm[s]*get_size(); |
1186 | |
|
1187 | 0 | for (uint32_t i = 0; i < sinfo.size(); ++i) { |
1188 | 0 | data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i]; |
1189 | 0 | } |
1190 | 0 | } |
1191 | 0 | } else { |
1192 | | // note: the V cache is transposed when not using flash attention |
1193 | 0 | const int64_t kv_size = get_size(); |
1194 | |
|
1195 | 0 | const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa_max(); |
1196 | |
|
1197 | 0 | for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { |
1198 | 0 | const int64_t offs = sinfo.strm[s]*kv_size*n_embd_v_gqa; |
1199 | |
|
1200 | 0 | for (uint32_t i = 0; i < sinfo.size(); ++i) { |
1201 | 0 | for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { |
1202 | 0 | data[s*sinfo.size()*n_embd_v_gqa + i*n_embd_v_gqa + j] = offs + j*kv_size + sinfo.idxs[s][i]; |
1203 | 0 | } |
1204 | 0 | } |
1205 | 0 | } |
1206 | 0 | } |
1207 | 0 | } |
1208 | | |
1209 | 0 | void llama_kv_cache::set_input_k_shift(ggml_tensor * dst) const { |
1210 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer)); |
1211 | |
|
1212 | 0 | int32_t * data = (int32_t *) dst->data; |
1213 | |
|
1214 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
1215 | 0 | const auto & cells = v_cells[s]; |
1216 | |
|
1217 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
1218 | 0 | data[s*cells.size() + i] = cells.is_empty(i) ? 0 : cells.get_shift(i); |
1219 | 0 | } |
1220 | 0 | } |
1221 | 0 | } |
1222 | | |
1223 | 0 | void llama_kv_cache::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const { |
1224 | 0 | const uint32_t n_tokens = ubatch->n_tokens; |
1225 | |
|
1226 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer)); |
1227 | 0 | float * data = (float *) dst->data; |
1228 | |
|
1229 | 0 | const int64_t n_kv = dst->ne[0]; |
1230 | 0 | const int64_t n_stream = dst->ne[3]; // num streams in the current ubatch |
1231 | |
|
1232 | 0 | GGML_ASSERT(n_tokens%n_stream == 0); |
1233 | | |
1234 | | // n_tps == n_tokens_per_stream |
1235 | 0 | const int64_t n_tps = n_tokens/n_stream; |
1236 | 0 | const int64_t n_tps_pad = GGML_PAD(n_tps, GGML_KQ_MASK_PAD); |
1237 | |
|
1238 | 0 | std::fill(data, data + ggml_nelements(dst), -INFINITY); |
1239 | | |
1240 | | // Use only the previous KV cells of the correct sequence for each token of the ubatch. |
1241 | | // It's assumed that if a token in the batch has multiple sequences, they are equivalent. |
1242 | | // Example with a cache of 10 tokens, 2 tokens populated in cache and 3 tokens in batch: |
1243 | | // Causal mask: |
1244 | | // xxx------- |
1245 | | // xxxx------ |
1246 | | // xxxxx----- |
1247 | | // Non-causal mask: |
1248 | | // xxxxx----- |
1249 | | // xxxxx----- |
1250 | | // xxxxx----- |
1251 | | // To visualize the mask, see https://github.com/ggml-org/llama.cpp/pull/12615 |
1252 | | // TODO: optimize this section |
1253 | 0 | for (uint32_t h = 0; h < 1; ++h) { |
1254 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
1255 | 0 | for (uint32_t ii = 0; ii < n_tps; ++ii) { |
1256 | 0 | const uint32_t i = s*n_tps + ii; |
1257 | |
|
1258 | 0 | const llama_seq_id seq_id = ubatch->seq_id[i][0]; |
1259 | |
|
1260 | 0 | const auto & cells = v_cells[seq_to_stream[seq_id]]; |
1261 | |
|
1262 | 0 | const llama_pos p1 = ubatch->pos[i]; |
1263 | | |
1264 | | // for M-RoPE |
1265 | 0 | const bool is_2d = ubatch->is_pos_2d(); |
1266 | 0 | const llama_pos p1_x = is_2d ? ubatch->pos[i + ubatch->n_tokens*2] : 0; |
1267 | 0 | const llama_pos p1_y = is_2d ? ubatch->pos[i + ubatch->n_tokens] : 0; |
1268 | |
|
1269 | 0 | const uint64_t idst = n_kv*(h*n_stream*n_tps_pad + s*n_tps_pad + ii); |
1270 | |
|
1271 | 0 | for (uint32_t j = 0; j < n_kv; ++j) { |
1272 | 0 | if (cells.is_empty(j)) { |
1273 | 0 | continue; |
1274 | 0 | } |
1275 | | |
1276 | | // mask the token if not the same sequence |
1277 | 0 | if (!cells.seq_has(j, seq_id)) { |
1278 | 0 | continue; |
1279 | 0 | } |
1280 | | |
1281 | 0 | const llama_pos p0 = cells.pos_get(j); |
1282 | | |
1283 | | // mask future tokens |
1284 | 0 | if (causal_attn && p0 > p1) { |
1285 | 0 | continue; |
1286 | 0 | } |
1287 | | |
1288 | | // M-RoPE causal mask |
1289 | 0 | if (causal_attn && is_2d && p0 == p1) { |
1290 | 0 | const auto & p0_ext = cells.ext_get(j); |
1291 | 0 | if (p0_ext.is_2d_gt(p1_x, p1_y)) { |
1292 | 0 | continue; |
1293 | 0 | } |
1294 | 0 | } |
1295 | | |
1296 | | // apply SWA if any |
1297 | 0 | if (is_masked_swa(p0, p1)) { |
1298 | 0 | continue; |
1299 | 0 | } |
1300 | | |
1301 | 0 | data[idst + j] = hparams.use_alibi ? -std::abs(p0 - p1) : 0.0f; |
1302 | 0 | } |
1303 | 0 | } |
1304 | 0 | } |
1305 | 0 | } |
1306 | 0 | } |
1307 | | |
1308 | 0 | void llama_kv_cache::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const { |
1309 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
1310 | |
|
1311 | 0 | GGML_ASSERT(n_stream == 1 && "TODO: support multiple streams"); |
1312 | 0 | const auto & cells = v_cells[0]; |
1313 | |
|
1314 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer)); |
1315 | 0 | GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing |
1316 | |
|
1317 | 0 | int32_t * data = (int32_t *) dst->data; |
1318 | |
|
1319 | 0 | const int32_t n_kv = dst->ne[0]; |
1320 | |
|
1321 | 0 | for (int h = 0; h < 1; ++h) { |
1322 | 0 | for (int i = 0; i < n_tokens; ++i) { |
1323 | 0 | for (int j = 0; j < n_kv; ++j) { |
1324 | | // the position when the cells is empty is irrelevant - it will be masked out later in the attention |
1325 | 0 | const llama_pos p0 = cells.is_empty(j) ? -1 : cells.pos_get(j); |
1326 | |
|
1327 | 0 | data[h*(n_kv*n_tokens) + i*n_kv + j] = llama_relative_position_bucket(p0, ubatch->pos[i], hparams.n_rel_attn_bkts, false); |
1328 | 0 | } |
1329 | 0 | } |
1330 | 0 | } |
1331 | 0 | } |
1332 | | |
1333 | 0 | size_t llama_kv_cache::total_size() const { |
1334 | 0 | size_t size = 0; |
1335 | |
|
1336 | 0 | for (const auto & [_, buf] : ctxs_bufs) { |
1337 | 0 | size += ggml_backend_buffer_get_size(buf.get()); |
1338 | 0 | } |
1339 | |
|
1340 | 0 | return size; |
1341 | 0 | } |
1342 | | |
1343 | 0 | size_t llama_kv_cache::size_k_bytes() const { |
1344 | 0 | size_t size_k_bytes = 0; |
1345 | |
|
1346 | 0 | for (const auto & layer : layers) { |
1347 | 0 | size_k_bytes += ggml_nbytes(layer.k); |
1348 | 0 | } |
1349 | |
|
1350 | 0 | return size_k_bytes; |
1351 | 0 | } |
1352 | | |
1353 | 0 | size_t llama_kv_cache::size_v_bytes() const { |
1354 | 0 | size_t size_v_bytes = 0; |
1355 | |
|
1356 | 0 | for (const auto & layer : layers) { |
1357 | 0 | size_v_bytes += ggml_nbytes(layer.v); |
1358 | 0 | } |
1359 | |
|
1360 | 0 | return size_v_bytes; |
1361 | 0 | } |
1362 | | |
1363 | | ggml_tensor * llama_kv_cache::build_rope_shift( |
1364 | | const llama_cparams & cparams, |
1365 | | ggml_context * ctx, |
1366 | | ggml_tensor * cur, |
1367 | | ggml_tensor * shift, |
1368 | | ggml_tensor * factors, |
1369 | | float freq_base, |
1370 | 0 | float freq_scale) const { |
1371 | 0 | const auto & n_ctx_orig = cparams.n_ctx_orig_yarn; |
1372 | |
|
1373 | 0 | const auto & yarn_ext_factor = cparams.yarn_ext_factor; |
1374 | 0 | const auto & yarn_beta_fast = cparams.yarn_beta_fast; |
1375 | 0 | const auto & yarn_beta_slow = cparams.yarn_beta_slow; |
1376 | |
|
1377 | 0 | const auto & n_rot = hparams.n_rot; |
1378 | 0 | const auto & rope_type = hparams.rope_type == LLAMA_ROPE_TYPE_MROPE || hparams.rope_type == LLAMA_ROPE_TYPE_IMROPE |
1379 | | // @ngxson : this is a workaround |
1380 | | // for M-RoPE, we want to rotate the whole vector when doing KV shift |
1381 | | // a normal RoPE should work, we just need to use the correct ordering |
1382 | | // ref: https://github.com/ggml-org/llama.cpp/pull/13870 |
1383 | 0 | ? LLAMA_ROPE_TYPE_NEOX |
1384 | 0 | : hparams.rope_type; |
1385 | | |
1386 | | // See llm_build_deepseek2() for why attn_factor has to be scaled for YaRN RoPE to work correctly. |
1387 | | // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation. |
1388 | 0 | const float yarn_attn_factor = model.arch == LLM_ARCH_DEEPSEEK2 |
1389 | 0 | ? 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale)) |
1390 | 0 | : cparams.yarn_attn_factor; |
1391 | |
|
1392 | 0 | ggml_tensor * tmp; |
1393 | |
|
1394 | 0 | if (ggml_is_quantized(cur->type)) { |
1395 | | // dequantize to f32 -> RoPE -> quantize back |
1396 | 0 | tmp = ggml_cast(ctx, cur, GGML_TYPE_F32); |
1397 | |
|
1398 | 0 | tmp = ggml_rope_ext(ctx, tmp, |
1399 | 0 | shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale, |
1400 | 0 | yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow); |
1401 | |
|
1402 | 0 | tmp = ggml_cpy(ctx, tmp, cur); |
1403 | 0 | } else { |
1404 | | // we rotate only the first n_rot dimensions |
1405 | 0 | tmp = ggml_rope_ext_inplace(ctx, cur, |
1406 | 0 | shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale, |
1407 | 0 | yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow); |
1408 | 0 | } |
1409 | |
|
1410 | 0 | return tmp; |
1411 | 0 | } |
1412 | | |
1413 | | class llm_graph_input_k_shift : public llm_graph_input_i { |
1414 | | public: |
1415 | 0 | llm_graph_input_k_shift(const llama_kv_cache * kv_self) : kv_self(kv_self) {} |
1416 | | virtual ~llm_graph_input_k_shift() = default; |
1417 | | |
1418 | | void set_input(const llama_ubatch * ubatch) override; |
1419 | | |
1420 | | ggml_tensor * k_shift; // I32 [kv_size*n_stream] |
1421 | | |
1422 | | const llama_kv_cache * kv_self; |
1423 | | }; |
1424 | | |
1425 | 0 | void llm_graph_input_k_shift::set_input(const llama_ubatch * ubatch) { |
1426 | 0 | GGML_UNUSED(ubatch); |
1427 | |
|
1428 | 0 | if (k_shift) { |
1429 | 0 | kv_self->set_input_k_shift(k_shift); |
1430 | 0 | } |
1431 | 0 | } |
1432 | | |
1433 | 0 | ggml_cgraph * llama_kv_cache::build_graph_shift(llm_graph_result * res, llama_context * lctx) const { |
1434 | 0 | auto * ctx = res->get_ctx(); |
1435 | 0 | auto * gf = res->get_gf(); |
1436 | |
|
1437 | 0 | const auto & n_embd_head_k = hparams.n_embd_head_k; |
1438 | | //const auto & n_embd_head_v = hparams.n_embd_head_v; |
1439 | |
|
1440 | 0 | auto inp = std::make_unique<llm_graph_input_k_shift>(this); |
1441 | |
|
1442 | 0 | inp->k_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, (int64_t) get_size()*n_stream); |
1443 | 0 | ggml_set_input(inp->k_shift); |
1444 | |
|
1445 | 0 | const auto & cparams = lctx->get_cparams(); |
1446 | |
|
1447 | 0 | for (const auto & layer : layers) { |
1448 | 0 | const uint32_t il = layer.il; |
1449 | |
|
1450 | 0 | const int64_t n_head_kv = hparams.n_head_kv(il); |
1451 | 0 | const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il); |
1452 | |
|
1453 | 0 | const float freq_base_l = model.get_rope_freq_base (cparams, il); |
1454 | 0 | const float freq_scale_l = model.get_rope_freq_scale(cparams, il); |
1455 | |
|
1456 | 0 | ggml_tensor * rope_factors = model.get_rope_factors(cparams, il); |
1457 | |
|
1458 | 0 | ggml_tensor * k = |
1459 | 0 | ggml_view_3d(ctx, layer.k, |
1460 | 0 | n_embd_head_k, n_head_kv, get_size()*n_stream, |
1461 | 0 | ggml_row_size(layer.k->type, n_embd_head_k), |
1462 | 0 | ggml_row_size(layer.k->type, n_embd_k_gqa), |
1463 | 0 | 0); |
1464 | |
|
1465 | 0 | ggml_tensor * cur = build_rope_shift(cparams, ctx, k, inp->k_shift, rope_factors, freq_base_l, freq_scale_l); |
1466 | |
|
1467 | 0 | ggml_build_forward_expand(gf, cur); |
1468 | 0 | } |
1469 | |
|
1470 | 0 | res->add_input(std::move(inp)); |
1471 | |
|
1472 | 0 | return gf; |
1473 | 0 | } |
1474 | | |
1475 | 0 | bool llama_kv_cache::is_masked_swa(llama_pos p0, llama_pos p1) const { |
1476 | 0 | return llama_hparams::is_masked_swa(n_swa, swa_type, p0, p1); |
1477 | 0 | } |
1478 | | |
1479 | 0 | void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const { |
1480 | 0 | GGML_UNUSED(flags); |
1481 | |
|
1482 | 0 | io.write(&n_stream, sizeof(n_stream)); |
1483 | |
|
1484 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
1485 | 0 | cell_ranges_t cr { s, {} }; |
1486 | |
|
1487 | 0 | uint32_t cell_count = 0; |
1488 | |
|
1489 | 0 | const auto & cells = v_cells[s]; |
1490 | | |
1491 | | // Count the number of cells with the specified seq_id |
1492 | | // Find all the ranges of cells with this seq id (or all, when -1) |
1493 | 0 | uint32_t cell_range_begin = cells.size(); |
1494 | |
|
1495 | 0 | for (uint32_t i = 0; i < cells.size(); ++i) { |
1496 | 0 | if (!cells.is_empty(i) && (seq_id == -1 || cells.seq_has(i, seq_id))) { |
1497 | 0 | ++cell_count; |
1498 | 0 | if (cell_range_begin == cells.size()) { |
1499 | 0 | cell_range_begin = i; |
1500 | 0 | } |
1501 | 0 | } else { |
1502 | 0 | if (cell_range_begin != cells.size()) { |
1503 | 0 | cr.data.emplace_back(cell_range_begin, i); |
1504 | 0 | cell_range_begin = cells.size(); |
1505 | 0 | } |
1506 | 0 | } |
1507 | 0 | } |
1508 | |
|
1509 | 0 | if (cell_range_begin != cells.size()) { |
1510 | 0 | cr.data.emplace_back(cell_range_begin, cells.size()); |
1511 | 0 | } |
1512 | | |
1513 | | // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count |
1514 | 0 | uint32_t cell_count_check = 0; |
1515 | 0 | for (const auto & range : cr.data) { |
1516 | 0 | cell_count_check += range.second - range.first; |
1517 | 0 | } |
1518 | 0 | GGML_ASSERT(cell_count == cell_count_check); |
1519 | |
|
1520 | 0 | io.write(&cell_count, sizeof(cell_count)); |
1521 | | |
1522 | | // skip empty streams |
1523 | 0 | if (cell_count == 0) { |
1524 | 0 | continue; |
1525 | 0 | } |
1526 | | |
1527 | 0 | state_write_meta(io, cr, seq_id); |
1528 | 0 | state_write_data(io, cr); |
1529 | 0 | } |
1530 | 0 | } |
1531 | | |
1532 | 0 | void llama_kv_cache::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { |
1533 | 0 | GGML_UNUSED(flags); |
1534 | |
|
1535 | 0 | GGML_ASSERT(seq_id == -1 || (seq_id >= 0 && (size_t) seq_id < seq_to_stream.size())); |
1536 | |
|
1537 | 0 | uint32_t n_stream_cur; |
1538 | 0 | io.read_to(&n_stream_cur, sizeof(n_stream_cur)); |
1539 | 0 | if (n_stream_cur != n_stream) { |
1540 | 0 | throw std::runtime_error("n_stream mismatch"); |
1541 | 0 | } |
1542 | | |
1543 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
1544 | 0 | uint32_t cell_count; |
1545 | 0 | io.read_to(&cell_count, sizeof(cell_count)); |
1546 | |
|
1547 | 0 | if (cell_count == 0) { |
1548 | 0 | continue; |
1549 | 0 | } |
1550 | | |
1551 | 0 | const uint32_t strm = seq_id == -1 ? s : seq_to_stream[seq_id]; |
1552 | |
|
1553 | 0 | bool res = true; |
1554 | 0 | res = res && state_read_meta(io, strm, cell_count, seq_id); |
1555 | 0 | res = res && state_read_data(io, strm, cell_count); |
1556 | |
|
1557 | 0 | if (!res) { |
1558 | 0 | if (seq_id == -1) { |
1559 | 0 | clear(true); |
1560 | 0 | } else { |
1561 | 0 | seq_rm(seq_id, -1, -1); |
1562 | 0 | } |
1563 | 0 | throw std::runtime_error("failed to restore kv cache"); |
1564 | 0 | } |
1565 | 0 | } |
1566 | 0 | } |
1567 | | |
1568 | 0 | void llama_kv_cache::state_write_meta(llama_io_write_i & io, const cell_ranges_t & cr, llama_seq_id seq_id) const { |
1569 | 0 | const auto & cells = v_cells[cr.strm]; |
1570 | |
|
1571 | 0 | for (const auto & range : cr.data) { |
1572 | 0 | for (uint32_t i = range.first; i < range.second; ++i) { |
1573 | 0 | std::vector<llama_seq_id> seq_ids; |
1574 | |
|
1575 | 0 | for (llama_seq_id cur = 0; cur < (int) n_seq_max; ++cur) { |
1576 | 0 | if (cur == seq_id || seq_id == -1) { |
1577 | 0 | if (cells.seq_has(i, cur)) { |
1578 | 0 | seq_ids.push_back(cur); |
1579 | 0 | } |
1580 | 0 | } |
1581 | 0 | } |
1582 | |
|
1583 | 0 | const llama_pos pos = cells.pos_get(i); |
1584 | 0 | const uint32_t n_seq_id = seq_ids.size(); |
1585 | |
|
1586 | 0 | io.write(&pos, sizeof(pos)); |
1587 | 0 | io.write(&n_seq_id, sizeof(n_seq_id)); |
1588 | | |
1589 | | // TODO: we also need to save llama_kv_cell_ext when apply_ubatch() support loading it |
1590 | | // see: https://github.com/ggml-org/llama.cpp/pull/16825#issuecomment-3460868350 |
1591 | |
|
1592 | 0 | for (const auto & seq_id : seq_ids) { |
1593 | 0 | io.write(&seq_id, sizeof(seq_id)); |
1594 | 0 | } |
1595 | 0 | } |
1596 | 0 | } |
1597 | 0 | } |
1598 | | |
1599 | 0 | void llama_kv_cache::state_write_data(llama_io_write_i & io, const cell_ranges_t & cr) const { |
1600 | 0 | const auto & cells = v_cells[cr.strm]; |
1601 | |
|
1602 | 0 | const uint32_t v_trans = this->v_trans ? 1 : 0; |
1603 | 0 | const uint32_t n_layer = layers.size(); |
1604 | |
|
1605 | 0 | io.write(&v_trans, sizeof(v_trans)); |
1606 | 0 | io.write(&n_layer, sizeof(n_layer)); |
1607 | |
|
1608 | 0 | std::vector<uint8_t> tmp_buf; |
1609 | | |
1610 | | // Iterate and write all the keys first, each row is a cell |
1611 | | // Get whole range at a time |
1612 | 0 | for (const auto & layer : layers) { |
1613 | 0 | const uint32_t il = layer.il; |
1614 | |
|
1615 | 0 | const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il); |
1616 | |
|
1617 | 0 | auto * k = layer.k_stream[cr.strm]; |
1618 | | |
1619 | | // Write key type |
1620 | 0 | const int32_t k_type_i = (int32_t) k->type; |
1621 | 0 | io.write(&k_type_i, sizeof(k_type_i)); |
1622 | | |
1623 | | // Write row size of key |
1624 | 0 | const uint64_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa); |
1625 | 0 | io.write(&k_size_row, sizeof(k_size_row)); |
1626 | | |
1627 | | // Read each range of cells of k_size length each into tmp_buf and write out |
1628 | 0 | for (const auto & range : cr.data) { |
1629 | 0 | const size_t range_size = range.second - range.first; |
1630 | 0 | const size_t buf_size = range_size * k_size_row; |
1631 | 0 | io.write_tensor(k, range.first * k_size_row, buf_size); |
1632 | 0 | } |
1633 | 0 | } |
1634 | |
|
1635 | 0 | if (!v_trans) { |
1636 | 0 | for (const auto & layer : layers) { |
1637 | 0 | const uint32_t il = layer.il; |
1638 | |
|
1639 | 0 | const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il); |
1640 | |
|
1641 | 0 | auto * v = layer.v_stream[cr.strm]; |
1642 | | |
1643 | | // Write value type |
1644 | 0 | const int32_t v_type_i = (int32_t) v->type; |
1645 | 0 | io.write(&v_type_i, sizeof(v_type_i)); |
1646 | | |
1647 | | // Write row size of value |
1648 | 0 | const uint64_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa); |
1649 | 0 | io.write(&v_size_row, sizeof(v_size_row)); |
1650 | | |
1651 | | // Read each range of cells of v_size length each into tmp_buf and write out |
1652 | 0 | for (const auto & range : cr.data) { |
1653 | 0 | const size_t range_size = range.second - range.first; |
1654 | 0 | const size_t buf_size = range_size * v_size_row; |
1655 | 0 | io.write_tensor(v, range.first * v_size_row, buf_size); |
1656 | 0 | } |
1657 | 0 | } |
1658 | 0 | } else { |
1659 | | // When v is transposed, we also need the element size and get the element ranges from each row |
1660 | 0 | const uint32_t kv_size = cells.size(); |
1661 | |
|
1662 | 0 | for (const auto & layer : layers) { |
1663 | 0 | const uint32_t il = layer.il; |
1664 | |
|
1665 | 0 | const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il); |
1666 | |
|
1667 | 0 | auto * v = layer.v_stream[cr.strm]; |
1668 | | |
1669 | | // Write value type |
1670 | 0 | const int32_t v_type_i = (int32_t) v->type; |
1671 | 0 | io.write(&v_type_i, sizeof(v_type_i)); |
1672 | | |
1673 | | // Write element size |
1674 | 0 | const uint32_t v_size_el = ggml_type_size(v->type); |
1675 | 0 | io.write(&v_size_el, sizeof(v_size_el)); |
1676 | | |
1677 | | // Write GQA embedding size |
1678 | 0 | io.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa)); |
1679 | | |
1680 | | // For each row, we get the element values of each cell |
1681 | 0 | for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { |
1682 | | // Read each range of cells of v_size_el length each into tmp_buf and write out |
1683 | 0 | for (const auto & range : cr.data) { |
1684 | 0 | const size_t range_size = range.second - range.first; |
1685 | 0 | const size_t src_offset = (range.first + j * kv_size) * v_size_el; |
1686 | 0 | const size_t buf_size = range_size * v_size_el; |
1687 | 0 | io.write_tensor(v, src_offset, buf_size); |
1688 | 0 | } |
1689 | 0 | } |
1690 | 0 | } |
1691 | 0 | } |
1692 | 0 | } |
1693 | | |
1694 | 0 | bool llama_kv_cache::state_read_meta(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, llama_seq_id dest_seq_id) { |
1695 | 0 | auto & cells = v_cells[strm]; |
1696 | 0 | auto & head = v_heads[strm]; |
1697 | |
|
1698 | 0 | if (dest_seq_id != -1) { |
1699 | | // single sequence |
1700 | 0 | seq_rm(dest_seq_id, -1, -1); |
1701 | |
|
1702 | 0 | llama_batch_allocr balloc(hparams.n_pos_per_embd()); |
1703 | |
|
1704 | 0 | llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1); |
1705 | |
|
1706 | 0 | ubatch.seq_id_unq[0] = dest_seq_id; |
1707 | |
|
1708 | 0 | for (uint32_t i = 0; i < cell_count; ++i) { |
1709 | 0 | llama_pos pos; |
1710 | 0 | uint32_t n_seq_id; |
1711 | |
|
1712 | 0 | io.read_to(&pos, sizeof(pos)); |
1713 | 0 | io.read_to(&n_seq_id, sizeof(n_seq_id)); |
1714 | |
|
1715 | 0 | if (n_seq_id != 1) { |
1716 | 0 | LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__); |
1717 | 0 | return false; |
1718 | 0 | } |
1719 | | |
1720 | | // read the sequence id, but directly discard it - we will use dest_seq_id instead |
1721 | 0 | { |
1722 | 0 | llama_seq_id seq_id; |
1723 | 0 | io.read_to(&seq_id, sizeof(seq_id)); |
1724 | 0 | } |
1725 | |
|
1726 | 0 | ubatch.pos[i] = pos; |
1727 | 0 | ubatch.n_seq_id[i] = n_seq_id; |
1728 | 0 | ubatch.seq_id[i] = &dest_seq_id; |
1729 | 0 | } |
1730 | | |
1731 | 0 | const auto sinfo = find_slot(ubatch, true); |
1732 | 0 | if (sinfo.empty()) { |
1733 | 0 | LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__); |
1734 | 0 | return false; |
1735 | 0 | } |
1736 | | |
1737 | | // TODO: we cannot yet restore llama_kv_cell_ext as the apply_ubatch() does not support it yet |
1738 | | // see: https://github.com/ggml-org/llama.cpp/pull/16825#issuecomment-3460868350 |
1739 | 0 | apply_ubatch(sinfo, ubatch); |
1740 | |
|
1741 | 0 | const auto head_cur = sinfo.head(); |
1742 | | |
1743 | | // keep the head at the old position because we will read the KV data into it in state_read_data() |
1744 | 0 | head = head_cur; |
1745 | |
|
1746 | 0 | LLAMA_LOG_DEBUG("%s: head_cur = %d, head = %d, cell_count = %d, dest_seq_id = %d\n", __func__, head_cur, head, cell_count, dest_seq_id); |
1747 | | |
1748 | | // 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) |
1749 | | // Assume that this is one contiguous block of cells |
1750 | 0 | GGML_ASSERT(head_cur + cell_count <= cells.size()); |
1751 | 0 | GGML_ASSERT(cells.pos_get(head_cur) == ubatch.pos[0]); |
1752 | 0 | GGML_ASSERT(cells.pos_get(head_cur + cell_count - 1) == ubatch.pos[cell_count - 1]); |
1753 | 0 | GGML_ASSERT(cells.seq_has(head_cur, dest_seq_id)); |
1754 | 0 | GGML_ASSERT(cells.seq_has(head_cur + cell_count - 1, dest_seq_id)); |
1755 | 0 | } else { |
1756 | | // whole KV cache restore |
1757 | |
|
1758 | 0 | if (cell_count > cells.size()) { |
1759 | 0 | LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__); |
1760 | 0 | return false; |
1761 | 0 | } |
1762 | | |
1763 | 0 | clear(true); |
1764 | |
|
1765 | 0 | for (uint32_t i = 0; i < cell_count; ++i) { |
1766 | 0 | llama_pos pos; |
1767 | 0 | uint32_t n_seq_id; |
1768 | |
|
1769 | 0 | io.read_to(&pos, sizeof(pos)); |
1770 | 0 | io.read_to(&n_seq_id, sizeof(n_seq_id)); |
1771 | |
|
1772 | 0 | cells.pos_set(i, pos); |
1773 | |
|
1774 | 0 | for (uint32_t j = 0; j < n_seq_id; ++j) { |
1775 | 0 | llama_seq_id seq_id; |
1776 | 0 | io.read_to(&seq_id, sizeof(seq_id)); |
1777 | |
|
1778 | 0 | if (seq_id < 0 || (uint32_t) seq_id >= n_seq_max) { |
1779 | 0 | LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, n_seq_max); |
1780 | 0 | return false; |
1781 | 0 | } |
1782 | | |
1783 | 0 | cells.seq_add(i, seq_id); |
1784 | 0 | } |
1785 | 0 | } |
1786 | | |
1787 | 0 | head = 0; |
1788 | 0 | } |
1789 | | |
1790 | 0 | return true; |
1791 | 0 | } |
1792 | | |
1793 | 0 | bool llama_kv_cache::state_read_data(llama_io_read_i & io, uint32_t strm, uint32_t cell_count) { |
1794 | 0 | auto & cells = v_cells[strm]; |
1795 | 0 | auto & head = v_heads[strm]; |
1796 | |
|
1797 | 0 | uint32_t v_trans; |
1798 | 0 | uint32_t n_layer; |
1799 | |
|
1800 | 0 | io.read_to(&v_trans, sizeof(v_trans)); |
1801 | 0 | io.read_to(&n_layer, sizeof(n_layer)); |
1802 | |
|
1803 | 0 | if (n_layer != layers.size()) { |
1804 | 0 | LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, (uint32_t) layers.size()); |
1805 | 0 | return false; |
1806 | 0 | } |
1807 | | |
1808 | 0 | if (cell_count > cells.size()) { |
1809 | 0 | LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, cells.size()); |
1810 | 0 | return false; |
1811 | 0 | } |
1812 | | |
1813 | 0 | if (this->v_trans != (bool) v_trans) { |
1814 | 0 | LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__); |
1815 | 0 | return false; |
1816 | 0 | } |
1817 | | |
1818 | | // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block |
1819 | 0 | for (const auto & layer : layers) { |
1820 | 0 | const uint32_t il = layer.il; |
1821 | |
|
1822 | 0 | const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il); |
1823 | |
|
1824 | 0 | auto * k = layer.k_stream[strm]; |
1825 | | |
1826 | | // Read type of key |
1827 | 0 | int32_t k_type_i_ref; |
1828 | 0 | io.read_to(&k_type_i_ref, sizeof(k_type_i_ref)); |
1829 | 0 | const int32_t k_type_i = (int32_t) k->type; |
1830 | 0 | if (k_type_i != k_type_i_ref) { |
1831 | 0 | LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il); |
1832 | 0 | return false; |
1833 | 0 | } |
1834 | | |
1835 | | // Read row size of key |
1836 | 0 | uint64_t k_size_row_ref; |
1837 | 0 | io.read_to(&k_size_row_ref, sizeof(k_size_row_ref)); |
1838 | 0 | const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa); |
1839 | 0 | if (k_size_row != k_size_row_ref) { |
1840 | 0 | LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il); |
1841 | 0 | return false; |
1842 | 0 | } |
1843 | | |
1844 | 0 | if (cell_count) { |
1845 | | // Read and set the keys for the whole cell range |
1846 | 0 | ggml_backend_tensor_set(k, io.read(cell_count * k_size_row), head * k_size_row, cell_count * k_size_row); |
1847 | 0 | } |
1848 | 0 | } |
1849 | | |
1850 | 0 | if (!this->v_trans) { |
1851 | 0 | for (const auto & layer : layers) { |
1852 | 0 | const uint32_t il = layer.il; |
1853 | |
|
1854 | 0 | const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il); |
1855 | |
|
1856 | 0 | auto * v = layer.v_stream[strm]; |
1857 | | |
1858 | | // Read type of value |
1859 | 0 | int32_t v_type_i_ref; |
1860 | 0 | io.read_to(&v_type_i_ref, sizeof(v_type_i_ref)); |
1861 | 0 | const int32_t v_type_i = (int32_t) v->type; |
1862 | 0 | if (v_type_i != v_type_i_ref) { |
1863 | 0 | LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il); |
1864 | 0 | return false; |
1865 | 0 | } |
1866 | | |
1867 | | // Read row size of value |
1868 | 0 | uint64_t v_size_row_ref; |
1869 | 0 | io.read_to(&v_size_row_ref, sizeof(v_size_row_ref)); |
1870 | 0 | const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa); |
1871 | 0 | if (v_size_row != v_size_row_ref) { |
1872 | 0 | LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il); |
1873 | 0 | return false; |
1874 | 0 | } |
1875 | | |
1876 | 0 | if (cell_count) { |
1877 | | // Read and set the values for the whole cell range |
1878 | 0 | ggml_backend_tensor_set(v, io.read(cell_count * v_size_row), head * v_size_row, cell_count * v_size_row); |
1879 | 0 | } |
1880 | 0 | } |
1881 | 0 | } else { |
1882 | | // For each layer, read the values for each cell (transposed) |
1883 | 0 | for (const auto & layer : layers) { |
1884 | 0 | const uint32_t il = layer.il; |
1885 | |
|
1886 | 0 | const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il); |
1887 | |
|
1888 | 0 | auto * v = layer.v_stream[strm]; |
1889 | | |
1890 | | // Read type of value |
1891 | 0 | int32_t v_type_i_ref; |
1892 | 0 | io.read_to(&v_type_i_ref, sizeof(v_type_i_ref)); |
1893 | 0 | const int32_t v_type_i = (int32_t) v->type; |
1894 | 0 | if (v_type_i != v_type_i_ref) { |
1895 | 0 | LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il); |
1896 | 0 | return false; |
1897 | 0 | } |
1898 | | |
1899 | | // Read element size of value |
1900 | 0 | uint32_t v_size_el_ref; |
1901 | 0 | io.read_to(&v_size_el_ref, sizeof(v_size_el_ref)); |
1902 | 0 | const size_t v_size_el = ggml_type_size(v->type); |
1903 | 0 | if (v_size_el != v_size_el_ref) { |
1904 | 0 | LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il); |
1905 | 0 | return false; |
1906 | 0 | } |
1907 | | |
1908 | | // Read GQA embedding size |
1909 | 0 | uint32_t n_embd_v_gqa_ref; |
1910 | 0 | io.read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref)); |
1911 | 0 | if (n_embd_v_gqa != n_embd_v_gqa_ref) { |
1912 | 0 | LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il); |
1913 | 0 | return false; |
1914 | 0 | } |
1915 | | |
1916 | 0 | if (cell_count) { |
1917 | | // For each row in the transposed matrix, read the values for the whole cell range |
1918 | 0 | for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { |
1919 | 0 | const size_t dst_offset = (head + j * cells.size()) * v_size_el; |
1920 | 0 | ggml_backend_tensor_set(v, io.read(cell_count * v_size_el), dst_offset, cell_count * v_size_el); |
1921 | 0 | } |
1922 | 0 | } |
1923 | 0 | } |
1924 | 0 | } |
1925 | | |
1926 | 0 | return true; |
1927 | 0 | } |
1928 | | |
1929 | | // |
1930 | | // llama_kv_cache_context |
1931 | | // |
1932 | | |
1933 | 0 | llama_kv_cache_context::llama_kv_cache_context(llama_memory_status status) : status(status) {} |
1934 | | |
1935 | | llama_kv_cache_context::llama_kv_cache_context( |
1936 | 0 | llama_kv_cache * kv) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv) { |
1937 | 0 | n_kv = kv->get_size(); |
1938 | |
|
1939 | 0 | const uint32_t n_stream = kv->get_n_stream(); |
1940 | | |
1941 | | // create a dummy slot info - the actual data is irrelevant. we just need to build the graph |
1942 | 0 | sinfos.resize(1); |
1943 | 0 | sinfos[0].s0 = 0; |
1944 | 0 | sinfos[0].s1 = n_stream - 1; |
1945 | 0 | sinfos[0].idxs.resize(n_stream); |
1946 | 0 | for (uint32_t s = 0; s < n_stream; ++s) { |
1947 | 0 | sinfos[0].strm.push_back(s); |
1948 | 0 | sinfos[0].idxs[s].resize(1, 0); |
1949 | 0 | } |
1950 | 0 | } |
1951 | | |
1952 | | llama_kv_cache_context::llama_kv_cache_context( |
1953 | | llama_kv_cache * kv, |
1954 | | llama_context * lctx, |
1955 | | bool do_shift, |
1956 | 0 | stream_copy_info sc_info) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), lctx(lctx), do_shift(do_shift), sc_info(std::move(sc_info)) { |
1957 | 0 | if (!do_shift && this->sc_info.empty()) { |
1958 | 0 | status = LLAMA_MEMORY_STATUS_NO_UPDATE; |
1959 | 0 | } |
1960 | 0 | } |
1961 | | |
1962 | | llama_kv_cache_context::llama_kv_cache_context( |
1963 | | llama_kv_cache * kv, |
1964 | | llama_kv_cache::slot_info_vec_t sinfos, |
1965 | 0 | std::vector<llama_ubatch> ubatches) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), sinfos(std::move(sinfos)), ubatches(std::move(ubatches)) { |
1966 | 0 | } |
1967 | | |
1968 | 0 | llama_kv_cache_context::~llama_kv_cache_context() = default; |
1969 | | |
1970 | 0 | bool llama_kv_cache_context::next() { |
1971 | 0 | assert(status == LLAMA_MEMORY_STATUS_SUCCESS); |
1972 | |
|
1973 | 0 | if (++i_cur >= ubatches.size()) { |
1974 | 0 | return false; |
1975 | 0 | } |
1976 | | |
1977 | 0 | return true; |
1978 | 0 | } |
1979 | | |
1980 | 0 | bool llama_kv_cache_context::apply() { |
1981 | 0 | assert(!llama_memory_status_is_fail(status)); |
1982 | | |
1983 | | // no ubatches -> this is a KV cache update |
1984 | 0 | if (ubatches.empty()) { |
1985 | 0 | kv->update(lctx, do_shift, sc_info); |
1986 | |
|
1987 | 0 | return true; |
1988 | 0 | } |
1989 | | |
1990 | 0 | kv->apply_ubatch(sinfos[i_cur], ubatches[i_cur]); |
1991 | 0 | n_kv = kv->get_n_kv(sinfos[i_cur]); |
1992 | |
|
1993 | 0 | return true; |
1994 | 0 | } |
1995 | | |
1996 | 0 | llama_memory_status llama_kv_cache_context::get_status() const { |
1997 | 0 | return status; |
1998 | 0 | } |
1999 | | |
2000 | 0 | const llama_ubatch & llama_kv_cache_context::get_ubatch() const { |
2001 | 0 | assert(status == LLAMA_MEMORY_STATUS_SUCCESS); |
2002 | |
|
2003 | 0 | return ubatches[i_cur]; |
2004 | 0 | } |
2005 | | |
2006 | 0 | uint32_t llama_kv_cache_context::get_n_kv() const { |
2007 | 0 | return n_kv; |
2008 | 0 | } |
2009 | | |
2010 | 0 | ggml_tensor * llama_kv_cache_context::get_k(ggml_context * ctx, int32_t il) const { |
2011 | 0 | return kv->get_k(ctx, il, n_kv, sinfos[i_cur]); |
2012 | 0 | } |
2013 | | |
2014 | 0 | ggml_tensor * llama_kv_cache_context::get_v(ggml_context * ctx, int32_t il) const { |
2015 | 0 | return kv->get_v(ctx, il, n_kv, sinfos[i_cur]); |
2016 | 0 | } |
2017 | | |
2018 | 0 | ggml_tensor * llama_kv_cache_context::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il) const { |
2019 | 0 | return kv->cpy_k(ctx, k_cur, k_idxs, il, sinfos[i_cur]); |
2020 | 0 | } |
2021 | | |
2022 | 0 | ggml_tensor * llama_kv_cache_context::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il) const { |
2023 | 0 | return kv->cpy_v(ctx, v_cur, v_idxs, il, sinfos[i_cur]); |
2024 | 0 | } |
2025 | | |
2026 | 0 | ggml_tensor * llama_kv_cache_context::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const { |
2027 | 0 | return kv->build_input_k_idxs(ctx, ubatch); |
2028 | 0 | } |
2029 | | |
2030 | 0 | ggml_tensor * llama_kv_cache_context::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const { |
2031 | 0 | return kv->build_input_v_idxs(ctx, ubatch); |
2032 | 0 | } |
2033 | | |
2034 | 0 | void llama_kv_cache_context::set_input_k_shift(ggml_tensor * dst) const { |
2035 | 0 | kv->set_input_k_shift(dst); |
2036 | 0 | } |
2037 | | |
2038 | 0 | void llama_kv_cache_context::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const { |
2039 | 0 | kv->set_input_k_idxs(dst, ubatch, sinfos[i_cur]); |
2040 | 0 | } |
2041 | | |
2042 | 0 | void llama_kv_cache_context::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const { |
2043 | 0 | kv->set_input_v_idxs(dst, ubatch, sinfos[i_cur]); |
2044 | 0 | } |
2045 | | |
2046 | 0 | void llama_kv_cache_context::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const { |
2047 | 0 | kv->set_input_kq_mask(dst, ubatch, causal_attn); |
2048 | 0 | } |
2049 | | |
2050 | 0 | void llama_kv_cache_context::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const { |
2051 | 0 | kv->set_input_pos_bucket(dst, ubatch); |
2052 | 0 | } |